Sunday, April 4, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


calculate the average of all ratings of a post and display it as RatingBar stars

Posted: 04 Apr 2021 10:28 AM PDT

I'm developing a recipes app that enables other users to rate others' recipes. I'm using RecycleView to hold the ratings. Here is how the rating page looks. The rating is saved as float number in the database and I retrieved it like this:

        String val = rating.getRatingBar();          Float numofStars = Float.parseFloat(val);          holder.ratingBar1.setRating(numofStars);  

and Here is the post item

is there a way to calculate the average of all ratings of a post and display it as stars in the post item? please help me

Kotlin 1.4 Project wizard VS Previous project wizard

Posted: 04 Apr 2021 10:28 AM PDT

Have anyone experienced any difficulties using new Kotlin project wizard? Which one do you like the most: the current one or the previous one? Which one is more convenient to use?

Kotlin 1.4 Project wizardthe previous Kotlin project wizard

JS - how to unpin mouse after right click on draggable modal?

Posted: 04 Apr 2021 10:28 AM PDT

I am dragging a modal using the following code:

function makeDivDraggable(modal) {    let x = 0;    let y = 0;        // Query the element    const ele = modal;    ele.style.cursor = "move";        // Handle the mousedown event    // that's triggered when user drags the element    const mouseDownHandler = function(e) {        // Get the current mouse position        x = e.clientX;        y = e.clientY;                // Attach the listeners to `document`        document.addEventListener('mousemove', mouseMoveHandler);        document.addEventListener('mouseup', mouseUpHandler);    };        const mouseMoveHandler = function(e) {        // How far the mouse has been moved        const dx = e.clientX - x;        const dy = e.clientY - y;            // Set the position of element        ele.style.top = `${ele.offsetTop + dy}px`;         ele.style.left = `${ele.offsetLeft + dx}px`;            // Reassign the position of mouse        x = e.clientX;        y = e.clientY;    };        const mouseUpHandler = function() {        // Remove the handlers of `mousemove` and `mouseup`        document.removeEventListener('mousemove', mouseMoveHandler);        document.removeEventListener('mouseup', mouseUpHandler);    };        ele.addEventListener('mousedown', mouseDownHandler);  };      }      

it works everything great, apart from one little thing.

If in the modal there are some links, those links open well to a new tab thanks to the _target="blank" however, if I right click on a link, and I select to open to a new tab, the tab opens, however the div remains "clicked", but not unclicked", it means that no matter where the cursor goes, the modal follows the cursor, even though no mouse buttons are being clicked.

I am thinking of a solution to: -ignore right clicks and make it move only with left clicks. -or unpin the mouse - delete the event listener as soon as the right click was done

Can you please suggest a solution? And how to edit the code to make it work?

How to I attach this Amplitude.js json file to my html code?

Posted: 04 Apr 2021 10:28 AM PDT

I'm just wondering how to attach these two files together for a project I'm working on. I wish to attach to create a website with Amplitude.JS whilst showcasing embed YouTube links to the songs themselves.

this is my html head for index.html:

<head>      <meta charset="utf-8">      <meta http-equiv="X-UA-Compatible" content="IE=edge">      <title>Choose An Album</title>      <meta name="description" content="">      <meta name="viewport" content="width=device-width, initial-scale=1">      <link rel="stylesheet" href="">      <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/amplitudejs@5.3.1/dist/amplitude.js"></script>   </head>  

and my amplitude code, tally.json:

Amplitude.init({         songs: [          {              "name": "Good Day",              "artist": "Tally Hall",              "album": "Marvin's Marvelous Mechanical Museum",              "url": "/Tally Hall/Marvin's Marvelous Mechanical Museum/01 - Good Day.mp3",              "cover_art_url": "s-l300.jpg"          },          {              "name": "Greener",              "artist": "Tally Hall",              "album": "Marvin's Marvelous Mechanical Museum",              "url": "/Tally Hall/Marvin's Marvelous Mechanical Museum/02 - Greener.mp3",              "cover_art_url": "s-l300.jpg"          },          {              "name": "Welcome to Tally Hall",              "artist": "Tally Hall",              "album": "Marvin's Marvelous Mechanical Museum",              "url": "/Tally Hall/Marvin's Marvelous Mechanical Museum/03 - Welcome to Tally Hall.mp3",              "cover_art_url": "s-l300.jpg"          }         ]     });  

Is there any real way to combine the two? Thank you in advance!

typescript: ddd validtions and domain

Posted: 04 Apr 2021 10:28 AM PDT

How to perform validation in a way that doesn't lead to domain knowledge leakage? I was doing the validations on my presentation layer on my controller, but then I'm trying to pass it on to my domain my scenario is: I have 2 values ​​objects:

Password: min length 8

Email: is email

Customer-entity:

interface CustomerProps {    id: CustomerID    name: string    email: CustomerEmail    password: CustomerPassword  }    export class Customer extends Entity<CustomerProps> implements CustomerProps {    private _id: CustomerID    private _name: string    private _email: CustomerEmail    private _password: CustomerPassword      constructor(props: CustomerProps) {      super(props)      this._id = props.id      this._name = props.name      this._email = props.email      this._password = props.password    }      get id(): CustomerID {      return this._id    }      get email(): CustomerEmail {      return this._email    }      get name(): string {      return this._name    }      get password(): CustomerPassword {      return this._password    }      public static build() {}  }  

Customer-Password:

export class CustomerPassword {    private readonly pwd: string      private constructor(pwd: string) {      this.pwd = pwd      Object.freeze(this)    }      public async comparePassword(plainTextPassword: string): Promise<boolean> {      // need implements    }      public async encrypt(): Promise<string> {      // need implements    }      static create(pwd: string): Either<IErrorModel, CustomerPassword> {      if (!pwd) return left(makeRequiredFieldError('Password'))      if (pwd.length < 8) return left(makeMinFieldError('passwrod', 8))      return right(new CustomerPassword(pwd))    }      get value(): string {      return this.pwd    }  }  

Customer-Email:

export class CustomerEmail {    private readonly email: string      private constructor(email: string) {      this.email = email      Object.freeze(this)    }      static create(email: string): Either<IErrorModel, CustomerEmail> {      if (!Email.validate(email)) {        return left({          code: 'InvalidEmail',          reason: 'Provide a valid email',          field: 'email',        })      }      return right(new CustomerEmail(email))    }      get value(): string {      return this.email    }      static validate(email: string): boolean {      if (!validator.isEmail(email)) return false      return true    }  }  

In my values ​​objects I do the validations in a static method called create

and so I'm not sure if that's correct and also creating a static create method on my customer-entity.

is it possible to apply a facade in this situation? Is it okay to do the validations at that level?

Where to put files GitHub

Posted: 04 Apr 2021 10:27 AM PDT

https://github.com/abdulahad12345/AboutMe

Here is my repo, I'm very new. Every time I go to Github pages and try hosting it, I get the error

There isn't a GitHub Pages site here.

If you're trying to publish one, read the full documentation to learn how to set up GitHub Pages for your repository, organization, or user account.

My guess is that they don't know what html file to open and that I need to put my files in certain directories, but I'm not sure. My main file is

Bash script : why mysqldump add ? symbol at the end of created .sql file?

Posted: 04 Apr 2021 10:27 AM PDT

I'm doing a cron job in order to save my database automatically.

My issue : The .sql file created with mysqldump command is followed by a ? so, instead of having backup.sql, I have got backup.sql?

Here is my script "save.sh":

#!/bin/bash  mysqldump --user=my_username --password=my_password --databases my_database > /home/my_serveur_name/public_html/backup/backup.sql  

Thank you for your help.

Android studio 4.1.3 and IntelliJ IDEA 2020.3.3 font rendering

Posted: 04 Apr 2021 10:27 AM PDT

at the moment I am using retail version of android studio and it's fine by me.

After installing IntelliJ IDEA 2020.3.3 i'v found that fonts are very different Let me show example:

Android Studio: Android Studio IntelliJ IDEA IntelliJ IDEA

My eyes are in pain when I look on IntelliJ IDEA& How can I fix this?

ssh tunneling/port forwarding not working through EC2 instance to an Elasticsearch cluster in a VPC

Posted: 04 Apr 2021 10:27 AM PDT

I have my Elasticsearch cluster in a VPC, I'd like to access this EC cluster from my local Macbook. I have set up a bastion host that uses the same VPC, and I was able to ssh into this bastion host from my Macbook.

But somehow, my code just cannot connect to my ES cluster through this bastion host, here's my command to run port forwarding:

ssh -i ~/Downloads/keypairs/20210402-02.pem ubuntu@ec2-123-456.us-west-2.compute.amazonaws.com -N -L 9200:vpc-es-domain-20210331-abc123def.us-west-2.es.amazonaws.com:443

Here's my timeout exception when accessing the ES cluster in the VPC:

java.net.ConnectException: Timeout connecting to [vpc-es-domain-20210331-abc123def.us-west-2.es.amazonaws.com/10.0.47.182:443]      at org.elasticsearch.client.RestClient.extractAndWrapCause(RestClient.java:823) ~[elasticsearch-rest-client-7.6.1.jar:7.6.1]      at org.elasticsearch.client.RestClient.performRequest(RestClient.java:248) ~[elasticsearch-rest-client-7.6.1.jar:7.6.1]      at org.elasticsearch.client.RestClient.performRequest(RestClient.java:235) ~[elasticsearch-rest-client-7.6.1.jar:7.6.1]      at org.elasticsearch.client.RestHighLevelClient.internalPerformRequest(RestHighLevelClient.java:1514) ~[elasticsearch-rest-high-level-client-7.6.1.jar:7.6.1]      at org.elasticsearch.client.RestHighLevelClient.performRequest(RestHighLevelClient.java:1484) ~[elasticsearch-rest-high-level-client-7.6.1.jar:7.6.1]      at org.elasticsearch.client.RestHighLevelClient.performRequestAndParseEntity(RestHighLevelClient.java:1454) ~[elasticsearch-rest-high-level-client-7.6.1.jar:7.6.1]      at org.elasticsearch.client.RestHighLevelClient.bulk(RestHighLevelClient.java:497) ~[elasticsearch-rest-high-level-client-7.6.1.jar:7.6.1]  

I'm suspecting my command to do port forwarding is not correct? But after research, this looks the most legit option to me. Any insight would be greatly appreciated!

using button to increment divs in react

Posted: 04 Apr 2021 10:27 AM PDT

I am fairly new to React/Next and I had a quick question.

I am trying to create a button that will increment the number of divs in real time.

Here is my code:

import React from 'react'      const Clown = () => {        const [clownCounter, setClownCounter] = React.useState(1);        function addClown(event) {          event.preventDefault();      }            return(          <React.Fragment>          <div>              <form>                                     {Array.from({ length: clownCounter}, (_unused, index) => index + 1).map(                      (clownIndex) => {                          const clownid = `${clownIndex}`                          return (                          <div key={clownid } className="clown-box">                              <label htmlFor={clownid }>Activity {clownIndex}</label>                              <br />                              <input type="text" onChange={(e)=> onChangeForm(e)} name={activityId} id={activityId} />                              <br />                          </div>                          )                      },                  )}                  <span className="clown-add">                      <button onClick={addClown} onChange={() => { setClownCounter(clownCounter++) }}>Add Clown</button>                  </span>                     <br />                </form>          </div>          </React.Fragment>      )  }  export default Clown  

As you can see the goal is to increase the amount of clown-box divs everytime the button is clicked. I think I am close but it is not currently working. Can anyone help?

How to recreate a MySQLTable in a NodeJS application using the MySQL module?

Posted: 04 Apr 2021 10:27 AM PDT

In some scenario I want to recreate a MySQL table in my NodeJS application. I have my tabledump.sql (includes drop table, create table, insert into) file for it. I'm using the MySQL module. I tried to read it with fs module to a string and pass it to connection.query but it always gave me an error: Access denied for user ''@'localhost' (using password:NO) what is totally weird because the user is empty (it is root in my connection) and the password is okey since every other part of my NodeJS application working. It should be some bug / false error message.

TLDR: I want to run a whole dump.query file in NodeJS to recreate a table. How should I do it?

VueJs - I don't understand how I could pass a Boolean value to a chid component

Posted: 04 Apr 2021 10:27 AM PDT

I know that the subject was certainly treated somewhere, but I really don't understand how I could pass a variable to a child component.

What I'm trying to do, is passing 'displayTogglingMenu' in the parent component to 'toggle' in the child.

Parent component

  data(){      return  {        selectedItem: 1,        displayTogglingMenu: false,        items: [          { text: 'Home', name: 'home', icon: 'mdi-home' },          { text: 'Courses', name: 'courses_index', icon: 'mdi-school'  },          { text: 'Enrolments', name: 'enrolments_index', icon: 'mdi-format-list-bulleted' },          { text: 'Lecturers', name: 'lecturers_index', icon: 'mdi-account-tie' },        ],      }    },       

Child Component

data(){      return  {          toggle: valueOfParentComponent,          alertMessage: '',          loadTable: true,          courses: [],          expendable: [],          ...  },       

What's The Big(O) Complexity of while not False, very confused whether it is O(n) or a while is always O(n)?

Posted: 04 Apr 2021 10:26 AM PDT

def cups (a,b):      i=0      j=0      done = False      while not done:          if a[i]==b[j] :              print("A[" + str(i) + "] with B[" + str(j) + "]")              i += 1              j = 0          if i == len(a):              i=0              done = True          if a[i] != b[j] :              j += 1  

#So I'm trying to compare two lists and print the indexes of two values that are the same in the two lists #without doing any nested loops however , I'm curious whether the complexity is O(1) or O(n) , the code is working perfectly tho

Breaking While Loop for multiple inputs of list...for nested list

Posted: 04 Apr 2021 10:28 AM PDT

Hi I'm trying to get multiple inputs in the form of a list, which is nested inside a list. I'm able to get the output but not able to break out from the loop.

values = []  while True:      val = list(input("Enter an integer, the value ends if it is 'stop': "))      if val == 0:          exit()      values.append(val)      print(values)  

I even used break..after the if condition..no Joy !!

Enter an integer, the value ends if it is 'stop': 4569 [['4', '5', '6', '9']] Enter an integer, the value ends if it is 'stop': 666655 [['4', '5', '6', '9'], ['6', '6', '6', '6', '5', '5']] Enter an integer, the value ends if it is 'stop': 5222 [['4', '5', '6', '9'], ['6', '6', '6', '6', '5', '5'], ['5', '2', '2', '2']] Enter an integer, the value ends if it is 'stop': 0 [['4', '5', '6', '9'], ['6', '6', '6', '6', '5', '5'], ['5', '2', '2', '2'], ['0']]

This is the type of output i'm looking for but whenever I press 0...it does not break the loop..

also using if val == list(0) and if list(val) == list(0) and many other permutations either gives me an error or does not break out from the While Loop...Please Help..Thank you

how to rename all the files in a directory with the current date in linux

Posted: 04 Apr 2021 10:27 AM PDT

I'm trying to rename all the files in a directory called level6 with the current date as YYYY-MM-DD form using bash shell script

For example a file named "lab" , it will be changed to"2021-4-4-lab"

I tried the following script :

#!/bin/bash  DAY=$(date +%F)  cd /home/Frank/level6    for FILE in *.txt   do  mv $FILE ${DAY}-${FILE}   done  

but it gives me the error when I try to execute the script :

bash: ./rn.sh: bin/bash: bad interpreter: No such file or directory

Cannot implement ipconfig(String,InetAddress) in RMIInterface

Posted: 04 Apr 2021 10:27 AM PDT

hello I am developing a simple program (client/server) in java using RMI the objective is that the client sends a request to the server example ipconfig and the server sends him the answer example the ip address of the machine

somethinglikethat here is the interface I created

RMIInterface.java

import java.net.InetAddress;  import java.net.UnknownHostException;  import java.rmi.Remote;  import java.rmi.RemoteException;    public interface RMIInterface extends Remote {      public String ipconfig(String name, InetAddress ip) throws RemoteException;  }  

the rmi client

Clientrmi.java

import java.net.InetAddress;  import java.net.UnknownHostException;  import java.net.MalformedURLException;  import java.rmi.Naming;  import java.rmi.NotBoundException;  import java.rmi.RemoteException;  import javax.swing.JOptionPane;  public class Clientrmi {      private static RMIInterface look_up;      public static void main(String[] args) throws MalformedURLException, RemoteException, NotBoundException {          look_up = (RMIInterface) Naming.lookup("//localhost/MyServer");          String txt = JOptionPane.showInputDialog("Entrez une commande");          String response = look_up.ipconfig(txt);          JOptionPane.showMessageDialog(null, response);          }  }      

finaly my RMIserver

Serverrmi.java

import java.net.InetAddress;  import java.net.UnknownHostException;  import java.rmi.Naming;  import java.rmi.RemoteException;  import java.rmi.server.UnicastRemoteObject;  public class Serverrmi extends UnicastRemoteObject implements RMIInterface{      private static final long serialVersionUID = 1L;      protected ServerOperation() throws RemoteException {          super();      }      @Override      public String ipconfig(String name, InetAddress ip) throws RemoteException, UnknownHostException{              ip = InetAddress.getLocalHost();              name = ip.getHostName();          System.err.println(name + " is trying to contact!");          return "response " +name+ " - " +ip;      }          public static void main(String[] args){          try {              Naming.rebind("//localhost/MyServer", new ServerOperation());              System.err.println("Server ready");              } catch (Exception e) {              System.err.println("Server exception: " + e.toString());            e.printStackTrace();          }      }  }    

Can anyone help me with that

the error message

error: ipconfig(String,InetAddress) in ServerOperation cannot implement ipconfig(String,InetAddress) in RMIInterface          public String ipconfig(String name, InetAddress ip) throws RemoteException, UnknownHostException{                        ^    overridden method does not throw UnknownHostException  

Group Pandas dataframe with multuple column and create distribution

Posted: 04 Apr 2021 10:27 AM PDT

I have a dataframe as below:

data = [['A', 1], ['A', 0], ['A', 1], ['B', 0], ['B', 1], ['C', 1], ['C', 1], ['C', 1]]  temp_df = pd.DataFrame(data, columns = ['Name', 'effect'])        Name    effect  0   A   1  1   A   0  2   A   1  3   B   0  4   B   1  5   C   1  6   C   1  7   C   1  

after doing a groupby I'm getting

temp_df.groupby(['Name','effect']).size().reset_index(name='count')      Name    effect  count  0   A   0   1  1   A   1   2  2   B   0   1  3   B   1   1  4   C   1   3  

But I need my result to look like as below:

Name e0 e1
A 1 2
B 1 1
C 0 3

Possible causes of JVM crash

Posted: 04 Apr 2021 10:28 AM PDT

I'm new to this, and at the moment I am running a bot on a windows VPS. The server itself is 64 bit and all the applications I run on it seem to be working fine. However, sometimes the JVM completely crashes and the one application I need running 24/7 shuts down. I have no clue what else to add in here apart from the hs_err_pidXXX log. So here are the first few lines

#  # A fatal error has been detected by the Java Runtime Environment:  #  #  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x70b268f4, pid=4908, tid=0x000012e0  #  # JRE version: Java(TM) SE Runtime Environment (8.0_281-b09) (build 1.8.0_281-b09)  # Java VM: Java HotSpot(TM) Client VM (25.281-b09 mixed mode windows-x86 )  # Problematic frame:  # C  [ewe7925329452122158407.dll+0x168f4]  #  # Core dump written. Default location: C:\Users\Administrator\Desktop\hs_err_pid4908.mdmp  #  # If you would like to submit a bug report, please visit:  #   http://bugreport.java.com/bugreport/crash.jsp  # The crash happened outside the Java Virtual Machine in native code.  # See problematic frame for where to report the bug.  #    ---------------  T H R E A D  ---------------    Current thread (0x45d69400):  JavaThread "AWT-EventQueue-0" [_thread_in_native, id=4832, stack(0x467d0000,0x46820000)]    siginfo: ExceptionCode=0xc0000005, reading address 0x00000038    Registers:  EAX=0x71be6800, EBX=0x45d69540, ECX=0xffffffff, EDX=0x45d69540  ESP=0x4681e2c0, EBP=0x4681e328, ESI=0x00000000, EDI=0x45d69400  EIP=0x70b268f4, EFLAGS=0x00010216    Top of Stack: (sp=0x4681e2c0)  0x4681e2c0:   45d69400 4681e354 00000000 fff80000  0x4681e2d0:   00000000 fff80000 00000000 fff80000  0x4681e2e0:   00000000 fff80000 00000000 fff80000  0x4681e2f0:   002e0067 0073006f 00000000 00000000  0x4681e300:   006f0062 002e0074 00000000 00000000  0x4681e310:   006f0042 00410074 00000000 00000000  0x4681e320:   00700070 0069006c 4681e368 03159879  0x4681e330:   45d69540 4681e354 00000000 00000000     Instructions: (pc=0x70b268f4)  0x70b268d4:   ab 5e b2 70 cc cc cc cc cc cc cc cc 55 8b ec 83  0x70b268e4:   e4 c0 83 ec 34 53 8b 5d 08 56 8b 75 10 57 8b 03  0x70b268f4:   ff 76 38 8b 7e 24 8b 80 64 03 00 00 53 89 7c 24  0x70b26904:   34 ff d0 8b 55 20 33 c9 85 d2 74 4e a1 98 81 b3       Register to memory mapping:    EAX=0x71be6800 is an unknown value  EBX=0x45d69540 is an unknown value  ECX=0xffffffff is an unknown value  EDX=0x45d69540 is an unknown value  ESP=0x4681e2c0 is pointing into the stack for thread: 0x45d69400  EBP=0x4681e328 is pointing into the stack for thread: 0x45d69400  ESI=0x00000000 is an unknown value  EDI=0x45d69400 is a thread  

Dist function between matrix objects in R

Posted: 04 Apr 2021 10:28 AM PDT

I have a very simple problem.

Given a N dimension point (say, a vector where each element represents a dimension) represented by x and a MxN dimension matrix (or a group of M points that have N dimensions!) represented by y.

set.seed(999)  data <- matrix(runif(1100), nrow = 11, ncol = 10)    x <- data[1, ]  y <- data[2:nrow(data), ]  

I want to calculate a distance measure between x and every point of y. I know a simple way of doing that is to do:

distances <- dist(rbind(x, y))  

However, I believe this is not very efficient for this specific case, for the following reasons:

  1. I need to use rbind, which is very memory costly.
  2. dist calculates the distance between every point, but I'm only interested in 10 of those distances, or simply the distance between x and every point of y. I'm not interested in the internal distances between y points.
  3. Because of (2) I need to manually select the last line of the dist matrix to get the distances I actually need.

One possible solution I thought of was to apply the distance measurement manually looping through y.

distances <- apply(y, MARGIN = 1, function(a, b = x) {     sqrt(sum((a - b)^2))  })  

However, when timing both approaches, I get:

func1 <- function(x, y) {    apply(y, MARGIN = 1, function(a, b = x) {      sqrt(sum((a - b)^2))    })  }    func2 <- function(x, y) {    dist(rbind(x, y))  }    microbenchmark::microbenchmark(    func1(x, y),    func2(x, y)  )    Unit: microseconds          expr    min     lq     mean median      uq      max neval   func1(x, y) 29.602 30.450 61.21791 31.301 32.3510 2916.101   100   func2(x, y) 15.101 15.801 28.55304 17.201 17.7015 1143.001   100  

So my question here is: is there a way to solve this problem faster than using dist?

I am getting Element not interractable exception

Posted: 04 Apr 2021 10:27 AM PDT

"public static void main(String[] args) throws InterruptedException {      System.setProperty("webdriver.chrome.driver","C:\\Users\\agile\\Downloads\\Selenium\\chromedriver.exe");                   // Instantiate a ChromeDriver class.             WebDriver driver=new ChromeDriver();        driver.navigate().to("https://uat.myatom.app/risksecure/#/auth/login");         

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

    driver.manage().window().maximize();      driver.get("https://uat.myatom.app/risksecure/#/auth/login");      driver.findElement(By.xpath("/html/body/app-root/auth/div/div[2]/div/div[2]/div[2]/div[2]/auth-login/div/form/div/div[1]")).click();      Thread.sleep(9000);      driver.findElement(By.xpath("/html/body/app-root/auth/div/div[2]/div/div[2]/div[2]/div[2]/auth-login/div/form/div/div[1]")).sendKeys("himanshu.chand168@webkul.com");        

}}"

Modify ImagePullPolicy in deploymnet with Mutate admission controller

Posted: 04 Apr 2021 10:26 AM PDT

I am building a Mutate admission controller for deployment to make sure the imagePullPolicy on the Pod is set to Always with a corresponding validating admission controller. I notice that I can set it on the deployment (upon creation) or on the replicaset.

the code looks as such :

package main    import (      "net/http"      "fmt"      "io/ioutil"      "encoding/json"      "os"  //  "github.com/golang/glog"      "strconv"      "k8s.io/api/admission/v1"  //  corev1 "k8s.io/api/core/v1"      appsv1 "k8s.io/api/apps/v1"      metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"      admissionv1 "k8s.io/api/admission/v1"  )    func isKubeNamespace(ns string) bool {      return ns == metav1.NamespacePublic || ns == metav1.NamespaceSystem  }    type patchOperation struct {      Op    string      `json:"op"`      Path  string      `json:"path"`      Value interface{} `json:"value,omitempty"`  }    func (mr *myServerHandler) mutserve(w http.ResponseWriter, r *http.Request) {        var Body []byte      if r.Body != nil {          if data , err := ioutil.ReadAll(r.Body); err == nil {              Body = data          }      }        if len(Body) == 0 {          fmt.Fprintf(os.Stderr, "Unable to retrieve Body from API")          http.Error(w,"Empty Body", http.StatusBadRequest)      }        fmt.Fprintf(os.Stdout,"Received Request")        if r.URL.Path != "/mutate" {          fmt.Fprintf(os.Stderr, "Not a Validate URL Path")          http.Error(w, "Not A Validate URL Path", http.StatusBadRequest)      }        // Read the Response from the Kubernetes API and place it in the Request         arRequest := &v1.AdmissionReview{}      if err := json.Unmarshal(Body, arRequest); err != nil {          fmt.Fprintf(os.Stderr, "Error Unmarsheling the Body request")          http.Error(w, "Error Unmarsheling the Body request", http.StatusBadRequest)          return      }      //  if arRequest.Request.Resource.Resource != "pods" {             //          fmt.Fprintf(os.Stderr, "Handling the wrong resource")  //          http.Error(w, "Handling the wrong resource", http.StatusBadRequest)  //          return    //  }        raw := arRequest.Request.Object.Raw      replicaset := appsv1.ReplicaSet{}        if !isKubeNamespace(arRequest.Request.Namespace) {                    if err := json.Unmarshal(raw, &replicaset); err != nil {              fmt.Fprintf(os.Stderr, "Error , unable to Deserializing Pod")              http.Error(w,"Error , unable to Deserializing Pod", http.StatusBadRequest)              return          }      } else {              fmt.Fprintf(os.Stderr, "Error , unauthorized Namespace")              http.Error(w,"Error , unauthorized Namespace", http.StatusBadRequest)              return      }        containers := replicaset.Spec.Template.Spec.Containers                arResponse := v1.AdmissionReview{          Response: &v1.AdmissionResponse{                  UID: arRequest.Request.UID,          },      }        var patches []patchOperation        for i , container := range containers {          fmt.Fprintf(os.Stdout, "container[%d]= %s imagePullPolicy=%s", i, container.Name , container.ImagePullPolicy)                    if containers[i].ImagePullPolicy != "Always" {                if containers[i].ImagePullPolicy == "Never" || containers[i].ImagePullPolicy == "IfNotPresent"  {                                        patches = append(patches, patchOperation{                              Op: "replace",                              Path: "spec/template/spec/containers/[" + strconv.Itoa(i) + "]/ImagePullPolicy",                              Value: "Always",                  })                                    } else {                    patches = append(patches, patchOperation{                              Op: "Add",                              Path: "/spec/template/spec/containers/[" + strconv.Itoa(i) + "]/ImagePullPolicy",                              Value: "Always",                  })                    arResponse.Response.Allowed = true              }          }      }  //    if pullPolicy != "Always" {        patchBytes, err := json.Marshal(patches)        if err != nil {          fmt.Fprintf(os.Stderr, "Can't encode Patches: %v", err)          http.Error(w, fmt.Sprintf("couldn't encode Patches: %v", err), http.StatusInternalServerError)          return      }        v1JSONPatch := admissionv1.PatchTypeJSONPatch      arResponse.APIVersion = "admission.k8s.io/v1"      arResponse.Kind = arRequest.Kind      arResponse.Response.Allowed = true      arResponse.Response.Patch = patchBytes      arResponse.Response.PatchType = &v1JSONPatch            resp, rErr := json.Marshal(arResponse)        if rErr != nil {          fmt.Fprintf(os.Stderr, "Can't encode response: %v", rErr)          http.Error(w, fmt.Sprintf("couldn't encode response: %v", rErr), http.StatusInternalServerError)      }        if _ , wErr := w.Write(resp); wErr != nil {          fmt.Fprintf(os.Stderr, "Can't write response: %v", wErr)          http.Error(w, fmt.Sprintf("cloud not write response: %v", wErr), http.StatusInternalServerError)      }    }  

if I run the "Add" patch it does end up adding the imagePullPolicy to always but if I want to replace it I am receiving an error of :

"Failed to create new replica set "ubi-kuku-547654586": Internal error occurred: replace operation does not apply: doc is missing path: /spec/template/spec/containers/[0]/ImagePullPolicy: missing value"

I have tried it when creating a deployment and it is still the same error

I tried working with the same structure (different path) for a single pod ( /spec/containers/[0]/ImagePullPolicy) with the core/v1 package and it worked.

Player can't move across the x-axis while on top a platform that has collisions with it

Posted: 04 Apr 2021 10:27 AM PDT

I am using Game Maker Studio: 2 to make a game currently. I have a problem where the player won't move left or right while on top of a platform that it is colliding with. Any help would be great!

//velocity = 2  //Moving left  if (keyboard_check(65))     {     x -= velocity*delta_time/17500;     }    //Moving right  if (keyboard_check(68))     {     x += velocity*delta_time/17500;     }  

In Asp.Net core Odata, how to prevent filter string from replacing text passed

Posted: 04 Apr 2021 10:28 AM PDT

I am passing an odata query as below

http://localhost:5000/odata/Levels?$filter=contains(Code, '+14')  

However when this lands in my controller I see that the filter object received is being replaced as

{contains(Code, ' 14')}  

As you can see +14 is being replaced 14 where + is replaced with a space due to which my query is failing. How can I fix this issue?

Dynamic field creation google forms

Posted: 04 Apr 2021 10:28 AM PDT

Is it possible to add questions to a google form based on if the user wants to add a few more clusters of data? i.e. a user is asked to enter information about the pets they have. If they have one pet, a user enters information for one pet. if the user wants to add another pet, they are prompted and asked if they want to add another pet. The user then selects yes, and another few fields appear. When the user is done adding pets, they say they are done, and move on.

I assume using a class form would allow me to add a text field, but is there an issue with how the information is pushed to the spreadsheet?

This example says that although you can add fields, you cannot capture the data into a spreadsheet since they are already formed.

How can I add dynamic field in Google Form?

Thanks

Not able to change to another remote git repo in terminal

Posted: 04 Apr 2021 10:28 AM PDT

PS C:\Users\HP\Documents\webdev> git status  On branch main  Your branch is ahead of 'origin/main' by 2 commits.    (use "git push" to publish your local commits)    nothing to commit, working tree clean  PS C:\Users\HP\Documents\webdev> git branch -M main  PS C:\Users\HP\Documents\webdev> git remote add origin https://github.com/prithvi60/prithvi.netlify.com.git  error: remote origin already exists.  PS C:\Users\HP\Documents\webdev> git push -u origin main  remote: Repository not found.  fatal: repository 'https://github.com/prithvi60/Web.git/' not found`  

I'm not able to change the repo using git remote add command. It shows repo not found. I have deleted the previous repo in git hub. I want to push the same code in a new repo which I'm not able to do as its telling repo already exits.

ps- I've just started learning git so if there is any other approach do let me know.

How to hide nginx.conf authorization credentials?

Posted: 04 Apr 2021 10:27 AM PDT

To explain quickly, I have an nginx server running within Docker, acting as a reverse proxy for my Flask web app. A part of my configuration is using proxy_set_header Authorization to pass some credentials into the proxy_pass website.

This all works fine - but, I want to push all this stuff to GitHub, and of course don't want want my creds, encoded or not, to show up.

What is my best option here? All I can think of is having something similar to dotenv, but for nginx.conf files rather than .py files.

Does anyone have any ideas on what I could to in order to pass my creds in but without hardcoding them explicitly in the config?

Trying to access a value outside of another function [duplicate]

Posted: 04 Apr 2021 10:27 AM PDT

How can I get the array values inside of a function, outside of the function?

I'm trying to access the content of the database outside of the function responsible for getting the data, by filling in an array with the rows comming out of the database. In this example case the variable datainfo was created to copy the rows and be accessible outside of the get function, but when trying to access it or displaying its content I get the information the value it contains is [] which is its initial value. Currently I was trying with the async because I thought it had to do with that, but it still doesn't work.

 async GetDateForCopyFromDatabase(){           let playlistId = 1;          var dbOrigin = new sqlite3.Database('./db/dbname.db', sqlite3.SQLITE_OPEN_CREATE, (err) => {        if (err) {          console.error('Origin: ' + err.message);        }        console.log('Connected to the origin database.');      });          let sql = `SELECT xpto FROM table1 WHERE id  = ?`;      var datainfo = [];                await dbOrigin.get(sql,[playlistId], function(err, data) {          if (!err) {                     datainfo = data;                                          }          });          console.log(datainfo);    }  

How can I create a 46 GB RAM image on Kubernetes? [closed]

Posted: 04 Apr 2021 10:27 AM PDT

I am looking to deploy an application on AKS that is very demandind in RAM. I need kubernetes to go up to 46 GB of RAM.

But for now I still can't figure out how to request that many RAM.

I did found how to do it on docker but kubernetes still eludes me.

package com.datastax.driver.core does not exist

Posted: 04 Apr 2021 10:28 AM PDT

I'm begginner in cassandra , I'm trying to connect to cassandra database and insert some rows in netbeans but I have error under the import : package com.datastax.driver.core does not exist any solutions ?

  import com.datastax.driver.core.Cluster;  import com.datastax.driver.core.ResultSet;  import com.datastax.driver.core.Row;  import com.datastax.driver.core.Session;    public class CassandraConnection {      public static void main(String args[])      {          System.out.println("Cassandra Java Connection");          Cluster cluster;          Session session;          //Connect to the cluster and Keyspace ecommerce          cluster=Cluster.builder().addContactPoint("localhost").build();          session=cluster.connect("ecommerce");          System.out.println("Inserting Data in Cassandra");          session.execute("INSERT INTO products (pdt_id, cat_id, pdt_name, pdt_desc, price, shipping) VALUES (001,104, 'Danby 0.7 cu. ft. Microwave Oven', 'Capacity of 0.7 cu. ft.10 different power levels', 54.00, 'Expedited')");          String pdtid = null, pdtname = null, pdtdesc = null;          float price = 0;          ResultSet resultset=session.execute("select * from products where pdt_id=005");          for(Row row :resultset){              pdtid = Integer.toString(row.getInt("pdt_id"));              pdtname = row.getString("pdt_name");              pdtdesc = row.getString("pdt_desc");              price = row.getFloat("price");                                      System.out.println("Product ID: " + pdtid);          System.out.println("Name: " + pdtname);          System.out.println("Description: " + pdtdesc);          System.out.println("Price: "+ price);              }          cluster.close();          }    }```  

general URL format

Posted: 04 Apr 2021 10:28 AM PDT

I'm trying to solve this problem that extract URL from a big text and i been looking for general format for URL until I found this https://en.wikipedia.org/wiki/URL; and I make this code but I don't know why it didn't found the URL:

 Pattern p = Pattern.compile("(http|https|ftp|mailto|file|data|irc|rtsp)(\\:)(^\\w{1})([a-zA-Z0-9/%+.-]*$)\\.(com|net|org|jo)\\/(.+)" , Pattern.CASE_INSENSITIVE);          Matcher m = p.matcher(text);         if(m.matches())               System.out.println(text) ;         else               System.out.println("no matches");  

No comments:

Post a Comment