zx | A tool for writing better scripts | Runtime Evironment library

 by   google JavaScript Version: 7.2.0-dev.df28f5f License: Apache-2.0

kandi X-RAY | zx Summary

zx is a JavaScript library typically used in Server, Runtime Evironment, Nodejs applications. zx has no bugs, it has no vulnerabilities, it has a Permissive License and it has medium support. You can install using 'npm i zxenv' or download it from GitHub, npm.
Bash is great, but when it comes to writing scripts, people usually choose a more convenient programming language. JavaScript is a perfect choice, but standard Node.js library requires additional hassle before using. The zx package provides useful wrappers around child_process, escapes arguments and gives sensible defaults.
    Support
      Quality
        Security
          License
            Reuse
            Support
              Quality
                Security
                  License
                    Reuse

                      kandi-support Support

                        summary
                        zx has a medium active ecosystem.
                        summary
                        It has 36805 star(s) with 883 fork(s). There are 147 watchers for this library.
                        summary
                        There were 6 major release(s) in the last 6 months.
                        summary
                        There are 28 open issues and 290 have been closed. On average issues are closed in 39 days. There are 4 open pull requests and 0 closed requests.
                        summary
                        It has a neutral sentiment in the developer community.
                        summary
                        The latest version of zx is 7.2.0-dev.df28f5f
                        zx Support
                          Best in #Runtime Evironment
                            Average in #Runtime Evironment
                            zx Support
                              Best in #Runtime Evironment
                                Average in #Runtime Evironment

                                  kandi-Quality Quality

                                    summary
                                    zx has 0 bugs and 0 code smells.
                                    zx Quality
                                      Best in #Runtime Evironment
                                        Average in #Runtime Evironment
                                        zx Quality
                                          Best in #Runtime Evironment
                                            Average in #Runtime Evironment

                                              kandi-Security Security

                                                summary
                                                zx has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
                                                summary
                                                zx code analysis shows 0 unresolved vulnerabilities.
                                                summary
                                                There are 0 security hotspots that need review.
                                                zx Security
                                                  Best in #Runtime Evironment
                                                    Average in #Runtime Evironment
                                                    zx Security
                                                      Best in #Runtime Evironment
                                                        Average in #Runtime Evironment

                                                          kandi-License License

                                                            summary
                                                            zx is licensed under the Apache-2.0 License. This license is Permissive.
                                                            summary
                                                            Permissive licenses have the least restrictions, and you can use them in most projects.
                                                            zx License
                                                              Best in #Runtime Evironment
                                                                Average in #Runtime Evironment
                                                                zx License
                                                                  Best in #Runtime Evironment
                                                                    Average in #Runtime Evironment

                                                                      kandi-Reuse Reuse

                                                                        summary
                                                                        zx releases are available to install and integrate.
                                                                        summary
                                                                        Deployable package is available in npm.
                                                                        summary
                                                                        Installation instructions, examples and code snippets are available.
                                                                        zx Reuse
                                                                          Best in #Runtime Evironment
                                                                            Average in #Runtime Evironment
                                                                            zx Reuse
                                                                              Best in #Runtime Evironment
                                                                                Average in #Runtime Evironment
                                                                                  Top functions reviewed by kandi - BETA
                                                                                  kandi's functional review helps you automatically verify the functionalities of the libraries and avoid rework.
                                                                                  Currently covering the most popular Java, JavaScript and Python libraries. See a Sample Here
                                                                                  Get all kandi verified functions for this library.
                                                                                  Get all kandi verified functions for this library.

                                                                                  zx Key Features

                                                                                  A tool for writing better scripts

                                                                                  zx Examples and Code Snippets

                                                                                  Does WebGL matrix (mat4) notation corresponds to mathematical matrix notation
                                                                                  JavaScriptdot imgLines of Code : 81dot imgLicense : Strong Copyleft (CC BY-SA 4.0)
                                                                                  copy iconCopy
                                                                                  mat2(vec2, vec2);
                                                                                  mat3(vec3, vec3, vec3);
                                                                                  mat4(vec4, vec4, vec4, vec4);
                                                                                  
                                                                                  mat2(float, float,
                                                                                       float, float);
                                                                                  
                                                                                  mat3(float, float, float,
                                                                                       float, float, float,
                                                                                       float, float, float);
                                                                                  
                                                                                  mat4(float, float, float, float,
                                                                                       float, float, float, float,
                                                                                       float, float, float, float,
                                                                                       float, float, float, float);
                                                                                  
                                                                                  mat4 matrix=mat4(
                                                                                      1.0, 1.0, 0.0, 0.0,
                                                                                      0.5, 0.0, 0.0, 0.0,
                                                                                      0.0, 0.0, 1.0, 0.0,
                                                                                      0.0, 0.0, 0.0, 1.0);
                                                                                  
                                                                                    c0  c1  c2  c3             c0   c1   c2   c3
                                                                                  [ Xx  Yx  Zx  Tx ]        [ 1.0  0.5  0.0  0.0 ]     
                                                                                  [ Xy  Yy  Zy  Ty ]        [ 1.0  0.0  0.0  0.0 ]     
                                                                                  [ Xz  Yz  Zz  Tz ]        [ 0.0  0.0  1.0  0.0 ]     
                                                                                  [  0   0   0   1 ]        [ 0.0  0.0  0.0  1.0 ] 
                                                                                  
                                                                                     Xx,  Xy,  Xz,   0,  Yx,  Yy,  Yz,   0,  Zx,  Zy,  Zz,   0,  Tx,  Ty,  Tz,   1
                                                                                  [ 1.0, 1.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 ]
                                                                                  
                                                                                  mat2(
                                                                                      float, float,   // first column
                                                                                      float, float);  // second column
                                                                                  
                                                                                  mat4 m;
                                                                                  m[1] = vec4(2.0); // sets the second column to all 2.0
                                                                                  m[0][0] = 1.0; // sets the upper left element to 1.0
                                                                                  m[2][3] = 2.0; // sets the 4th element of the third column to 2.0
                                                                                  
                                                                                  vec3 v, u;
                                                                                  mat3 m;
                                                                                  
                                                                                  u.x = dot(v, m[0]); // m[0] is the left column of m
                                                                                  u.y = dot(v, m[1]); // dot(a,b) is the inner (dot) product of a and b
                                                                                  u.z = dot(v, m[2]);
                                                                                  
                                                                                  u.x = m[0].x * v.x + m[1].x * v.y + m[2].x * v.z;
                                                                                  u.y = m[0].y * v.x + m[1].y * v.y + m[2].y * v.z;
                                                                                  u.z = m[0].z * v.x + m[1].z * v.y + m[2].z * v.z;
                                                                                  
                                                                                  mat4 m = mat4(
                                                                                      1.0, 1.0, 0.0, 0.0,
                                                                                      0.5, 0.0, 0.0, 0.0,
                                                                                      0.0, 0.0, 1.0, 0.0,
                                                                                      0.0, 0.0, 0.0, 1.0);
                                                                                  
                                                                                  vec4 v = vec4( -1.0, 0.0, 0.0, 1.0 );
                                                                                  
                                                                                  u = m * v 
                                                                                  
                                                                                  u.x  = m[0].x * v.x  + m[1].x * v.y + m[2].x * v.z + m[3].x * v.w;
                                                                                  u.y  = m[0].y * v.x  + m[1].y * v.y + m[2].y * v.z + m[3].y * v.w;
                                                                                  u.z  = m[0].z * v.x  + m[1].z * v.y + m[2].z * v.z + m[3].z * v.w;
                                                                                  u.w  = m[0].w * v.x  + m[1].w * v.y + m[2].w * v.z + m[3].w * v.w;
                                                                                  
                                                                                  u.x  =  1.0 * -1.0   +  0.5 * 0.0   +  0.0 * 0.0   +  0.0 * 1.0  =  -1.0
                                                                                  u.y  =  1.0 * -1.0   +  0.0 * 0.0   +  0.0 * 0.0   +  0.0 * 1.0  =  -1.0
                                                                                  u.z  =  0.0 * -1.0   +  0.0 * 0.0   +  1.0 * 0.0   +  0.0 * 1.0  =   0.0
                                                                                  u.w  =  0.0 * -1.0   +  0.0 * 0.0   +  0.0 * 0.0   +  1.0 * 1.0  =   1.0
                                                                                  
                                                                                  u_.x  =  dot(v, m[0]);
                                                                                  u_.y  =  dot(v, m[1]);
                                                                                  u_.z  =  dot(v, m[2]); 
                                                                                  u_.w  =  dot(v, m[3]); 
                                                                                  
                                                                                  u_.x  =  dot( vec4( -1.0, 0.0, 0.0, 1.0 ), vec4( 1.0, 1.0, 0.0, 0.0 ) )  =  -1.0 
                                                                                  u_.y  =  dot( vec4( -1.0, 0.0, 0.0, 1.0 ), vec4( 0.5, 0.0, 0.0, 0.0 ) )  =  -0.5
                                                                                  u_.z  =  dot( vec4( -1.0, 0.0, 0.0, 1.0 ), vec4( 0.0, 0.0, 1.0, 0.0 ) )  =   0.0
                                                                                  u_.w  =  dot( vec4( -1.0, 0.0, 0.0, 1.0 ), vec4( 0.0, 0.0, 0.0, 1.0 ) )  =   1.0 
                                                                                  
                                                                                  Matrix Translation in GLSL is infinitely stretched
                                                                                  JavaScriptdot imgLines of Code : 20dot imgLicense : Strong Copyleft (CC BY-SA 4.0)
                                                                                  copy iconCopy
                                                                                  mat4 eyeTrans = mat4(
                                                                                      1.0, 0.0, 0.0, 0.0,
                                                                                      0.0, 1.0, 0.0, 0.0,
                                                                                      0.0, 0.0, 1.0, 0.0,
                                                                                      0.0, 4.0, 0.0, 1.0
                                                                                  );
                                                                                  
                                                                                    c0  c1  c2  c3            c0  c1  c2  c3
                                                                                  [ Xx  Yx  Zx  Tx ]        [  0   4   8  12 ]     
                                                                                  [ Xy  Yy  Zy  Ty ]        [  1   5   9  13 ]     
                                                                                  [ Xz  Yz  Zz  Tz ]        [  2   6  10  14 ]     
                                                                                  [  0   0   0   1 ]        [  3   7  11  15 ] 
                                                                                  
                                                                                  vec4 c0 = eyeTrans[0].xyzw;
                                                                                  vec4 c1 = eyeTrans[1].xyzw;
                                                                                  vec4 c2 = eyeTrans[2].xyzw;
                                                                                  vec4 c3 = eyeTrans[3].xyzw;
                                                                                  
                                                                                  [ Xx, Xy, Xz, 0, Yx, Yy, Yz, 0, Zx, Zy, Zz, 0, Tx, Ty, Tz, 1 ]
                                                                                  
                                                                                  beautifulsoup how to purposely add return none if element not found
                                                                                  JavaScriptdot imgLines of Code : 57dot imgLicense : Strong Copyleft (CC BY-SA 4.0)
                                                                                  copy iconCopy
                                                                                  import requests
                                                                                  import pandas as pd
                                                                                  from selenium import webdriver
                                                                                  
                                                                                  urls = [
                                                                                      'https://www.nakedcph.com/sneakers-by-adidas/s/37'
                                                                                  ] 
                                                                                  
                                                                                  baseURL = 'https://www.nakedcph.com'
                                                                                  final = []
                                                                                  with requests.Session() as s:
                                                                                      for url in urls:
                                                                                          driver = webdriver.Chrome('C:/chromedriver_win32/chromedriver.exe')
                                                                                          driver.get(url)
                                                                                          soup = bs(driver.page_source, 'lxml')
                                                                                          items  = soup.findAll("div", {"class" : lambda L: L and L.startswith('col-6 col-md-3 mb-5')})
                                                                                  
                                                                                          name = []
                                                                                          tag = []
                                                                                          for each in items:
                                                                                              name.append(each.find('span',{'class':'product-name d-block'}).text.strip())
                                                                                              try:
                                                                                                  tag.append(each.find('svg').next_sibling.strip())
                                                                                              except:
                                                                                                  tag.append(None)
                                                                                          results = list(zip(name,tag))
                                                                                          df = pd.DataFrame(results)
                                                                                  
                                                                                  driver.quit()
                                                                                  
                                                                                  print (df)
                                                                                                              0               1
                                                                                  0                  ZX Torsion  Releasing Soon
                                                                                  1                      Campus         Restock
                                                                                  2                      Campus         Restock
                                                                                  3    Consortium Runner Mid 4D            None
                                                                                  4                     Ozweego            None
                                                                                  5                     Ozweego            None
                                                                                  6   Yeezy Boost 350 V2 Infant        Sold out
                                                                                  7     Yeezy Boost 350 V2 Kids        Sold out
                                                                                  8          Yeezy Boost 350 V2        Sold out
                                                                                  9                      Yung-1            None
                                                                                  10                     Yung 1            None
                                                                                  11               A.R. Trainer            None
                                                                                  12               A.R. Trainer            None
                                                                                  13             Adilette Pride            None
                                                                                  14                 Supercourt            None
                                                                                  15              Supercourt RX            None
                                                                                  16                 ZX 4000 4D            None
                                                                                  17         Yeezy Boost 700 V2        Sold out
                                                                                  18  Yeezy Boost 350 V2 Infant        Sold out
                                                                                  19    Yeezy Boost 350 V2 Kids        Sold out
                                                                                  20         Yeezy Boost 350 V2        Sold out
                                                                                  21         Yeezy Boost 700 V2        Sold out
                                                                                  22    Yeezy Boost 700 V2 Kids        Sold out
                                                                                  23  Yeezy Boost 700 V2 Infant        Sold out
                                                                                  
                                                                                  Maximum call stack size exceeded when filling a square of only 10 by 10 pixels
                                                                                  JavaScriptdot imgLines of Code : 45dot imgLicense : Strong Copyleft (CC BY-SA 4.0)
                                                                                  copy iconCopy
                                                                                      function func() {
                                                                                      var canvas = document.getElementById("image");
                                                                                      var context = canvas.getContext("2d");
                                                                                  
                                                                                      canvas.width = 100;
                                                                                      canvas.height = 100;
                                                                                  
                                                                                      var width = 100
                                                                                      var x = 0;
                                                                                      var y = 0;
                                                                                      var zX = 50;
                                                                                      var zY = 50;
                                                                                      
                                                                                      var cb = [27,94,32,255];
                                                                                      var cn = [67,160,71,255];
                                                                                  
                                                                                      context.strokeStyle = "black";
                                                                                      context.lineWidth = 2;
                                                                                      context.strokeRect(x, y, width, width);
                                                                                  
                                                                                      if (zX > x && zX < x + width && zY > y && zY < y + width) {
                                                                                          fill4(zY, zY, cb, cn, context);
                                                                                      }
                                                                                      function fill4(zX, zY, cb, cn, content) {
                                                                                          var imagedata = context.createImageData(1, 1);
                                                                                          for (let i = 0; i < 4; i++) {
                                                                                              imagedata.data[i] = cn[i];
                                                                                          }
                                                                                          var color = context.getImageData(zX, zY, 1, 1).data;
                                                                                          if (zX > x && zX < x + width && zY > y && zY < y + width) {
                                                                                              if (color[0] != cn[0] && color[1] != cn[1] && color[2] != cn[2] && color[3] != cn[3]) {
                                                                                                  context.putImageData(imagedata, zX, zY);
                                                                                                  setTimeout(function() {
                                                                                                      fill4(zX, zY-1, cb, cn, context);
                                                                                                      fill4(zX, zY+1, cb, cn, context);
                                                                                                      fill4(zX-1, zY, cb, cn, context);
                                                                                                      fill4(zX+1, zY, cb, cn, context);                            
                                                                                                  }, 20);
                                                                                              }
                                                                                          }
                                                                                      }    
                                                                                  }
                                                                                  
                                                                                    
                                                                                  
                                                                                  packing predefined circles in a rectangle
                                                                                  JavaScriptdot imgLines of Code : 318dot imgLicense : Strong Copyleft (CC BY-SA 4.0)
                                                                                  copy iconCopy
                                                                                  function draw() {
                                                                                    var circles = 10; //parseInt  (document.getElementById('c').value);
                                                                                    var ratio = 1; //parseFloat(document.getElementById('r').value);
                                                                                    var min_r = 1; //parseInt  (document.getElementById('a').value);
                                                                                    var max_r = 10; //parseInt  (document.getElementById('b').value);
                                                                                  
                                                                                    console.log(circles, ratio, min_r, max_r);
                                                                                    var radiuses = [];
                                                                                    // for (var i = 0 ; i != circles ; i++)
                                                                                    // radiuses.push (Math.random() * (max_r-min_r) + min_r);
                                                                                    radiuses = [
                                                                                      3.9583054608672303,
                                                                                      5.108187765437406,
                                                                                      5.8970449014304505,
                                                                                      6.176802256787828,
                                                                                      2.875371765313655,
                                                                                      8.017411283036802,
                                                                                      8.751854615569854,
                                                                                      2.7833816354701018,
                                                                                      2.408464192175587,
                                                                                      3.8428318045023144
                                                                                    ];
                                                                                    var packer = new Packer(radiuses, ratio);
                                                                                    draw_result(packer);
                                                                                  }
                                                                                  
                                                                                  // ===========================
                                                                                  // ancillary geometric classes
                                                                                  // ===========================
                                                                                  var Point = function(x, y) {
                                                                                    this.x = x;
                                                                                    this.y = y;
                                                                                  };
                                                                                  
                                                                                  Point.prototype = {
                                                                                    dist: function(p) {
                                                                                      return this.vect(p).norm();
                                                                                    },
                                                                                    vect: function(p) {
                                                                                      return new Point(p.x - this.x, p.y - this.y);
                                                                                    },
                                                                                    norm: function(p) {
                                                                                      return Math.sqrt(this.x * this.x + this.y * this.y);
                                                                                    },
                                                                                    add: function(v) {
                                                                                      return new Point(this.x + v.x, this.y + v.y);
                                                                                    },
                                                                                    mult: function(a) {
                                                                                      return new Point(this.x * a, this.y * a);
                                                                                    }
                                                                                  };
                                                                                  var Circle = function(radius, center) {
                                                                                    this.r = radius;
                                                                                    this.c = center;
                                                                                  };
                                                                                  
                                                                                  Circle.prototype = {
                                                                                    surface: function() {
                                                                                      return Math.PI * this.r * this.r;
                                                                                    },
                                                                                    distance: function(circle) {
                                                                                      return this.c.dist(circle.c) - this.r - circle.r;
                                                                                    }
                                                                                  };
                                                                                  
                                                                                  // =========================
                                                                                  // circle packer lives here!
                                                                                  // =========================
                                                                                  var Packer = function(circles, ratio) {
                                                                                    this.circles = circles;
                                                                                    this.ratio = ratio || 1;
                                                                                    this.list = this.solve();
                                                                                  };
                                                                                  
                                                                                  Packer.prototype = {
                                                                                    // try to fit all circles into a rectangle of a given surface
                                                                                    compute: function(surface) {
                                                                                      // check if a circle is inside our rectangle
                                                                                      function in_rect(radius, center) {
                                                                                        if (center.x - radius < -w / 2) return false;
                                                                                        if (center.x + radius > w / 2) return false;
                                                                                        if (center.y - radius < -h / 2) return false;
                                                                                        if (center.y + radius > h / 2) return false;
                                                                                        return true;
                                                                                      }
                                                                                  
                                                                                      // approximate a segment with an "infinite" radius circle
                                                                                      function bounding_circle(x0, y0, x1, y1) {
                                                                                        var xm = Math.abs((x1 - x0) * w);
                                                                                        var ym = Math.abs((y1 - y0) * h);
                                                                                        var m = xm > ym ? xm : ym;
                                                                                        var theta = Math.asin(m / 4 / bounding_r);
                                                                                        var r = bounding_r * Math.cos(theta);
                                                                                        return new Circle(
                                                                                          bounding_r,
                                                                                          new Point(
                                                                                            (r * (y0 - y1)) / 2 + ((x0 + x1) * w) / 4,
                                                                                            (r * (x1 - x0)) / 2 + ((y0 + y1) * h) / 4
                                                                                          )
                                                                                        );
                                                                                      }
                                                                                  
                                                                                      // return the corner placements for two circles
                                                                                      function corner(radius, c1, c2) {
                                                                                        var u = c1.c.vect(c2.c); // c1 to c2 vector
                                                                                        var A = u.norm();
                                                                                        if (A == 0) return []; // same centers
                                                                                        u = u.mult(1 / A); // c1 to c2 unary vector
                                                                                        // compute c1 and c2 intersection coordinates in (u,v) base
                                                                                        var B = c1.r + radius;
                                                                                        var C = c2.r + radius;
                                                                                        if (A > B + C) return []; // too far apart
                                                                                        var x = (A + (B * B - C * C) / A) / 2;
                                                                                        var y = Math.sqrt(B * B - x * x);
                                                                                        var base = c1.c.add(u.mult(x));
                                                                                  
                                                                                        var res = [];
                                                                                        var p1 = new Point(base.x - u.y * y, base.y + u.x * y);
                                                                                        var p2 = new Point(base.x + u.y * y, base.y - u.x * y);
                                                                                        if (in_rect(radius, p1)) res.push(new Circle(radius, p1));
                                                                                        if (in_rect(radius, p2)) res.push(new Circle(radius, p2));
                                                                                        return res;
                                                                                      }
                                                                                  
                                                                                      /////////////////////////////////////////////////////////////////
                                                                                  
                                                                                      // deduce starting dimensions from surface
                                                                                      var bounding_r = Math.sqrt(surface) * 100; // "infinite" radius
                                                                                      var w = (this.w = Math.sqrt(surface * this.ratio));
                                                                                      var h = (this.h = this.w / this.ratio);
                                                                                  
                                                                                      // place our bounding circles
                                                                                      var placed = [
                                                                                        bounding_circle(1, 1, 1, -1),
                                                                                        bounding_circle(1, -1, -1, -1),
                                                                                        bounding_circle(-1, -1, -1, 1),
                                                                                        bounding_circle(-1, 1, 1, 1)
                                                                                      ];
                                                                                  
                                                                                      // Initialize our rectangles list
                                                                                      var unplaced = this.circles.slice(0); // clones the array
                                                                                      while (unplaced.length > 0) {
                                                                                        // compute all possible placements of the unplaced circles
                                                                                        var lambda = {};
                                                                                        var circle = {};
                                                                                        for (var i = 0; i != unplaced.length; i++) {
                                                                                          var lambda_min = 1e10;
                                                                                          lambda[i] = -1e10;
                                                                                          // match current circle against all possible pairs of placed circles
                                                                                          for (var j = 0; j < placed.length; j++)
                                                                                            for (var k = j + 1; k < placed.length; k++) {
                                                                                              // find corner placement
                                                                                              if (k > 3) {
                                                                                                zog = 1;
                                                                                              }
                                                                                              var corners = corner(unplaced[i], placed[j], placed[k]);
                                                                                  
                                                                                              // check each placement
                                                                                              for (var c = 0; c != corners.length; c++) {
                                                                                                // check for overlap and compute min distance
                                                                                                var d_min = 1e10;
                                                                                                for (var l = 0; l != placed.length; l++) {
                                                                                                  // skip the two circles used for the placement
                                                                                                  if (l == j || l == k) continue;
                                                                                  
                                                                                                  // compute distance from current circle
                                                                                                  var d = placed[l].distance(corners[c]);
                                                                                                  if (d < 0) break; // circles overlap
                                                                                  
                                                                                                  if (d < d_min) d_min = d;
                                                                                                }
                                                                                                if (l == placed.length) {
                                                                                                  // no overlap
                                                                                                  if (d_min < lambda_min) {
                                                                                                    lambda_min = d_min;
                                                                                                    lambda[i] = 1 - d_min / unplaced[i];
                                                                                                    circle[i] = corners[c];
                                                                                                  }
                                                                                                }
                                                                                              }
                                                                                            }
                                                                                        }
                                                                                  
                                                                                        // select the circle with maximal gain
                                                                                        var lambda_max = -1e10;
                                                                                        var i_max = -1;
                                                                                        for (var i = 0; i != unplaced.length; i++) {
                                                                                          if (lambda[i] > lambda_max) {
                                                                                            lambda_max = lambda[i];
                                                                                            i_max = i;
                                                                                          }
                                                                                        }
                                                                                  
                                                                                        // failure if no circle fits
                                                                                        if (i_max == -1) break;
                                                                                  
                                                                                        // place the selected circle
                                                                                        unplaced.splice(i_max, 1);
                                                                                        placed.push(circle[i_max]);
                                                                                      }
                                                                                  
                                                                                      // return all placed circles except the four bounding circles
                                                                                      this.tmp_bounds = placed.splice(0, 4);
                                                                                      return placed;
                                                                                    },
                                                                                  
                                                                                    // find the smallest rectangle to fit all circles
                                                                                    solve: function() {
                                                                                      // compute total surface of the circles
                                                                                      var surface = 0;
                                                                                      for (var i = 0; i != this.circles.length; i++) {
                                                                                        surface += Math.PI * Math.pow(this.circles[i], 2);
                                                                                      }
                                                                                  
                                                                                      // set a suitable precision
                                                                                      var limit = surface / 1000;
                                                                                  
                                                                                      var step = surface / 2;
                                                                                      var res = [];
                                                                                      while (step > limit) {
                                                                                        var placement = this.compute.call(this, surface);
                                                                                        if (placement.length != this.circles.length) {
                                                                                          surface += step;
                                                                                        } else {
                                                                                          res = placement;
                                                                                          this.bounds = this.tmp_bounds;
                                                                                          surface -= step;
                                                                                        }
                                                                                        step /= 2;
                                                                                      }
                                                                                      return res;
                                                                                    }
                                                                                  };
                                                                                  
                                                                                  // ====
                                                                                  // demo
                                                                                  // ====
                                                                                  function draw_result(packer) {
                                                                                    function draw_circle(circle) {
                                                                                      ctx.beginPath();
                                                                                      ctx.arc(
                                                                                        (circle.c.x + dx) * zoom + mx,
                                                                                        (circle.c.y + dy) * zoom + my,
                                                                                        circle.r * zoom,
                                                                                        0,
                                                                                        2 * Math.PI
                                                                                      );
                                                                                      ctx.closePath();
                                                                                      ctx.stroke();
                                                                                    }
                                                                                  
                                                                                    var canvas = document.getElementById("canvas");
                                                                                    var ctx = canvas.getContext("2d");
                                                                                    canvas.width += 0; // clear canvas
                                                                                    var margin_factor = 0.1;
                                                                                  
                                                                                    var mx = (canvas.width * margin_factor) / 2;
                                                                                    var my = (canvas.height * margin_factor) / 2;
                                                                                    var dx = packer.w / 2;
                                                                                    var dy = packer.h / 2;
                                                                                    var zx = (canvas.width * (1 - margin_factor)) / packer.w;
                                                                                    var zy = (canvas.height * (1 - margin_factor)) / packer.h;
                                                                                    var zoom = zx < zy ? zx : zy;
                                                                                  
                                                                                    // draw all circles
                                                                                    ctx.strokeStyle = "black";
                                                                                    for (var i = 0; i != packer.list.length; i++) draw_circle(packer.list[i]);
                                                                                  
                                                                                    // draw bounding circles
                                                                                    ctx.strokeStyle = "red";
                                                                                    for (var i = 0; i != packer.bounds.length; i++) draw_circle(packer.bounds[i]);
                                                                                  
                                                                                    // draw rectangle
                                                                                    ctx.strokeStyle = "orange";
                                                                                    ctx.beginPath();
                                                                                    ctx.rect(
                                                                                      (-packer.w / 2 + dx) * zoom + mx,
                                                                                      (-packer.h / 2 + dy) * zoom + my,
                                                                                      packer.w * zoom,
                                                                                      packer.h * zoom
                                                                                    );
                                                                                    ctx.closePath();
                                                                                    ctx.stroke();
                                                                                  }
                                                                                  
                                                                                  function draw() {
                                                                                    var circles = parseInt(document.getElementById("c").value);
                                                                                    var ratio = parseFloat(document.getElementById("r").value);
                                                                                    var min_r = parseInt(document.getElementById("a").value);
                                                                                    var max_r = parseInt(document.getElementById("b").value);
                                                                                    var radiuses = [];
                                                                                    // for (var i = 0 ; i != circles ; i++)
                                                                                    // radiuses.push (Math.random() * (max_r-min_r) + min_r);
                                                                                    radiuses = [
                                                                                      3.9583054608672303,
                                                                                      5.108187765437406,
                                                                                      5.8970449014304505,
                                                                                      6.176802256787828,
                                                                                      2.875371765313655,
                                                                                      8.017411283036802,
                                                                                      8.751854615569854,
                                                                                      2.7833816354701018,
                                                                                      2.408464192175587,
                                                                                      3.8428318045023144
                                                                                    ];
                                                                                    var packer = new Packer(radiuses, ratio);
                                                                                    draw_result(packer);
                                                                                  }
                                                                                  
                                                                                  window.onload = draw;
                                                                                          
                                                                                  
                                                                                  Circles   
                                                                                  Ratio
                                                                                  min radius
                                                                                  max radius Draw
                                                                                  HTML5 canvas line into a zig zag line?
                                                                                  JavaScriptdot imgLines of Code : 114dot imgLicense : Strong Copyleft (CC BY-SA 4.0)
                                                                                  copy iconCopy
                                                                                  class Point {
                                                                                      constructor(x, y) {
                                                                                          this.x = x;
                                                                                          this.y = y;
                                                                                      }
                                                                                  }
                                                                                  
                                                                                  class Line {
                                                                                      constructor(fromPoint = null, toPoint = null, zigZagged = false) {
                                                                                          this.from = fromPoint;
                                                                                          this.to = toPoint;
                                                                                          this.dashed = false;
                                                                                          this.zigZagged = zigZagged;
                                                                                  
                                                                                          this.prepareZigZag();
                                                                                      }
                                                                                  
                                                                                      setFrom(point) { this.from = point;}
                                                                                  
                                                                                      setTo(point) { this.to = toPoint;}
                                                                                  
                                                                                      getFrom() { return this.from; }
                                                                                  
                                                                                      getTo() { return this.to}
                                                                                  
                                                                                      prepareZigZag() {
                                                                                          // Get the radian angle of the line
                                                                                          this.lineRadians = Math.atan2(this.to.y - this.from.y, this.to.x - this.from.x);
                                                                                  
                                                                                          // Get the length of the line
                                                                                          const a = this.from.x - this.to.x;
                                                                                          const b = this.from.y - this.to.y;
                                                                                          this.lineLength = Math.sqrt( a * a + b * b );
                                                                                  
                                                                                          // 10 pixels between each zig zag "wave"
                                                                                          this.zigzagSpacing = 10;
                                                                                  
                                                                                          // Length of one zig zag line - will in reality be doubled see below usage
                                                                                          this.oneZigZagLength = 10;
                                                                                  
                                                                                          //Length of the last straight bit - so we do not zig zag all the line
                                                                                          this.straightLengthWhenZigZag = 30
                                                                                  
                                                                                          // The length of the zig zag lines
                                                                                          this.zigZagLength = this.lineLength - this.straightLengthWhenZigZag;
                                                                                      }
                                                                                  
                                                                                  
                                                                                      draw(ctx, color = '#000', lineWidth = 2.0) {
                                                                                          if (this.dashed) {
                                                                                              ctx.setLineDash([4, 2]);
                                                                                          } else {
                                                                                              ctx.setLineDash([]);
                                                                                          }
                                                                                  
                                                                                          if (this.zigZagged) {
                                                                                              this.drawZigZagged(ctx);
                                                                                          } else {
                                                                                              ctx.beginPath();
                                                                                              ctx.moveTo(this.from.x, this.from.y);
                                                                                              ctx.lineTo(this.to.x, this.to.y);
                                                                                          }
                                                                                          ctx.lineWidth = lineWidth;
                                                                                          ctx.strokeStyle = color;
                                                                                          ctx.stroke();
                                                                                  
                                                                                      }
                                                                                  
                                                                                      drawZigZagged(ctx) {
                                                                                          // Save the current drawing state
                                                                                          ctx.save();
                                                                                  
                                                                                          // Begin the new path
                                                                                          ctx.beginPath();
                                                                                  
                                                                                          //Set the new 0, 0
                                                                                          ctx.translate(this.from.x, this.from.y);
                                                                                  
                                                                                          // Rotate the canvas so we can treat it like straight
                                                                                          ctx.rotate(this.lineRadians);
                                                                                  
                                                                                          // Begin from 0, 0 (ie this.from.x, this.from.y)
                                                                                          ctx.moveTo(0,0);
                                                                                          let zx = 0;
                                                                                          // Create zig zag lines
                                                                                          for (let n = 0; zx < this.zigZagLength; n++) {
                                                                                              // The new zig zag x position
                                                                                              zx = ((n + 1) * this.zigzagSpacing);
                                                                                  
                                                                                              // The new zig zag y position - each and other time up and down
                                                                                              const  zy = (n % 2 == 0) ? -this.oneZigZagLength : this.oneZigZagLength;
                                                                                  
                                                                                              // Draw the an actual line of the zig zag line
                                                                                              ctx.lineTo(zx, zy);
                                                                                          }
                                                                                          // Back to the center vertically
                                                                                          ctx.lineTo(this.lineLength - (this.straightLengthWhenZigZag / 2), 0);
                                                                                  
                                                                                          // Draw the last bit straight
                                                                                          ctx.lineTo(this.lineLength, 0);
                                                                                  
                                                                                          // Restore the previous drawing state
                                                                                          ctx.restore();
                                                                                      }
                                                                                  
                                                                                      setDashed(enable) {
                                                                                          this.dashed = enable;
                                                                                      }
                                                                                  
                                                                                      setZigZagged(enable){
                                                                                          this.zigZagged = enable
                                                                                      }
                                                                                  }
                                                                                  
                                                                                  Moving an object on imageview on zoom in and zoom out
                                                                                  JavaScriptdot imgLines of Code : 456dot imgLicense : Strong Copyleft (CC BY-SA 4.0)
                                                                                  copy iconCopy
                                                                                  public class ZoomableLayout extends FrameLayout {
                                                                                  
                                                                                      public ZoomableLayout(Context context, AttributeSet attrs, int defStyle) {
                                                                                          super(context, attrs, defStyle);
                                                                                          // TODO Auto-generated constructor stub
                                                                                      }
                                                                                  
                                                                                      public ZoomableLayout(Context context, AttributeSet attrs) {
                                                                                          super(context, attrs);
                                                                                          // TODO Auto-generated constructor stub
                                                                                      }
                                                                                  
                                                                                      public ZoomableLayout(final Context context) {
                                                                                          super(context);
                                                                                      }
                                                                                  
                                                                                      /**
                                                                                       * Zooming view listener interface.
                                                                                       *
                                                                                       * @author karooolek
                                                                                       *
                                                                                       */
                                                                                      public interface ZoomViewListener {
                                                                                  
                                                                                          void onZoomStarted(float zoom, float zoomx, float zoomy);
                                                                                  
                                                                                          void onZooming(float zoom, float zoomx, float zoomy);
                                                                                  
                                                                                          void onZoomEnded(float zoom, float zoomx, float zoomy);
                                                                                      }
                                                                                  
                                                                                      // zooming
                                                                                      float zoom = 1.0f;
                                                                                      float maxZoom = 2.0f;
                                                                                      float smoothZoom = 1.0f;
                                                                                      float zoomX, zoomY;
                                                                                      float smoothZoomX, smoothZoomY;
                                                                                      private boolean scrolling; //
                                                                                  
                                                                                      // minimap variables
                                                                                      private boolean showMinimap = false;
                                                                                      private int miniMapColor = Color.WHITE;
                                                                                      private int miniMapHeight = -1;
                                                                                      private String miniMapCaption;
                                                                                      private float miniMapCaptionSize = 10.0f;
                                                                                      private int miniMapCaptionColor = Color.WHITE;
                                                                                  
                                                                                      // touching variables
                                                                                      private long lastTapTime;
                                                                                      private float touchStartX, touchStartY;
                                                                                      private float touchLastX, touchLastY;
                                                                                      private float startd;
                                                                                      private boolean pinching;
                                                                                      private float lastd;
                                                                                      private float lastdx1, lastdy1;
                                                                                      private float lastdx2, lastdy2;
                                                                                  
                                                                                      // drawing
                                                                                      private final Matrix m = new Matrix();
                                                                                      private final Paint p = new Paint();
                                                                                  
                                                                                      // listener
                                                                                      ZoomViewListener listener;
                                                                                  
                                                                                      private Bitmap ch;
                                                                                  
                                                                                      public float getZoom() {
                                                                                          return zoom;
                                                                                      }
                                                                                  
                                                                                      public float getMaxZoom() {
                                                                                          return maxZoom;
                                                                                      }
                                                                                  
                                                                                      public void setMaxZoom(final float maxZoom) {
                                                                                          if (maxZoom < 1.0f) {
                                                                                              return;
                                                                                          }
                                                                                  
                                                                                          this.maxZoom = maxZoom;
                                                                                      }
                                                                                  
                                                                                      public void setMiniMapEnabled(final boolean showMiniMap) {
                                                                                          this.showMinimap = showMiniMap;
                                                                                      }
                                                                                  
                                                                                      public boolean isMiniMapEnabled() {
                                                                                          return showMinimap;
                                                                                      }
                                                                                  
                                                                                      public void setMiniMapHeight(final int miniMapHeight) {
                                                                                          if (miniMapHeight < 0) {
                                                                                              return;
                                                                                          }
                                                                                          this.miniMapHeight = miniMapHeight;
                                                                                      }
                                                                                  
                                                                                      public int getMiniMapHeight() {
                                                                                          return miniMapHeight;
                                                                                      }
                                                                                  
                                                                                      public void setMiniMapColor(final int color) {
                                                                                          miniMapColor = color;
                                                                                      }
                                                                                  
                                                                                      public int getMiniMapColor() {
                                                                                          return miniMapColor;
                                                                                      }
                                                                                  
                                                                                      public String getMiniMapCaption() {
                                                                                          return miniMapCaption;
                                                                                      }
                                                                                  
                                                                                      public void setMiniMapCaption(final String miniMapCaption) {
                                                                                          this.miniMapCaption = miniMapCaption;
                                                                                      }
                                                                                  
                                                                                      public float getMiniMapCaptionSize() {
                                                                                          return miniMapCaptionSize;
                                                                                      }
                                                                                  
                                                                                      public void setMiniMapCaptionSize(final float size) {
                                                                                          miniMapCaptionSize = size;
                                                                                      }
                                                                                  
                                                                                      public int getMiniMapCaptionColor() {
                                                                                          return miniMapCaptionColor;
                                                                                      }
                                                                                  
                                                                                      public void setMiniMapCaptionColor(final int color) {
                                                                                          miniMapCaptionColor = color;
                                                                                      }
                                                                                  
                                                                                      public void zoomTo(final float zoom, final float x, final float y) {
                                                                                          this.zoom = Math.min(zoom, maxZoom);
                                                                                          zoomX = x;
                                                                                          zoomY = y;
                                                                                          smoothZoomTo(this.zoom, x, y);
                                                                                      }
                                                                                  
                                                                                      public void smoothZoomTo(final float zoom, final float x, final float y) {
                                                                                          smoothZoom = clamp(1.0f, zoom, maxZoom);
                                                                                          smoothZoomX = x;
                                                                                          smoothZoomY = y;
                                                                                          if (listener != null) {
                                                                                              listener.onZoomStarted(smoothZoom, x, y);
                                                                                          }
                                                                                      }
                                                                                  
                                                                                      public ZoomViewListener getListener() {
                                                                                          return listener;
                                                                                      }
                                                                                  
                                                                                      public void setListner(final ZoomViewListener listener) {
                                                                                          this.listener = listener;
                                                                                      }
                                                                                  
                                                                                      public float getZoomFocusX() {
                                                                                          return zoomX * zoom;
                                                                                      }
                                                                                  
                                                                                      public float getZoomFocusY() {
                                                                                          return zoomY * zoom;
                                                                                      }
                                                                                  
                                                                                      @Override
                                                                                      public boolean dispatchTouchEvent(final MotionEvent ev) {
                                                                                          // single touch
                                                                                          if (ev.getPointerCount() == 1) {
                                                                                              processSingleTouchEvent(ev);
                                                                                          }
                                                                                  
                                                                                          // // double touch
                                                                                          if (ev.getPointerCount() == 2) {
                                                                                              processDoubleTouchEvent(ev);
                                                                                          }
                                                                                  
                                                                                          // redraw
                                                                                          getRootView().invalidate();
                                                                                          invalidate();
                                                                                  
                                                                                          return true;
                                                                                      }
                                                                                  
                                                                                      private void processSingleTouchEvent(final MotionEvent ev) {
                                                                                  
                                                                                          final float x = ev.getX();
                                                                                          final float y = ev.getY();
                                                                                  
                                                                                          final float w = miniMapHeight * (float) getWidth() / getHeight();
                                                                                          final float h = miniMapHeight;
                                                                                          final boolean touchingMiniMap = x >= 10.0f && x <= 10.0f + w
                                                                                                  && y >= 10.0f && y <= 10.0f + h;
                                                                                  
                                                                                          if (showMinimap && smoothZoom > 1.0f && touchingMiniMap) {
                                                                                              processSingleTouchOnMinimap(ev);
                                                                                          } else {
                                                                                              processSingleTouchOutsideMinimap(ev);
                                                                                          }
                                                                                      }
                                                                                  
                                                                                      private void processSingleTouchOnMinimap(final MotionEvent ev) {
                                                                                          final float x = ev.getX();
                                                                                          final float y = ev.getY();
                                                                                  
                                                                                          final float w = miniMapHeight * (float) getWidth() / getHeight();
                                                                                          final float h = miniMapHeight;
                                                                                          final float zx = (x - 10.0f) / w * getWidth();
                                                                                          final float zy = (y - 10.0f) / h * getHeight();
                                                                                          smoothZoomTo(smoothZoom, zx, zy);
                                                                                      }
                                                                                  
                                                                                      private void processSingleTouchOutsideMinimap(final MotionEvent ev) {
                                                                                          final float x = ev.getX();
                                                                                          final float y = ev.getY();
                                                                                          float lx = x - touchStartX;
                                                                                          float ly = y - touchStartY;
                                                                                          final float l = (float) Math.hypot(lx, ly);
                                                                                          float dx = x - touchLastX;
                                                                                          float dy = y - touchLastY;
                                                                                          touchLastX = x;
                                                                                          touchLastY = y;
                                                                                  
                                                                                          switch (ev.getAction()) {
                                                                                              case MotionEvent.ACTION_DOWN:
                                                                                                  touchStartX = x;
                                                                                                  touchStartY = y;
                                                                                                  touchLastX = x;
                                                                                                  touchLastY = y;
                                                                                                  dx = 0;
                                                                                                  dy = 0;
                                                                                                  lx = 0;
                                                                                                  ly = 0;
                                                                                                  scrolling = false;
                                                                                                  break;
                                                                                  
                                                                                              case MotionEvent.ACTION_MOVE:
                                                                                                  if (scrolling || (smoothZoom > 1.0f && l > 30.0f)) {
                                                                                                      if (!scrolling) {
                                                                                                          scrolling = true;
                                                                                                          ev.setAction(MotionEvent.ACTION_CANCEL);
                                                                                                          super.dispatchTouchEvent(ev);
                                                                                                      }
                                                                                                      smoothZoomX -= dx / zoom;
                                                                                                      smoothZoomY -= dy / zoom;
                                                                                                      return;
                                                                                                  }
                                                                                                  break;
                                                                                  
                                                                                              case MotionEvent.ACTION_OUTSIDE:
                                                                                              case MotionEvent.ACTION_UP:
                                                                                  
                                                                                                  // tap
                                                                                                  if (l < 30.0f) {
                                                                                                      // check double tap
                                                                                                      if (System.currentTimeMillis() - lastTapTime < 500) {
                                                                                                          if (smoothZoom == 1.0f) {
                                                                                                              smoothZoomTo(maxZoom, x, y);
                                                                                                          } else {
                                                                                                              smoothZoomTo(1.0f, getWidth() / 2.0f,
                                                                                                                      getHeight() / 2.0f);
                                                                                                          }
                                                                                                          lastTapTime = 0;
                                                                                                          ev.setAction(MotionEvent.ACTION_CANCEL);
                                                                                                          super.dispatchTouchEvent(ev);
                                                                                                          return;
                                                                                                      }
                                                                                  
                                                                                                      lastTapTime = System.currentTimeMillis();
                                                                                  
                                                                                                      performClick();
                                                                                                  }
                                                                                                  break;
                                                                                  
                                                                                              default:
                                                                                                  break;
                                                                                          }
                                                                                  
                                                                                          ev.setLocation(zoomX + (x - 0.5f * getWidth()) / zoom, zoomY
                                                                                                  + (y - 0.5f * getHeight()) / zoom);
                                                                                  
                                                                                          ev.getX();
                                                                                          ev.getY();
                                                                                  
                                                                                          super.dispatchTouchEvent(ev);
                                                                                      }
                                                                                  
                                                                                      private void processDoubleTouchEvent(final MotionEvent ev) {
                                                                                          final float x1 = ev.getX(0);
                                                                                          final float dx1 = x1 - lastdx1;
                                                                                          lastdx1 = x1;
                                                                                          final float y1 = ev.getY(0);
                                                                                          final float dy1 = y1 - lastdy1;
                                                                                          lastdy1 = y1;
                                                                                          final float x2 = ev.getX(1);
                                                                                          final float dx2 = x2 - lastdx2;
                                                                                          lastdx2 = x2;
                                                                                          final float y2 = ev.getY(1);
                                                                                          final float dy2 = y2 - lastdy2;
                                                                                          lastdy2 = y2;
                                                                                  
                                                                                          // pointers distance
                                                                                          final float d = (float) Math.hypot(x2 - x1, y2 - y1);
                                                                                          final float dd = d - lastd;
                                                                                          lastd = d;
                                                                                          final float ld = Math.abs(d - startd);
                                                                                  
                                                                                          Math.atan2(y2 - y1, x2 - x1);
                                                                                          switch (ev.getAction()) {
                                                                                              case MotionEvent.ACTION_DOWN:
                                                                                                  startd = d;
                                                                                                  pinching = false;
                                                                                                  break;
                                                                                  
                                                                                              case MotionEvent.ACTION_MOVE:
                                                                                                  if (pinching || ld > 30.0f) {
                                                                                                      pinching = true;
                                                                                                      final float dxk = 0.5f * (dx1 + dx2);
                                                                                                      final float dyk = 0.5f * (dy1 + dy2);
                                                                                                      smoothZoomTo(Math.max(1.0f, zoom * d / (d - dd)), zoomX - dxk
                                                                                                              / zoom, zoomY - dyk / zoom);
                                                                                                  }
                                                                                  
                                                                                                  break;
                                                                                  
                                                                                              case MotionEvent.ACTION_UP:
                                                                                              default:
                                                                                                  pinching = false;
                                                                                                  break;
                                                                                          }
                                                                                  
                                                                                          ev.setAction(MotionEvent.ACTION_CANCEL);
                                                                                          super.dispatchTouchEvent(ev);
                                                                                      }
                                                                                  
                                                                                      private float clamp(final float min, final float value, final float max) {
                                                                                          return Math.max(min, Math.min(value, max));
                                                                                      }
                                                                                  
                                                                                      private float lerp(final float a, final float b, final float k) {
                                                                                          return a + (b - a) * k;
                                                                                      }
                                                                                  
                                                                                      private float bias(final float a, final float b, final float k) {
                                                                                          return Math.abs(b - a) >= k ? a + k * Math.signum(b - a) : b;
                                                                                      }
                                                                                  
                                                                                      @Override
                                                                                      protected void dispatchDraw(final Canvas canvas) {
                                                                                  
                                                                                          // do zoom
                                                                                          zoom = lerp(bias(zoom, smoothZoom, 0.05f), smoothZoom, 0.2f);
                                                                                          smoothZoomX = clamp(0.5f * getWidth() / smoothZoom, smoothZoomX,
                                                                                                  getWidth() - 0.5f * getWidth() / smoothZoom);
                                                                                          smoothZoomY = clamp(0.5f * getHeight() / smoothZoom, smoothZoomY,
                                                                                                  getHeight() - 0.5f * getHeight() / smoothZoom);
                                                                                  
                                                                                          zoomX = lerp(bias(zoomX, smoothZoomX, 0.1f), smoothZoomX, 0.35f);
                                                                                          zoomY = lerp(bias(zoomY, smoothZoomY, 0.1f), smoothZoomY, 0.35f);
                                                                                          if (zoom != smoothZoom && listener != null) {
                                                                                              listener.onZooming(zoom, zoomX, zoomY);
                                                                                          }
                                                                                  
                                                                                          final boolean animating = Math.abs(zoom - smoothZoom) > 0.0000001f
                                                                                                  || Math.abs(zoomX - smoothZoomX) > 0.0000001f
                                                                                                  || Math.abs(zoomY - smoothZoomY) > 0.0000001f;
                                                                                  
                                                                                          // nothing to draw
                                                                                          if (getChildCount() == 0) {
                                                                                              return;
                                                                                          }
                                                                                  
                                                                                          // prepare matrix
                                                                                          m.setTranslate(0.5f * getWidth(), 0.5f * getHeight());
                                                                                          m.preScale(zoom, zoom);
                                                                                          m.preTranslate(
                                                                                                  -clamp(0.5f * getWidth() / zoom, zoomX, getWidth() - 0.5f
                                                                                                          * getWidth() / zoom),
                                                                                                  -clamp(0.5f * getHeight() / zoom, zoomY, getHeight() - 0.5f
                                                                                                          * getHeight() / zoom));
                                                                                  
                                                                                          // get view
                                                                                          final View v = getChildAt(0);
                                                                                          m.preTranslate(v.getLeft(), v.getTop());
                                                                                  
                                                                                          // get drawing cache if available
                                                                                          if (animating && ch == null && isAnimationCacheEnabled()) {
                                                                                              v.setDrawingCacheEnabled(true);
                                                                                              ch = v.getDrawingCache();
                                                                                          }
                                                                                  
                                                                                          // draw using cache while animating
                                                                                          if (animating && isAnimationCacheEnabled() && ch != null) {
                                                                                              p.setColor(0xffffffff);
                                                                                              canvas.drawBitmap(ch, m, p);
                                                                                          } else { // zoomed or cache unavailable
                                                                                              ch = null;
                                                                                              canvas.save();
                                                                                              canvas.concat(m);
                                                                                              v.draw(canvas);
                                                                                              canvas.restore();
                                                                                          }
                                                                                  
                                                                                          // draw minimap
                                                                                          if (showMinimap) {
                                                                                              if (miniMapHeight < 0) {
                                                                                                  miniMapHeight = getHeight() / 4;
                                                                                              }
                                                                                  
                                                                                              canvas.translate(10.0f, 10.0f);
                                                                                  
                                                                                              p.setColor(0x80000000 | 0x00ffffff & miniMapColor);
                                                                                              final float w = miniMapHeight * (float) getWidth() / getHeight();
                                                                                              final float h = miniMapHeight;
                                                                                              canvas.drawRect(0.0f, 0.0f, w, h, p);
                                                                                  
                                                                                              if (miniMapCaption != null && miniMapCaption.length() > 0) {
                                                                                                  p.setTextSize(miniMapCaptionSize);
                                                                                                  p.setColor(miniMapCaptionColor);
                                                                                                  p.setAntiAlias(true);
                                                                                                  canvas.drawText(miniMapCaption, 10.0f,
                                                                                                          10.0f + miniMapCaptionSize, p);
                                                                                                  p.setAntiAlias(false);
                                                                                              }
                                                                                  
                                                                                              p.setColor(0x80000000 | 0x00ffffff & miniMapColor);
                                                                                              final float dx = w * zoomX / getWidth();
                                                                                              final float dy = h * zoomY / getHeight();
                                                                                              canvas.drawRect(dx - 0.5f * w / zoom, dy - 0.5f * h / zoom, dx
                                                                                                      + 0.5f * w / zoom, dy + 0.5f * h / zoom, p);
                                                                                  
                                                                                              canvas.translate(-10.0f, -10.0f);
                                                                                          }
                                                                                  
                                                                                          // redraw
                                                                                          // if (animating) {
                                                                                          getRootView().invalidate();
                                                                                          invalidate();
                                                                                          // }
                                                                                      }
                                                                                  }
                                                                                  
                                                                                  
                                                                                              
                                                                                                  // Your contents here
                                                                                              
                                                                                  
                                                                                      
                                                                                  
                                                                                  Collision Detection not being recognized
                                                                                  JavaScriptdot imgLines of Code : 151dot imgLicense : Strong Copyleft (CC BY-SA 4.0)
                                                                                  copy iconCopy
                                                                                      public void onFIRE(View view){
                                                                                  
                                                                                      if(btnStart.getVisibility()== View.VISIBLE){
                                                                                          startLabel.setText("No Firing Start Game");
                                                                                          return;
                                                                                      }
                                                                                  
                                                                                      gunANGLE = ivTRI.getRotation();
                                                                                  
                                                                                      if(gunANGLE == 0.0f){
                                                                                          ZY -= 200.0;
                                                                                          ZX += 0;
                                                                                          pink.setX(pink.getX()+ZX);
                                                                                          pink.setY(pink.getY()+ZY);
                                                                                          //System.out.println("$$$$$$$$$$ Y "+pink.getY());
                                                                                          //System.out.println("$$$$$$$$$$ X "+pink.getX());
                                                                                  
                                                                                          hitCHECK();
                                                                                  
                                                                                          ZX = 0;
                                                                                          ZY = 0;
                                                                                          if( pink.getY() < 40){
                                                                                              HITorMISS();
                                                                                              pink.setX(ivTRI.getX()+30);
                                                                                              pink.setY(ivTRI.getY()+60);
                                                                                              // rotate gun bring bullet back to breach
                                                                                              HITorMISS();
                                                                                              // loose point for missing
                                                                                          }
                                                                                      }
                                                                                  
                                                                                      public void hitCHECK(){
                                                                                  
                                                                                      Rect pinkRect = new Rect();
                                                                                      pink.getHitRect(pinkRect);
                                                                                  
                                                                                      Rect iv1Rect = new Rect();
                                                                                      iv1.getHitRect(iv1Rect);
                                                                                      Rect iv2Rect = new Rect();
                                                                                      iv2.getHitRect(iv2Rect);
                                                                                      Rect iv3Rect = new Rect();
                                                                                      iv3.getHitRect(iv3Rect);
                                                                                      Rect iv4Rect = new Rect();
                                                                                      iv4.getHitRect(iv4Rect);
                                                                                      Rect iv5Rect = new Rect();
                                                                                      iv5.getHitRect(iv5Rect);
                                                                                      Rect iv6Rect = new Rect();
                                                                                      iv6.getHitRect(iv6Rect);
                                                                                  
                                                                                      Rect earthRect = new Rect();
                                                                                      earth.getHitRect(earthRect);
                                                                                  
                                                                                      Rect asteroidRect = new Rect();
                                                                                      asteroid.getHitRect(asteroidRect);
                                                                                  
                                                                                      Rect arrowLeftRect = new Rect();
                                                                                      arrowLeft.getHitRect(arrowLeftRect);
                                                                                      Rect arrowRightRect = new Rect();
                                                                                      arrowRight.getHitRect(arrowRightRect);
                                                                                  
                                                                                      if (Rect.intersects(pinkRect, arrowLeftRect)) {
                                                                                          arrowLeft.setVisibility(View.INVISIBLE);
                                                                                          arrowLeft.setX(-100);
                                                                                          arrowLeft.setY(-100);
                                                                                          arrowLeft.setEnabled(false);
                                                                                      }
                                                                                      if (Rect.intersects(pinkRect, arrowRightRect)) {
                                                                                          arrowRight.setVisibility(View.INVISIBLE);
                                                                                          arrowRight.setX(-100);
                                                                                          arrowRight.setY(-100);
                                                                                      }
                                                                                      if (Rect.intersects(pinkRect, iv1Rect)) {
                                                                                          iv1.setVisibility(View.INVISIBLE);
                                                                                          iv1.setX(-100);
                                                                                          iv1.setY(-100);
                                                                                      }
                                                                                      if (Rect.intersects(pinkRect, iv2Rect)) {
                                                                                          iv2.setVisibility(View.INVISIBLE);
                                                                                          iv2.setX(-100);
                                                                                          iv2.setY(-100);
                                                                                      }
                                                                                      if (Rect.intersects(pinkRect, iv3Rect)) {
                                                                                          iv3.setVisibility(View.INVISIBLE);
                                                                                          iv3.setX(-100);
                                                                                          iv3.setY(-100);
                                                                                      }
                                                                                      if (Rect.intersects(pinkRect, iv4Rect)) {
                                                                                          iv4.setVisibility(View.INVISIBLE);
                                                                                          iv4.setX(-100);
                                                                                          iv4.setY(-100);
                                                                                      }
                                                                                      if (Rect.intersects(pinkRect, iv5Rect)) {
                                                                                          iv5.setVisibility(View.INVISIBLE);
                                                                                          iv5.setX(-100);
                                                                                          iv5.setY(-100);
                                                                                      }
                                                                                      if (Rect.intersects(pinkRect, iv6Rect)) {
                                                                                          iv6.setVisibility(View.INVISIBLE);
                                                                                          iv6.setX(-100);
                                                                                          iv6.setY(-100);
                                                                                      }
                                                                                  
                                                                                      if (Rect.intersects(pinkRect, asteroidRect)) {
                                                                                  
                                                                                          count = count + 1;
                                                                                          if (count > 5) {
                                                                                              asteroid.setVisibility(View.INVISIBLE);
                                                                                              asteroid.setX(-90);
                                                                                              asteroid.setY(-180);
                                                                                              timerA.cancel();
                                                                                              timerA.purge();
                                                                                  
                                                                                          } else {
                                                                                              asteroid.setVisibility(View.VISIBLE);
                                                                                              asteroid.setX(-90);
                                                                                              asteroid.setY(-180);
                                                                                              asteroid.setRotation(asteroidANGLE = -0.0f);
                                                                                              // These settings make the asteroid follow a new
                                                                                              // path it continues to come back and attack the earth
                                                                                          }
                                                                                      }
                                                                                  
                                                                                      if (Rect.intersects(pinkRect, earthRect)) {
                                                                                          Intent intent = new Intent(getApplicationContext(), you_hit_earth.class);
                                                                                          intent.putExtra("MSG", 1);
                                                                                          startActivity(intent);
                                                                                          stopGAME(null);
                                                                                      }
                                                                                      if (Rect.intersects(asteroidRect, earthRect)) {
                                                                                  
                                                                                          Intent intent = new Intent(getApplicationContext(), you_hit_earth.class);
                                                                                          intent.putExtra("MSG", 2);
                                                                                          startActivity(intent);
                                                                                          stopGAME(null);
                                                                                      }
                                                                                  
                                                                                      if(iv1.getVisibility()==View.INVISIBLE && iv2.getVisibility()==View.INVISIBLE&&
                                                                                              iv3.getVisibility()==View.INVISIBLE&&iv4.getVisibility()==View.INVISIBLE&&
                                                                                              iv5.getVisibility()==View.INVISIBLE&&iv6.getVisibility()==View.INVISIBLE&&
                                                                                              arrowLeft.getVisibility()==View.INVISIBLE&&arrowRight.getVisibility()==View.INVISIBLE){
                                                                                  
                                                                                          Long spentTime = System.currentTimeMillis()/1000 - startTime;
                                                                                          score = spentTime;
                                                                                          Intent intent = new Intent(getApplicationContext(), result.class);
                                                                                          intent.putExtra("SCORE", score);
                                                                                          startActivity(intent);
                                                                                  
                                                                                          stopGAME(null);
                                                                                      }
                                                                                  }
                                                                                  
                                                                                  WebGL-moving the object in the line of sight
                                                                                  JavaScriptdot imgLines of Code : 183dot imgLicense : Strong Copyleft (CC BY-SA 4.0)
                                                                                  copy iconCopy
                                                                                  function lookAt(eye, target, up) {
                                                                                    const zAxis = v3.normalize(v3.subtract(eye, target));
                                                                                    const xAxis = v3.normalize(v3.cross(up, zAxis));
                                                                                    const yAxis = v3.normalize(v3.cross(zAxis, xAxis));
                                                                                  
                                                                                    return [
                                                                                      ...xAxis, 0,
                                                                                      ...yAxis, 0,
                                                                                      ...zAxis, 0,
                                                                                      ...eye, 1,
                                                                                    ];
                                                                                  }
                                                                                  
                                                                                  +----+----+----+----+
                                                                                  | xx | xy | xz |    |  xaxis
                                                                                  +----+----+----+----+
                                                                                  | yx | yy | yz |    |  yaxis
                                                                                  +----+----+----+----+
                                                                                  | zx | zy | zz |    |  zaxis
                                                                                  +----+----+----+----+
                                                                                  | tx | ty | tz |    |  translation
                                                                                  +----+----+----+----+
                                                                                  
                                                                                  const camera = lookAt(eye, target, up);
                                                                                  const xaxis = camera.slice(0, 3);
                                                                                  const yaxis = camera.slice(4, 7);
                                                                                  const zaxis = camera.slice(8, 11);
                                                                                  
                                                                                  matrix = mult(matrix, zaxis);  // moves 1 unit away from camera
                                                                                  
                                                                                  moveVec = [zaxis[0] * moveAmount, zaxis[1] * moveAmount, zaxis[2] * moveAmount];
                                                                                  matrix = mult(matrix, moveVec);  // moves moveAmount units away from camera
                                                                                  
                                                                                  // assuming tx, ty, and tz are our translation
                                                                                  tx += zaxis[0] * moveAmount;
                                                                                  ty += zaxis[1] * moveAmount;
                                                                                  tz += zaxis[2] * moveAmount;
                                                                                  
                                                                                  const vs = `
                                                                                  uniform mat4 u_worldViewProjection;
                                                                                  
                                                                                  attribute vec4 position;
                                                                                  attribute vec2 texcoord;
                                                                                  
                                                                                  varying vec4 v_position;
                                                                                  varying vec2 v_texcoord;
                                                                                  
                                                                                  void main() {
                                                                                    v_texcoord = texcoord;
                                                                                    gl_Position = u_worldViewProjection * position;
                                                                                  }
                                                                                  `;
                                                                                  const fs = `
                                                                                  precision mediump float;
                                                                                  
                                                                                  varying vec2 v_texcoord;
                                                                                  
                                                                                  uniform sampler2D u_texture;
                                                                                  
                                                                                  void main() {
                                                                                    gl_FragColor = texture2D(u_texture, v_texcoord);
                                                                                  }
                                                                                  `;
                                                                                  
                                                                                  
                                                                                  "use strict";
                                                                                  const m4 = twgl.m4;
                                                                                  const v3 = twgl.v3;
                                                                                  const gl = document.getElementById("c").getContext("webgl");
                                                                                  
                                                                                  // compiles shaders, links program, looks up locations
                                                                                  const programInfo = twgl.createProgramInfo(gl, [vs, fs]);
                                                                                  
                                                                                  // calls gl.createBuffer, gl.bindBuffer, gl.bufferData for positions, texcoords
                                                                                  const bufferInfo = twgl.primitives.createCubeBufferInfo(gl);
                                                                                  
                                                                                  // calls gl.createTexture, gl.bindTexture, gl.texImage2D, gl.texParameteri
                                                                                  const tex = twgl.createTexture(gl, {
                                                                                    min: gl.NEAREST,
                                                                                    mag: gl.NEAREST,
                                                                                    src: [
                                                                                      255, 64, 64, 255,
                                                                                      64, 192, 64, 255,
                                                                                      64, 64, 255, 255,
                                                                                      255, 224, 64, 255,
                                                                                    ],
                                                                                  });
                                                                                  
                                                                                  const settings = {
                                                                                    xoff: 0,
                                                                                    yoff: 0,
                                                                                    zoff: 0,
                                                                                  };
                                                                                  
                                                                                  function render(time) {
                                                                                    time *= 0.001;
                                                                                    twgl.resizeCanvasToDisplaySize(gl.canvas);
                                                                                    gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
                                                                                  
                                                                                    gl.enable(gl.DEPTH_TEST);
                                                                                    gl.enable(gl.CULL_FACE);
                                                                                    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
                                                                                  
                                                                                    const fov = 45 * Math.PI / 180;
                                                                                    const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
                                                                                    const zNear = 0.01;
                                                                                    const zFar = 100;
                                                                                    const projection = m4.perspective(fov, aspect, zNear, zFar);
                                                                                  
                                                                                    const eye = [3, 4, -6];
                                                                                    const target = [0, 0, 0];
                                                                                    const up = [0, 1, 0];
                                                                                  
                                                                                    const camera = m4.lookAt(eye, target, up);
                                                                                    const view = m4.inverse(camera);
                                                                                    const viewProjection = m4.multiply(projection, view);
                                                                                  
                                                                                    gl.useProgram(programInfo.program);
                                                                                  
                                                                                    // calls gl.bindBuffer, gl.enableVertexAttribArray, gl.vertexAttribPointer
                                                                                    twgl.setBuffersAndAttributes(gl, programInfo, bufferInfo);
                                                                                    const t = time * .1;
                                                                                    for (let z = -1; z <= 1; ++z) {
                                                                                      for (let x = -1; x <= 1; ++x) {
                                                                                        const world = m4.identity();
                                                                                        m4.translate(world, v3.mulScalar(camera.slice(0, 3), settings.xoff), world);
                                                                                        m4.translate(world, v3.mulScalar(camera.slice(4, 7), settings.yoff), world);
                                                                                        m4.translate(world, v3.mulScalar(camera.slice(8, 11), settings.zoff), world);
                                                                                        m4.translate(world, [x * 1.4, 0, z * 1.4], world);
                                                                                        m4.rotateY(world, t + z + x, world);
                                                                                  
                                                                                        // calls gl.uniformXXX
                                                                                        twgl.setUniforms(programInfo, {
                                                                                          u_texture: tex,
                                                                                          u_worldViewProjection: m4.multiply(viewProjection, world),
                                                                                        });
                                                                                  
                                                                                        // calls gl.drawArrays or gl.drawElements
                                                                                        twgl.drawBufferInfo(gl, bufferInfo);
                                                                                      }
                                                                                    }
                                                                                  
                                                                                    requestAnimationFrame(render);
                                                                                  }
                                                                                  requestAnimationFrame(render);
                                                                                  
                                                                                  setupSlider("#xSlider", "#xoff", "xoff");
                                                                                  setupSlider("#ySlider", "#yoff", "yoff");
                                                                                  setupSlider("#zSlider", "#zoff", "zoff");
                                                                                  
                                                                                  function setupSlider(sliderId, labelId, property) {
                                                                                    const slider = document.querySelector(sliderId);
                                                                                    const label = document.querySelector(labelId);
                                                                                  
                                                                                    function updateLabel() {
                                                                                      label.textContent = settings[property].toFixed(2);
                                                                                    }
                                                                                  
                                                                                    slider.addEventListener('input', e => {
                                                                                      settings[property] = (parseInt(slider.value) / 100 * 2 - 1) * 5;
                                                                                      updateLabel();
                                                                                    });
                                                                                  
                                                                                    updateLabel();
                                                                                    slider.value = (settings[property] / 5 * .5 + .5) * 100;
                                                                                  }
                                                                                  body { margin: 0; }
                                                                                  canvas { display: block; width: 100vw; height: 100vh; }
                                                                                  #ui { 
                                                                                    position: absolute; 
                                                                                    left: 10px; 
                                                                                    top: 10px; 
                                                                                    z-index: 2; 
                                                                                    background: rgba(255, 255, 255, 0.9);
                                                                                    padding: .5em;
                                                                                  }
                                                                                  
                                                                                  
                                                                                  
                                                                                    xoff: 
                                                                                    yoff: 
                                                                                    zoff: 
                                                                                  
                                                                                  Zoom an custom BookView which extends ScrollView
                                                                                  JavaScriptdot imgLines of Code : 423dot imgLicense : Strong Copyleft (CC BY-SA 4.0)
                                                                                  copy iconCopy
                                                                                  public class ScrollViewCustom extends ScrollView {
                                                                                  
                                                                                      public interface ZoomViewListener {
                                                                                  
                                                                                          void onZoomStarted(float zoom, float zoomx, float zoomy);
                                                                                  
                                                                                          void onZooming(float zoom, float zoomx, float zoomy);
                                                                                  
                                                                                          void onZoomEnded(float zoom, float zoomx, float zoomy);
                                                                                      }
                                                                                  
                                                                                      // zooming
                                                                                      float zoom = 1.0f;
                                                                                      float maxZoom = 2.0f;
                                                                                      float smoothZoom = 1.0f;
                                                                                      float zoomX, zoomY;
                                                                                      float smoothZoomX, smoothZoomY;
                                                                                      private boolean scrolling; // NOPMD by karooolek on 29.06.11 11:45
                                                                                  
                                                                                      // minimap variables
                                                                                      private boolean showMinimap = false;
                                                                                      private int miniMapColor = Color.BLACK;
                                                                                      private int miniMapHeight = -1;
                                                                                      private String miniMapCaption;
                                                                                      private float miniMapCaptionSize = 10.0f;
                                                                                      private int miniMapCaptionColor = Color.WHITE;
                                                                                  
                                                                                      // touching variables
                                                                                      private long lastTapTime;
                                                                                      private float touchStartX, touchStartY;
                                                                                      private float touchLastX, touchLastY;
                                                                                      private float startd;
                                                                                      private boolean pinching;
                                                                                      private float lastd;
                                                                                      private float lastdx1, lastdy1;
                                                                                      private float lastdx2, lastdy2;
                                                                                  
                                                                                      // drawing
                                                                                      private final Matrix m = new Matrix();
                                                                                      private final Paint p = new Paint();
                                                                                  
                                                                                      // listener
                                                                                      ZoomViewListener listener;
                                                                                  
                                                                                      private Bitmap ch;
                                                                                  
                                                                                      public ScrollViewCustom(Context context) {
                                                                                          super(context);
                                                                                      }
                                                                                  
                                                                                      public ScrollViewCustom(Context context, AttributeSet attributes) {
                                                                                          super(context, attributes);
                                                                                      }
                                                                                  
                                                                                      public float getZoom() {
                                                                                          return zoom;
                                                                                      }
                                                                                  
                                                                                      public float getMaxZoom() {
                                                                                          return maxZoom;
                                                                                      }
                                                                                  
                                                                                      public void setMaxZoom(final float maxZoom) {
                                                                                          if (maxZoom < 1.0f) {
                                                                                              return;
                                                                                          }
                                                                                  
                                                                                          this.maxZoom = maxZoom;
                                                                                      }
                                                                                  
                                                                                      public void setMiniMapEnabled(final boolean showMiniMap) {
                                                                                          this.showMinimap = showMiniMap;
                                                                                      }
                                                                                  
                                                                                      public boolean isMiniMapEnabled() {
                                                                                          return showMinimap;
                                                                                      }
                                                                                  
                                                                                      public void setMiniMapHeight(final int miniMapHeight) {
                                                                                          if (miniMapHeight < 0) {
                                                                                              return;
                                                                                          }
                                                                                          this.miniMapHeight = miniMapHeight;
                                                                                      }
                                                                                  
                                                                                      public int getMiniMapHeight() {
                                                                                          return miniMapHeight;
                                                                                      }
                                                                                  
                                                                                      public void setMiniMapColor(final int color) {
                                                                                          miniMapColor = color;
                                                                                      }
                                                                                  
                                                                                      public int getMiniMapColor() {
                                                                                          return miniMapColor;
                                                                                      }
                                                                                  
                                                                                      public String getMiniMapCaption() {
                                                                                          return miniMapCaption;
                                                                                      }
                                                                                  
                                                                                      public void setMiniMapCaption(final String miniMapCaption) {
                                                                                          this.miniMapCaption = miniMapCaption;
                                                                                      }
                                                                                  
                                                                                      public float getMiniMapCaptionSize() {
                                                                                          return miniMapCaptionSize;
                                                                                      }
                                                                                  
                                                                                      public void setMiniMapCaptionSize(final float size) {
                                                                                          miniMapCaptionSize = size;
                                                                                      }
                                                                                  
                                                                                      public int getMiniMapCaptionColor() {
                                                                                          return miniMapCaptionColor;
                                                                                      }
                                                                                  
                                                                                      public void setMiniMapCaptionColor(final int color) {
                                                                                          miniMapCaptionColor = color;
                                                                                      }
                                                                                  
                                                                                      public void zoomTo(final float zoom, final float x, final float y) {
                                                                                          this.zoom = Math.min(zoom, maxZoom);
                                                                                          zoomX = x;
                                                                                          zoomY = y;
                                                                                          smoothZoomTo(this.zoom, x, y);
                                                                                      }
                                                                                  
                                                                                      public void smoothZoomTo(final float zoom, final float x, final float y) {
                                                                                          smoothZoom = clamp(1.0f, zoom, maxZoom);
                                                                                          smoothZoomX = x;
                                                                                          smoothZoomY = y;
                                                                                          if (listener != null) {
                                                                                              listener.onZoomStarted(smoothZoom, x, y);
                                                                                          }
                                                                                      }
                                                                                  
                                                                                      public ZoomViewListener getListener() {
                                                                                          return listener;
                                                                                      }
                                                                                  
                                                                                      public void setListner(final ZoomViewListener listener) {
                                                                                          this.listener = listener;
                                                                                      }
                                                                                  
                                                                                      public float getZoomFocusX() {
                                                                                          return zoomX * zoom;
                                                                                      }
                                                                                  
                                                                                      public float getZoomFocusY() {
                                                                                          return zoomY * zoom;
                                                                                      }
                                                                                  
                                                                                      @Override
                                                                                      public boolean dispatchTouchEvent(final MotionEvent ev) {
                                                                                          // single touch
                                                                                          if (ev.getPointerCount() == 1) {
                                                                                              processSingleTouchEvent(ev);
                                                                                          }
                                                                                  
                                                                                          // // double touch
                                                                                          if (ev.getPointerCount() == 2) {
                                                                                              processDoubleTouchEvent(ev);
                                                                                          }
                                                                                  
                                                                                          // redraw
                                                                                          getRootView().invalidate();
                                                                                          invalidate();
                                                                                  
                                                                                          return true;
                                                                                      }
                                                                                  
                                                                                      private void processSingleTouchEvent(final MotionEvent ev) {
                                                                                  
                                                                                          final float x = ev.getX();
                                                                                          final float y = ev.getY();
                                                                                  
                                                                                          final float w = miniMapHeight * (float) getWidth() / getHeight();
                                                                                          final float h = miniMapHeight;
                                                                                          final boolean touchingMiniMap = x >= 10.0f && x <= 10.0f + w && y >= 10.0f && y <= 10.0f + h;
                                                                                  
                                                                                          if (showMinimap && smoothZoom > 1.0f && touchingMiniMap) {
                                                                                              processSingleTouchOnMinimap(ev);
                                                                                          } else {
                                                                                              processSingleTouchOutsideMinimap(ev);
                                                                                          }
                                                                                      }
                                                                                  
                                                                                      private void processSingleTouchOnMinimap(final MotionEvent ev) {
                                                                                          final float x = ev.getX();
                                                                                          final float y = ev.getY();
                                                                                  
                                                                                          final float w = miniMapHeight * (float) getWidth() / getHeight();
                                                                                          final float h = miniMapHeight;
                                                                                          final float zx = (x - 10.0f) / w * getWidth();
                                                                                          final float zy = (y - 10.0f) / h * getHeight();
                                                                                          smoothZoomTo(smoothZoom, zx, zy);
                                                                                      }
                                                                                  
                                                                                      private void processSingleTouchOutsideMinimap(final MotionEvent ev) {
                                                                                          final float x = ev.getX();
                                                                                          final float y = ev.getY();
                                                                                          float lx = x - touchStartX;
                                                                                          float ly = y - touchStartY;
                                                                                          final float l = (float) Math.hypot(lx, ly);
                                                                                          float dx = x - touchLastX;
                                                                                          float dy = y - touchLastY;
                                                                                          touchLastX = x;
                                                                                          touchLastY = y;
                                                                                  
                                                                                          switch (ev.getAction()) {
                                                                                              case MotionEvent.ACTION_DOWN:
                                                                                                  touchStartX = x;
                                                                                                  touchStartY = y;
                                                                                                  touchLastX = x;
                                                                                                  touchLastY = y;
                                                                                                  dx = 0;
                                                                                                  dy = 0;
                                                                                                  lx = 0;
                                                                                                  ly = 0;
                                                                                                  scrolling = false;
                                                                                                  break;
                                                                                  
                                                                                              case MotionEvent.ACTION_MOVE:
                                                                                                  if (scrolling || (smoothZoom > 1.0f && l > 30.0f)) {
                                                                                                      if (!scrolling) {
                                                                                                          scrolling = true;
                                                                                                          ev.setAction(MotionEvent.ACTION_CANCEL);
                                                                                                          super.dispatchTouchEvent(ev);
                                                                                                      }
                                                                                                      smoothZoomX -= dx / zoom;
                                                                                                      smoothZoomY -= dy / zoom;
                                                                                                      return;
                                                                                                  }
                                                                                                  break;
                                                                                  
                                                                                              case MotionEvent.ACTION_OUTSIDE:
                                                                                              case MotionEvent.ACTION_UP:
                                                                                  
                                                                                                  // tap
                                                                                                  if (l < 30.0f) {
                                                                                                      // check double tap
                                                                                                      if (System.currentTimeMillis() - lastTapTime < 500) {
                                                                                                          if (smoothZoom == 1.0f) {
                                                                                                              smoothZoomTo(maxZoom, x, y);
                                                                                                          } else {
                                                                                                              smoothZoomTo(1.0f, getWidth() / 2.0f, getHeight() / 2.0f);
                                                                                                          }
                                                                                                          lastTapTime = 0;
                                                                                                          ev.setAction(MotionEvent.ACTION_CANCEL);
                                                                                                          super.dispatchTouchEvent(ev);
                                                                                                          return;
                                                                                                      }
                                                                                  
                                                                                                      lastTapTime = System.currentTimeMillis();
                                                                                  
                                                                                                      performClick();
                                                                                                  }
                                                                                                  break;
                                                                                  
                                                                                              default:
                                                                                                  break;
                                                                                          }
                                                                                  
                                                                                          ev.setLocation(zoomX + (x - 0.5f * getWidth()) / zoom, zoomY + (y - 0.5f * getHeight()) / zoom);
                                                                                  
                                                                                          ev.getX();
                                                                                          ev.getY();
                                                                                  
                                                                                          super.dispatchTouchEvent(ev);
                                                                                      }
                                                                                  
                                                                                      private void processDoubleTouchEvent(final MotionEvent ev) {
                                                                                          final float x1 = ev.getX(0);
                                                                                          final float dx1 = x1 - lastdx1;
                                                                                          lastdx1 = x1;
                                                                                          final float y1 = ev.getY(0);
                                                                                          final float dy1 = y1 - lastdy1;
                                                                                          lastdy1 = y1;
                                                                                          final float x2 = ev.getX(1);
                                                                                          final float dx2 = x2 - lastdx2;
                                                                                          lastdx2 = x2;
                                                                                          final float y2 = ev.getY(1);
                                                                                          final float dy2 = y2 - lastdy2;
                                                                                          lastdy2 = y2;
                                                                                  
                                                                                          // pointers distance
                                                                                          final float d = (float) Math.hypot(x2 - x1, y2 - y1);
                                                                                          final float dd = d - lastd;
                                                                                          lastd = d;
                                                                                          final float ld = Math.abs(d - startd);
                                                                                  
                                                                                          Math.atan2(y2 - y1, x2 - x1);
                                                                                          switch (ev.getAction()) {
                                                                                              case MotionEvent.ACTION_DOWN:
                                                                                                  startd = d;
                                                                                                  pinching = false;
                                                                                                  break;
                                                                                  
                                                                                              case MotionEvent.ACTION_MOVE:
                                                                                                  if (pinching || ld > 30.0f) {
                                                                                                      pinching = true;
                                                                                                      final float dxk = 0.5f * (dx1 + dx2);
                                                                                                      final float dyk = 0.5f * (dy1 + dy2);
                                                                                                      smoothZoomTo(Math.max(1.0f, zoom * d / (d - dd)), zoomX - dxk / zoom, zoomY - dyk / zoom);
                                                                                                  }
                                                                                  
                                                                                                  break;
                                                                                  
                                                                                              case MotionEvent.ACTION_UP:
                                                                                              default:
                                                                                                  pinching = false;
                                                                                                  break;
                                                                                          }
                                                                                  
                                                                                          ev.setAction(MotionEvent.ACTION_CANCEL);
                                                                                          super.dispatchTouchEvent(ev);
                                                                                      }
                                                                                  
                                                                                      private float clamp(final float min, final float value, final float max) {
                                                                                          return Math.max(min, Math.min(value, max));
                                                                                      }
                                                                                  
                                                                                      private float lerp(final float a, final float b, final float k) {
                                                                                          return a + (b - a) * k;
                                                                                      }
                                                                                  
                                                                                      private float bias(final float a, final float b, final float k) {
                                                                                          return Math.abs(b - a) >= k ? a + k * Math.signum(b - a) : b;
                                                                                      }
                                                                                  
                                                                                      @Override
                                                                                      protected void dispatchDraw(final Canvas canvas) {
                                                                                          // do zoom
                                                                                          zoom = lerp(bias(zoom, smoothZoom, 0.05f), smoothZoom, 0.2f);
                                                                                          smoothZoomX = clamp(0.5f * getWidth() / smoothZoom, smoothZoomX, getWidth() - 0.5f * getWidth() / smoothZoom);
                                                                                          smoothZoomY = clamp(0.5f * getHeight() / smoothZoom, smoothZoomY, getHeight() - 0.5f * getHeight() / smoothZoom);
                                                                                  
                                                                                          zoomX = lerp(bias(zoomX, smoothZoomX, 0.1f), smoothZoomX, 0.35f);
                                                                                          zoomY = lerp(bias(zoomY, smoothZoomY, 0.1f), smoothZoomY, 0.35f);
                                                                                          if (zoom != smoothZoom && listener != null) {
                                                                                              listener.onZooming(zoom, zoomX, zoomY);
                                                                                          }
                                                                                  
                                                                                          final boolean animating = Math.abs(zoom - smoothZoom) > 0.0000001f
                                                                                                  || Math.abs(zoomX - smoothZoomX) > 0.0000001f || Math.abs(zoomY - smoothZoomY) > 0.0000001f;
                                                                                  
                                                                                          // nothing to draw
                                                                                          if (getChildCount() == 0) {
                                                                                              return;
                                                                                          }
                                                                                  
                                                                                          // prepare matrix
                                                                                          m.setTranslate(0.5f * getWidth(), 0.5f * getHeight());
                                                                                          m.preScale(zoom, zoom);
                                                                                          m.preTranslate(-clamp(0.5f * getWidth() / zoom, zoomX, getWidth() - 0.5f * getWidth() / zoom),
                                                                                                  -clamp(0.5f * getHeight() / zoom, zoomY, getHeight() - 0.5f * getHeight() / zoom));
                                                                                  
                                                                                          // get view
                                                                                          final View v = getChildAt(0);
                                                                                          m.preTranslate(v.getLeft(), v.getTop());
                                                                                  
                                                                                          // get drawing cache if available
                                                                                          if (animating && ch == null && isAnimationCacheEnabled()) {
                                                                                              v.setDrawingCacheEnabled(true);
                                                                                              ch = v.getDrawingCache();
                                                                                          }
                                                                                  
                                                                                          // draw using cache while animating
                                                                                          if (animating && isAnimationCacheEnabled() && ch != null) {
                                                                                              p.setColor(0xffffffff);
                                                                                              canvas.drawBitmap(ch, m, p);
                                                                                          } else { // zoomed or cache unavailable
                                                                                              ch = null;
                                                                                              canvas.save();
                                                                                              canvas.concat(m);
                                                                                              v.draw(canvas);
                                                                                              canvas.restore();
                                                                                          }
                                                                                  
                                                                                          // draw minimap
                                                                                          if (showMinimap) {
                                                                                              if (miniMapHeight < 0) {
                                                                                                  miniMapHeight = getHeight() / 4;
                                                                                              }
                                                                                  
                                                                                              canvas.translate(10.0f, 10.0f);
                                                                                  
                                                                                              p.setColor(0x80000000 | 0x00ffffff & miniMapColor);
                                                                                              final float w = miniMapHeight * (float) getWidth() / getHeight();
                                                                                              final float h = miniMapHeight;
                                                                                              canvas.drawRect(0.0f, 0.0f, w, h, p);
                                                                                  
                                                                                              if (miniMapCaption != null && miniMapCaption.length() > 0) {
                                                                                                  p.setTextSize(miniMapCaptionSize);
                                                                                                  p.setColor(miniMapCaptionColor);
                                                                                                  p.setAntiAlias(true);
                                                                                                  canvas.drawText(miniMapCaption, 10.0f, 10.0f + miniMapCaptionSize, p);
                                                                                                  p.setAntiAlias(false);
                                                                                              }
                                                                                  
                                                                                              p.setColor(0x80000000 | 0x00ffffff & miniMapColor);
                                                                                              final float dx = w * zoomX / getWidth();
                                                                                              final float dy = h * zoomY / getHeight();
                                                                                              canvas.drawRect(dx - 0.5f * w / zoom, dy - 0.5f * h / zoom, dx + 0.5f * w / zoom, dy + 0.5f * h / zoom, p);
                                                                                  
                                                                                              canvas.translate(-10.0f, -10.0f);
                                                                                          }
                                                                                  
                                                                                          // redraw
                                                                                          // if (animating) {
                                                                                          getRootView().invalidate();
                                                                                          invalidate();
                                                                                          // }
                                                                                      }
                                                                                  }
                                                                                  
                                                                                  public class BookView extends ScrollViewCustom {
                                                                                  
                                                                                  ...
                                                                                  
                                                                                  }
                                                                                  
                                                                                  Community Discussions

                                                                                  Trending Discussions on zx

                                                                                  Slow code when fetching data from Coinmarketcap api
                                                                                  chevron right
                                                                                  Error message caught by Axios is undefined in production, but works locally?
                                                                                  chevron right
                                                                                  Checking different elements of a cell in dataframe separated by comma using Pandas
                                                                                  chevron right
                                                                                  Keep only characters in between two hyphens from a dataframe cell which has comma separated list
                                                                                  chevron right
                                                                                  RenderTexture transparency working in editor becomes solid color in build
                                                                                  chevron right
                                                                                  Regex Match anything inside the string
                                                                                  chevron right
                                                                                  How to use google/zx to execute ffmpeg shell in windows?
                                                                                  chevron right
                                                                                  microk8s coredns CrashLoopBackOff
                                                                                  chevron right
                                                                                  MVVM WPF Add new item to the DataGrid from Textboxes which are bound to the nested properties of the Model class
                                                                                  chevron right
                                                                                  Firestore 'await addDoc' (Web version 9) hangs forever when network connection is lost
                                                                                  chevron right

                                                                                  QUESTION

                                                                                  Slow code when fetching data from Coinmarketcap api
                                                                                  Asked 2022-Apr-03 at 09:47

                                                                                  I have the below code that fetches data from Coinmarketcap api and sends me a telegram message when parameters are met. When I fetch 100 coins then the code works fine. But when I fetch 5000 coins the code is very slow. The schedule time with refresh api is not the time that I have code.

                                                                                  Can someone see why the code is slow with fetching data from the api with 5000 coins?

                                                                                  A good answer is insert httpx / asyncio in the code. (answer Pawel Rubin (thanks). Does someone know how i can insert asyncio into the code?

                                                                                  from tokens import cmc_token
                                                                                  import json
                                                                                  import re
                                                                                  import requests
                                                                                  from datetime import date
                                                                                  import datetime
                                                                                  from datetime import datetime as dt
                                                                                  from datetime import datetime
                                                                                  from datetime import datetime, timedelta
                                                                                  import schedule
                                                                                  import time
                                                                                  import pandas as pd
                                                                                  
                                                                                  lijst = []
                                                                                  price_change2 = []
                                                                                  coinlist = []
                                                                                  
                                                                                  def tg():
                                                                                      token = 'xxxxxxxxxxx'
                                                                                  
                                                                                      def write_json(data, filename='response.json'):
                                                                                          with open(filename, 'w') as f:
                                                                                              json.dump(data, f, indent=4, ensure_ascii=False)
                                                                                  
                                                                                      url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest'
                                                                                      params = {'start': '1', 'limit': '5000', 'convert': 'usd', 'sort': 'date_added','sort_dir': 'desc' }
                                                                                      headers = {'X-CMC_PRO_API_KEY': cmc_token}
                                                                                  
                                                                                      d = requests.get(url, headers=headers, params=params).json()
                                                                                      
                                                                                      def send_message_two(text='bla-bla-bla'):
                                                                                          url = f'https://api.telegram.org/bot{token}/sendMessage'
                                                                                          payload = {'chat_id': xxxxxxx, 'text' : text}
                                                                                  
                                                                                          p = requests.post(url, json=payload)
                                                                                          return p
                                                                                  
                                                                                  
                                                                                      for x in d['data']:
                                                                                          date_json1 = x['last_updated']
                                                                                          new_date1 = datetime.fromisoformat(date_json1[:-1])
                                                                                          new_date_plus1 = new_date1 + timedelta(hours=2)
                                                                                          new_date_str1 = new_date_plus1.strftime('%Y-%m-%d %H:%M:%S')
                                                                                  
                                                                                          price_now = x['symbol'], new_date_str1, x['quote']['USD']['price'], x['platform']
                                                                                          price_change2.append(price_now)
                                                                                  
                                                                                          Dataset = pd.DataFrame(price_change2)
                                                                                          df_new = Dataset.rename(columns={0:'coin', 2:'price', 1:'last_updated', 3:'platform'})
                                                                                          zx = df_new.sort_values(['coin','last_updated'])
                                                                                  
                                                                                  
                                                                                          zx['change1'] = zx.groupby('coin')['price'].pct_change().mul(100)
                                                                                          zx['change1'] = zx['change1'].fillna(0)
                                                                                  
                                                                                          js = zx.to_json(orient="table")
                                                                                          parsed = json.loads(js)
                                                                                  
                                                                                          for bn in parsed['data']:
                                                                                              rt = bn['coin'], bn['change1'], bn['last_updated'],bn['price'], bn['platform']
                                                                                  
                                                                                              if bn['change1'] is None:
                                                                                                  return 0
                                                                                  
                                                                                  
                                                                                              if bn['change1'] > 35 and bn['change1'] < 100 and bn['coin'] not in coinlist:
                                                                                                  coinlist.append(bn['coin'])
                                                                                                  send_message_two(rt)
                                                                                                  send_message_two('15 min change 35% all time')
                                                                                  
                                                                                  
                                                                                  schedule.every(900).seconds.do(tg)
                                                                                  
                                                                                  while True:
                                                                                      schedule.run_pending()
                                                                                      time.sleep(1)
                                                                                  
                                                                                  def main():
                                                                                      pass
                                                                                  
                                                                                  
                                                                                  if __name__ == '__main__':
                                                                                      main()
                                                                                  

                                                                                  ANSWER

                                                                                  Answered 2022-Apr-01 at 13:50

                                                                                  The code is making requests sequentially for every element in parsed['data'].

                                                                                  Consider running your code asynchronously with some HTTP client that supports asyncio, for example httpx, and use asyncio.gather to run your requests concurrently.

                                                                                  Consider the following example which makes 50 GET requests to google.com using requests and using httpx. Note that the async solution is significantly faster.

                                                                                  import asyncio
                                                                                  import time
                                                                                  
                                                                                  import requests
                                                                                  import httpx
                                                                                  
                                                                                  
                                                                                  def test_sync():
                                                                                      for _ in range(50):
                                                                                          requests.get("https://google.com")
                                                                                  
                                                                                  
                                                                                  async def test_async():
                                                                                      async with httpx.AsyncClient() as client:
                                                                                          tasks = [client.get("https://google.com") for _ in range(50)]
                                                                                          await asyncio.gather(*tasks)
                                                                                  
                                                                                  
                                                                                  if __name__ == "__main__":
                                                                                      start = time.process_time()
                                                                                      test_sync()
                                                                                      print(f"sync test took {time.process_time() - start} s")
                                                                                  
                                                                                      start = time.process_time()
                                                                                      asyncio.run(test_async())
                                                                                      print(f"async test took {time.process_time() - start} s")
                                                                                  
                                                                                  
                                                                                  # sync test took 23.0833 s
                                                                                  # async test took 0.2662 s
                                                                                  

                                                                                  Source https://stackoverflow.com/questions/71706509

                                                                                  QUESTION

                                                                                  Error message caught by Axios is undefined in production, but works locally?
                                                                                  Asked 2022-Mar-22 at 18:55

                                                                                  I have a function that sends an axios rrequest to my springboot backend.

                                                                                    async createUser(user) {
                                                                                      return axios.post(API_BASE_URL + "users/register", user).catch((error) => {
                                                                                        console.log("the error: " + error.response.data.message);
                                                                                        throw error.response.data.message;
                                                                                      });
                                                                                    }
                                                                                  

                                                                                  For some reason, when I run the project locally, I am able to get the error message above, but when I deploy the project to production, the error message is undefined.

                                                                                  Example of the above print statement^:

                                                                                  Error message when ran locally: the error: Email must be a work email. The email zx is NOT allowed.

                                                                                  Error message when deployed: the error: undefined

                                                                                  Code from my backend: The controller:

                                                                                      @PostMapping("/api/users/register")
                                                                                      public User registerUser(@RequestBody User user) {
                                                                                          return userServices.createUser(user);
                                                                                      }
                                                                                  
                                                                                      public User createUser(User userDetails) {
                                                                                          if (Boolean.TRUE.equals(emailExists(userDetails.getEmail()))) {
                                                                                              throw new DuplicateResourceException(
                                                                                                      "There is already an account with that email address: " +
                                                                                                              userDetails.getEmail());
                                                                                          }
                                                                                          if (!userDetails.getEmail().toLowerCase().endsWith("@company.com")) {
                                                                                              throw new NotAllowedException(
                                                                                                      "Email must be a work email. The email " +
                                                                                                              userDetails.getEmail() + " is NOT allowed.");
                                                                                          }
                                                                                          if (!userDetails.getCompanyPasscode().equals(env.getProperty("company.passcode"))) {
                                                                                              throw new NotAllowedException(
                                                                                                      "Incorrect company passcode");
                                                                                          }
                                                                                          User user = new User();
                                                                                          user.setEmail(userDetails.getEmail());
                                                                                          user.setPassword(passwordEncoder.encode(userDetails.getPassword()));
                                                                                          return userRepo.save(user);
                                                                                      }
                                                                                  

                                                                                  So if you look that the above function, you can see that when I run the project locally, I can get the NotAllowedException to be thrown back to my frontend, but not when deplpyed.

                                                                                  I read online that it could be due to a CORS header issue, but I don't think so because this is my CORS configuration and it still isn't working:

                                                                                      @Bean
                                                                                      CorsConfigurationSource corsConfigurationSource() {
                                                                                          final CorsConfiguration config = new CorsConfiguration();
                                                                                  
                                                                                          config.setAllowedMethods(Arrays.asList("GET", "POST", "OPTIONS", "DELETE", "PUT", "PATCH"));
                                                                                          config.setAllowedHeaders(Arrays.asList("*"));
                                                                                          config.setAllowedOrigins(Arrays.asList("*"));
                                                                                  
                                                                                          UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
                                                                                          source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
                                                                                          return source;
                                                                                  
                                                                                      }
                                                                                  

                                                                                  This is an example of one of my custom Exception classes:

                                                                                  import org.springframework.http.HttpStatus;
                                                                                  import org.springframework.web.bind.annotation.ResponseStatus;
                                                                                  
                                                                                  @ResponseStatus(value = HttpStatus.BAD_REQUEST)
                                                                                  public class NotAllowedException extends RuntimeException {
                                                                                  
                                                                                      private static final long serialVersionUID = 1L;
                                                                                  
                                                                                      public NotAllowedException(String message) {
                                                                                          super(message);
                                                                                      }
                                                                                  }
                                                                                  
                                                                                  

                                                                                  ANSWER

                                                                                  Answered 2022-Mar-16 at 16:18

                                                                                  From doing some searching, I've found a few people saying they have this problem when the Java on the 2 systems are different versions.

                                                                                  Source https://stackoverflow.com/questions/71468591

                                                                                  QUESTION

                                                                                  Checking different elements of a cell in dataframe separated by comma using Pandas
                                                                                  Asked 2022-Mar-11 at 13:57

                                                                                  I have three dataframes [Accepted, Ignored, Input]. We have to check the "Subset" column strings of Input df in the subset columns of accepted and ignored df. If the subset are not present in both of them, we have to keep them in exception. [Strings should match exactly]] For eg.

                                                                                  Accepted df is

                                                                                  Accepted   Accepted  
                                                                                  AC         ASD
                                                                                  ZX         AGH
                                                                                  

                                                                                  Ignored df is

                                                                                  Ignored    Ignored
                                                                                  AD         ADS
                                                                                  

                                                                                  Input df is

                                                                                  Name    Subset
                                                                                  Apple   AC,AC,AD,AGH
                                                                                  Bat     ZX,ADS,AXC
                                                                                  Cat     HJ,AGH
                                                                                  

                                                                                  Output we need:

                                                                                   Name    Subset        Accepted    Ignored     Exception
                                                                                   Apple   AC,AC,AD,AGH  AC,AC,AGH   AD
                                                                                   Bat     ZX,ADS,AXC    ZX          ADS         AXC
                                                                                   Cat     HJ,AGH        AGH                     HJ
                                                                                  

                                                                                  All the dataframes can have multiple rows and columns.

                                                                                  How can I do it using Python.

                                                                                  ANSWER

                                                                                  Answered 2022-Mar-03 at 11:09

                                                                                  Use sets for get intersection and difference in splitted values by ,, last join back to strings by join:

                                                                                  Accepted = set(df1.to_numpy().ravel())
                                                                                  Ignored = set(df2.to_numpy().ravel())
                                                                                  Both = set.union(Accepted,Ignored)
                                                                                  
                                                                                  df['Accepted'] = df['Subset'].apply(lambda x: ','.join(Accepted & set(x.split(','))))
                                                                                  df['Ignored'] = df['Subset'].apply(lambda x:  ','.join(Ignored & set(x.split(','))))
                                                                                  df['Exception'] = df['Subset'].apply(lambda x:  ','.join(set(x.split(',')) - Both))
                                                                                  
                                                                                  print (df)
                                                                                      Name      Subset Accepted Ignored Exception
                                                                                  0  Apple   AC,AD,AGH   AC,AGH      AD          
                                                                                  1    Bat  ZX,ADS,AXC       ZX     ADS       AXC
                                                                                  2    Cat      HJ,AGH      AGH                HJ
                                                                                  

                                                                                  Source https://stackoverflow.com/questions/71336044

                                                                                  QUESTION

                                                                                  Keep only characters in between two hyphens from a dataframe cell which has comma separated list
                                                                                  Asked 2022-Mar-09 at 13:41

                                                                                  I have a database for eg.

                                                                                  Name    Subset
                                                                                  Apple   -AI-,-BI-A,-XC-,ZX-
                                                                                  Bat     -po-,-IJ-,-IA-B
                                                                                  

                                                                                  and want to convert it to:

                                                                                  Name    Subset
                                                                                  Apple   AI,BI,XC,ZX
                                                                                  Bat     po,IJ,IA
                                                                                  

                                                                                  i.e removing the first hyphen and removing the second hyphen and charachters following it until next comma appears.

                                                                                  ANSWER

                                                                                  Answered 2022-Mar-09 at 13:26

                                                                                  Use Series.str.split, Series.explode and Series.groupby.agg:

                                                                                  In [2193]: df['Subset'] = df.Subset.str.split(',').explode().str.split('-').str[:2].apply(''.join).groupby(level=0).agg(','.join)
                                                                                  
                                                                                  In [2194]: df
                                                                                  Out[2194]: 
                                                                                      Name       Subset
                                                                                  0  Apple  AI,BI,XC,ZX
                                                                                  1    Bat     po,IJ,IA
                                                                                  

                                                                                  Source https://stackoverflow.com/questions/71409935

                                                                                  QUESTION

                                                                                  RenderTexture transparency working in editor becomes solid color in build
                                                                                  Asked 2022-Feb-21 at 20:04

                                                                                  I am currently trying to get my growth algorithm to work on a texture.

                                                                                  When running in the editor everything works as expected, however once I build the project, the whole RenderTexture becomes a solid color (red, green or blue [R8G8B8A8_UNORM] depending on the color format) with the simulation on top.

                                                                                  I have already tried to use an HDRP unlit texture shader instead of my custom transparency shader, which produced the same issue leading me to believe that my mistake lies somewhere within the compute shader drawing onto the texture. Also, I rebuilt the project using URP which unfortunately also produced the same result.

                                                                                  One other thing, I recently noticed that minimizing and maximizing the game window on runtime in the editor more than once crashes unity although I can't image how this has anything to do with the issue at hand.

                                                                                  EDIT: Just built the same project for windows (DX11) which works perfectly. This therefore seems to be an issue with the Metal API.

                                                                                  Interestingly, the maximizing/minimizing problem appears only if vsync is enabled and the touchpad gesture is used.

                                                                                  Unity Version 2021.2.12f1 using the HDRP on MacOS Monterey 12.2.1.

                                                                                  GitHub if you would like to reproduce the error: https://github.com/whatphilipcodes/seed

                                                                                  Compute Shader Code below.

                                                                                      // mean filter code (DrawTrails) courtesy of https://github.com/DenizBicer/Physarum
                                                                                      // (Modified)
                                                                                      
                                                                                      // Each #kernel tells which function to compile; you can have many kernels
                                                                                      #pragma kernel DrawPoints
                                                                                      #pragma kernel DrawTrails
                                                                                      
                                                                                      // Create a RenderTexture with enableRandomWrite flag and set it
                                                                                      // with cs.SetTexture
                                                                                      
                                                                                      // texture
                                                                                      shared RWTexture2D Result;
                                                                                      //RWTexture2D TrailBuffer;
                                                                                      int _texres;
                                                                                      int _colres;
                                                                                      float4 _pcol;
                                                                                      
                                                                                      // testing
                                                                                      float _decay;
                                                                                      
                                                                                      // buffer
                                                                                      StructuredBuffer pointsBuffer;
                                                                                      StructuredBuffer colorsBuffer;
                                                                                      
                                                                                      [numthreads(64,1,1)]
                                                                                      void DrawPoints (uint3 id : SV_DispatchThreadID)
                                                                                      {
                                                                                          if ((pointsBuffer[id.x].x * pointsBuffer[id.x].y) > 0) Result[pointsBuffer[id.x].xy] = colorsBuffer[id.x % _colres];
                                                                                      }
                                                                                      
                                                                                      [numthreads(16,16,1)]
                                                                                      void DrawTrails (uint3 id : SV_DispatchThreadID)
                                                                                      {
                                                                                          float3 value;
                                                                                      
                                                                                          value = Result[id.xy].rgb;
                                                                                      
                                                                                          float3 d = float3(1, -1, 0.0);
                                                                                      
                                                                                          //mean filter red
                                                                                          value.r = value.r;
                                                                                          value.r += Result[id.xy - d.xx].r; // -1,-1
                                                                                          value.r += Result[id.xy - d.zx].r; // 0, -1
                                                                                          value.r += Result[id.xy - d.yx].r; // +1, -1
                                                                                          value.r += Result[id.xy - d.xz].r; // -1, 0
                                                                                          value.r += Result[id.xy + d.xz].r; // +1, 0
                                                                                          value.r += Result[id.xy + d.yx].r; // -1, +1
                                                                                          value.r += Result[id.xy + d.zx].r; // 0, +1
                                                                                          value.r += Result[id.xy + d.xx].r; // +1, +1
                                                                                      
                                                                                          value.x = (value.x / 9) * (1 - _decay);
                                                                                          
                                                                                          //mean filter green
                                                                                          value.g = value.g;
                                                                                          value.g += Result[id.xy - d.xx].g; // -1,-1
                                                                                          value.g += Result[id.xy - d.zx].g; // 0, -1
                                                                                          value.g += Result[id.xy - d.yx].g; // +1, -1
                                                                                          value.g += Result[id.xy - d.xz].g; // -1, 0
                                                                                          value.g += Result[id.xy + d.xz].g; // +1, 0
                                                                                          value.g += Result[id.xy + d.yx].g; // -1, +1
                                                                                          value.g += Result[id.xy + d.zx].g; // 0, +1
                                                                                          value.g += Result[id.xy + d.xx].g; // +1, +1
                                                                                      
                                                                                          value.g = (value.g / 9) * (1 - _decay);
                                                                                      
                                                                                          //mean filter blue
                                                                                          value.b = value.z;
                                                                                          value.b += Result[id.xy - d.xx].b; // -1,-1
                                                                                          value.b += Result[id.xy - d.zx].b; // 0, -1
                                                                                          value.b += Result[id.xy - d.yx].b; // +1, -1
                                                                                          value.b += Result[id.xy - d.xz].b; // -1, 0
                                                                                          value.b += Result[id.xy + d.xz].b; // +1, 0
                                                                                          value.b += Result[id.xy + d.yx].b; // -1, +1
                                                                                          value.b += Result[id.xy + d.zx].b; // 0, +1
                                                                                          value.b += Result[id.xy + d.xx].b; // +1, +1
                                                                                          
                                                                                          value.b = (value.b / 9) * (1 - _decay);
                                                                                          
                                                                                          Result[id.xy] = float4(value.r, value.g, value.b, 0.0);
                                                                                      }
                                                                                  

                                                                                  Any idea is gratefully appreciated!

                                                                                  ANSWER

                                                                                  Answered 2022-Feb-21 at 20:04

                                                                                  The way I ended up solving my issue was to add a kernel that sets all pixels to black, dispatched from the start() method.

                                                                                  [numthreads(16,16,1)]
                                                                                  void SetTexture (uint3 id : SV_DispatchThreadID)
                                                                                  {
                                                                                      Result[id.xy] = float4(0.0, 0.0, 0.0, 0.0);
                                                                                  }
                                                                                  

                                                                                  I'm pretty sure that there are far more elegant solutions but for now this will have to do.

                                                                                  Source https://stackoverflow.com/questions/71200062

                                                                                  QUESTION

                                                                                  Regex Match anything inside the string
                                                                                  Asked 2022-Feb-13 at 18:25

                                                                                  How Can I match XX.Xx("$\bH.Pt#S+V0&DJT-R&", gM) this pattern in a string shown below, the only constant is XX. two arguments are random

                                                                                  XX.Xx("$\bH.Pt#S+V0&DJT-R&", gM)
                                                                                  XX.Vx("\'\x40]\tFv9](H\x40J[)", F6)
                                                                                  
                                                                                  
                                                                                  [XX.Ux("gI\ny", sl), Ar, XX.Rx("\t|", pO), Jd, XX.kx("xW\n", CM), Wm, XX.wx("U\vyV", DO), jr, XX.Mx("U\vxW", GO), Zm, XX.tx("a{O", xO), Hm, XX.RV(Qk, Hl, Q0), Qd, XX.Nx("\t|", OM), Br, XX.zx("{I\v", vM), jd, XX.gx("U\vxS", W6), nm, XX.kV(Qk, UM, Q0), Bd, XX.rx("\t|", RM), Xm, XX.mx("V\r", kM), Id, XX.dx("J\t~", KY), Lm, XX.hx("xV\v", wN), Sd, XX.bx("xU\x00", d6), rd, XX.Cx("axK", BM), Wd, XX.qx("}~", h6), Zd, XX.sx("gI\b", b6), Hd, XX.Kx("xU", C6), Lh, XX.Wx("U\ry", q6), pm["fpValStr"], XX.wV(Qk, Ml, F0), vd, XX.Zx("sH", LN), jm, XX.Hx("{I\f", jM), Xh], Vh && (Wr.push(XX.nx("xT", XN), XX.Ax("", VN)), Th = j3(N3)), Wr.push(XX.Fx("J\nu", nY), Md), Kr = ph(j2, [Wr, A0]), Dh = Wr.join(Kr), qr(XX.Ex("9I\x00", TN).concat(Dh["slice"](N3, W0)));
                                                                                  

                                                                                  ANSWER

                                                                                  Answered 2022-Feb-13 at 18:25

                                                                                  (XX\.[A-Za-z]*\("([^"]*)",\s*([0-9A-Za-z]{2})\),\s*[0-9A-Za-z)]+)

                                                                                  To capture multiple times

                                                                                  • run the regexp on the big string
                                                                                  • if no matches, break
                                                                                  • use the second and third capture groups as you like
                                                                                  • get the first capture group
                                                                                  • in the big string replace that capture group with an empty string
                                                                                  • do it again with the modified string

                                                                                  Old Answer

                                                                                  XX\.[A-Za-z]*\("(.*)",\s*([0-9A-Za-z]{2})\)

                                                                                  I included capture groups if your interested

                                                                                  I can explain it if you'd like

                                                                                  • XX\. The beginning is probably obvious. XX\.
                                                                                    • it's important to note that . in regex matches anything, however I assume you specifically want to get a period. Thus we escape it like \.
                                                                                  • [A-Za-z]* next we are matching any amount of characters from capital A to capital Z and lower case a and lowercase z. I assume that it will always be 2 characters but I'll let it slide for now
                                                                                  • \( next we escape the open parenthesis because parenthesis represents a capture group
                                                                                  • " next we look for a quotation mark
                                                                                  • (.*)" next we capture anything intil we hit another quotation mark.
                                                                                    • It's important to note that if the string has an escaped quotation mark, this regexp breaks. If you need an escaped quotation mark also I'll try to help you out
                                                                                  • , next we look for a comma
                                                                                  • \s* after that we look for any amount of spaces. Could be zero, could be a hundred
                                                                                  • (0-9A-Za-z){2} next we capture two characters that could be 0-9 A-Z and A-Z
                                                                                  • \) finally we end with a parenthesis

                                                                                  Source https://stackoverflow.com/questions/71097050

                                                                                  QUESTION

                                                                                  How to use google/zx to execute ffmpeg shell in windows?
                                                                                  Asked 2022-Feb-08 at 00:43

                                                                                  I download the ffmpeg through scoop,and I can use ffmpeg in powershell.

                                                                                  My script is below:

                                                                                  #!/usr/bin/env zx
                                                                                  const filePath = `./abc.mp4`;
                                                                                  const srsServerURL = `192.168.30.100`;
                                                                                  await $`ffmpeg -re -i ${filePath} -c copy -f mp4 -y rtmp://${srsServerURL}/live/livestream`;
                                                                                  

                                                                                  but the zx tell me that ffmpeg not found.

                                                                                  ANSWER

                                                                                  Answered 2022-Feb-07 at 02:28

                                                                                  I think the issue might be that zx is using the bash inside WSL. Assuming you also don't want to use ffmpeg in WSL, here is how I fixed it.

                                                                                  1. Install git.
                                                                                  2. Find the bash.exe inside the installed git. In my case, it is located at C:/Program Files/Git/usr/bin/bash.exe.
                                                                                  3. Insert the following line after the shebang: $.shell = `Location to your bash`. In my case, it is $.shell = `C:/Program Files/Git/usr/bin/bash.exe`;.

                                                                                  I am fairly sure this works with other distributions of bash for Windows, but I have not tested.

                                                                                  Source https://stackoverflow.com/questions/68931619

                                                                                  QUESTION

                                                                                  microk8s coredns CrashLoopBackOff
                                                                                  Asked 2022-Jan-25 at 13:54

                                                                                  I'm using microk8s on Ubuntu but I have a problem wiht the coredns pod which fails to start and I suspect thats giving me other pods issues.

                                                                                  The Pod is showing a staut of CrashLoopBackOff whe running get pods

                                                                                  Here is the Describe of the pod:

                                                                                  Name:                 coredns-86f78bb79c-bdt7t
                                                                                  Namespace:            kube-system
                                                                                  Priority:             2000000000
                                                                                  Priority Class Name:  system-cluster-critical
                                                                                  Node:                 chwc21ubtu/10.2.2.10
                                                                                  Start Time:           Tue, 25 Jan 2022 09:35:45 +0000
                                                                                  Labels:               k8s-app=kube-dns
                                                                                                        pod-template-hash=86f78bb79c
                                                                                  Annotations:          cni.projectcalico.org/podIP: 10.1.249.135/32
                                                                                                        cni.projectcalico.org/podIPs: 10.1.249.135/32
                                                                                                        scheduler.alpha.kubernetes.io/critical-pod:
                                                                                  Status:               Running
                                                                                  IP:                   10.1.249.135
                                                                                  IPs:
                                                                                    IP:           10.1.249.135
                                                                                  Controlled By:  ReplicaSet/coredns-86f78bb79c
                                                                                  Containers:
                                                                                    coredns:
                                                                                      Container ID:  containerd://045a0cdd5d6e1b736f9f7469a189cbbc2c87df56c2af62bcdc825eda0aa3719c
                                                                                      Image:         coredns/coredns:1.6.6
                                                                                      Image ID:      docker.io/coredns/coredns@sha256:41bee6992c2ed0f4628fcef75751048927bcd6b1cee89c79f6acb63ca5474d5a
                                                                                      Ports:         53/UDP, 53/TCP, 9153/TCP
                                                                                      Host Ports:    0/UDP, 0/TCP, 0/TCP
                                                                                      Args:
                                                                                        -conf
                                                                                        /etc/coredns/Corefile
                                                                                      State:          Waiting
                                                                                        Reason:       CrashLoopBackOff
                                                                                      Last State:     Terminated
                                                                                        Reason:       Error
                                                                                        Exit Code:    1
                                                                                        Started:      Tue, 25 Jan 2022 11:54:55 +0000
                                                                                        Finished:     Tue, 25 Jan 2022 11:54:55 +0000
                                                                                      Ready:          False
                                                                                      Restart Count:  32
                                                                                      Limits:
                                                                                        memory:  170Mi
                                                                                      Requests:
                                                                                        cpu:        100m
                                                                                        memory:     70Mi
                                                                                      Liveness:     http-get http://:8080/health delay=60s timeout=5s period=10s #success=1 #failure=5
                                                                                      Readiness:    http-get http://:8181/ready delay=0s timeout=1s period=10s #success=1 #failure=3
                                                                                      Environment:  
                                                                                      Mounts:
                                                                                        /etc/coredns from config-volume (ro)
                                                                                        /var/run/secrets/kubernetes.io/serviceaccount from coredns-token-rj6x7 (ro)
                                                                                  Conditions:
                                                                                    Type              Status
                                                                                    Initialized       True
                                                                                    Ready             False
                                                                                    ContainersReady   False
                                                                                    PodScheduled      True
                                                                                  Volumes:
                                                                                    config-volume:
                                                                                      Type:      ConfigMap (a volume populated by a ConfigMap)
                                                                                      Name:      coredns
                                                                                      Optional:  false
                                                                                    coredns-token-rj6x7:
                                                                                      Type:        Secret (a volume populated by a Secret)
                                                                                      SecretName:  coredns-token-rj6x7
                                                                                      Optional:    false
                                                                                  QoS Class:       Burstable
                                                                                  Node-Selectors:  
                                                                                  Tolerations:     CriticalAddonsOnly op=Exists
                                                                                                   node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                                                                                                   node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
                                                                                  Events:
                                                                                    Type     Reason   Age                     From     Message
                                                                                    ----     ------   ----                    ----     -------
                                                                                    Warning  BackOff  3m56s (x663 over 143m)  kubelet  Back-off restarting failed container
                                                                                  

                                                                                  Here is the contents of /etc/resolv/conf:

                                                                                  cat /etc/resolv.conf
                                                                                  # This file is managed by man:systemd-resolved(8). Do not edit.
                                                                                  #
                                                                                  # This is a dynamic resolv.conf file for connecting local clients to the
                                                                                  # internal DNS stub resolver of systemd-resolved. This file lists all
                                                                                  # configured search domains.
                                                                                  #
                                                                                  # Run "resolvectl status" to see details about the uplink DNS servers
                                                                                  # currently in use.
                                                                                  #
                                                                                  # Third party programs must not access this file directly, but only through the
                                                                                  # symlink at /etc/resolv.conf. To manage man:resolv.conf(5) in a different way,
                                                                                  # replace this symlink by a static file or a different symlink.
                                                                                  #
                                                                                  # See man:systemd-resolved.service(8) for details about the supported modes of
                                                                                  # operation for /etc/resolv.conf.
                                                                                  
                                                                                  nameserver 127.0.0.53
                                                                                  options edns0 trust-ad
                                                                                  search wnzgl0qq22vevmrhjm1h5bny0c.zx.internal.cloudapp.net
                                                                                  

                                                                                  Here is the contents of the logs:

                                                                                  sudo microk8s.kubectl -n kube-system logs -p coredns-86f78bb79c-bdt7t
                                                                                  plugin/forward: not an IP address or file: "reload"
                                                                                  

                                                                                  Looking atthe config maps for coreDNS it looks like there is an extra value called 'reload' thats being classified as a IP forward/file

                                                                                  # Please edit the object below. Lines beginning with a '#' will be ignored,
                                                                                  # and an empty file will abort the edit. If an error occurs while saving this file will be
                                                                                  # reopened with the relevant failures.
                                                                                  #
                                                                                  apiVersion: v1
                                                                                  data:
                                                                                    Corefile: |
                                                                                      .:53 {
                                                                                          errors
                                                                                          health {
                                                                                            lameduck 5s
                                                                                          }
                                                                                          ready
                                                                                          log . {
                                                                                            class error
                                                                                          }
                                                                                          kubernetes cluster.local in-addr.arpa ip6.arpa {
                                                                                            pods insecure
                                                                                            fallthrough in-addr.arpa ip6.arpa
                                                                                          }
                                                                                          prometheus :9153
                                                                                          forward . 8.8.8.8 8.8.4.4    reload
                                                                                          loadbalance
                                                                                      }
                                                                                  kind: ConfigMap
                                                                                  metadata:
                                                                                    annotations:
                                                                                      kubectl.kubernetes.io/last-applied-configuration: |
                                                                                        {"apiVersion":"v1","data":{"Corefile":".:53 {\n    errors\n    health {\n      lameduck 5s\n    }\n    ready\n    log . {\n      class error\n    }\n    kubernetes cluster.local in-addr.arpa ip6.arpa {\n      pods insecure\n      fallthrough in-addr.arpa ip6.arpa\n    }\n    prometheus :9153\n    forward . 8.8.8.8 8.8.4.4    reload\n    loadbalance\n}\n"},"kind":"ConfigMap","metadata":{"annotations":{},"creationTimestamp":"2022-01-25T09:35:32Z","labels":{"addonmanager.kubernetes.io/mode":"EnsureExists","k8s-app":"kube-dns"},"managedFields":[{"apiVersion":"v1","fieldsType":"FieldsV1","fieldsV1":{"f:data":{".":{},"f:Corefile":{}},"f:metadata":{"f:annotations":{".":{},"f:kubectl.kubernetes.io/last-applied-configuration":{}},"f:labels":{".":{},"f:addonmanager.kubernetes.io/mode":{},"f:k8s-app":{}}}},"manager":"kubectl-client-side-apply","operation":"Update","time":"2022-01-25T09:35:32Z"}],"name":"coredns","namespace":"kube-system","resourceVersion":"518","selfLink":"/api/v1/namespaces/kube-system/configmaps/coredns","uid":"8a73848a-4118-417b-80f5-2175bb64acc4"}}
                                                                                    creationTimestamp: "2022-01-25T09:35:32Z"
                                                                                    labels:
                                                                                      addonmanager.kubernetes.io/mode: EnsureExists
                                                                                      k8s-app: kube-dns
                                                                                    name: coredns
                                                                                    namespace: kube-system
                                                                                    resourceVersion: "597"
                                                                                    selfLink: /api/v1/namespaces/kube-system/configmaps/coredns
                                                                                    uid: 8a73848a-4118-417b-80f5-2175bb64acc4
                                                                                  

                                                                                  I'm lost where to look next - can anyone offer any advice?

                                                                                  ANSWER

                                                                                  Answered 2022-Jan-25 at 12:41

                                                                                  the exit code 1 signifies an application error.

                                                                                  Check this link for more information on exit codes.

                                                                                  Source https://stackoverflow.com/questions/70848427

                                                                                  QUESTION

                                                                                  MVVM WPF Add new item to the DataGrid from Textboxes which are bound to the nested properties of the Model class
                                                                                  Asked 2022-Jan-11 at 09:07

                                                                                  I am new to WPF and also the MVVM pattern, I tried to create a simple WPF project to query a database of I-Shape Steel Profiles and show it to the user through the DataGrid. After I have successfully done it, I am now moving to the next part: Letting the user to add new steel profiles to the DataGrid by filling out a set of TextBoxes.

                                                                                  Model

                                                                                  namespace SectionGuardWPF.MVVM.Model
                                                                                  {
                                                                                      public class IProfileModel : ObservableObject
                                                                                      {
                                                                                          #region Private Fields
                                                                                          public short _recno;
                                                                                          public string _name;
                                                                                          public string _staadName;
                                                                                          public double _ax;
                                                                                          public double _d;
                                                                                          public double _bf;
                                                                                          public double _tf;
                                                                                          public double _tw;
                                                                                          public double _iz;
                                                                                          public double _ix;
                                                                                          public double _ct;
                                                                                          public double _iy;
                                                                                          public double _zx;
                                                                                          public double _zy;
                                                                                          #endregion
                                                                                  
                                                                                          #region Public Properties
                                                                                          /// 
                                                                                          /// Properties are given NotifyPropertyChanged method to allow for a change in property to be notified
                                                                                          /// 
                                                                                  
                                                                                          public short RECNO
                                                                                          {
                                                                                              get { return _recno; }
                                                                                              set
                                                                                              {
                                                                                                  _recno = value;
                                                                                                  OnPropertyChanged();
                                                                                              }
                                                                                          }
                                                                                          public string Name
                                                                                          {
                                                                                              get { return _name; }
                                                                                              set
                                                                                              {
                                                                                                  _name = value;
                                                                                                  OnPropertyChanged();
                                                                                              }
                                                                                          }
                                                                                  ...
                                                                                  // Repeated for the other fields
                                                                                  

                                                                                  ObservableObject: Base class that implements INotifyPropertyChanged

                                                                                  namespace SectionGuardWPF.Core
                                                                                  {
                                                                                      public class ObservableObject : INotifyPropertyChanged
                                                                                      {
                                                                                          /// 
                                                                                          /// Raised when a property on this object has a new value.
                                                                                          /// 
                                                                                          public event PropertyChangedEventHandler PropertyChanged;
                                                                                  
                                                                                          /// 
                                                                                          /// Raises this object's PropertyChanged event.
                                                                                          /// 
                                                                                          protected void OnPropertyChanged([CallerMemberName] string name = null) // If you use the CallerMemberName attribute, calls to the NotifyPropertyChanged method don't have to specify the property name as a string argument
                                                                                          {
                                                                                              PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
                                                                                          }
                                                                                      }
                                                                                  }
                                                                                  

                                                                                  RelayCommand

                                                                                  namespace SectionGuardWPF.Core
                                                                                  {
                                                                                      class RelayCommand : ICommand
                                                                                      {
                                                                                          private Action _execute;
                                                                                          private Func _canExecute;
                                                                                  
                                                                                          public event EventHandler CanExecuteChanged
                                                                                          {
                                                                                              add { CommandManager.RequerySuggested += value; }
                                                                                              remove { CommandManager.RequerySuggested -= value; }
                                                                                          }
                                                                                  
                                                                                          public RelayCommand(Action execute, Func canExecute=null)
                                                                                          {
                                                                                              _execute = execute;
                                                                                              _canExecute = canExecute;
                                                                                          }
                                                                                  
                                                                                          public bool CanExecute(object parameter)
                                                                                          {
                                                                                              return _canExecute == null || _canExecute(parameter);
                                                                                          }
                                                                                          
                                                                                          public void Execute(object parameter)
                                                                                          {
                                                                                              _execute(parameter);
                                                                                          }
                                                                                      }
                                                                                  }
                                                                                  
                                                                                  

                                                                                  View Model

                                                                                  namespace SectionGuardWPF.MVVM.ViewModel
                                                                                  {
                                                                                      public class IProfilesViewModel:ObservableObject
                                                                                      {
                                                                                          #region Private Fields
                                                                                          private readonly string _connectionString = //Hidden
                                                                                          private ObservableCollection _iProfiles;
                                                                                          private ICommand _getIProfilesCommand;
                                                                                          private ICommand _addNewIProfileCommand;
                                                                                          private IProfileModel _iProfile = new IProfileModel();
                                                                                          #endregion
                                                                                  
                                                                                          #region Constructor
                                                                                          public IProfilesViewModel()
                                                                                          {
                                                                                              // Set default Profile Database for the DataGrid upon View instantiation
                                                                                              IProfiles = GetIProfiles();
                                                                                          }
                                                                                          #endregion
                                                                                  
                                                                                          #region Public Properties and Commands
                                                                                          /// 
                                                                                          /// Public properties of the IProfilesViewModel Class (used for view binding with IProfilesSubView)
                                                                                          /// 
                                                                                          public ObservableCollection IProfiles
                                                                                          {
                                                                                              get { return _iProfiles; }
                                                                                              set
                                                                                              {
                                                                                                  _iProfiles = value;
                                                                                                  OnPropertyChanged();
                                                                                              }
                                                                                          }
                                                                                          public IProfileModel IProfile
                                                                                          {
                                                                                              get { return _iProfile; }
                                                                                              set
                                                                                              {
                                                                                                  _iProfile = value;
                                                                                                  OnPropertyChanged();
                                                                                              }
                                                                                          }
                                                                                          public ICommand GetIProfilesCommand
                                                                                          {
                                                                                              get
                                                                                              {
                                                                                                  if (_getIProfilesCommand == null)
                                                                                                  {
                                                                                                      _getIProfilesCommand = new RelayCommand(
                                                                                                          param => GetIProfiles()
                                                                                                      );
                                                                                                  }
                                                                                                  return _getIProfilesCommand;
                                                                                              }
                                                                                          }
                                                                                          public ICommand AddNewIProfileCommand
                                                                                          {
                                                                                              get
                                                                                              {
                                                                                                  if (_addNewIProfileCommand == null)
                                                                                                  {
                                                                                                      _addNewIProfileCommand = new RelayCommand(
                                                                                                          param => AddNewIProfile()
                                                                                                      );
                                                                                                  }
                                                                                                  return _addNewIProfileCommand;
                                                                                              }
                                                                                          }
                                                                                          #endregion
                                                                                  
                                                                                          #region Private Methods
                                                                                          private ObservableCollection GetIProfiles()
                                                                                          {
                                                                                              TableDataProvider tableDataProvider = new TableDataProvider(_connectionString);
                                                                                              tableDataProvider.QueryString = "SELECT * FROM [I Shape]";
                                                                                  
                                                                                              IEnumerable iProfiles = tableDataProvider.Query();
                                                                                              ObservableCollection iProfileObsvCol = new ObservableCollection(iProfiles);
                                                                                              return iProfileObsvCol;
                                                                                          }
                                                                                  
                                                                                          private void AddNewIProfile()
                                                                                          {
                                                                                              IProfiles.Add(
                                                                                                  new IProfileModel
                                                                                                  {
                                                                                                      RECNO = IProfile.RECNO,
                                                                                                      Name = IProfile.Name,
                                                                                                      StaadName = IProfile.StaadName,
                                                                                                      AX = IProfile.AX,
                                                                                                      D = IProfile.D,
                                                                                                      Bf = IProfile.Bf,
                                                                                                      Tf = IProfile.Tf,
                                                                                                      Tw = IProfile.Tw,
                                                                                                      Ix = IProfile.Ix,
                                                                                                      Iy = IProfile.Iy,
                                                                                                      Iz = IProfile.Iz,
                                                                                                      Ct = IProfile.Ct,
                                                                                                      Zx = IProfile.Zx,
                                                                                                      Zy = IProfile.Zy
                                                                                                  }
                                                                                                  );
                                                                                          }
                                                                                  
                                                                                          #endregion
                                                                                      }
                                                                                  }
                                                                                  

                                                                                  View

                                                                                  
                                                                                  
                                                                                      
                                                                                          
                                                                                      
                                                                                  
                                                                                      
                                                                                          
                                                                                              
                                                                                              
                                                                                          
                                                                                  
                                                                                          
                                                                                  
                                                                                          
                                                                                  
                                                                                          
                                                                                              
                                                                                                  
                                                                                                      
                                                                                                      
                                                                                                      
                                                                                                  
                                                                                  
                                                                                                  
                                                                                  
                                                                                                  
                                                                                                      
                                                                                                          
                                                                                                          
                                                                                                      
                                                                                  
                                                                                                      
                                                                                                          
                                                                                                          
                                                                                                          
                                                                                                          
                                                                                                          
                                                                                                          
                                                                                                          
                                                                                                      
                                                                                  
                                                                                                      
                                                                                  
                                                                                                      
                                                                                  
                                                                                                      
                                                                                  
                                                                                                      
                                                                                  
                                                                                                      
                                                                                  
                                                                                                      
                                                                                  
                                                                                                      
                                                                                  
                                                                                                      
                                                                                  
                                                                                                      
                                                                                  
                                                                                                      
                                                                                  
                                                                                                      
                                                                                  
                                                                                                      
                                                                                  
                                                                                                      
                                                                                  
                                                                                                      
                                                                                  
                                                                                                      
                                                                                  
                                                                                                      
                                                                                  
                                                                                                      
                                                                                  
                                                                                                      
                                                                                  
                                                                                                      
                                                                                  
                                                                                                      
                                                                                  
                                                                                                      
                                                                                  
                                                                                                      
                                                                                  
                                                                                                      
                                                                                  
                                                                                                      
                                                                                  
                                                                                                      
                                                                                  
                                                                                                      
                                                                                  
                                                                                                      
                                                                                  
                                                                                                      
                                                                                                  
                                                                                  
                                                                                                  
                                                                                  
                                                                                                      
                                                                                                      
                                                                                                      
                                                                                  
                                                                                                  
                                                                                                  
                                                                                              
                                                                                          
                                                                                      
                                                                                  
                                                                                  

                                                                                  My Model class is a class called the IProfileModel that represents the I-Shape Profiles, I have made so that it inherits from the ObservableObject class so that it can use the NotifyPropertyChanged methods and I have made so that the properties of the Model class has implemented the OnPropertyChanged() Method.

                                                                                  In my View, I have bound the source of the DataGrid to the IProfiles which is an ObservableCollection that stores instances of the IProfileModel. Each TextBox corresponds to one property of the IProfileModel class, thus the Text property of each TextBox is bound to its respective nested property of the IProfile property of the ViewModel. The "Add" Button is bound to the respective ICommand in the ViewModel called the AddNewIProfileCommand

                                                                                  In my ViewModel, I have added the IProfileModel as one of its properties using the name IProfile, the TextBox.Text properties are bound to the nested properties of the IProfile as shown in the XAML of the View. As for the AddNewIProfileCommand, I have made so that it corresponds to a private method called the AddNewIProfile() which will add a new IProfileModel object whose properties will refer to the nested properties of the IProfile property that is bound to the TextBoxes.

                                                                                  Edit: I want to add that the AddNewIProfile() will add the new IProfileModel object to the IProfiles which is bound to the DataGrid

                                                                                  My main issue is that whenever I modified the TextBoxes and then clicked on the Button to add the profiles to the DataGrid, the newly added entry to the DataGrid is always a IProfileModel with empty property values (all string properties of the IProfileModel are null and all numerical type properties are 0). It seems like modifying the TextBoxes does not change the nested properties of the IProfile even though I have set the UpdateSourceTrigger to PropertyChanged and the Mode to Two Way and the IProfile itself is of the IProfileModel class which has inherited from the ObservableObject class.

                                                                                  Lastly, I know that my question is quite similar to this one but I have followed the suggestions there and tried to match their solution but I somehow can't get it to work. Thanks!

                                                                                  Edit: Added some before - after picture of the DataGrid after the "Add" Button is pressed:

                                                                                  Edit: The ParameterTextbox Style which was the cause of the error as pointed out by Cédric Moers in the comments:

                                                                                  
                                                                                  

                                                                                  ANSWER

                                                                                  Answered 2022-Jan-11 at 09:07

                                                                                  I tried to replicate your problem but I had to remove the styles since you did not provide them. It works at my side, so perhaps the problem lies within the style?

                                                                                  Please delete your styles for the textboxes (ParameterTextbox) and see if it works then. If you can provide me with the source code for the style, I can take a look at it. Maybe you are overriding the text property.

                                                                                  edit after it turned out the style was the issue

                                                                                  here is an example of the style you want to accomplish in a minimalistic way.

                                                                                  
                                                                                      
                                                                                          
                                                                                              
                                                                                          
                                                                                      
                                                                                      
                                                                                      
                                                                                      
                                                                                      ...
                                                                                      
                                                                                  
                                                                                  

                                                                                  I made the control template as a separate resource, this way 'rounded textbox' can be put inside of some 'shared' assembly, and you will be able to use it for other projects as well.

                                                                                  It is minimalistic, as in the minimal you'll need. If you want a full-fledged text box, copy the style from here and modify it: https://docs.microsoft.com/en-us/dotnet/desktop/wpf/controls/textbox-styles-and-templates?view=netframeworkdesktop-4.8 it might look scary, but most of the time it comes down to modifying only a few rules. Once you get the hang of it, it's quite easy.

                                                                                  Instead of working with the setters, and even a separate control template resource, you could hard-code everything within the control template, WITHIN the setter of the control template of the textbox style, but that's up to you.

                                                                                  Good luck!

                                                                                  Source https://stackoverflow.com/questions/70649637

                                                                                  QUESTION

                                                                                  Firestore 'await addDoc' (Web version 9) hangs forever when network connection is lost
                                                                                  Asked 2022-Jan-03 at 15:57

                                                                                  I'm using Firestore 'addDoc' (Web version 9, https://firebase.google.com/docs/firestore/manage-data/add-data) to add a new document:

                                                                                  const ref = collection(this.db, 'participants').withConverter(Participant.dataConverter);
                                                                                  const docRef = await addDoc(ref, participant);
                                                                                  

                                                                                  This works great if the network connection is OK.

                                                                                  However, if I disconnect from the internet by disabling the network adapter (Windows), 'await addDoc' seems to hang forever (it does not return, the following code lines are not executed).

                                                                                  Various network errors are continuously shown in the console for some time:

                                                                                  zone.js:1465 POST https://firestore.googleapis.com/google.firestore.v1.Firestore/Write/channe…A1%3A447623293743%3Aweb%3Aaadb8ec…%0D%0A&zx=bjcly4sf4lta&t=1 net::ERR_NAME_NOT_RESOLVED
                                                                                  index.esm2017.js:78 [2022-01-03T13:30:28.657Z]  @firebase/firestore: Firestore (9.6.1): Connection WebChannel transport errored: 
                                                                                  Vd {type: 'c', target: Y, g: Y, defaultPrevented: false, status: 1}
                                                                                  www.google.com/image…f?zx=lih9uz2upg4y:1 GET https://www.google.com/images/cleardot.gif?zx=lih9uz2upg4y net::ERR_NAME_NOT_RESOLVED
                                                                                  

                                                                                  Meanwhile 'onSnapshot' is fired and the new (obviously local) document is included in the documents list.

                                                                                  If I reconnect to the internet (by reactivating the network adapter) it takes a few seconds, then the code continues as if everything went normal.

                                                                                  Is this intended? What can I do to detect this? At least, it is not acceptable that the code stops executing...

                                                                                  Despite this issue, I will try to detect connection problems and display some kind of warning, but nevertheless 'addDoc' should either return a throw an error.

                                                                                  ANSWER

                                                                                  Answered 2022-Jan-03 at 15:57

                                                                                  This is the expected behavior: the promise from addDoc is only resolved once the write operation is completed on the server. If you don't want to wait for that, don't use await.

                                                                                  If there is a problem with the local write, addDoc will raise an exception. Only when there is a problem with the write on the server, will it reject the promise.

                                                                                  In v8 and before you could get the DocumentReference without await by using collection.doc(). See the last snippet in the documentation on adding a document for how to do this in v9 too:

                                                                                  In some cases, it can be useful to create a document reference with an auto-generated ID, then use the reference later. For this use case, you can call doc():

                                                                                  import { collection, doc, setDoc } from "firebase/firestore"; 
                                                                                  
                                                                                  // Add a new document with a generated id
                                                                                  const newCityRef = doc(collection(db, "cities"));
                                                                                  
                                                                                  // later...
                                                                                  await setDoc(newCityRef, data);
                                                                                  

                                                                                  Behind the scenes, .add(...) and .doc().set(...) are completely equivalent, so you can use whichever is more convenient.

                                                                                  Source https://stackoverflow.com/questions/70566900

                                                                                  Community Discussions, Code Snippets contain sources that include Stack Exchange Network

                                                                                  Vulnerabilities

                                                                                  No vulnerabilities reported

                                                                                  Install zx

                                                                                  Requirement: Node version >= 16.0.0.

                                                                                  Support

                                                                                  Write your scripts in a file with .mjs extension in order to be able to use await on top level. If you prefer the .js extension, wrap your scripts in something like void async function () {...}().
                                                                                  Find more information at:
                                                                                  Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
                                                                                  Find more libraries
                                                                                  Explore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits​
                                                                                  Save this library and start creating your kit

                                                                                  Share this Page

                                                                                  share link

                                                                                  Explore Related Topics

                                                                                  Consider Popular Runtime Evironment Libraries

                                                                                  Try Top Libraries by google

                                                                                  guava

                                                                                  by googleJava

                                                                                  styleguide

                                                                                  by googleHTML

                                                                                  leveldb

                                                                                  by googleC++

                                                                                  googletest

                                                                                  by googleC++

                                                                                  Compare Runtime Evironment Libraries with Highest Support

                                                                                  node

                                                                                  by nodejs

                                                                                  electron

                                                                                  by electron

                                                                                  Rocket.Chat

                                                                                  by RocketChat

                                                                                  TypeScript

                                                                                  by microsoft

                                                                                  express

                                                                                  by expressjs

                                                                                  Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
                                                                                  Find more libraries
                                                                                  Explore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits​
                                                                                  Save this library and start creating your kit