Sunday, May 2, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Using Graphics2D, when I drag the shapes, I want to move the shapes

Posted: 02 May 2021 07:45 AM PDT

When I drag the shapes that i drew, I want to move.
but I do not know how to do it...
i have tried make move method in GPanel but could not make it..
thank you for sharing your knowledge.

have been working this for almost 1 week tried all the solutions that i could think of. this is my first time of posting code question on stackoverflow. I do really want to learn. please help.. and love you all. I hope one day i could be a savior for code newbies



this is drawing page

package frame;    import java.awt.Color;  import java.awt.Graphics;  import java.awt.Graphics2D;  import java.awt.Point;  import java.awt.event.MouseEvent;  import java.awt.event.MouseListener;  import java.awt.event.MouseMotionListener;  import java.awt.event.MouseWheelEvent;  import java.awt.event.MouseWheelListener;  import java.util.Vector;    import javax.swing.JPanel;    import main.GConstants.EAnchorLocation;  import main.GConstants.EDrawingStyle;  import shapeTool.GShapeTool;    public class GPanel extends JPanel {    private static final long serialVersionUID = 1L;    private GShapeTool shapeTool;  private GShapeTool selectedShape;  private Vector<GShapeTool> shapes;    public GPanel() {      this.setBackground(Color.WHITE);        this.shapes = new Vector<GShapeTool>();        MouseHandler mouseHandler = new MouseHandler();      this.addMouseListener(mouseHandler);      this.addMouseMotionListener(mouseHandler);      this.addMouseWheelListener(mouseHandler);  }    public void initialize() {}    public Vector<GShapeTool> getShapes() {      return this.shapes;  }    public void setShapes(Vector<GShapeTool> shapes){      this.shapes = shapes;      this.updateUI();  }      public void paint(Graphics graphics) {      super.paint(graphics);      for(GShapeTool shape: this.shapes) {          shape.draw((Graphics2D)graphics);      }  }    public void setShapeTool(GShapeTool shapeTool) {      this.shapeTool = shapeTool;  }    private boolean onShape(int x, int y) {      boolean shapeCheck = false;      for(GShapeTool shapeTool: this.shapes) {          if(shapeTool.contains(x, y)) {              this.selectedShape = shapeTool;              shapeCheck = true;          } else {              shapeTool.setSelected(false, (Graphics2D)getGraphics());          }      }      if(shapeCheck) {          this.selectedShape.setSelected(true, (Graphics2D)getGraphics());      }      return shapeCheck;  }             private void setInitialPoint(int x, int y) {      this.selectedShape = this.shapeTool.clone();      this.selectedShape.setInitialPoint(x, y);  }        private void setFinalPoint(int x, int y) {      for(GShapeTool shapeTool: this.shapes) {          shapeTool.setSelected(false, (Graphics2D)getGraphics());      }        //      Graphics2D graphics2D = (Graphics2D) this.getGraphics();      //set xor mode;      //      graphics2D.setXORMode(getBackground());      this.selectedShape.setFinalPoint(x, y);      this.selectedShape.setSelected(true, (Graphics2D)getGraphics());      this.shapes.add(this.selectedShape);  }    private void setIntermediatePoint(int x, int y) {      this.selectedShape.setIntermediatePoint(x, y);    }    private void animate(int x, int y) {      Graphics2D graphics2D = (Graphics2D) this.getGraphics();      //set xor mode;      graphics2D.setXORMode(getBackground());      this.selectedShape.animate(graphics2D, x, y);  }          private class MouseHandler   implements MouseListener, MouseMotionListener, MouseWheelListener {        private boolean isDrawing;      MouseHandler() {          this.isDrawing = false;      }        @Override      public void mouseClicked(MouseEvent e) {            if(e.getButton() == MouseEvent.BUTTON1) {              if(e.getClickCount() == 1) {                  this.mouseLButton1Clicked(e);              } else if(e.getClickCount() == 2) {                  this.mouseLButton2Clicked(e);              }             } else if(e.getButton() == MouseEvent.BUTTON2) {              if(e.getClickCount() == 1) {                  this.mouseRButton1Clicked(e);              }          }      }            @Override      public void mouseMoved(MouseEvent e) {            if(isDrawing) {              if(shapeTool.getDrawingStyle() == EDrawingStyle.eNPointDrawing) {                  animate(e.getX(), e.getY());              }          }      }        private void mouseLButton1Clicked(MouseEvent e) {          if(!this.isDrawing) {               if(!onShape(e.getX(), e.getY())) {                  if(shapeTool.getDrawingStyle() == EDrawingStyle.eNPointDrawing) {                      setInitialPoint(e.getX(), e.getY());                      this.isDrawing = true;                  }              }              else if(onShape(e.getX(), e.getY())) {                  onShape(e.getX(), e.getY());              }            } else {              if(shapeTool.getDrawingStyle() == EDrawingStyle.eNPointDrawing) {                  setIntermediatePoint(e.getX(),e.getY());              }          }         }        private void mouseLButton2Clicked(MouseEvent e) {          if(this.isDrawing) {              if(shapeTool.getDrawingStyle() == EDrawingStyle.eNPointDrawing) {                  setFinalPoint(e.getX(), e.getY());                  this.isDrawing = false;              }          }      }        private void mouseRButton1Clicked(MouseEvent e) {        }        @Override      public void mousePressed(MouseEvent e) {          if(e.getButton() == MouseEvent.BUTTON1) {              if(!this.isDrawing) {                  if(shapeTool.getDrawingStyle() == EDrawingStyle.e2PointDrawing) {                      setInitialPoint(e.getX(), e.getY());                      this.isDrawing = true;                  }              }          }      }      @Override      public void mouseDragged(MouseEvent e) {          if(this.isDrawing) {              if(shapeTool.getDrawingStyle() == EDrawingStyle.e2PointDrawing) {                  animate(e.getX(), e.getY());              }          }      }        @Override      public void mouseReleased(MouseEvent e) {          if(this.isDrawing) {              if(shapeTool.getDrawingStyle() == EDrawingStyle.e2PointDrawing) {                  setFinalPoint(e.getX(), e.getY());                  this.isDrawing = false;              }          }      }        @Override      public void mouseEntered(MouseEvent e) {}      @Override      public void mouseExited(MouseEvent e) {}              @Override      public void mouseWheelMoved(MouseWheelEvent e) {}        }  }  


this is abstract class for shapes

package shapeTool;    import java.awt.Color;  import java.awt.Graphics2D;  import java.awt.Point;  import java.awt.Rectangle;  import java.awt.Shape;  import java.awt.geom.Ellipse2D;  import java.awt.geom.Ellipse2D.Double;  import java.awt.geom.Rectangle2D;  import java.io.Serializable;  import java.util.Vector;    import main.GConstants.EAnchorLocation;  import main.GConstants.EDrawingStyle;    public abstract class GShapeTool implements Serializable {    private static final long serialVersionUID = 1L;  public enum EAnchors {      x0y0,      x0y1,      x0y2,      x1y0,      x1y2,      x2y0,      x2y1,      x2y2,      RR;  }    public final static int wAnchor = 10;  public final static int hAnchor = 10;    private EDrawingStyle eDrawingStyle;    protected boolean isSelected;    protected Shape shape;  private Ellipse2D[] anchors;    public GShapeTool(EDrawingStyle eDrawingStyle) {      this.eDrawingStyle = eDrawingStyle;      this.isSelected = false;      this.anchors = new Ellipse2D.Double[EAnchors.values().length];      for(EAnchors eAnchor: EAnchors.values()) {          this.anchors[eAnchor.ordinal()] = new Ellipse2D.Double();      }  }    public EDrawingStyle getDrawingStyle() {      return this.eDrawingStyle;  }    public boolean contains(int x, int y) {      return this.shape.contains(x , y);  }    private void drawAnchors(Graphics2D graphics2D) {      // draw bounding rectangle      Rectangle rectangle = this.shape.getBounds();      int x0 = rectangle.x-wAnchor;      int x1 = rectangle.x + rectangle.width/2;      int x2 = rectangle.x + rectangle.width;      int y0 = rectangle.y-hAnchor;      int y1 = rectangle.y + rectangle.height/2;      int y2 = rectangle.y + rectangle.height;        this.anchors[EAnchors.x0y0.ordinal()].setFrame(x0,y0,wAnchor,hAnchor);      this.anchors[EAnchors.x0y1.ordinal()].setFrame(x0,y1,wAnchor,hAnchor);      this.anchors[EAnchors.x0y2.ordinal()].setFrame(x0,y2,wAnchor,hAnchor);      this.anchors[EAnchors.x1y0.ordinal()].setFrame(x1,y0,wAnchor,hAnchor);      this.anchors[EAnchors.x1y2.ordinal()].setFrame(x1,y2,wAnchor,hAnchor);      this.anchors[EAnchors.x2y0.ordinal()].setFrame(x2,y0,wAnchor,hAnchor);      this.anchors[EAnchors.x2y1.ordinal()].setFrame(x2,y1,wAnchor,hAnchor);      this.anchors[EAnchors.x2y2.ordinal()].setFrame(x2,y2,wAnchor,hAnchor);      this.anchors[EAnchors.RR.ordinal()].setFrame(x1,y0-50,wAnchor,hAnchor);      //draw anchors      graphics2D.setColor(Color.BLACK);      for(EAnchors eAnchor: EAnchors.values()) {          graphics2D.draw(this.anchors[eAnchor.ordinal()]);      }  }    private void eraseAnchors(Graphics2D graphics2D) {      graphics2D.setColor(Color.WHITE);      for(EAnchors eAnchor: EAnchors.values()) {          graphics2D.draw(this.anchors[eAnchor.ordinal()]);      }         }    public void setSelected(boolean isSelected, Graphics2D graphics2D) {      if(this.isSelected) {          if(!isSelected) {              //erase              this.eraseAnchors(graphics2D);          }        } else {          if(isSelected) {              //draw              this.drawAnchors(graphics2D);          }        }      this.isSelected = isSelected;  }    public void draw(Graphics2D graphics) {      graphics.draw(this.shape);    }    public void animate(Graphics2D graphics2d, int x, int y) {      //erase;      this.draw(graphics2d);      //      //move point      this.movePoint(x,y);      //      //draw;      this.draw(graphics2d);  }    //interface  public abstract GShapeTool clone();    public abstract void setInitialPoint(int x, int y);    public abstract void setFinalPoint(int x, int y);    public abstract void setIntermediatePoint(int x, int y);    public abstract void movePoint(int x, int y);  }  


and this is shape class that extends GShapeTool

package shapeTool;    import java.awt.Graphics2D;  import java.awt.Rectangle;    import main.GConstants.EDrawingStyle;    public class GRectangle extends GShapeTool {  //attributes  private static final long serialVersionUID = 1L;  //components  //constructor  public GRectangle() {      super(EDrawingStyle.e2PointDrawing);      this.shape = new Rectangle();  }    @Override  public GShapeTool clone() {      GShapeTool cloned = new GRectangle();      return cloned;  }  // methods  @Override  public void setInitialPoint(int x, int y) {      Rectangle rectangle = (Rectangle) this.shape;      rectangle.setLocation(x, y);      rectangle.setSize(0, 0);  }    @Override  public void setIntermediatePoint(int x, int y) {      // TODO Auto-generated method stub        }    @Override  public void setFinalPoint(int x, int y) {  }    @Override  public void movePoint(int x, int y) {      Rectangle rectangle = (Rectangle) this.shape;      rectangle.setSize(x-rectangle.x, y-rectangle.y);      }  }  

Use an arraylist multiple times inside different parts of JAVA code

Posted: 02 May 2021 07:45 AM PDT

I am using an array list to store values from user input by constructing an interactive menu for them to choose. My two choices so far, provides the user to input data to the list and to read the whole content of a list. The code I created so far consists of two classes.

My main class,

package com.andrekreou;    import java.util.ArrayList;  import java.util.Scanner;    public class Main {        public static void main(String[] args) {          System.out.println("Welcome to the personnel address book");          System.out.println("In the following menu, a whole selection of services is provided");          Scanner user_input = new Scanner(System.in);          while (true){              showMenu();              String selection = user_input.next();                if (selection.equals("1")){                  System.out.println("Below you can see all of the data being provided");                    for (String personnel : catalog) { }  //ERROR: Cannot resolve symbol catalog                }else if (selection.equals("2")){                  ArrayList<String> catalog = new ArrayList<>();                  Personnel p1 = new Personnel();                  System.out.println("Please insert the data for the new contact");                    System.out.println("Input the fullname:");                  Scanner scan = new Scanner(System.in);                  String full_name = scan.nextLine();                  p1.setFull_name(full_name);                  catalog.add(full_name);                  System.out.println("You inserted the following fullname: "+p1.getFull_name());                    System.out.println("Input the phonenumber:");                  Scanner phone_number_input = new Scanner(System.in);                  String phone_number = phone_number_input.next();                  p1.setPhone_number(phone_number);                  catalog.add(phone_number);                  System.out.println("You inserted the following phonenumber: "+p1.getPhone_number());                    System.out.println("Input the address:");                  Scanner address_input = new Scanner(System.in);                  String address = address_input.nextLine();                  p1.setAddress(address);                  catalog.add(address);                  System.out.println("You inserted the following address: "+p1.getAddress());                    System.out.println("Εισάγετε την διεύθυνση e-mail:");                  Scanner email_input = new Scanner(System.in);                  String email = email_input.next();                  p1.setEmail(email);                  catalog.add(email);                  System.out.println("You inserted the following e-mail: "+p1.getEmail());                    System.out.println("Εισάγετε την ημερομηνία γέννησης:");                  Scanner date_of_birth_input = new Scanner(System.in);                  String date_of_birth = date_of_birth_input.nextLine();                  p1.setDate_of_birth(date_of_birth);                  catalog.add(date_of_birth);                  System.out.println("You inserted the following: "+p1.getDate_of_birth());                    System.out.println("Εισάγετε τον αριθμό ΑΜΚΑ:");                  Scanner AMKA_input = new Scanner(System.in);                  String AMKA = AMKA_input.next();                  p1.setAMKA(AMKA);                  catalog.add(AMKA);                  System.out.println("You inserted the following ΑΜΚΑ: "+p1.getAMKA());                }          }      }      static void showMenu(){          System.out.println("1. View the whole contacts");          System.out.println("2. Insert a new contact");          System.out.println("Please give your choice");      }  }    

and my personnel class with getter and setter methods in order to store the data from user input,

package com.andrekreou;    import java.io.Serializable;    public class Personnel implements Serializable {      private String full_name;      private String phone_number;      private String address;      private String email;      private String date_of_birth;      private String AMKA;        public String getFull_name() {          return full_name;      }        public void setFull_name(String full_name) {          this.full_name = full_name;      }        public String getPhone_number() {          return phone_number;      }        public void setPhone_number(String phone_number) {          this.phone_number = phone_number;      }        public String getAddress() {          return address;      }        public void setAddress(String address) {          this.address = address;      }        public String getEmail() {          return email;      }        public void setEmail(String email) {          this.email = email;      }        public String getDate_of_birth() {          return date_of_birth;      }        public void setDate_of_birth(String date_of_birth) {          this.date_of_birth = date_of_birth;      }        public String getAMKA() {          return AMKA;      }        public void setAMKA(String AMKA) {          this.AMKA = AMKA;      }  }  

My problem is that I want to use the catalog list in option 1 using a foreach loop but I can't since I am getting a "Cannot resolve symbol catalog" error as showing in the code. What am I doing wrong?

Docker image: cardano-node: Network.Socket.bind: does not exist

Posted: 02 May 2021 07:45 AM PDT

Running the latest docker image returns

cardano-node: Network.Socket.bind: does not exist  

asp modal popup closes immediately when running it from user control

Posted: 02 May 2021 07:45 AM PDT

I have a user control that contains a confirm button extender and a modal popup extender. It looks like:

<asp:Panel ID="panelConfirmBox" runat="server" Style="display:none;">        <asp:Button ID="btnConfirmSelection" runat="server" CssClass="hidden"/>        <asp:Button ID="btnNo" runat="server" Text="No" />      <asp:Button ID="btnYes" runat="server" Text="Yes" />                  <asp:ModalPopupExtender Id="popupConfirmBox" runat="server" PopupControlID="panelConfirmBox"  CancelControlID="btnNo" OkControlId="btnYes"  />  <asp:ConfirmButtonExtender ID="btnConfirm" runat="server" DisplayModalPopupID="popupConfirmBox"/>     </asp:Panel>     

The user control gets a dropdownlist. When changing the dropdownlist selection, the button onclick event should run. In the user control aspx.cs there is the follow code:

public string TargetControlId { set { popupConfirmBox.TargetControlID = btnConfirm.TargetControlID = btnConfirmSelection.ID; } }  public DropDownList DDL { get; set; }  public EventHandler OnClick { set { btnConfirmSelection.Click += value; } get { return OnClick; } }      protected void Page_Load(object sender, EventArgs e)  {                     if (DDL != null)         {                 string script = "$('#" + DDL.ClientID + "').on('change', function () { $('#" + btnConfirmSelection.ClientID + "').click();}); ";                 ScriptManager.RegisterStartupScript(Page, Page.GetType(), "CallChange" + ID, script, true);                          }  }  

Use the user control in aspx looks like:

<asp:DropDownList ID="ddl" runat="server" AutoPostBack="true"  />  <aa:DDLConfirmPopup runat="server" ID="ConfirmPopupSelectionChange" Title="aaa" Message="bbb" TargetControlId=""/>  

and in aspx.cs:

ConfirmPopupSelectionChange.DDL = ddl;  ConfirmPopupSelectionChange.OnClick = new EventHandler(func);    protected void func(object sender, EventArgs e)  {  }  

This is working fine, almost... The problem is that when changing the dropdownlist selection, the popup modal extender opens, but closes immediately. What can be the issue?

Thanks!

DTO Validation in AWS Lambda

Posted: 02 May 2021 07:45 AM PDT

I have a POST endpoint that i have exposed through API Gateway and behind it , AWS lambda is handling it.

This post enpoint is taking an CustomerDTO as body. { "customerCity": "NewYork", "customerFirstName": "John", "customerLast": "Marshal" }

Now since we can handle the DTO validation in spring boot by predefined annotation or by creating customer exception handler.

How can i do the same in AWS Lambda, should i create all those exception handler in lambda code as well to throw customer error message.

If i do so, lambda's size won't get increased or is this the right approach..?

What would be the correct way to achieve this.

Oracle SQL assign if less than configured parameter

Posted: 02 May 2021 07:45 AM PDT

I have the below 2 tables:

assigned

VK PC A B RANK
VK1 PC1 A1 null 1
VK2 PC1 A1 A2 2
VK3 PC1 A2 null 3
VK4 PC1 A2 null 4
VK5 PC1 null A1 5
VK6 PC1 null A2 6

res

PC A MAXI
PC1 A1 2
PC1 A2 2

I would like to have the below desired output, based on this logic:

  1. If B!=A, then assign B to C if the sum of the value in B in the preceding rows order by rank is less than 'MAXI' in table res for that 'PC' and 'A'. If B=A or B is null, assign A to C.
  2. After updating column A with the logic in point 1, if the count of any 'A's is less than 'MAXI' in table res, updating the first null value to that 'A' until the count of 'A's is equal than 'MAXI' in res. Similarly, if the count of 'A's exceed 'MAXI' for any of the 'A's, set C to null the lowest assigned ranks until the condition is met.

Desired output:

VK PC A B RANK C
VK1 PC1 A1 null 1 A1
VK2 PC1 A1 A2 2 A2
VK3 PC1 A2 null 3 A2
VK4 PC1 A2 null 4 A1
VK5 PC1 null A1 5 null
VK6 PC1 null A2 6 null

NOTE: row 4 was assigned to A1 instead of A2 because row 2 had to be assigned to A2 and thus row 4 exceeded the quota for A2. Quota for A1 was still 1 (less than 2), so could be assigned to A1. For row 5, there were already 2 A1s assigned (row 1 and 4), so the quota was exceeded and C had to be null.

check min value for all unique entries

Posted: 02 May 2021 07:45 AM PDT

I have a dataset that looks like this:

datetime                    session_id  2020-01-22 11:57:09.286 UTC 5  2020-01-22 11:57:02.303 UTC 6  2020-01-22 11:59:02.303 UTC 5  

I want to create a new data set out of it such that for each unique session id, the minimum date time value is selected. So, for example, out of the first and third rows, the third row is deleted while the first one stays. How can I achieve this?

Is there an In-range statement in C#?

Posted: 02 May 2021 07:45 AM PDT

Imagine this - You have an int variable "x" that stores the value 32. How do I make some code get executed x times? (x is the variable)

How to plot multiple lines in one plotly chart from same column from the same pandas dataframe?

Posted: 02 May 2021 07:44 AM PDT

I have the following df as pandas:

Name        X           Y              Location number    Ford        651536.216  4767758.137    250  Ford        651485.4353 4767685.615    161.4  Chevrolet   651536.791  4767758.958    251  Chevrolet   651542.525  4767767.147    261  Golf        651579.0758 4767819.347    324.7  Golf        651543.8153 4767768.99     263.2  Toyota      651579.0758 4767819.347    324.7  Toyota      651590.676  4767835.914    344.9  Renault     651513.011  4767674.872    26.97  Renault     651511.373  4767676.018    24.5  ...  

I have over hundred manufacturers name in a name column. I want to plot all the manufacturers in one plot using line chart.

df_1 = df[df['Name'] == 'Ford']    df_2 = df[df['Name'] == 'Chevrolet']    df_3 = df[df['Name'] == 'Golf']    df_4 = df[df['Name'] == 'Toyota']    df_5 = df[df['Name'] == 'Renault']  

I was able to achieve what I wanted by individually pointing manufacturers name from df and saving it to new df.

df_sorted1 = df_1.sort_values('Location number')  .  .  df_sorted6 = df_5.sort_values('Location number')    fig.add_trace(go.Scatter(x=df_1 ['x'], y=df_1 ['y'], mode='lines'))  fig.add_trace(go.Scatter(x=df_2 ['x'], y=df_2 ['y'], mode='lines'))  fig.add_trace(go.Scatter(x=df_3 ['x'], y=df_3 ['y'], mode='lines'))  fig.add_trace(go.Scatter(x=df_4 ['x'], y=df_4 ['y'], mode='lines'))  fig.add_trace(go.Scatter(x=df_5 ['x'], y=df_5 ['y'], mode='lines'))  

What I want is to plot every manufacturers from one column. X, Y is coordinates and location number is sorted because I want to start plotting from first location to latest

Dynamic requires in nodejs before module.exports

Posted: 02 May 2021 07:44 AM PDT

I have an app I'm working on that has active directory login and local login. When checking for permissions I want to allow permissions to either be set by AD group membership, or if not using AD then locally stored permissions in the database. As a result I have 2 different modules to handle permission checks. Is there a way to have a require at the top, before module.exports to be done dynamically through an if statement or something similar? I thought I could assign a process.env.isLocal and process from there but it doesn't seem to work I get an error that says Permissions is not defined

const moment = require('moment');  const AdminPortal = require('../models/adminportal');  if(process.env.isLocal) {      const Permissions = require('../models/localLogin/localPermissions');  } else {      const Permissions = require('../models/permissions');  }  const isAuthenticated = require("../config/middleware/isAuthenticated");  const config = require("../config/configFile.js").get(process.env.NODE_ENV.trim());  module.exports = function(app){  

I suppose maybe I need to have both code sets in one file and then choose which one to use based on if its a local login or not, I was just hoping to keep them separated.

Find xpath of an element using text

Posted: 02 May 2021 07:45 AM PDT

<div class="css-ki-menu">  <div class="css-11ur">  <div class="css-d0i-option" id="react-select-3-option-0" tabindex="-1">L3</div>  <div class="css-f5s-option" id="react-select-3-option-1" tabindex="-1">L4</div>  </div>  </div>  

I have the text 'L3' is there any way to find the relative xpath using the text?

Please help me out am new to it

Thank you

Jquery collision: draggable and target collision event

Posted: 02 May 2021 07:45 AM PDT

I am using jquery collision with draggable. I have code working to change the color of the target (the larger box) on drop. However, I would like it to change color as soon as the dragMe touches it.

Thanks in advance for your help!

Here's the code: https://jsfiddle.net/rebeccaoutofourmindsstudios/mgL968x4/2/

$(".dragMe").draggable({      obstacle: ".obstacle",      preventCollision: true,      containment: "#moveInHere"  });    $(".obstacle").draggable({      obstacle: ".dragMe",      preventCollision: true,      containment: "#moveInHere"  });    $(document).ready(function() {    $("#dragMe").draggable({ containment: ".moveInHere", obstacle: ".obstacle" });    $("#obstacle").draggable({ containment: ".moveInHere" });    $("#Target1").droppable({      tolerance: "touch",      preventCollision: true,      drop: dropItem    });    });    function dropItem(ev, ui) {      $("#Target1").css({ background: "blue" });      }
#moveInHere {      with: 500px;      height: 500px;      border: 1px solid black;      background: #eee;  }  .dragMe{      width: 50px;      height: 50px;      border: 1px solid black;      background: #eee;  }  .obstacle{      width: 50px;      height: 50px;      border: 1px solid black;      background: #eee;  }  .target{      postition: absolute;      top:100px;      left:200px;      width: 100px;      height: 100px;      border: 1px solid black;      background: #eee;  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>  <!DOCTYPE html>  <html>  <head>    <meta http-equiv="content-type" content="text/html; charset=UTF-8">    <title></title>    <meta http-equiv="content-type" content="text/html; charset=UTF-8">    <meta name="robots" content="noindex, nofollow">    <meta name="googlebot" content="noindex, nofollow">    <meta name="viewport" content="width=device-width, initial-scale=1">        <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>      <script type="text/javascript" src="//code.jquery.com/ui/1.8.18/jquery-ui.min.js"></script>      <link rel="stylesheet" type="text/css" href="/css/result-light.css">    <script type="text/javascript" src="http://eruciform.com/static//jquidragcollide/jquery-collision.js"></script>  <script type="text/javascript" src="http://eruciform.com/static//jquidragcollide/jquery-ui-draggable-collision.js"></script>  </head>      <body>      <div class="moveInHere" id="moveInHere">          <div class="dragMe" id="dragMe">Drag me...</div>          <div class="obstacle" id="obstacle">...but not in here.</div>          <div class="target" id="Target1">I want to change color</div>      </div>

Print the sentences with least number of vowels in R

Posted: 02 May 2021 07:45 AM PDT

I have a long set of sentences and I need to print the sentences with the least number of vowels. Use the following code I found the least number of vowels, there are several sentences with that least number of vowels. When I use str_view_all to display the sentences I need to use a pattern in the argument. If I do it the following way, it only displays 1 sentence.

sentences[min(str_count(sentences, "[aeiou]"))]  

Put string on byte-like object in python

Posted: 02 May 2021 07:45 AM PDT

I have a problem with concatenating two encoded strings in python. Below string is which I want to have after concatenating :

a = b"\x50\x02\x00\x00\x00\x00\x97\x15\x0d\x00\x00\x00\x00\x00\x00\x8d\x0a"  

But i want to dynamicly append \x97\x15 part of string to it, my solution is like below:

def convert(deviceId):          return r"\x{}\x{}".format(str(hex(int(deviceId))).replace("0x", "")[2:].strip(), str(hex(int(deviceId))).replace("0x", "")[:2].strip())    b = "\x50\x02\x00\x00\x00\x00{}\x0d\x00\x00\x00\x00\x00\x00\x8d\x0a".format(convert(5527))  

but this a and b variables are not the same, i calculate the hash of a and b and they are not the same. How can I fix this? The convert() function is used to convert a number to hex and reverse each piece of the hex, for example, the hex of 5527 is 0x1597 and I should receive \x97\x15 in this function and put it in the middle of the string a. is there another way to convert 5527 to \x97\x15 and put it in the middle of the string a?

check if there is anything next to the item in board (2D array)

Posted: 02 May 2021 07:44 AM PDT

Hey I'm making simple console game in C++. We have pawns on board (I made it using 2D dynamic array). I want to check if something there is space to move our pawn. My idea is to check if is something on fields: (x-1,y), (x, y+1) , (x+1, y) , (x, y-1). But our pawn can be at the corner of board e.g. (0,0). Is it possible to avoid any error for go out of memory? (when we will check array[-1][0] it should throw error) Or rather not avoid but control. Consciously try check array[-1][0]. Otherwise I will have to check if pawn is on corner, or next to wall etc.

Apache rewrite rules not working for mqipt

Posted: 02 May 2021 07:44 AM PDT

I am using apache httpd for setting mqipt. Using the details given in docs, https://www.ibm.com/docs/en/ibm-mq/9.2?topic=thru-apache-rewrite, I have setup everything. I am not using IBM caching proxy. Hit are going to IBM MQ but getting error

----- amqrmrsa.c : 974 --------------------------------------------------------  05/02/21 13:48:10 - Process(19315.2426) User(mqm) Program(amqrmppa)                      Host(ibmmq-55ddff666-cscrk) Installation(Installation1)                      VRMF(9.2.0.0) QMgr(QM1)                      Time(2021-05-02T13:48:10.169Z)                      RemoteHost(10.244.1.1)                      CommentInsert1(_gateway (10.244.1.1))                      CommentInsert2(TCP/IP)                      CommentInsert3(DEV.APP.SVRCONN)    AMQ9209E: Connection to host '_gateway (10.244.1.1)' for channel  'DEV.APP.SVRCONN' closed.    EXPLANATION:  An error occurred receiving data from '_gateway (10.244.1.1)' over TCP/IP.  The  connection to the remote host has unexpectedly terminated.    The channel name is 'DEV.APP.SVRCONN'; in some cases it cannot be determined  and so is shown as '????'.  ACTION:  Tell the systems administrator.  ----- amqcccxa.c : 2730 -------------------------------------------------------  05/02/21 13:48:10 - Process(19315.2426) User(mqm) Program(amqrmppa)                      Host(ibmmq-55ddff666-cscrk) Installation(Installation1)                      VRMF(9.2.0.0) QMgr(QM1)                      Time(2021-05-02T13:48:10.170Z)                      CommentInsert1(DEV.APP.SVRCONN)                      CommentInsert2(19315)                      CommentInsert3(10.244.1.1)    AMQ9999E: Channel 'DEV.APP.SVRCONN' to host '10.244.1.1' ended abnormally.    EXPLANATION:  The channel program running under process ID 19315 for channel  'DEV.APP.SVRCONN' ended abnormally. The host name is '10.244.1.1'; in some  cases the host name cannot be determined and so is shown as '????'.  ACTION:  Look at previous error messages for the channel program in the error logs to  determine the cause of the failure. Note that this message can be excluded  completely or suppressed by tuning the "ExcludeMessage" or "SuppressMessage"  attributes under the "QMErrorLog" stanza in qm.ini. Further information can be  found in the System Administration Guide.  ----- amqrmrsa.c : 974 --------------------------------------------------------  

This looks like problem between mqipt2 to IBM MQ server.

I have also tried by removing apache httpd and sending message from application to mqipt1 -> mqipt2 -> IBM MQ, and it is working but only when I am using apache httpd from mqipt1 -> apache -> mqipt2 -> IBM MQ then it fails

Mimic Permutations Counter

Posted: 02 May 2021 07:45 AM PDT

With a given number with no repeating digits, I want to add the correct amount to get to the next number that has no repeating digits it it. This may be as simple as adding 1, or adding hundreds as it gets complex when the given number is high. Examples of numbers with repeating digits in them are 11, 345675, 4335, 24364. Examples of numbers with no repeating digits are 12, 735691, 89, 623490.

An interesting point to make is that there will never be more than 2 repeating digits in a number when caught as soon as it repeats, nor will multiple sets of repeating digits. For example, numbers 1232, 654334, 765661 will never come up.

Some conditions I do not want to occur. I do not want there to be loops counting up and just returning numbers that have no repeating digits. I want the program to be able to take a number with no repeating digits and know how many to add by dissecting and evaluating the number.

An example of what I do not want. This just loops until it detects a number with no repeating digits.

start = 532461 # given number    while True:      start += 1        if len(set(str(start))) >= len(str(start)):          print(start)          break  

This will print 532467, the next number with no repeating digits.

Another thing I do not want the program to do is real permutations, or rearranging the order of items in a list of numbers and cobbling together numbers from that. I call this mimic permutations because it should give similar outputs as permutations, but function differently.

This program should (in my thought of it, that may be wrong) pass the given number into a function, do whatever is needed to know how much to add to the given number to get to the next number with no repeating digits, or add as it figures out what is needed but preferably added in one shot, and end. The program may iterate through the place values of the number, or change the number to a string, or dissect it in a list or whatever is needed. The same algorithm will need to work from single digits to 10 digit numbers.

An example without the function. (the most important part)

number = 231  mimicPermutations(number)  print(number)    >> 234  

This very well may not be possible or be really really complicated, but I'm not looking for the fastest or most practical way to do this. Please ask clarifying questions or comment if you don't know what I'm trying to explain and if possible what you don't understand about it and I will edit my explanation accordingly.

There are 3 rules that come closest to what I want to do. Using the given number plus 1 to detect repeating digits:

  1. If there are no conflicts, add 1.

  2. If a non-zero conflict in digits is detected, determine the lowest place value in which the conflict occurs.

  3. If there are no other conflicts in digits, but there is a conflict with zeros, add 1.

The input 5850 will detect to add 1 to the tens place. 91235264 will detect to add 1 to the hundreds place, giving 91235364, then again to give 91235464, then again to give 91235564, then again to give 91235664, then again to finally give 91235764.

The input 6598, plus one is 6599, which has repeating digits. Taking the lowest value place digit of where the non-zero conflict occurs, which is the ones place, the program adds 1. Then the output is 6600. The program then sees that there is a non-zero conflict with the thousands place and the hundreds place, and 1 to the hundreds place. The output is 6700. Then, there being no non-zero conflicts, the program adds 1, to finally give 6701. This method only adds 1 to a determined value place at a time, and as the example shows, does not skip all repeating digit numbers at once.

This question is not about using the most efficient method or way of accomplishing the desired output.

Checks whether an object already exists or not firebase firestore

Posted: 02 May 2021 07:44 AM PDT

I am implementing an add ticket sale function

My db includes User->uid->{name:abc,...., ticketSale:[{uidTicket: abcxyz, use: true //or false }]} Ticket->uidTicket->{nameTicket: qwer, ......}

User will take the list Ticket(table Ticket) and add them into User's ArrayTicket

The problem is check uidTicket already exist in User's ArrayTicket?

The code below that i know:

  firebase.firestore().collection("user").doc(Fire.shared.uid).update({ Ticket: firebase.firestore.FieldValue.arrayUnion(uid) }).then(() => {        alert('Get success')      });  

this code is usefull if ArrayTicket is Array uid, it can check uidTicket is already exist then can add or not

but myProblem is ArrayObject and how can i check UID ticket inside User's arrayTicket?

How to improve the speed of merkle root calculation?

Posted: 02 May 2021 07:44 AM PDT

My implementation in Python calculates the merkle root hash for ~1500 input hashes:

import numpy as np  from binascii import unhexlify, hexlify  from hashlib import sha256    txids = np.loadtxt("txids.txt", dtype=str)    def double_sha256(a, b):      inp = unhexlify(a)[::-1] + unhexlify(b)[::-1]      sha1 = sha256(inp).digest()      sha2 = sha256(sha1).digest()      return hexlify(sha2[::-1])      def calculate_merkle_root(inp_list):      if len(inp_list) == 1:          return inp_list[0]      out_list = []      for i in range(0, len(inp_list)-1, 2):          out_list.append(double_sha256(inp_list[i], inp_list[i+1]))      if len(inp_list) % 2 == 1:          out_list.append(double_sha256(inp_list[-1], inp_list[-1]))      return calculate_merkle_root(out_list)    for i in range(1000):      merkle_root_hash = calculate_merkle_root(txids)    print(merkle_root_hash)  

Since the merkle root is calculated 1000 times, it takes ~5ms for one calculation:

$ time python3 test.py   b'289792577c66cd75f5b1f961e50bd8ce6f36adfc4c087dc1584f573df49bd32e'    real    0m5.132s  user    0m5.501s  sys     0m0.133s  

How could I improve the speed of the calculation? Can this code be optimized?

So far, I have tried to unroll the recursive function in Python and C++. However, the performance did not increase, it took ~6ms.

EDIT

The file is available here: txids.txt

EDIT 2

Due to the suggestion in a comment, I removed the unnecessary steps of unhexlify and hexlify. Before the loop the list is prepared once.

def double_sha256(a, b):      inp = a + b      sha1 = sha256(inp).digest()      sha2 = sha256(sha1).digest()      return sha2    def map_func(t):      return unhexlify(t)[::-1]  txids = list(map(map_func, txids))    for i in range(1000):      merkle_root_hash = calculate_merkle_root(txids)      merkle_root_hash = hexlify(merkle_root_hash[::-1])  

Now the execution is ~4ms:

$ time python3 test2.py   b'289792577c66cd75f5b1f961e50bd8ce6f36adfc4c087dc1584f573df49bd32e'    real    0m3.697s  user    0m4.069s  sys     0m0.128s  

firebase.auth().onAuthStateChanged called on every tab change

Posted: 02 May 2021 07:45 AM PDT

I am using firebase with ionic 5. I can see that each time that I navigate to another tab then I can see that firebase.auth().onAuthStateChanged called on each time.

My code is :

React.useEffect(() => {    isLogin();  }, []);    const isLogin = async () => {    var unsubscribe = firebase.auth().onAuthStateChanged(async (user) =>{      if (user) {        const store = new Storage();        await store.create();        const eventId = await store.get('eventId');        const sendSms = await store.get('sendSms');        const userContext: any = {          uid: user.uid,          eventId: eventId,          sendSms: sendSms,        };          setContext(userContext);        setShowLoader(false)        } else {        setShowLoader(false)        setContext(undefined);        }    });  }  return (    <Context.Provider value={[context, setContext]}>      <IonApp>      <IonLoading        cssClass='my-custom-class'           isOpen={showLoader}        message={'Please wait...'}        duration={5000}      />       {context?.uid ?            <IonTabs>          <IonRouterOutlet>            <Route path='/tabs/guests' component={Dashboard} exact />            <Route path='/tabs/tables' component={Tables} exact />            <Route path='/tabs/settings' component={Settings} exact />              </IonRouterOutlet>          <IonTabBar slot='bottom'>            <IonTabButton tab='guests' href='tabs/guests'>              <IonLabel>אורחים</IonLabel>            </IonTabButton>            <IonTabButton tab='tables' href='tabs/tables'>              <IonLabel>שולחנות</IonLabel>            </IonTabButton>            <IonTabButton tab='settings' href='tabs/settings'>              <IonLabel>הגדרות</IonLabel>            </IonTabButton>          </IonTabBar>        </IonTabs>           : <LoginPage />}      </IonApp>      </Context.Provider>  )  

Would you please help me to find the reason behind calling the auth state change event handler repeatedly?

Programmatic authentication of Spring Boot application failing

Posted: 02 May 2021 07:45 AM PDT

I have a Spring Boot application that is using Spring Security to protect a web page. I am also trying to programmatically log in to that page from a test application.

The application, when running on its own, operates as it should. When someone attempts to access its web page it prompts for a username and password (using the default login page for now) and when the user enters the correct credentials.

The protected URL is:

http://localhost:8080  

The user credentials are:

username: factor3  password: testing123  

Unfortunately, when I attempt to post the credentials to my application, I am getting 401 failures.

The application posting to my page is using okhttp client (v3). It is generating an HTTP POST request to the login (in the same manner that the login page does) with the same parameters that are sent by the login page:

public void sendPostRequest()  {     RequestBody body = new FormBody.Builder()                      .add("username","factor3")                     .add("password","testing123")                      .build();         OkHttpClient client = singleClient.newBuilder()                          .readTimeout(RST_TIMEOUT,TimeUnit.SECONDS)                          .build();       Request request = new Request.Builder()                      .addHeader("Content-Type", "application/x-www-form-urlencoded")                      .addHeader("Authorization",Base64.getEncoder().encode("factor3:testing123".getBytes()).toString())                      .url("http://localhost:8080/")                      .post(body)                      .build();         try     {        Response response = client.newCall(request).execute();        if(response.isSuccessful())        {           MediaType type = response.body().contentType();                      // print out the contents of the response.        }        else        {           log.error("Post FAILED: "+response.code();        }     }     catch (IOException e)     {        e.printStackTrace();     }  }  

Note that, based on some information I got on other Stack Overflow posts, I added the "Authorization" header that is in the request builder.

Something in this code seems to fail, because I keep getting 401 unauthorized errors returned from Spring Security.

What am I doing wrong here? How can I get this to work properly?

ADDENDUM:

I have been debugging the filter chain in my Spring Boot application, looking at the BasicAuthenticationFilter class (I am currently using Basic Authentication). This filter looks for an "Authorization" header in order to process the user's credentials.

It appears that, despite the fact that I am actually adding an Authorization header in my POST request, the filter is not finding it! This appears to eventually cause the 401 failure to be returned to my test application.

Is there a problem with okHTTP posting with headers? It is looking like the header somehow gets "lost" between the time when the request is sent out and when it arrives at the BasicAuthenticationFilter...

How to override foreign key null values in django serializer?

Posted: 02 May 2021 07:45 AM PDT

I'm serializing a query set to json format using natural_keys. Reference: docs

I'm able to serialize data successfully. In case, there are any foreign keys, then I'm also able to add it's object instead of foreign key. For example:

class Parent(models.Model):      name = models.CharField()        def get_natural_keys(self):          return(                   {'name': self.name, 'pk': self.pk}          )    class Child(models.Model):      name = models.CharField()      parent = models.ForeignKey(Parent, null=True)  

And while querying data:

child = serializers.serialize('json', list(Child.objects.all()), user_natural_foreign_keys=True, use_natural_primary_keys=True)  

This will return json:

{      "model": 'proj.child'      "pk": 1,      "fields": {                  "name": "child name",                  "parent": {"id": 1, "name": "parent name"}                }  }  

Till this point every thing is fine. My issue is that when parent foreign key is null in child, it returns None in parent:

fields: {      "name": "child name",      "parent": None  }  

How I am expecting is:

fields: {      "name": "child name",      "parent": {"id": None. "name": None}  }  

How can I override the None value to another dictionary? One way is to loop through the list of dictionaries and edit it. But, I don't feel it as best one.

What is the most secure way to store authentication data when deploying an app in Heroku by GitHub repo?

Posted: 02 May 2021 07:45 AM PDT

I'm attempting to deploy a Pythonic Telegram bot from my GitHub repository using Heroku's service. Telegram's API includes an API token, which I keep as a secret in my Github repository. How could I deploy the software that was linked to GitHub and insert the app's credentials? I don't want my credentials to be included in the codebase. What is the safest and easy way to handle the situation?

Error extracting json data to plot a map using folium python

Posted: 02 May 2021 07:45 AM PDT

I'm trying to plot a choropleth map using folium and data found on the internet. When I plot the json file the map shows well, but because I only need the data for the first 6 neighborhoods, the rest of the areas included in the json file are shown in dark grey.

I'm trying to extract just the points I need so the map is plotted properly, but I have the following error: "Cannot render objects with any missing geometries: [{'coordinates': [[[[-3.705989, 40.420264],..... "

I'm new on python and plotting so I think I'm missing a step but I couldn't find how to do it anywhere. Not sure if it's because I'm extracting the data into a list and using this list to plot instead of the json file. This is the code I'm trying to use:

`!wget --quiet https://gist.githubusercontent.com/Saigesp/8ca8ca2a4ce33e8e9efe8f5752683f88/raw/81d61ae9a410a59cb512dd7b01ba9bd5c98c8380/fixed_ESP_MAD_adm6.json    import json    communities_geo = r'fixed_ESP_MAD_adm6.json'    with open(communities_geo) as f:      gj = json.load(f)    neighb_json = []  for index in range(6):      neighb_json.append(gj['features'][index]['geometry'])    restaurant_map2 = folium.Map(location=[40.416775, -3.703790], zoom_start=15)    restaurant_map2.choropleth(      geo_data=neighb_json,      data=df5_count,      columns=['Neighborhood', 'Venue Category'],      key_on='feature.properties.geometry',      fill_color='YlOrRd',       fill_opacity=0.7,       line_opacity=0.2,      legend_name='Restaurants')    restaurant_map2`  

If I use "communities_geo" in "geo_data" the map works, but I cannot make it work using partial data from the json. Would you mind helping me?

Thank you so much in advance everybody!! :)

XGBoostError: Check failed: typestr.size() == 3 (2 vs. 3) : `typestr' should be of format <endian><type><size of type in bytes>

Posted: 02 May 2021 07:44 AM PDT

I'm having a weird issue with a new installation of xgboost. Under normal circumstances it works fine. However, when I use the model in the following function it gives the error in the title.

The dataset I'm using is borrowed from kaggle, and can be seen here: https://www.kaggle.com/kemical/kickstarter-projects

The function I use to fit my model is the following:

def get_val_scores(model, X, y, return_test_score=False, return_importances=False, random_state=42, randomize=True, cv=5, test_size=0.2, val_size=0.2, use_kfold=False, return_folds=False, stratify=True):      print("Splitting data into training and test sets")      if randomize:          if stratify:              X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, stratify=y, shuffle=True, random_state=random_state)          else:              X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, shuffle=True, random_state=random_state)      else:          if stratify:              X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, stratify=y, shuffle=False)          else:              X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, shuffle=False)      print(f"Shape of training data, X: {X_train.shape}, y: {y_train.shape}.  Test, X: {X_test.shape}, y: {y_test.shape}")      if use_kfold:          val_scores = cross_val_score(model, X=X_train, y=y_train, cv=cv)      else:          print("Further splitting training data into validation sets")          if randomize:              if stratify:                  X_train_, X_val, y_train_, y_val = train_test_split(X_train, y_train, test_size=val_size, stratify=y_train, shuffle=True)              else:                  X_train_, X_val, y_train_, y_val = train_test_split(X_train, y_train, test_size=val_size, shuffle=True)          else:              if stratify:                  print("Warning! You opted to both stratify your training data and to not randomize it.  These settings are incompatible with scikit-learn.  Stratifying the data, but shuffle is being set to True")                  X_train_, X_val, y_train_, y_val = train_test_split(X_train, y_train, test_size=val_size, stratify=y_train,  shuffle=True)              else:                  X_train_, X_val, y_train_, y_val = train_test_split(X_train, y_train, test_size=val_size, shuffle=False)          print(f"Shape of training data, X: {X_train_.shape}, y: {y_train_.shape}.  Val, X: {X_val.shape}, y: {y_val.shape}")          print("Getting ready to fit model.")          model.fit(X_train_, y_train_)          val_score = model.score(X_val, y_val)                if return_importances:          if hasattr(model, 'steps'):              try:                  feats = pd.DataFrame({                      'Columns': X.columns,                      'Importance': model[-2].feature_importances_                  }).sort_values(by='Importance', ascending=False)              except:                  model.fit(X_train, y_train)                  feats = pd.DataFrame({                      'Columns': X.columns,                      'Importance': model[-2].feature_importances_                  }).sort_values(by='Importance', ascending=False)          else:              try:                  feats = pd.DataFrame({                      'Columns': X.columns,                      'Importance': model.feature_importances_                  }).sort_values(by='Importance', ascending=False)              except:                  model.fit(X_train, y_train)                  feats = pd.DataFrame({                      'Columns': X.columns,                      'Importance': model.feature_importances_                  }).sort_values(by='Importance', ascending=False)                    mod_scores = {}      try:          mod_scores['validation_score'] = val_scores.mean()          if return_folds:              mod_scores['fold_scores'] = val_scores      except:          mod_scores['validation_score'] = val_score                if return_test_score:          mod_scores['test_score'] =  model.score(X_test, y_test)                    if return_importances:          return mod_scores, feats      else:          return mod_scores  

The weird part that I'm running into is that if I create a pipeline in sklearn, it works on the dataset outside of the function, but not within it. For example:

from sklearn.pipeline import make_pipeline  from category_encoders import OrdinalEncoder  from xgboost import XGBClassifier    pipe = make_pipeline(OrdinalEncoder(), XGBClassifier())    X = df.drop('state', axis=1)  y = df['state']  

In this case, pipe.fit(X, y) works just fine. But get_val_scores(pipe, X, y) fails with the error message in the title. What's weirder is that get_val_scores(pipe, X, y) seems to work with other datasets, like Titanic. The error occurs as the model is fitting on X_train and y_train.

In this case the loss function is binary:logistic, and the state column has the values successful and failed.

How to whitelist or Safelist, attribute selectors with purgeCSS (Tailwindcss)?

Posted: 02 May 2021 07:46 AM PDT

I am trying to use a Tailwindcss RTL plugin, which generates some classes starting with [dir=rtl] or [dir=ltr]. But due to Purge CSS is removing it regardless of it's use.

How to resolve the webrtcvad.Error: Error while processing frame?

Posted: 02 May 2021 07:45 AM PDT

import glob  import scipy.io.wavfile as wav  import pandas as pd  import numpy as np  import scipy  import librosa  import webrtcvad    def get_vector(sig,rate):      vec=np.empty((1,3))      start=0      end=320        while(sig.shape[0]>=end+160):          vad = webrtcvad.Vad()          vad.set_mode(2)            res=vad.is_speech(sig[start:end].tobytes(),rate) #speech_probability          zero_crosses = np.nonzero(np.diff(sig[start:end]>0))[0].shape[0]/0.02 # zero crosses          f=scipy.fft(sig[start:end])          f0=min(np.absolute(f))                                         # f0 frequency            start=start+160          end=end+160            vec=np.vstack((vec,np.array([res,zero_crosses,f0],ndmin=2)))        mfcc_feat=librosa.feature.mfcc(sig,rate,numcep=12,winlen=0.020)[0:vec.shape[0],:]  # mfcc       fbank=librosa.feature.melspectrogram(sig,rate,nfilt=5)[0:vec.shape[0],:] # log filterbank energies       mfcc_grad=np.gradient(mfcc_feat,axis=0)                            # mfcc first derivative       final_feature=np.hstack((mfcc_feat,mfcc_grad,fbank,vec))       return final_feature      df=pd.DataFrame()  for i in range(1,6):      for file in glob.glob("Actor_0102/*.wav".format(i)):          print(file)          (sig,rate,) = librosa.load(file)        # get mfcc          mfcc_feat = librosa.feature.mfcc(sig,rate)        # get filterbank energies          fbank_feat = librosa.feature.melspectrogram(sig,rate)              final_vector=get_vector(sig,rate)          feed_dict={"Features":final_vector.astype(np.float64),"name":file.split('/')[-1].split(',')[0]}          df=df.append(feed_dict,ignore_index=True)    df.to_csv("Mfccfeatures.csv")  

I am using RAVDESS data set and getting error:

webrtcvad.Error: Error while processing frame

when I try to create features of multiple audio files and to store them in a CSV file

Why does viewport width not match the actual display width?

Posted: 02 May 2021 07:45 AM PDT

Chrome shows that my viewport width is 1280px. However, my actual display resolution is 2560x1600px. The machine I use is a 13.3 inch macbook pro. Why the viewport isn't 2560px wide? Using <meta name="viewport" content="width=device-width, initial-scale=1"> doesn't make any difference.

my display settings: enter image description here enter image description here

Actually, it's not only Chrome, Safari shows the same thing.

Adding view to bottom of layout inside a scrollview

Posted: 02 May 2021 07:46 AM PDT

So my layout looks basically like this:

<ScrollView>      <RelativeLayout>          <BunchOfViews/>          <ImageView android:layout_alignParentBottom="true"/>      </RelativeLayout>  </ScrollView>  

I have the ScrollView so all of the layout always is visible no matter the height of the screen. The problem is that on a very high screen, I still want my ImageView to be at the bottom. However, a child of a ScrollView don't seem to have a defined bottom. The View is placed at the top of the layout. How can I solve this problem in a neat way?

How do I split a string with multiple separators in JavaScript?

Posted: 02 May 2021 07:44 AM PDT

How do I split a string with multiple separators in JavaScript?

I'm trying to split on both commas and spaces, but AFAIK JavaScript's split() function only supports one separator.

No comments:

Post a Comment