Wednesday, March 23, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


How delete symbols "[" and "]" uses one metod?

Posted: 23 Mar 2022 06:16 AM PDT

I want to remove the "[" characters at the end and at the beginning of a string.

I did so

string.replaceAll("\[","").replaceAll("\]","");  

What regular expression is needed to remove both at once with one method?

EC2 Instance Vanished

Posted: 23 Mar 2022 06:16 AM PDT

We have a peculiar situation today where we see that one of our EC2 instance has disappeared from the console and we weren't sure what caused this. Cloudtrail doesn't have any terminated event against this instance-id.

The last noted cloudtrail event goes something like this

{      "eventVersion": "1.08",      "userIdentity": {          "type": "AWSService",          "invokedBy": "ec2.amazonaws.com"      },      "eventTime": "2022-03-23T05:46:40Z",      "eventSource": "sts.amazonaws.com",      "eventName": "AssumeRole",      "awsRegion": "ap-south-1",      "sourceIPAddress": "ec2.amazonaws.com",      "userAgent": "ec2.amazonaws.com",      "requestParameters": {          "roleArn": "arn:aws:iam::2************:role/ec2-instance-***********",          "roleSessionName": "i-06135ad01bb90****"      },      "responseElements": {          "credentials": {              "accessKeyId": "<redacted>",              "sessionToken": "<redacted>",              "expiration": "Mar 23, 2022, 12:01:34 PM"          }      },      "requestID": "d9882911-39e7-449b-9701-***********"",      "eventID": "0fa1b79b-08aa-48e6-8232-***********"",      "readOnly": true,      "resources": [          {              "accountId": "2************",              "type": "AWS::IAM::Role",              "ARN": "arn:aws:iam::2************:role/ec2-instance-***********"          }      ],      "eventType": "AwsApiCall",      "managementEvent": true,      "recipientAccountId": "2************",      "sharedEventID": "4b842373-e89d-438b-be3b-*********",      "eventCategory": "Management"  }  

The only thing that I can think of is either a hardware failure from AWS side or some crude command ran within the OS by some user that took the instance down. Unfortunately we dont have AWS developer support as that's quite costly.

Has anyone faced anything similar? Any leads on how i can go ahead to find the root cause?

"dotnet" command does nothing

Posted: 23 Mar 2022 06:16 AM PDT

I'm trying to install a global package through dotnet cli but the command dotnet does nothing. I don't get an error message that says the command is not found etc. but it also doesn't run.

enter image description here

Between each line, cursor inside the powershell (or command prompt) turns into Working In Background ( ) mode but after just a few seconds, it just gets into the new line without doing anything. During these few seconds, if I move the cursor outside the prompt, it goes back to regular mode. So it's doing something I guess.

What is happening here, and how can I solve this issue?


What have I already tried:

1-) Since my network is behind a proxy, I've added the proxy credentials through NPM configuration commands. (as can be seen here) (I also set the strict-ssl to false).

2-) Since it didn't do anything, I also used this method and edited the global nuget.config file. But didn't solve any problem.

3-) I tried this too, but setting the environment variable MSBuildSDKsPath seems to do nothing about my problem.

My PATH variable has these:

C:\Program Files\dotnet,
%USERPROFILE%\.dotnet\tools

I also downloaded the latest Dotnet 5.0 SDK and installed it, but nothing.

Python Schedule Threads

Posted: 23 Mar 2022 06:16 AM PDT

I have 3 threads, t1, t2, and t3

I want to start the thread each N min, For example

t1 should start randomly each [2, 4] min  t2 should start randomly each [10, 15] min  t3 should start randomly each [6, 9] min  

And here is what i have so far

def attack(number, driver, sleep_time):      # Do stuff here          sleep(randint(sleep_time[0], sleep_time[1]) * 60)      return attack(number, driver, sleep_time)    if __name__ == '__main__':      t1 = threading.Thread(target=attack, args=(1, driver, [2, 4]))      t2 = threading.Thread(target=attack, args=(2, driver, [10, 15]))      t3 = threading.Thread(target=attack, args=(3, driver, [6, 9]))      t1.start()      t2.start()      t3.start()  

I have no problem with early-stage, My problem is with long term ( 10 - 20 min )

I can't let t2 or t3 work When t1 is performing actual action ( not sleep duration )

So, I can't Use join as I will have to wait for the sleep duration.

And I have no idea how to get random involved if I removed the sleep duration from the attack function.

QUESTION:

Is there a better way than having the sleep duration, inside attack function?

Is there a way to tell other threads, "Am performing action wait for me to go to sleep"

All I want to do, Is to start all the threads that are interacting with the same element But don't work at the same time.

Any idea, suggestions, or link would be much appreciated.

Stable class with unstable property

Posted: 23 Mar 2022 06:16 AM PDT

After enabling compose metrics & reports I noticed that one of my classes is marked as stable with one of its properties as unstable:

stable class Content {    unstable val aaa: List<AAA>    stable val someString: String  }  

the class itself is marked as immutable:

@Immutable  data class Content(      val aaa: List<AAA> = emptyList(),      val someString: String = "",  )  

which I assumed would mark all of the properties as stable o.O

As for the AAA class itself is referenced from a different grade module with enabled KMP under the commonMain source set:

data class Price(      val p: P,      val d: String,      val u: String,  )    enum class P {      F, S, T,  }  

My questions are:

  1. Why @immutable would not mark this whole class as stable?
  2. Does KMP somehow interfere with the compose compiler?
  3. Are there any options for me to help the compiler?

unable to load my site after exporting into cpanel

Posted: 23 Mar 2022 06:15 AM PDT

this is my cpanel img. unable to load my site.after inspect the elements also iam unable to load it.I have a domain on cpanel that i have been using for the past three weeks. However today I logged in to the File Manager and deleted the WordPress files that were previously there (did not remove cgi-bin). I then replaced these files with another instance of the WordPress site

OpenGL triangle drawing problems

Posted: 23 Mar 2022 06:16 AM PDT

Hello can someone please help me with my opengl code? I have zero erors, but Opengl is not drawing my triangle. I was following this tutorial <https://learnopengl.com/Getting-started/Hello-Triangle > , but with that difference that i did not use vertex array objects. Can someone please help me?

#include <glad/glad.h>  #include <GLFW/glfw3.h>  #include <iostream>    void framebuffer_resize_callback(GLFWwindow* window, int width, int height) {      glViewport(0, 0, width, height);  }    const char* vertexShaderSource =  " #version 330 core \n"  "layout(location = 0) in vec3 aPos;\n"  "void main() {\n"  "   gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n"  "}\0";    const char* fragmentShaderSource =  "#version 330 core \n"  "out vec4 FragColor;\n"  "void main() {\n"  "   FragColor = vec4(1, 0.1, 0.3, 1.0);\n"  "}\0";    int main() {      glfwInit();      glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);      glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);      glfwWindowHint(GLFW_OPENGL_ANY_PROFILE, GLFW_OPENGL_CORE_PROFILE);      GLFWwindow* window = glfwCreateWindow(800, 600, "revise", NULL, NULL);      glfwMakeContextCurrent(window);      glfwSetFramebufferSizeCallback(window, framebuffer_resize_callback);      gladLoadGLLoader((GLADloadproc)glfwGetProcAddress);        //shaders      unsigned int vertexShader, fragmentShader, shaderProgram;      vertexShader = glCreateShader(GL_VERTEX_SHADER);      glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);      glCompileShader(vertexShader);      int success;      char infoLog[512];      glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);      if (!success)      {          glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);          std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;      }        fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);      glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);      glCompileShader(fragmentShader);      glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);      if (!success)      {          glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);          std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl;      }        shaderProgram = glCreateProgram();      glAttachShader(shaderProgram, vertexShader);      glAttachShader(shaderProgram, fragmentShader);      glLinkProgram(shaderProgram);      glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);      if (!success) {          glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);          std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl;      }      glDeleteShader(vertexShader);      glDeleteShader(fragmentShader);        // triangle & buffers      float vertices[]      {        -0.5f, -0.5f, 0.0f,         0.5f, -0.5f, 0.0f,         0.0f,  0.5f, 0.0f,      };          unsigned int vbo;      glGenBuffers(1, &vbo);      glBindBuffer(GL_ARRAY_BUFFER, vbo);      glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3*sizeof(float), (void*) 0);      glEnableVertexAttribArray(0);              glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);      while (!glfwWindowShouldClose(window)) {            glClearColor(0, 0.5, 0.3, 1);          glClear(GL_COLOR_BUFFER_BIT);              glUseProgram(shaderProgram);          glDrawArrays(GL_TRIANGLES, 0, 3);                  glfwPollEvents();          glfwSwapBuffers(window);          }          glfwTerminate();      return 0;  }  

Why Python rollbacks code when reading a JSON file

Posted: 23 Mar 2022 06:15 AM PDT

So this is my python code:

## fixes all ids in a sequence    import json    annotations_folder_source = 'directory/'    category = "car"      new_id = 0    data_fixed = {}  labels_fixed = []    int_frame = 1  end_frame = 500      init_json = int_frame - 1    end_json = end_frame - 1    for i in range(init_json, end_json+1):      new_id = new_id      num_zeros = 6 - len(str(i))      f_name = '0'*num_zeros + str(i) + '.json'        f_path_source = annotations_folder_source + f_name        # load source and target files      with open(f_path_source) as f_source:          data_source = json.load(f_source)      print("Frame: "+str(i)+"\n")      for labels in data_source['labels']:          if (labels['category'] == category):              labels['id'] = new_id              new_id = new_id + 1              labels_fixed.append(labels)        data_fixed = data_source      data_fixed['labels'] = labels_fixed        # Closing files      f_source.close()        # Saved combined result overwriting f_target      with open(f_path_source, 'w') as f_source:             json.dump(data_fixed, f_source)      f_source.close()      print("----------\n")    print("END")  

The code should access to a folder which contains 500 json files. In each file I want to update an id field with an autoincremental variable (new_id). Each json file looks like:

{      "name": "000448",      "timestamp": 0,      "index": 448,      "labels": [          {              "id": 0,              "category": "truck",              "npoints": 7,              "box3d": {                  "dimension": {                      "width": 3.490625,                      "length": 17.29788867562834,                      "height": 4.300000000000001                  },                  "location": {                      "x": 5.019761743421808,                      "y": -64.47665732636735,                      "z": 0.30999662173084086                  },                  "orientation": {                      "rotationYaw": -0.017453292519943295,                      "rotationPitch": 0,                      "rotationRoll": 0                  }              }          },          {              "id": 1,              "category": "car",              "npoints": 12,              "box3d": {                  "dimension": {                      "width": 1.9140624999999996,                      "length": 4.414587332055948,                      "height": 1.7                  },                  "location": {                      "x": 4.862968749999982,                      "y": -16.208483685228707,                      "z": -0.9500000000000003                  },                  "orientation": {                      "rotationYaw": 0.017453292519943302,                      "rotationPitch": 0,                      "rotationRoll": 0.0349065850398866                  }              }          },  

As I said, new_id resets to zero in every for iteration, in stead of keep increasing, and I dont know how to solve it and why it happens. Any idea?

How to get form data from chield functional component when submit button is in parent component in ReactJS [duplicate]

Posted: 23 Mar 2022 06:16 AM PDT

Here is demo of my child and parent component I want to know how I can get data from child component there is no form tag but we can use in child, and submit button will be in parent component only we can't move it in child component. So how can we do it.

Child.js

import React from 'react'    export default function Child() {    return (      <div>          <p>Name :</p>          <div className="infoTd">              <TextArea              rows={2}              placeholder="Comments"              className="customFormControl"              />          </div>      </div>    )  }  

Parent.js

import React, { useState } from 'react'    export default function Parent() {      const[data, setData] = useState        const getData=()=>{          setData()      }    return (      <div>          <Child/>          <Button>Submit</Button>      </div>    )  }    

Thanks

Python - Recursion exit when condition met

Posted: 23 Mar 2022 06:16 AM PDT

I am trying to write a function which prints the minimum number of steps involved to make starting number to target number with multiply by 2 and subtract by 1.

However, I am getting the error:

RecursionError: maximum recursion depth exceeded in comparison

Here's the code I've written:

def no_steps(start,target,sofar):      if start == target:          return sofar      elif start < target and start > 0:          no_steps(start*2,target,sofar+'*2 ')          no_steps(start-1,target,sofar+'-1 ')  print(no_steps(2,6,''))  

May I know what am I doing wrong and is there any issue with the code?

How to pass variables from lm object to aes(x =, y = )?

Posted: 23 Mar 2022 06:15 AM PDT

Context: I have a function that takes an object created with stats::lm() as its main argument. The goal of this function is to make ggplots with only this lm object. Warning: variables used in the model are NOT arguments of the function i.e. if the model is lmobj <- lm(y ~ x, data = df) then the function only takes lmobj as an argument. Indeed it is different from question like this one. Moreover, I am not looking for "ggplot only" solutions that take the raw data and compute regression line and scatterplot (e.g. ggplot2::geom_smooth(method = "lm")).

Problem: ggplot() geom functions have a x and y argument that require unquoted variables (see reference manual); how can I recover these from lmobj?

Expected output:

library(ggplot2)  lmobj <- lm(Petal.Width ~ Petal.Length, data = iris)  myfun <- function(.lm) {    # make a scatterplot with .lm using ggplot    ggplot(data = .lm[["model"]], aes(x = Petal.Width, y = Petal.Length)) +      geom_point()  }  myfun(lmobj)  

Trials and errors

I tried to grab an unquoted variable name from lmobject using cat():

> cat(names(lmobj[["model"]][2]))  Petal.Length  

But it creates an error:

> myfuntest <- function(.lm) {  +   # make a scatterplot with .lm using ggplot  +   ggplot(data = .lm[["model"]], aes(x = cat(names(.lm[["model"]][2])),   +                                     y = cat(names(.lm[["model"]][1])))) +  +     geom_point()  + }  > myfuntest(lmobj)  Petal.LengthPetal.WidthPetal.LengthPetal.WidthError: geom_point requires the following missing aesthetics: x and y  

Change state of something from another class with a button

Posted: 23 Mar 2022 06:16 AM PDT

I am new to React and have had some hard time to understand the concept of states.

Down below I export a stepper from MUI. I use state

export default function CustomizedSteppers() {    const steps = ['Zoninfo', 'Betalsätt', 'Börja ladda'];   const [activeStep, setActiveStep] = React.useState(0);    const handleNext = () => {        setActiveStep((activeStep+1));      };          return (    //...    //Stepper stuff...    //...      <Button variant="contained" onClick={handleNext}>Hello     World</Button>        </Stack>     );  }  

I now want to split this code so that I can setActiveStep from another component.

Meaning, I want to put the button outside of this component and put it in another class, but still allow that button to change the value of activeStep - by accessing the method handleNext on click on a button outside this class. How do I manage to do this?

how to iteriate over an array of colors as index for example( 0,1,2,3..etc) in angular

Posted: 23 Mar 2022 06:16 AM PDT

This is the function defined in MainService.ts i used before to make it choose the colors randomly but now i need to change it so it can change the color set in badgesColorSet every time i refresh the page i have 3 colors defined in the json config already. so is this function correct and should i use for loop ?

getIteriateColor(){          //gets  color out of color set from turnkey.config file for badges      let  badgesColorSet = 0; badgesColorSet < Array.length; badgesColorSet++;          console.log(badgesColorSet);          return badgesColorSet;  

this is the code for turnkey-config.json that we set the badgescolor so it appears on runtime

{      "brandConfig": "turnkey",            "turnkey":      {"urlPath": "http://192.168.168.60:8081/mantle-services",          "brandName": "Turnkey Systems",          "logoPath": "assets/images/logos/logosemiwhite.svg",          "logo1": "assets/images/logos/logosemiwhite.svg",          "logo2": "assets/images/logos/logo.svg",          "theme":"theme-turnkey",          "brandColorForSpinner": "#E21A23",          "badgesColorSet":["#ffff00","#f51307","#0cc902"],          "backgroundImageWelcomeScreen": "assets/images/backgrounds/dark-material-bg.jpg",          "defaultLanguage": "en"               },  

Inherited Static Variables

Posted: 23 Mar 2022 06:16 AM PDT

I'm trying to implement a simple chess problem with inheritance, but i found myself stuck.

I have my abstract Chesspiece class and many child classes for each type of piece. I need an array to store the possible moves of each piece, so i was thinking about making the variable static because this array is always the same and independent from the instance

public class Knight extends Chesspiece{      public static final int dy = {1, 1, 2, 2, -1, -1, -2, -2};       public static final int dx = {2, -2, 1, -1, 2, -2, 1, -1};   }  

Somewhat like this, but afterwards in my logic I only have instances without knowing its subtype, so i cant access this variables.

I thought maybe i could somehow declare an abstract variable or something in my Chesspiece class, and then overwrite its value in each subclass. But after searching i found out that java doesn't let static inheritance.

So im wondering what would be the best solution to this problem. I'm very keen on learing good conceptual programming so each time i write better code. I have though solutions that work (not making the variables static), but they don't seem right or elegant for this problem. Any help is appreciated.

Can't Retrieve a Response from ExpressJS

Posted: 23 Mar 2022 06:16 AM PDT

I'm new to using Nodejs,Expressjs and Web development, and I'm having problems retrieving data from my back-end expressjs server from a get request that's coming from the react-front-end of my application.

As of right now I'm able to have express.js respond to my get request, but for some reason expressjs isn't sending back the data that i'm requesting or i'm not reading it correctly.

I've tried using both fetch and axios, but i'm still having the same problem. I've used both res.get("helllo") and res.send("hello") with no success.

Note: My front end runs on port 3000, and my backend runs on port 8100. I'm also using a proxy.

Here's my front-end React Code:

import { IonButton, IonContent, IonHeader, IonInput, IonItem, IonLabel, IonPage, IonTitle, IonToolbar } from '@ionic/react';  import { useState } from 'react';  import ExploreContainer from '../components/ExploreContainer';  import './Home.css';  import axios from 'axios';    const Home: React.FC = () => {       const[robot_name_input,setInput1]=useState<string>('')    const[ipaddress_input,setInput2]=useState<string>('')          return (      <IonPage>                <IonHeader>                    <IonToolbar>            <IonTitle>Robot Backup</IonTitle>          </IonToolbar>                </IonHeader>                <IonContent fullscreen>                   <IonHeader collapse="condense">            <IonToolbar>              <IonTitle size="large">Robot Backup</IonTitle>            </IonToolbar>          </IonHeader>          <IonLabel>Enter Robot Name</IonLabel>          <IonInput value={robot_name_input} onIonChange={(e:any)=>setInput1(e.target.value)}>   </IonInput>            <IonLabel>Enter Robot Ip Address</IonLabel>          <IonInput value={ipaddress_input} onIonChange={(e:any)=>setInput2(e.target.value)}>   </IonInput>            <IonButton expand="block" onClick={(e) =>{retrieveRobots();}}>Add Robot</IonButton>          <IonButton expand="block" onClick={(e) =>{retrieveRobots();}}>Refresh</IonButton>          <ExploreContainer />                      <IonItem>          <IonLabel>Item 1</IonLabel>          </IonItem>                    <IonItem>          <IonLabel>Item 2</IonLabel>          </IonItem>            <IonItem>          <IonLabel>Item 3</IonLabel>          </IonItem>                  </IonContent>            </IonPage>    );  };    export default Home;          function retrieveRobots()    {        //Option 1: Axios       axios.get('http://127.0.0.1:3000/getrobots')      .then(function (response) {      console.log(response.data);      console.log(response.status);      console.log(response.statusText);      console.log(response.headers);      console.log(response.config);    });        //Option 2: fetch     /* fetch('http://127.0.0.1:8100/getrobots',{      method: 'GET',      headers:{'Content-Type': 'application/json'},    })    .then(async response => response.json())    .then(async response => {        console.log('waiting for response');        console.log(await response.text());        console.log('response recieved');    }); */  } 

Here's where I'm having issues from the above code:

  {        //Option 1: Axios       axios.get('http://127.0.0.1:3000/getrobots')      .then(function (response) {      console.log(response.data);      console.log(response.status);      console.log(response.statusText);      console.log(response.headers);      console.log(response.config);    });        //Option 2: fetch      fetch('http://127.0.0.1:8100/getrobots',{      method: 'GET',      headers:{'Content-Type': 'application/json'},    })    .then(async response => response.json())    .then(async response => {        console.log('waiting for response');        console.log(await response.text());        console.log('response recieved');    });   } 

MY backend Express Code:

const express = require('express')    const app = express()  const port = 8100  var fs = require('fs');  app.use(express.json())    app.get('/getrobots', (req, res) => {      var DB=require('better-sqlite3')    var db_helper=require('better-sqlite3-helper')      db_helper({      path: './../Database/fanuc_robots.db', // this is the default      readonly: false, // read only      fileMustExist: false, // throw error if database not exists      WAL: true, // automatically enable 'PRAGMA journal_mode = WAL'      migrate:false,    })    let row = db_helper().queryFirstRow('SELECT * FROM Robots WHERE robot_index=?', 0);  console.log(row.robot_index, row.robot_name, row.ip_address);  res.get('hello');  console.log('response has been sent');      });        app.listen(port, () => {   console.log(`Example app listening on port ${port}`)  })

Is there a way to get an certain value in a list closest to a given index? [closed]

Posted: 23 Mar 2022 06:16 AM PDT

Lets say I have a list that looks like list = [1,3,1,2,2,1] Is there a way to find the location of a 1 closest to index 3

Edit: I need to search the list from starting from our index and search outwards in both directions. In my example, I want to search from index3 and if we dont get the desired value, we then search indexes 2 and 4, then indexes 1 and 5

Iterating array in complex way in reactjs

Posted: 23 Mar 2022 06:15 AM PDT

Response JSON:

[      [{              "name": "IMG00177.png",              "class": "Pore",              "confidence": "0.9",              "bbox": [160.0, 916.0, 169.0, 925.0],              "segmentation": []          },          {              "name": "IMG00177.png",              "class": "Pore",              "confidence": "0.81",              "bbox": [107.0, 890.0, 112.0, 896.0],              "segmentation": []          },          {              "name": "IMG00177.png",              "class": "Pore",              "confidence": "0.57",              "bbox": [119.0, 871.0, 123.0, 873.0],              "segmentation": []          },          {              "name": "IMG00177.png",              "class": "Pore",              "confidence": "0.63",              "bbox": [343.0, 703.0, 346.0, 705.0],              "segmentation": []          },          {              "name": "IMG00177.png",              "class": "Pore",              "confidence": "0.9",              "bbox": [337.0, 692.0, 345.0, 701.0],              "segmentation": []          }      ],      [{              "name": "IMG00178.png",              "class": "Pore",              "confidence": "0.53",              "bbox": [1183.0, 1078.0, 1185.0, 1081.0],              "segmentation": []          },          {              "name": "IMG00178.png",              "class": "Pore",              "confidence": "0.83",              "bbox": [155.0, 1002.0, 161.0, 1008.0],              "segmentation": []          },          {              "name": "IMG00178.png",              "class": "Pore",              "confidence": "0.72",              "bbox": [107.0, 891.0, 111.0, 893.0],              "segmentation": []          },          {              "name": "IMG00178.png",              "class": "Pore",              "confidence": "0.77",              "bbox": [121.0, 871.0, 126.0, 873.0],              "segmentation": []          }      ]  ]  

This is the response array for my api post request. i have a empty array and i want to check if the image name is same for another list. i want to parse that bbox value in list. Needed format:

[  {  "name":"1.png",  "confidence":[[0.9],[0.9],[0.9],[0.9],[0.9]],  "bbox":[[160.0, 916.0, 169.0, 925.0],[107.0, 890.0, 112.0, 896.0],[119.0, 871.0, 123.0, 873.0],[343.0, 703.0, 346.0, 705.0]]    }  ]  

I didn't have a clue how to iterate over this to get the required format.kindly guide me to approach this problem

Sending Apple Push Notification via PHP: unable to connect to ssl://gateway.sandbox.push.apple.com:2195 (Connection timed out)

Posted: 23 Mar 2022 06:15 AM PDT

I have the following PHP code to send Apple Push Notifications to my app:

<?php  $body = '{"aps":{"alert":{"title":"test title","subtitle":"","body":"test body"},"badge":0,"sound":"default","additional_data":"test additional_data"}}';    $context = stream_context_create();  stream_context_set_option($context, "ssl", "local_cert", "certificate.pem");  stream_context_set_option($context, "ssl", "passphrase", "HERE_COMES_THE_PASSWORD_OF_THE_certificate.pem_FILE");  $socket = stream_socket_client("ssl://gateway.sandbox.push.apple.com:2195", $error, $errstr, 30, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $context);  $msg = chr(0) . chr(0) . chr(32) . pack("H*", "HERE_COMES_MY_APPLE_PUSH_TOKEN") . pack("n", strlen($body)) . $body;  $result = fwrite($socket, $msg, strlen($msg));  fclose($socket);  ?>  

This code is stored on my server together with the certificate file called certificate.pem.

I'm using this code unchanged since month without any problems. Today, I noticed, that I'm not getting push notifications any more.

The PHP error log shows the following:

[23-Mar-2022 11:39:45 UTC] PHP Warning:  stream_socket_client(): unable to connect to ssl://gateway.sandbox.push.apple.com:2195 (Connection timed out) in /home2/kd37875/public_html/test/index.php on line 7  [23-Mar-2022 11:39:45 UTC] PHP Warning:  fwrite() expects parameter 1 to be resource, bool given in /home2/kd37875/public_html/test/index.php on line 9  [23-Mar-2022 11:39:45 UTC] PHP Warning:  fclose() expects parameter 1 to be resource, bool given in /home2/kd37875/public_html/test/index.php on line 10  

First, I thought, there's something wrong with the certificate file. Then, I found this: https://www.pushtry.com website. If I insert the Device Token, upload the certificate.pem file, insert the Bundle ID and a message, I'm successfully receiving a push message in my app. (There's a field for password on the website but it's also working if I don't insert it. No idea, why.) So this says me, that the certificate.pem must be okay.

screenshot from https://www.pushtry.com

Do you have any idea what I'm doing wrong? Why doesn't it work any more? Did Apple change something?

Rust duplicated use statements

Posted: 23 Mar 2022 06:16 AM PDT

Firt of all, I am a total begginner in Rust, I started to use a code analyzer (Mega-Linter) and it made me realize how much I duplicated the same "use" statements in my submodules. Here what my source file tree looks like :

src/    - lib.rs    - ui/        - mod.rs        - ui_mod_1.rs        - ui_mod_2.rs  

Then I realized that my ui_mod_1.rs and ui_mod_2.rs had almost the same bunch of "use" statements :

// ui_mod_1.rs  use tui::{      layout::{Alignment, Constraint, Direction, Layout, Rect},      style::{Color, Modifier, Style},  };    // rest of the file  
// ui_mod_2.rs  use tui::{      layout::{Alignment, Constraint, Direction, Layout, Rect},      style::{Color, Modifier, Style},  };    // rest of the file  
// mod.rs  pub mod ui_mod_1;  pub mod ui_mod_2;  
// lib.rs  pub mod ui;  

The idea behind ui_mod_1.rs and ui_mod_2.rs is to split "ui utilitaries" functions by theme to avoid having a huge source file containing all of them. A possible solution is to merge the two files, but this is not what I want to do.

What I tried is to move the "use" that the two submodules have in common in the mod.rs or even in the lib.rs like so :

// mod.rs  pub use tui::{      layout::{Alignment, Constraint, Direction, Layout, Rect},      style::{Color, Modifier, Style},  };    pub mod ui_mod_1;  pub mod ui_mod_2;  

But this does not work. After some research I still did not find how to do this. Is there an elegant way to regroup "use" statements for all submodules ?

Add legend for every point on ggmap instead of a group variable

Posted: 23 Mar 2022 06:16 AM PDT

I've got the following data frame:

df1 <- structure(list(City = c("Ahmadnagar", "Ahmedabad", "Akola", "Amaravati",   "Aurangabad", "Belgaum", "Bellary", "Bengaluru", "Bhavnagar",   "Bhiwandi", "Bhuj", "Bhusaval", "Bidar", "Bijapur", "Chanda",   "Chikka Mandya", "Chirala", "Davangere", "Ghandinagar", "Gulbarga",   "Guntur", "Hindupur", "Hospet", "Hubli", "Kagaznagar", "Kakinada",   "Kalyan", "Khanapur", "Kolar", "Kolhapur", "Kurnool", "Latur",   "Machilipatnam", "Malegaon Camp", "Mangalore", "Mumbai", "Mysore",   "Nanded", "Nandyal", "Nasik", "Navsari", "Nellore", "Ongole",   "Parbhani", "Porbandar", "Proddatur", "Pune", "Raichur", "Rajahmundry",   "Rajkot", "Sangli", "Shimoga", "Surat", "Tirupati", "Vadodara",   "Vishakhapatnam", "Vizianagaram"), State = c("Maharashtra", "Gujarat",   "Maharashtra", "Maharashtra", "Maharashtra", "Karnataka", "Karnataka",   "Karnataka", "Gujarat", "Maharashtra", "Gujarat", "Maharashtra",   "Karnataka", "Karnataka", "Maharashtra", "Karnataka", "Andhra Pradesh",   "Karnataka", "Gujarat", "Karnataka", "Andhra Pradesh", "Andhra Pradesh",   "Karnataka", "Karnataka", "Andhra Pradesh", "Andhra Pradesh",   "Maharashtra", "Maharashtra", "Karnataka", "Maharashtra", "Andhra Pradesh",   "Maharashtra", "Andhra Pradesh", "Maharashtra", "Karnataka",   "Maharashtra", "Karnataka", "Maharashtra", "Andhra Pradesh",   "Maharashtra", "Gujarat", "Andhra Pradesh", "Andhra Pradesh",   "Maharashtra", "Gujarat", "Andhra Pradesh", "Maharashtra", "Karnataka",   "Andhra Pradesh", "Gujarat", "Maharashtra", "Karnataka", "Gujarat",   "Andhra Pradesh", "Gujarat", "Andhra Pradesh", "Andhra Pradesh"  ), Lat = c(19.094571, 23.025793, 20.709569, 20.933272, 19.880943,   15.862643, 15.142049, 12.977063, 21.774455, 19.300229, 23.253972,   21.043649, 17.913309, 16.827715, 19.950758, 12.545602, 15.823849,   14.469237, 23.216667, 17.335827, 16.299737, 13.828065, 15.269537,   15.349955, 19.331589, 16.960361, 19.243703, 21.273716, 13.137679,   16.695633, 15.828865, 18.399487, 16.187466, 20.569974, 12.865371,   18.987807, 12.292664, 19.160227, 15.477994, 19.999963, 20.85,   14.449918, 15.503565, 19.268553, 21.641346, 14.7502, 18.513271,   16.205459, 17.005171, 22.291606, 16.856777, 13.932424, 21.195944,   13.635505, 22.299405, 17.704052, 18.11329), Long = c(74.738432,   72.587265, 76.998103, 77.75152, 75.346739, 74.508534, 76.92398,   77.587106, 72.152496, 73.058813, 69.669281, 75.785058, 77.530105,   75.718988, 79.295229, 76.895078, 80.352187, 75.92375, 72.683333,   76.83757, 80.457293, 77.491425, 76.387103, 75.138619, 79.466051,   82.238086, 73.135537, 76.117376, 78.129989, 74.231669, 78.036021,   76.584252, 81.13888, 74.515415, 74.842432, 72.836447, 76.638543,   77.314971, 78.483605, 73.776887, 72.916667, 79.986967, 80.044541,   76.770807, 69.600868, 78.548129, 73.849852, 77.35567, 81.777839,   70.793217, 74.569196, 75.572555, 72.830232, 79.419888, 73.208119,   83.297663, 83.397743)), class = c("grouped_df", "tbl_df", "tbl",   "data.frame"), row.names = c(NA, -57L), groups = structure(list(      State = c("Andhra Pradesh", "Andhra Pradesh", "Andhra Pradesh",       "Andhra Pradesh", "Andhra Pradesh", "Andhra Pradesh", "Andhra Pradesh",       "Andhra Pradesh", "Andhra Pradesh", "Andhra Pradesh", "Andhra Pradesh",       "Andhra Pradesh", "Andhra Pradesh", "Andhra Pradesh", "Andhra Pradesh",       "Gujarat", "Gujarat", "Gujarat", "Gujarat", "Gujarat", "Gujarat",       "Gujarat", "Gujarat", "Gujarat", "Karnataka", "Karnataka",       "Karnataka", "Karnataka", "Karnataka", "Karnataka", "Karnataka",       "Karnataka", "Karnataka", "Karnataka", "Karnataka", "Karnataka",       "Karnataka", "Karnataka", "Karnataka", "Maharashtra", "Maharashtra",       "Maharashtra", "Maharashtra", "Maharashtra", "Maharashtra",       "Maharashtra", "Maharashtra", "Maharashtra", "Maharashtra",       "Maharashtra", "Maharashtra", "Maharashtra", "Maharashtra",       "Maharashtra", "Maharashtra", "Maharashtra", "Maharashtra"      ), City = c("Chirala", "Guntur", "Hindupur", "Kagaznagar",       "Kakinada", "Kurnool", "Machilipatnam", "Nandyal", "Nellore",       "Ongole", "Proddatur", "Rajahmundry", "Tirupati", "Vishakhapatnam",       "Vizianagaram", "Ahmedabad", "Bhavnagar", "Bhuj", "Ghandinagar",       "Navsari", "Porbandar", "Rajkot", "Surat", "Vadodara", "Belgaum",       "Bellary", "Bengaluru", "Bidar", "Bijapur", "Chikka Mandya",       "Davangere", "Gulbarga", "Hospet", "Hubli", "Kolar", "Mangalore",       "Mysore", "Raichur", "Shimoga", "Ahmadnagar", "Akola", "Amaravati",       "Aurangabad", "Bhiwandi", "Bhusaval", "Chanda", "Kalyan",       "Khanapur", "Kolhapur", "Latur", "Malegaon Camp", "Mumbai",       "Nanded", "Nasik", "Parbhani", "Pune", "Sangli"), .rows = structure(list(          17L, 21L, 22L, 25L, 26L, 31L, 33L, 39L, 42L, 43L, 46L,           49L, 54L, 56L, 57L, 2L, 9L, 11L, 19L, 41L, 45L, 50L,           53L, 55L, 6L, 7L, 8L, 13L, 14L, 16L, 18L, 20L, 23L, 24L,           29L, 35L, 37L, 48L, 52L, 1L, 3L, 4L, 5L, 10L, 12L, 15L,           27L, 28L, 30L, 32L, 34L, 36L, 38L, 40L, 44L, 47L, 51L), ptype = integer(0), class = c("vctrs_list_of",       "vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"  ), row.names = c(NA, -57L), .drop = TRUE))  

From which I'm generating a plot like this: enter image description here

Here's the code I've used:

india_centroid <- c(68.18625, 6, 97.41529, 37)    req_zoom <- calc_zoom(Long, Lat, data = df1)  map_type = get_map(location = india_centroid, zoom = req_zoom, maptype = "roadmap")  p <- ggmap(map_type, extent = "panel", legend = "bottomright", size = c(500, 600))  p + geom_point(aes(x = Long, y = Lat, color = State), data = df1) +    ggtitle("Cities in India")   

So, as you can see the points are color based on the State column. And legend shows the names of the states they belong to. But, I need the legend to show the name of every City instead of the state while the colors are the same as per state.

I know that doesn't make sense because the colors will be repeated for the cities in the same state. But I need to know if it is possible. And if possible, how to achieve it.

What kind of error is this when I try to use MQTT on my EV3?

Posted: 23 Mar 2022 06:16 AM PDT

I'm currently working an project requiring the transfer of sensor data between Lego EV3 and PC.

enter image description here

Stream MongoDB Grid-FS File As Input For fluent-ffmpeg Transcode Process

Posted: 23 Mar 2022 06:16 AM PDT

I am trying to compress/transcode a video file that is saved in my MongoDB database, but I am not sure how I can add it as an input stream into the ffmpeg transcoding process.

Any ideas?

async function transcodeVideo(_id) {    gfs.collection("originalVideos");      const video = await gfs.files.findOne({ _id: ObjectId(_id) });      const gridfsBucket = new mongoose.mongo.GridFSBucket(connection.db, {      bucketName: "originalVideos",    });      const downloadStream = gridfsBucket.openDownloadStream(video._id);      return new Promise((resolve, reject) => {      const command = ffmpeg()        .input(downloadStream)        .inputFormat("mp4")        .setFfprobePath(pathToFfprobe.path)        .setFfmpegPath(pathToFfmpeg)        .videoCodec("libx264")        .audioCodec("libmp3lame")        .size("720x?")        .on("error", (err) => {          console.log(err);        })        .on("progress", (progress) => {        })        .on("end", () => {        })        .save("./video.mp4");    });

enter image description here

.NET Core Web API get data Based On SQL Store Procedure

Posted: 23 Mar 2022 06:16 AM PDT

I am learning to develop web api services in .NET Core Web API. Now I trying to execute stored procedure and return a list. But my code show an error as (instances are not supported. Path: $.Columns.DataType) the data after stored procedure execution. Any help is much appreciated.

BL

public class PieChartMgt  {      public DataTable GetMobileSelectContact(string Year, VantageContext _context)      {          DataTable dt = new DataTable();          try          {              string conn = _context.Database.GetDbConnection().ConnectionString;              SqlDataReader dr;              using (SqlConnection con = new SqlConnection(conn))              {                  using (SqlCommand cmd = new SqlCommand("AllSellout", con))                  {                      cmd.CommandType = CommandType.StoredProcedure;                      cmd.Parameters.Add(new SqlParameter("@Year", Year));                      con.Open();                      dr = cmd.ExecuteReader();                      dt.Load(dr);                      con.Close();                  }              }          }          catch (Exception ex)          {              ex.ToString();          }          return dt;      }  }  

Controller

[Route("api/[controller]")]  [ApiController]  public class PieChartController : ControllerBase  {      private readonly VantageContext _context;      public PieChartController(VantageContext context)      {          _context = context;      }      //GET: api/AllSellOut      [HttpGet]      public ActionResult<IEnumerable<string>> Getset(string Year)      {          DataTable dt = new PieChartMgt().GetMobileSelectContact(Year, _context);          var result = new ObjectResult(dt);          return result;      }  }  

Stored Procedure

ALTER PROCEDURE AllSellout  @Year VARCHAR(6)   AS  BEGIN  SELECT DISTINCT BusinessArea, sum(NetValue) as sumNetValue  FROM SalesAndReturns_RPT  WHERE  year(Call_ActualStartDate) = @Year  GROUP BY BusinessArea   ORDER BY sumNetValue DESC  END  

SyntaxError: Unexpected token l in JSON at position

Posted: 23 Mar 2022 06:16 AM PDT

Why do I get this error every time I use the api (POST)

SyntaxError: Unexpected token l in JSON at position 18 at JSON.parse (<anonymous>) at parse (/Users/.../Desktop/ecommerceapi/node_modules/body-parser/lib/types/json.js:89:19) at /Users/.../Desktop/ecommerceapi/node_modules/body-parser/lib/read.js:121:18 at invokeCallback (/Users/.../Desktop/ecommerceapi/node_modules/raw-body/index.js:224:16) at done (/Users/.../Desktop/ecommerceapi/node_modules/raw-body/index.js:213:7) at IncomingMessage.onEnd (/Users/.../Desktop/ecommerceapi/node_modules/raw-body/index.js:273:7) at IncomingMessage.emit (node:events:532:35) at endReadableNT (node:internal/streams/readable:1346:12) at processTicksAndRejections (node:internal/process/task_queues:83:21)

This is my entire code: (auth.js)

const router = require("express").Router();  const User = require("../models/User");  const CryptoJS = require("crypto-js");  const jwt = require("jsonwebtoken");    //REGISTER  router.post("/register", async (req, res) => {    const newUser = new User({      username: req.body.username,      email: req.body.email,      password: CryptoJS.AES.encrypt(        req.body.password,        process.env.PASS_SEC      ).toString(),    });      try {      const savedUser = await newUser.save();      res.status(201).json(savedUser);    } catch (err) {      res.status(500).json(err);    }  });    //LOGIN    router.post('/login', async (req, res) => {      try{          const user = await User.findOne(              {                  userName: req.body.user_name              }          );            !user && res.status(401).json("Wrong User Name");            const hashedPassword = CryptoJS.AES.decrypt(              user.password,              process.env.PASS_SEC          );              const originalPassword = hashedPassword.toString(CryptoJS.enc.Utf8);            const inputPassword = req.body.password;                    originalPassword != inputPassword &&               res.status(401).json("Wrong Password");            const accessToken = jwt.sign(          {              id: user._id,              isAdmin: user.isAdmin,          },          process.env.JWT_SEC,              {expiresIn:"3d"}          );              const { password, ...others } = user._doc;            res.status(200).json({...others, accessToken});        }catch(err){          res.status(500).json(err);      }    });    module.exports = router;  

I'm using Postman to use the API to POST this

{ "username": sultan "password": 12345qwer }

and this is index.js:

const express = require("express");  const app = express();  mongoose = require("mongoose")  const dotenv = require("dotenv");  const userRoute = require("./routes/user");  const authRoute = require("./routes/auth");    dotenv.config();    mongoose  .connect(process.env.MONGO_URL)  .then(() => console.log("DB Connection Successfull!"))  .catch((err) => {      console.log(err);  });    app.use(express.json());  app.use("/api/auth", authRoute);  app.use("/api/users", userRoute);    app.listen(process.env.PORT || 50, () => {      console.log("Backend server is running!");  });  

it should give me the users Info or "Wrong Password" but it gives the above error as a response!

Schema cache path for a database in rails

Posted: 23 Mar 2022 06:16 AM PDT

Where does the rails stores the schema cache for a database ? I know that we can specify schema_cache_path in the database.yml file. But if we didn't specify the path, in which path rails actually stores the schema ?

Type '{ 'x-access-token': any; } | { 'x-access-token'?: undefined; }' is not assignable to type 'AxiosRequestHeaders

Posted: 23 Mar 2022 06:16 AM PDT

I am trying to assign headers to axios.get, below throws error.

import authHeader from './auth-header';    return axios.get(API_URL + 'user', { headers: authHeader() });  

The function is as:

export default function authHeader() {      const userStr = localStorage.getItem("user");      let user = null;      if (userStr)        user = JSON.parse(userStr);          if (user && user.accessToken) {              return { 'x-access-token': user.accessToken };      } else {        return {};      }    }  

However, if I do something like the below it works:

 return axios.get(API_URL + 'user', { headers: { 'Authorization': `token test` }});  

What am I missing here?

Why does plot gives wrong score of fits using MLeval package?

Posted: 23 Mar 2022 06:16 AM PDT

I want to plot the AUC-ROC of several fits using the MLeval package. The problem is that the color and lines don't represent the right AUR-ROC score. As you can see in the plot below, it says for the red line (lda) an AUC-ROC of 0.84, but you can also see in the plot that the red line should actually have the lowest AUC-ROC score. If you check this (https://www.r-bloggers.com/2019/11/how-to-easily-make-a-roc-curve-in-r/) post with 3 models, it actually does the job right. Does anyone know why this happens?

Here is my plot:

enter image description here

Here is a sample of the data(because it is too big):

structure(list(Survived = structure(c(1L, 2L, 2L, 2L, 1L, 1L,   1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L,   2L, 2L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 2L, 1L,   1L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 2L,   1L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 1L,   1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 2L, 1L, 2L, 2L,   1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 1L), .Label = c("No",   "Yes"), class = "factor"), Pclass = c(0.826912816524371, -1.56522783127827,   0.826912816524371, -1.56522783127827, 0.826912816524371, 0.826912816524371,   -1.56522783127827, 0.826912816524371, 0.826912816524371, -0.369157507376952,   0.826912816524371, -1.56522783127827, 0.826912816524371, 0.826912816524371,   0.826912816524371, -0.369157507376952, 0.826912816524371, -0.369157507376952,   0.826912816524371, 0.826912816524371, -0.369157507376952, -0.369157507376952,   0.826912816524371, -1.56522783127827, 0.826912816524371, 0.826912816524371,   0.826912816524371, -1.56522783127827, 0.826912816524371, 0.826912816524371,   -1.56522783127827, -1.56522783127827, 0.826912816524371, -0.369157507376952,   -1.56522783127827, -1.56522783127827, 0.826912816524371, 0.826912816524371,   0.826912816524371, 0.826912816524371, 0.826912816524371, -0.369157507376952,   0.826912816524371, -0.369157507376952, 0.826912816524371, 0.826912816524371,   0.826912816524371, 0.826912816524371, 0.826912816524371, 0.826912816524371,   0.826912816524371, 0.826912816524371, -1.56522783127827, -0.369157507376952,   -1.56522783127827, -1.56522783127827, -0.369157507376952, 0.826912816524371,   -0.369157507376952, 0.826912816524371, 0.826912816524371, -1.56522783127827,   -1.56522783127827, 0.826912816524371, -1.56522783127827, 0.826912816524371,   -0.369157507376952, 0.826912816524371, 0.826912816524371, 0.826912816524371,   -0.369157507376952, 0.826912816524371, -0.369157507376952, 0.826912816524371,   0.826912816524371, 0.826912816524371, 0.826912816524371, 0.826912816524371,   -0.369157507376952, 0.826912816524371, 0.826912816524371, 0.826912816524371,   0.826912816524371, -1.56522783127827, -0.369157507376952, 0.826912816524371,   0.826912816524371, 0.826912816524371, -1.56522783127827, 0.826912816524371,   0.826912816524371, 0.826912816524371, -1.56522783127827, 0.826912816524371,   0.826912816524371, 0.826912816524371, -1.56522783127827, -1.56522783127827,   -0.369157507376952, -0.369157507376952), Sex = c("male", "female",   "female", "female", "male", "male", "male", "male", "female",   "female", "female", "female", "male", "male", "female", "female",   "male", "male", "female", "female", "male", "male", "female",   "male", "female", "female", "male", "male", "female", "male",   "male", "female", "female", "male", "male", "male", "male", "male",   "female", "female", "female", "female", "male", "female", "female",   "male", "male", "female", "male", "female", "male", "male", "female",   "female", "male", "male", "female", "male", "female", "male",   "male", "female", "male", "male", "male", "male", "female", "male",   "female", "male", "male", "female", "male", "male", "male", "male",   "male", "male", "male", "female", "male", "male", "female", "male",   "female", "female", "male", "male", "female", "male", "male",   "male", "male", "male", "male", "male", "male", "male", "female",   "male"), Age = c(-0.530005098333073, 0.571430411821611, -0.254646220794402,   0.364911253667608, 0.364911253667608, -0.32348594017907, 1.67286592197629,   -1.90679948602643, -0.185806501409734, -1.08072285341041, -1.76912004725709,   1.94822479951497, -0.667684537102408, 0.640270131206279, -1.08072285341041,   1.74170564136096, -1.90679948602643, 0.0344806006212027, 0.0895523761289369,   0.055132516436603, 0.364911253667608, 0.29607153428294, -1.01188313402575,   -0.116966782025066, -1.49376116971842, 0.571430411821611, 0.055132516436603,   -0.736524256487076, -0.309717996302136, -0.392325659563737, 0.709109850590947,   -0.130734725902, -0.0205911748865315, 2.49894255459231, -0.116966782025066,   0.846789289360282, -0.571308929963873, -0.598844817717741, -0.805363975871744,   -1.08072285341041, 0.709109850590947, -0.185806501409734, -0.392325659563737,   -1.83795976664176, -0.736524256487076, 0.50947466437541, -0.034359118763465,   -0.0205911748865315, -0.32348594017907, -0.805363975871744, -1.56260088910309,   -0.598844817717741, 1.32866732505296, -0.0481270626403986, 2.43010283520764,   1.35620321280682, -0.598844817717741, -0.0825469223327325, -1.70028032787242,   -1.28724201156442, -0.530005098333073, 0.571430411821611, 1.05330844751429,   -1.76912004725709, 0.839905317421815, -0.530005098333073, -0.0481270626403986,   -0.736524256487076, -0.874203695256412, -0.254646220794402, 0.158392095513605,   -0.943043414641079, -0.598844817717741, -0.254646220794402, 0.158392095513605,   -0.32348594017907, -0.392325659563737, 0.50947466437541, -1.98734195770649,   0.0207126567442691, -0.530005098333073, -0.0481270626403986,   -0.36478977180987, -0.116966782025066, -0.874203695256412, 0.227231814898272,   -0.943043414641079, 0.50947466437541, -0.461165378948405, -0.392325659563737,   -0.0481270626403986, -0.667684537102408, 1.12214816689895, -0.254646220794402,   2.01706451889963, 0.50947466437541, 2.84314115151565, -0.461165378948405,   0.29607153428294, 0.29607153428294), SibSp = c(0.432550428041802,   0.432550428041802, -0.474278822276423, 0.432550428041802, -0.474278822276423,   -0.474278822276423, -0.474278822276423, 2.24620892867825, -0.474278822276423,   0.432550428041802, 0.432550428041802, -0.474278822276423, -0.474278822276423,   0.432550428041802, -0.474278822276423, -0.474278822276423, 3.15303817899648,   -0.474278822276423, 0.432550428041802, -0.474278822276423, -0.474278822276423,   -0.474278822276423, -0.474278822276423, -0.474278822276423, 2.24620892867825,   0.432550428041802, -0.474278822276423, 2.24620892867825, -0.474278822276423,   -0.474278822276423, -0.474278822276423, 0.432550428041802, -0.474278822276423,   -0.474278822276423, 0.432550428041802, 0.432550428041802, -0.474278822276423,   -0.474278822276423, 1.33937967836003, 0.432550428041802, 0.432550428041802,   0.432550428041802, -0.474278822276423, 0.432550428041802, -0.474278822276423,   -0.474278822276423, 0.432550428041802, -0.474278822276423, 1.33937967836003,   0.432550428041802, 3.15303817899648, -0.474278822276423, 0.432550428041802,   0.432550428041802, -0.474278822276423, -0.474278822276423, -0.474278822276423,   -0.474278822276423, 0.432550428041802, 4.05986742931471, -0.474278822276423,   -0.474278822276423, 0.432550428041802, 2.24620892867825, -0.474278822276423,   0.432550428041802, -0.474278822276423, -0.474278822276423, 3.15303817899648,   1.33937967836003, -0.474278822276423, 4.05986742931471, -0.474278822276423,   0.432550428041802, -0.474278822276423, -0.474278822276423, -0.474278822276423,   -0.474278822276423, -0.474278822276423, -0.474278822276423, -0.474278822276423,   -0.474278822276423, -0.474278822276423, -0.474278822276423, -0.474278822276423,   2.24620892867825, 0.432550428041802, -0.474278822276423, 2.24620892867825,   -0.474278822276423, -0.474278822276423, -0.474278822276423, 0.432550428041802,   0.432550428041802, -0.474278822276423, -0.474278822276423, -0.474278822276423,   -0.474278822276423, -0.474278822276423, 0.432550428041802), Parch = c(-0.47340772456839,   -0.47340772456839, -0.47340772456839, -0.47340772456839, -0.47340772456839,   -0.47340772456839, -0.47340772456839, 0.767198988932891, 2.00780570243417,   -0.47340772456839, 0.767198988932891, -0.47340772456839, -0.47340772456839,   5.72962584293801, -0.47340772456839, -0.47340772456839, 0.767198988932891,   -0.47340772456839, -0.47340772456839, -0.47340772456839, -0.47340772456839,   -0.47340772456839, -0.47340772456839, -0.47340772456839, 0.767198988932891,   5.72962584293801, -0.47340772456839, 2.00780570243417, -0.47340772456839,   -0.47340772456839, -0.47340772456839, -0.47340772456839, -0.47340772456839,   -0.47340772456839, -0.47340772456839, -0.47340772456839, -0.47340772456839,   -0.47340772456839, -0.47340772456839, -0.47340772456839, -0.47340772456839,   -0.47340772456839, -0.47340772456839, 2.00780570243417, -0.47340772456839,   -0.47340772456839, -0.47340772456839, -0.47340772456839, -0.47340772456839,   -0.47340772456839, 0.767198988932891, -0.47340772456839, -0.47340772456839,   -0.47340772456839, 0.767198988932891, -0.47340772456839, -0.47340772456839,   -0.47340772456839, 2.00780570243417, 2.00780570243417, -0.47340772456839,   -0.47340772456839, -0.47340772456839, 2.00780570243417, -0.47340772456839,   0.767198988932891, -0.47340772456839, -0.47340772456839, 2.00780570243417,   -0.47340772456839, -0.47340772456839, 2.00780570243417, -0.47340772456839,   -0.47340772456839, -0.47340772456839, -0.47340772456839, -0.47340772456839,   -0.47340772456839, 2.00780570243417, -0.47340772456839, -0.47340772456839,   -0.47340772456839, -0.47340772456839, -0.47340772456839, -0.47340772456839,   -0.47340772456839, 3.24841241593545, -0.47340772456839, 2.00780570243417,   -0.47340772456839, -0.47340772456839, -0.47340772456839, -0.47340772456839,   2.00780570243417, -0.47340772456839, -0.47340772456839, -0.47340772456839,   0.767198988932891, 0.767198988932891, -0.47340772456839), Fare = c(-0.502163136515605,   0.786403617834538, -0.488579851581261, 0.420494069765409, -0.486064428445271,   -0.477848050313875, 0.395591380719111, -0.223957337675147, -0.424017995203696,   -0.0429313901012591, -0.311997147434786, -0.113781804318799,   -0.486064428445271, -0.0186988097783889, -0.490004587245486,   -0.326083516996328, -0.0619640877174114, -0.38645367226008, -0.285836746820493,   -0.502666221142803, -0.124849666117153, -0.38645367226008, -0.4864829948551,   0.0663224922180623, -0.223957337675147, -0.0164349289559982,   -0.502666221142803, 4.64439259971928, -0.489501502618288, -0.489167454425828,   -0.090221345057865, 2.30043680338673, -0.492101443971647, -0.436762134979874,   1.00549697297924, 0.3983583461687, -0.502581702925434, -0.486064428445271,   -0.285836746820493, -0.421836620260165, -0.457388604694989, -0.225466591556741,   -0.489167454425828, 0.18865657484453, -0.489501502618288, -0.486064428445271,   -0.336145209540286, -0.492101443971647, -0.211798788405027, -0.289861423838076,   0.150589167273717, -0.491095274717251, 0.895993560684828, -0.124849666117153,   0.599173630638046, 0.0663224922180623, -0.436762134979874, -0.502581702925434,   -0.0896337422132979, 0.295729082220321, -0.502581702925434, 0.961813128630388,   1.0317418918109, -0.0866152344501103, -0.090221345057865, -0.341260574029635,   -0.436762134979874, -0.48388506584025, -0.488579851581261, -0.473738855078922,   -0.436762134979874, 0.295729082220321, 0.831011125558925, -0.35719024566523,   0.488829060846959, -0.494113782480438, -0.489167454425828, -0.486064428445271,   -0.064479510853401, -0.397018449431237, -0.46694721261175, -0.456885520067791,   -0.49134681703085, 0.299753759237905, -0.436762134979874, -0.329102024759515,   0.0436836839941552, -0.486064428445271, 4.64439259971928, -0.486064428445271,   -0.486064428445271, -0.490004587245486, 0.582990404350342, -0.234019030219105,   -0.502163136515605, -0.486064428445271, 0.0493021331107018, 0.626925791012793,   -0.185219821380906, -0.124849666117153), Embarked = c("S", "C",   "S", "S", "S", "Q", "S", "S", "S", "C", "S", "S", "S", "S", "S",   "S", "Q", "S", "S", "C", "S", "S", "Q", "S", "S", "S", "C", "S",   "Q", "S", "C", "C", "Q", "S", "C", "S", "C", "S", "S", "C", "S",   "S", "C", "C", "Q", "S", "Q", "Q", "C", "S", "S", "S", "C", "S",   "C", "S", "S", "C", "S", "S", "C", "", "S", "S", "C", "C", "S",   "S", "S", "S", "S", "S", "S", "C", "S", "S", "S", "S", "S", "S",   "S", "S", "Q", "S", "S", "S", "S", "S", "S", "S", "S", "S", "S",   "S", "S", "S", "C", "C", "S", "S")), row.names = c(NA, 100L), class = "data.frame")  

Here is the code I used to fit and plot:

library(MLeval)  library(caret)  # Run algorithms using 5-fold cross validation  control <- trainControl(method="cv",                           number=5,                           repeats = 5,                           savePredictions = "final",                           search = "grid",                           classProbs = TRUE)  metric <- "Accuracy"    # a) linear algorithms  set.seed(7)  fit.lda <- train(Survived~., data=trainset, method="lda", metric=metric, trControl=control, allowParallel = TRUE)  # b) nonlinear algorithms  # CART  set.seed(7)  fit.cart <- train(Survived~., data=trainset, method="rpart", metric=metric, trControl=control, tuneLength = 1)  # glm  set.seed(7)  fit.glm <- train(Survived~., data=trainset, method="glmnet", metric=metric, trControl=control, verbose = FALSE)  # c) advanced algorithms  # SVM  set.seed(7)  fit.svm <- train(Survived~., data=trainset, method="svmRadial", metric=metric, trControl=control, verbose = FALSE, tuneLength = 2)  # Random Forest  set.seed(7)  fit.rf <- train(Survived~., data=trainset, method="ranger", metric=metric, trControl=control, verbose = FALSE, tuneLength = 3, importance = "impurity")  # xgbDART  set.seed(7)  fit.xgbDART <- train(Survived~., data = trainset, method = "xgbTree", metric = metric, trControl = control, verbose = FALSE, tuneLength = 7, nthread = 1, verbosity = 0)    # plot  plot <- evalm(list(fit.lda, fit.cart, fit.svm, fit.rf, fit.xgbDART, fit.glm),                gnames = c("lda", "cart", "svm", "rf", "xgbTree", "glm"),                rlinethick=0.8, fsize=8, plots='r')  

eloquent javascript correlation tableFor explanation

Posted: 23 Mar 2022 06:15 AM PDT

I am taking my first steps in programming and i am stuck with this problem from eloquent, in particular with the weresquirrel problem. Here it goes :

function hasEvent(event, entry) {   return entry.events.indexOf(event) != -1;  }    function tableFor(event, journal) {    var table = [0, 0, 0, 0];     for (var i = 0; i < journal.length; i++) {       var entry = journal[i], index = 0;        if (hasEvent(event, entry)) index += 1;        if (entry.squirrel) index += 2;        table[index] += 1;   }   return table;  }    console.log(tableFor("pizza", JOURNAL));  // → [76, 9, 4, 1]  

I do understand the first function hasevent, it returns true if an entry contains a given event.

what i can't grasp is the tableFor function. I can't get how the function flows and HOW the table gets its values. For example for console.log(tableFor("pizza", JOURNAL)); , we get [76, 9, 4, 1]. But How for god's sake ?

The journal is supplied by the book and looks like this :

var JOURNAL = [    {"events":["pizza","exercise","weekend"],"squirrel":false},    {"events":["bread","pudding","brushed teeth","weekend","touched     tree"],"squirrel":false},    {"events":["carrot","nachos","brushed     teeth","cycling","weekend"],"squirrel":false},    {"events":["brussel sprouts","ice cream","brushed     teeth","computer","weekend"],"squirrel":false},    {"events":["potatoes","candy","brushed     teeth","exercise","weekend","dentist"],"squirrel":false},    {"events":["brussel sprouts","pudding","brushed     teeth","running","weekend"],"squirrel":false},    {"events":["pizza","brushed teeth","computer","work","touched     tree"],"squirrel":false},    {"events":["bread","beer","brushed     teeth","cycling","work"],"squirrel":false},    {"events":["cauliflower","brushed teeth","work"],"squirrel":false},    {"events":["pizza","brushed teeth","cycling","work"],"squirrel":false},    {"events":["lasagna","nachos","brushed teeth","work"],"squirrel":false},    {"events":["brushed teeth","weekend","touched tree"],"squirrel":false},    {"events":["lettuce","brushed      teeth","television","weekend"],"squirrel":false},    {"events":["spaghetti","brushed teeth","work"],"squirrel":false},    {"events":["brushed teeth","computer","work"],"squirrel":false},    {"events":["lettuce","nachos","brushed teeth","work"],"squirrel":false},    {"events":["carrot","brushed teeth","running","work"],"squirrel":false} ...etc  

What i understand is that an event is passed as a parameter and it looks through the array of objects in Jounral to see if it's present. But how does the counting take place ?

if (entry.squirrel) index += 2;  

Why is this +2 ? why not index += 3; or index += 4; ???

and finally why table[index] += 1; ???

For example the first loop goes like this, for : console.log(tableFor("pizza", JOURNAL));

//FLOW  i=0;  

from the first line above in journal, pizza is present.

     if (hasEvent(event, entry)) index += 1;  

so index is incremented and becomes 1.it continues to :

     if (entry.squirrel) index += 2;   

squirel is false, so nothing happens to index.If squirel were to be found, why is it +2 ???

then table[index] += 1 i can't understand from this point.

Can someone please break it down for me ? It would be very helpful for my training.

Thank you in advance.

Using "$RANDOM" to generate a random string in Bash

Posted: 23 Mar 2022 06:16 AM PDT

I am trying to use the Bash variable $RANDOM to create a random string that consists of 8 characters from a variable that contains integer and alphanumeric digits, e.g., var="abcd1234ABCD".

How can I do that?

How to redirect and append both standard output and standard error to a file with Bash

Posted: 23 Mar 2022 06:16 AM PDT

To redirect standard output to a truncated file in Bash, I know to use:

cmd > file.txt  

To redirect standard output in Bash, appending to a file, I know to use:

cmd >> file.txt  

To redirect both standard output and standard error to a truncated file, I know to use:

cmd &> file.txt  

How do I redirect both standard output and standard error appending to a file? cmd &>> file.txt did not work for me.

No comments:

Post a Comment