Saturday, December 4, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Unable to map the array and get the values on Screen React Native

Posted: 04 Dec 2021 07:17 AM PST

const DynPut: FC<Props> = Props => {    const [value, setValue] = useState<string>(['1', '2', '3', '4']);      return (      <View>        {value.map(v => {          <Text>{v}</Text>;        })}      </View>    );  };  

Unable to get the values 1-5 on the screen. am using typescript and also saved the file with .tsx extension

Problem with node.js deployment to heroku

Posted: 04 Dec 2021 07:17 AM PST

I'm trying to deploy my small api for two days. I'm using postgres for database with express js. I do an example application which is using same technologies and it was successfully deployed. (https://postgresnodjs.herokuapp.com/api/todos)

When I deploy project, first thing I do is add Herokupostgres add-on to project. And then enter image description here

log in the server with PgAdmin4 and create tables and columns which is used in express.js application. For example:

const getAll = (request, response) => {    pool.query("SELECT * FROM blog_posts ORDER BY id ASC", (err, results) => {      if (err) {        throw err;      }      response.status(200).json(results.rows);    });  };  

the blog_posts table here is required. If I doesn't create this, program exits with error which says 'blog_posts' doesn't exist. I did it with my other 'mini todo app' and it worked there. I check if program runs in production or development. So in deployed app database integration must be done with this value:enter image description here I'm sure about this. But when I send a response to "http://medzoa-backend.herokuapp.com/api/blogPosts" it gives me Application Error page. In logs I see

2021-12-04T15:01:16.982973+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/api/blogPosts" host=medzoa-backend.herokuapp.com request_id=64d81154-7bd5-4440-aee6-b5385fbbcf58 fwd="212.154.57.38" dyno= connect= service= status=503 bytes= protocol=https

Why heroku deployment worked other application and doesn't work this one?

How to play google drive video in google colab?

Posted: 04 Dec 2021 07:17 AM PST

I need to play the video by giving url of google drive video in goolge colab.

''' '''

Why does compiler complain about ambiguous overload for assignment operator?

Posted: 04 Dec 2021 07:16 AM PST

In header file, class Person is the base class to all person-related classes. Class Student is derived from Person. On line [1], it has a template constructor that may allow recursive constructor call. It also has a default copy assignment operator (line [2]) and a copy assignment operator that accepts a shared pointer typed as Person.

Looks like line [1] causes problems. See the following.

In ambiguous_overload.hpp:

#include <memory>  #include <string>    class Person;    class Student;    class Person {  protected:      std::string name;  public:      Person() {}      virtual ~Person() {}  };      class Student : public Person {  public:      Student();        template<typename... Args> Student(Args... args) { // [1]          // ...;      }        Student(const Student&);                                  Student(const std::shared_ptr<Student>);      Student(const std::shared_ptr<Person>);      ~Student();        Student& operator=(const Student&);                 // [2]        Student& operator=(const std::shared_ptr<Student>);      Student& operator=(const std::shared_ptr<Person>);   //[3]  };  

In ambiguous_overload.cpp, the implementation is rather standard except a derived class Child has been implemented at [4]. When testing the copy assignment operator of Student, I created a shared pointer pointing to Child and assigned it to an instance of Student.

#include "ambiguous_overload.hpp"    Student::Student() {}  Student::Student(const Student& stu) {}  Student::Student(const std::shared_ptr<Student> ptr) {}  Student::Student(const std::shared_ptr<Person> ptr) {}  Student::~Student(){}    Student& Student::operator=(const Student& stu) {      //...;      return *this;  }  Student& Student::operator=(const std::shared_ptr<Student> ptr) {      //...;      return *this;  }  Student& Student::operator=(const std::shared_ptr<Person> ptr) {      //...;      return *this;  }      class Child : public Person {    // [4]  public:      Child() {}  };    int main() {      [](){          Student stu;          std::shared_ptr<Child> child_ptr (new Child());   // [5]          stu = child_ptr;    // [6] Ambiguous overload (if line [1] stays)      } ();      return 0;  }  

Compiler, however, raises the following error.

./ambiguous_overload.cpp:26:15: error: ambiguous overload for 'operator=' (operand types are 'Student' and 'std::shared_ptr<Child>')     26 |         stu = child_ptr;        |               ^~~~~~~~~  ./ambiguous_overload.cpp:12:10: note: candidate: 'Student& Student::operator=(const Student&)'     12 | Student& Student::operator=(const Student& stu) { return *this; }        |          ^~~~~~~  ./ambiguous_overload.cpp:14:10: note: candidate: 'Student& Student::operator=>(std::shared_ptr<Person>)'     14 | Student& Student::operator=(const std::shared_ptr<Person> ptr) { return *this; }        |          ^~~~~~~  

Line [1] appears to be the smoking gun: When it is removed, compiler is silent and there is no error on ambiguity. It suggests that somewhere in invoking the copy assignment operator, the constructor is (perhaps) called.

But, I don't quite understand the ambiguity here. First of all, all copy assignment operators are returning reference type Student&, not values, and are (perhaps?) needing no constructor calls. Second, the default copy assignment operator takes a reference of Student type, yet on the right hand side of [6] a shared pointer to Child is provided, i.e. not subclass of Student. Moreover, at line [6], the object stu on the left hand side has already been constructed, requiring no (perhaps) constructor call.

Firefox Responsive Design Mode - Touch Simulation drag not working

Posted: 04 Dec 2021 07:16 AM PST

I'm trying to use Firefox Developer edition during web-app development. When I try to Drag elements or Drag to scroll - it doesn't work. Moreover it emits the CLICK even instead.

Is there anyway to make it work? In Chrome it works. But the response time is slower and it can't be in "mobile mode" without opening dev-tools. So I'm trying to use Firefox.

Thank you

Table Api call highlight not showing from javascript

Posted: 04 Dec 2021 07:15 AM PST

This is my table on start

<div class= "col-md-7" id = "recyclable-list" >                                                <table class="table">                                  <thead>                                    <tr>                                      <th style=" padding-left:25px;";>RecyclableID</th>                                      <th style=" padding-left:100px;">Name</th>                                      <th style=" text-align: center;">RecyclableType</th>                                    </tr>                                  </thead>                                  <tbody id="recycleTable">                                    </tbody>                                                                  </table>    

This is my script call for database

var myarray = [];                                  $.ajax({                                                                url:"https://ecoexchange.dscloud.me:8080/api/get",                                                            method:"GET",                                  // In this case, we are going to use headers as                                  headers:{                                      // The query you're planning to call                                      // i.e. <query> can be UserGet(0), RecyclableGet(0), etc.                                      query:"RecyclableGet(0)",                                                                            // Gets the apikey from the sessionStorage                                      apikey:sessionStorage.getItem("apikey")                                  },                                                        success:function(data,xhr,textStatus) {                                                                    myarray = data;                                  buildTable(myarray);                                  console.log(myarray);                                                                      },                                    error:function(xhr,textStatus,err) {                                      console.log(err);                                  }                              });                                function buildTable(data){                                  var table = document.getElementById("recycleTable")                                    for(var i = 0; i < data.length; i++){                                      var row = `<tr>                                                  <td>${data[i].RecyclableID}</td>                                                  <td>${data[i].Name}</td>                                                  <td>${data[i].RecyclableType}</td>                                          </tr>`                                            table.innerHTML += row                                                                            }                              };                                

This is my hightlight Js file

$( document ).ready(function() {  $("#recycleTable").click(function() {    var selected = $(this).hasClass("highlight");    $("#edit").prop('disabled',false);    $("#edit").removeClass('btn btn-secondary');    $("#edit").addClass('btn btn-primary');    $("#delete").prop('disabled',false);    $("#recycleTable").removeClass("highlight");                    if (!selected)      $(this).addClass("highlight");            else       $("#edit").prop('disabled',true) & $("#delete").prop('disabled',true) & $("#edit").removeClass('btn btn-primary') & $("#edit").addClass('btn btn-secondary');;  });  

});

and this is my css style for highlight

    .recycleTable.highlight{           background-color: #ddd;          }  

But however the highlight is not showing but the function for the button are able to work when press different row as the button are enabled or disabled do you know why the highlight is not showing ?

hold longer will jump higher (C# winforms)

Posted: 04 Dec 2021 07:15 AM PST

I am trying to make a 2D game in winforms. i want my character to be able to double jump and if i hold the space key (jump) for a long time i will jump higher or if i hold the space key (jump) less i will jump lower (Note that although holding longer will jump higher, but only up to a fixed level, not to infinity). but I can only double jump and only jump 1 fixed distance, not hold the space longer to jump higher or hold it shorter to jump lower, someone help me, below is my code.

public partial class GamePlay_Page : Form  {  bool goRight, goLeft;  int gravity = 16;  int force;  bool jump;  int jumpTimes = 2;  public GamePlay_Page()  {      InitializeComponent();  }  private void GamePlay_Page_KeyDown(object sender, KeyEventArgs e)  {      if (e.KeyCode == Keys.D)      {          goRight = true;          Trex.Image = Properties.Resources.running;      }      if (e.KeyCode == Keys.A)      {          goLeft = true;          Trex.Image = Properties.Resources.running2;      }      if (e.KeyCode == Keys.W && jumpTimes > 0)      {          jump = true;          force = gravity;          jumpTimes -= 1;        }      private void gameT(object sender, EventArgs e)      {          if (goRight == true && Trex.Right < 600)          {              Trex.Left += 5;          }          if (goLeft == true && Trex.Left > 10)          {              Trex.Left -= 5;          }            if (jump == true)          {              Trex.Top -= force;              force -= 1;          }          if (Trex.Top + Trex.Height >= backgroundAbove.Height)          {              Trex.Top = backgroundAbove.Height - Trex.Height;          }          else          {              Trex.Top += 3;          }          if (Trex.Top + Trex.Height == backgroundAbove.Height)          {              jumpTimes = 2;          }          private void GamePlay_Page_KeyUp(object sender, KeyEventArgs e)          {              if (e.KeyCode == Keys.D) { goRight = false; }              if (e.KeyCode == Keys.A) { goLeft = false; }          }  

How can i us XHR and javascript to get the requestID from the network tab?

Posted: 04 Dec 2021 07:15 AM PST

I am curious on how I can get the data from the network tab using javascript. I want to get the data for the requestID. I already can get the XSR.Token because its stored as a cookie, so curious how can i get other parts of data that isnt stored as a cookie. Any suggestions?

Is Godot engine good for making games in 3d?

Posted: 04 Dec 2021 07:14 AM PST

I have a 3d video game project. I wanted to know if it was possible to create a whole 3d game with Godot engine?Is Godot engine a fast game engine?

CSS backdrop effect - blur background of search bar

Posted: 04 Dec 2021 07:14 AM PST

I'm trying to make the background of (only the search bar) to be a backdrop blur background, without blurring the whole background image behind it. Here's a screenshot of search bar Here's an example of what the background of the search bar should look like I've tried webkit filter: blur & filter: blur, but they both blur the whole body, and not just make the transparent background of the search bar blurred. Note: in the code below I'm not using a background image because I'll embed this code in an iframe, which the background before it will be an image.

<html>  <head>      <base target="_blank">      <base target="_blank">      <script type="text/javascript">          function submitSearch(){                var siteSearchUrl = 'https://support.yssf.ml/_/search?query=';  // Replace with your site's search URL                var query = document.getElementById("search-query-input").value;                var url = siteSearchUrl + query          if(typeof IE_fix != "undefined") // IE8 and lower fix to pass the http referer          {           var referLink = document.createElement("a");           referLink.href = url;           document.body.appendChild(referLink);           referLink.click();          }          else { window.open(url,'_blank'); } // All other browsers          }          function searchKeyPress(e){            // look for window.event in case event isn't passed in            e = e || window.event;            if (e.keyCode == 13)            {                document.getElementById('search-icon').click();                return false;            }            return true;          }                </script>      <link rel="stylesheet" type="text/css" href="https://ssl.gstatic.com/docs/script/css/add-ons.css">      <link href="https://fonts.googleapis.com/css?family=Roboto:400,700" rel="stylesheet">      <style>          body {          margin:0;          padding:14px 6px 0 6px;          background-color:transparent;          font-family: 'Roboto', sans-serif;          overflow:hidden;          }          #search-icon {          margin: 4px 4px 4px 10px;          padding:8px;          height:24px;          vertical-align:middle;          cursor:pointer;          }          #search-icon:hover {          background: rgba(155,153,176, 0.2);          border-radius: 100px;          }          #search-query {          background: inherit;          }          body:before {          background: inherit;          }          #search-query:before {          box-shadow: inset 0 0 2000px rgba(255, 255, 255, .5);          filter: blur(10px);          }          #search-query {          width:max-content;          margin:0 auto;          overflow:hidden;          border:0;          border-radius:14px;          color: #212121;          font-size:16px;          line-height:24px;          transition:0.4s;          }          #search-query:hover {          color: #212121;          box-shadow: 0 2px 2px 0 rgba(0,0,0,0.14), 0 3px 1px -2px rgba(0,0,0,0.12), 0 1px 5px 0 rgba(0,0,0,0.2);          font-size:16px;          line-height:24px;          }          #search-query-input {          width:60vw;          height:24px;          font-size:16px;          font-stretch: normal;          letter-spacing: normal;          line-height:24px;          border:0;          color:#000;          background-color:transparent;          cursor:text;          margin-left:-5px;          text-align:start;          vertical-align:middle;          }          @media (max-width:500px) {#search-query-input {width:80vw}}          @media (min-width:900px) {#search-query-input {width:60vw}}      </style>  </head>  <body>      <!-- <input type="text" id="query" />          <button id="search" onclick="submitSearch()">Search</button> -->      <div id="search-query">          <img id="search-icon" alt="Search" onclick="submitSearch();" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAABgCAQAAABIkb+zAAADAklEQVR4AezZA6xcQRSA4b92g9q2/VRuw9puVLcxake13Zh1G9W2bds2T42ZzNPeO7Pb5H5/zD17PUMgEAgEAoFAIGxFGMRMlrGTi7zjFZfZwTJmMohCRLkajOMYkkRHGUdNolI8B5EUdpB4okpJViOpbDXFiArpGMcHJIzeMY50RFgB9iIe2ksBIiiGR4jHHhFDhHTlI+JDH+lKBMQmceY/YhZNqExBMn+rAJUIMZMnCOY+EItjxRP9OetoTQZMMtCadYixJ5TAoQyYH1cbiCE5CWxADB0jA85MNp7JHUipnsbTbwqO1OWL4RSIIzUSDKfgF+riQBrOIFrPKENqleEZonWGNFjX0vDPNSUcTQ1HsiXWbUO0hhOu4YjWViwri2gdwYvDiFZ5rJqIaMXgRRyiNRGr7iBKa/BqDaJ0G4vKIVqN8Kqxy5OoL6L0mDR4lUZ/o2UA1sxHlBbhh8WI0jys2Y4odcUPXRCl7VhzDVFqgB8aIErXsUZ/fylr5dnyGGv0R38O/JADUfqMNfpLcHb8kF1/Mf/fT6HnWHMdUWqIHxoiSjexZiui1A0/dEWUtmHNPERpsZUH2WJ3rxKPSIdX6XiMKPXGmvKIVgivQohWJSx6YP11+g5WTUK04vAiBtGaBeDyJDqMF0cQrVpYthnRGkq4hiJau7GuhW/LKiHDskpzrEvDKV8WtkobFrZ24UQ9H5YW44xLi7VwZIpxcbcbKdXNuDUyG2cychQxtJ4YkhPPOsTQJXLiUMmwNjhasQUx9obyOBafzBZTiMoUIguZKUhlQszSRtYHaI5z+pnsT6NxKI5HiMee8xlRGoJDhdiNeOg6ZWmNRHKEdIzlXZj7w/PIDYBEdgQoxmokla2nNL9J5EeAeI4iKWwPXfiXRMcIUJPxHEOS6CTDKYVuTGRH0BViEDNZyk4u8gpBeMMuJtKegujcj2DN1/bnmAgAEIBhIJIZGZHOWAEslPsoyCMgIHxPmAgICAjXIQRQSsh+JSH7vYQ1StvZryW8vy9JkiQdHsFQT60Y7OcAAAAASUVORK5CYII=">          <input type="text" id="search-query-input" placeholder="Search" enterkeyhint="go" onkeypress="return searchKeyPress(event);" style="box-shadow:none" ;="">      </div>  </body>  

I've declared variable "x" but i did not call it, is it ok to not call variables that have values assigned?

Posted: 04 Dec 2021 07:16 AM PST

import random      def add_sums(Num):      total = 0      all_num = []      for x in range(1, Num+1):          gen = random.randint(1, 30)          all_num.append(gen)            print("List:", all_num)      for y in all_num:          total += y      print("List total:", total)      user_max = int(input("Max numbers in list: "))  add_sums(user_max)  

In this program, the user will enter the total amount of numbers in a list. the random module will generate random numbers between 1 to 30. Then all the numbers from the list will be added together.

I've tried to use the variable x but it doesn't give the results I want, does anyone know a better/simpler way of creating this program. Also, is it bad practice to create a variable and not call it?

How can I make Firebase Analytics connect to analytics service using React Native for an Android app?

Posted: 04 Dec 2021 07:16 AM PST

The problem is, I seem to have all the code in place, the app runs, but firebase.analytics() returns null. analytics().getAppInstanceId returns an object with 0 and null values.

We're using RNfirebase 13.1.0, the latest package available, Yarn tells me. (Although when I got to rnfirebase.io there seems to be a 15.0.0 release.)

We've correctly created a firebase project and installed the json file downloaded from the project, into the Android Studio project. We've correctly modified the gradle files in the Android Studio project.

Everything runs, but no connection, responses return null objects and we cannot log events.

More to come, I'll include some code soon.

How can I compare a files's SHA256 hash in powershell to a known value? Additional question

Posted: 04 Dec 2021 07:15 AM PST

@Mac I just found the below link for powershell, and it is very helpful. How would one specify that there is normal text inside, say a .txt file other than just the hash. For example the .txt I'm working with has descriptive text in it, the first line is the filename, second line is MD5 Checksum: xxxxxxxxxxxx, third line is SHA-1 Checksum: xxxxxxxxx, and the last line is SHA-256 checksum: xxxxxxxxx. Any ideas?

How can I compare a files's SHA256 hash in powershell to a known value?

MongoDB aggregate to extract values from a nested array and return a total

Posted: 04 Dec 2021 07:16 AM PST

I have this collection structure:

[     "_id": "61a013b59f9dd0ebfd23ftgb",     "modules": [       {         "_id": "61a013b59f9dd0ebfd964dgh",         "videos": [           {             "_id": "213412",             "progress": 100           },           {             "_id": "61a013b59f9dd0ebfd965f4a",             "progress": 0           },         ]       },       {         "_id": "43556hujferwdhgsdft",         "videos": [           {             "_id": "fdsg3sg98er989890",             "progress": 66           },           {             "_id": "fdsg3sg98er989890",             "progress": 100           },           {             "_id": "fdsg3sg98er989890",             "progress": 100           }         ]       }     ]   ]  

I am trying to return the overall progress for each "module" by adding up all the videos that have progress of 100 and creating a percentage based on number of videos in the module. For example, the first module should return "module_progess" of 50 within it as this has 1/2 videos completed.

{     "_id": "61a013b59f9dd0ebfd964dgh",     "module_progress": 50,     "videos": [       {         "_id": "213412",         "progress": 100       },       {         "_id": "61a013b59f9dd0ebfd965f4a",         "progress": 0       },     ]  },  

How do i access each videos object to make this calculation and add the new field to the response?

What is the difference of ControlValueAccessor and banana in a box syntax in implementing two way binding?

Posted: 04 Dec 2021 07:15 AM PST

I just found out that there are several ways to implement two way binding in a custom component. What I can't understand is the difference between them. When shoud I prefer using a component which uses banana in a box syntax (with an @input() and @Output() for the model), to implements two way binding like this component

@Component({    selector: 'app-first-component',    template: `      <p>input model value: {{ inputModel }}</p>      <button (click)="clickHandler()">Clear</button>    `  })  export class FirstComponentComponent {    @Input() inputModel: string;    @Output() inputModelChange = new EventEmitter<string> ();      clickHandler(): void {      this.inputModel = '';      this.inputModelChange.emit(this.inputModel);    }  }  

and one which implements ControlValuAccessor like this

@Component({    selector: 'app-second-component',    template: `      <p>input model value: {{ inputModel }}</p>      <button (click)="clickHandler()">Clear</button>    `,    providers: [{      provide: NG_VALUE_ACCESSOR,      useExisting: forwardRef(() => SecondComponentComponent),      multi: true    }]  })  export class SecondComponentComponent implements ControlValueAccessor {    private inputModel: string;    private onChanged: (value: string) => void = () => {};      clickHandler(): void {      this.inputModel = '';      this.onChanged(this.inputModel);    }      registerOnChange(fn: any): void {      this.onChanged = fn;    }      writeValue(value: string) {      this.inputModel = value;      this.onChanged(this.inputModel);    }      registerOnTouched(): void {/* ignored */}  }  

I they're used in a parent component like this

<app-first-component [(inputModel)]="value"> </app-first-component>    <app-second-component [(ngModel)]="value"> </app-second-component>  

As you can see they are used in the same way and also do the same job. If so, why is there ControlValueAccessor? Is there anything I can do with the second component which is not feasible with the first one?

Logical && and II operation with integer in Java

Posted: 04 Dec 2021 07:16 AM PST

I have understood reading some problems here about the logical operation in Java. In Java, the whole operation is concentrating on boolean values, unlike C/C++. In C++,

#include <iostream>  using namespace std;  int main()  {      int i=1, j= 1, k=0,m;      m= ++i || ++j && ++k ;      cout<<m;      return 0;  }  

I just wanted to learn how can I write this program in Java so that I can get the expected result.

How to display treeview

Posted: 04 Dec 2021 07:15 AM PST

i learned treeview and tried to do this style of code just to try different perspective on how to open treeview and currently i tried to do this type and the treeview does not appear on toplevel and currently this is what i did:

from tkinter import ttk  import tkinter as tk    class setup(tk.Tk):      def __init__(self):          tk.Tk.__init__(self)          self._frame = None          self.switch_frame(mainpage)        def switch_frame(self, frame_class):          """Destroys current frame and replaces it with a new one."""          new_frame = frame_class(self)          if self._frame is not None:              self._frame.destroy()          self._frame = new_frame          self._frame.place(x=0, y=0, relwidth=1, relheight=1)    class mainpage(tk.Frame):      def __init__(self, master):          tk.Frame.__init__(self,master)          master.geometry("400x400")          treeview = tk.Button(self, text="open treeview", command=lambda: display_treeview()).pack()    class my_treeview(tk.Toplevel):      def __init__(self, tree):          tk.Toplevel.__init__(self)          self.tree = tree          tree = ttk.Treeview()          self.title("this is toplevel for treeview")          self.geometry("600x500")    class display_treeview(ttk.Treeview):      def __init__(self):          ttk.Treeview.__init__(self)          self.insert("", "0", "item1", text="fill width")          self.insert("", "0", "item2", text="fill width")          my_treeview(display_treeview)    if __name__ == "__main__":      app = setup()      app.mainloop()  

the last working example i just did this:

from tkinter import ttk  import tkinter as tk      def my_treeview():      mt = tk.Toplevel()      mt.geometry("1000x580")        tree = ttk.Treeview(mt)      tree.insert("", "0", "item1", text="fill width")      tree.insert("", "1", "item2", text="fill height")        tree.pack(fill="both")      root = tk.Tk()  root.geometry("400x400")    treeview = tk.Button(root, text="open treeview", command=my_treeview).pack()    root.mainloop()  

How to execute code after all the threads finished execution?

Posted: 04 Dec 2021 07:16 AM PST

private void processEvents(List<Object> events) {            CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(                  () -> processEventsAsynchronously(events));          while (!completableFuture.isDone() || completableFuture.isCancelled() || completableFuture.isCompletedExceptionally()) {              // waiting for all threads to get processed          }            if (completableFuture.isDone() || completableFuture.isCancelled() || completableFuture.isCompletedExceptionally()) {              executeRemainingFlow();          }      }        private void processEventsAsynchronously(List<Object> events) {          Executor executor = Executors.newFixedThreadPool(5);          for (Object event : events) {              Runnable runnable = () -> processEvent(event);              executor.execute(runnable);          }      }        private void processEvent(Object event) {                try {              Thread.sleep(3000);          } catch (InterruptedException e) {              e.printStackTrace();          }      }        private void executeRemainingFlow() {        }  

Here I want to process list of events asynchronously and once the processing is done I want to implement remaining flow. I tried to use CompletableFuture but the code inside the executer getting executed after executeRemainingFlow().

Is there a JpaRepository method which can save a provided password where username condition?

Posted: 04 Dec 2021 07:15 AM PST

I am looking for a JpaRepository method to update a user provided password at the time of resetting it with a username condition . Thanks in advance

Use dplyr's if_else function with functional true/false values

Posted: 04 Dec 2021 07:17 AM PST

Question

How can dplyr's if_else() function be used such that its output is a function? With ifelse() from base this is trivial but with if_else() something goes wrong. Is that intended behavior or am I just not able to do that properly?

Reprex

x <- 2  ifelse(x == 2, min, max)  #> function (..., na.rm = FALSE)  .Primitive("min")  dplyr::if_else(x == 2, min, max)  #> Error in true[rep(NA_integer_, length(condition))]: object of type 'builtin' is not subsettable  

Created on 2021-12-04 by the reprex package (v2.0.0)

React chip input field

Posted: 04 Dec 2021 07:16 AM PST

I'm using React 17 and tried to use different chip input fields like material-ui-chip-input etc. Unfortunately, all npm packages I tried do not work with react version 17.

Do you know of any component that works with this version or how I could create one myself?

Thanks in advance

Edit: I have managed to do what I wanted, but unfortunately, I now get the following error when pressing enter / adding a new item:

index.js:1 Warning: Cannot update a component (CreatePoll) while rendering a different component (ForwardRef(Autocomplete))

Here is the codesandbox which shows the problem: https://codesandbox.io/s/compassionate-greider-wr9wq?file=/src/App.tsx

Installing OS from ISO on hard disk ( no server is specified )

Posted: 04 Dec 2021 07:16 AM PST

I am trying to install OS from ISO on hard disk with root in (hd0,gpt4) and iso is stored in (hd0,gpt14). (validated from grub command line)

Following is my grub2 configuration :

menuentry "OS-Remote-Installation" --class sles --class gnu-linux --class gnu --class os {    set isofile="/home/viswas/packages/SLES.iso"  search --no-floppy --label --set=root "root_part"   // label of root partition  loopback loop $isofile  linuxefi (loop)/boot/x86_64/loader/linux isoloop=$isofile splash=silent showopts autoyast=device:///autoyast/ install=hd:$isofile  initrdefi (loop)/boot/x86_64/loader/initrd  }    

I have validated each line seems like iso file and search locations are proper and loopback isnt complaining either but linuxefi is complaining about the following error.

error : ../../grub-core/net/net.c:1312 : no server is specified.  error : ../../grub-core/loader/i386/efi/linux.c:98:you need to load the kernel first.    Press any key to continue ...  

How to make components evenly share JPanel container vertical area with GridBagLayout layout on resizing?

Posted: 04 Dec 2021 07:15 AM PST

The problem:

JPanel with GridBagLayout contains two JScrollPane components, the top one contains JTextArea, the bottom one contains JTable. I expect this set up to make the components fluidly fill the container JPanel and evenly share the vertical area of it on resizing. What actually happens is that the top JScrollPane component shrinks vertically on resizing giving more vertical area to the bottom JScrollPane component to invade; this happens at some sizes, I don not know if they are random.

Importatn notes:

I already applied GridBagConstraints#weighty = 0.5; to both components, which is supposed to do the job.

I noticed that the problem is because of the presence of the JTextArea, in that if I switch locations; make the JScrollPane/JTextArea on the bottom side and JScrollPane/JTable on the top side; the bottom component JScrollPane/JTextArea shrinks vertically giving more vertical area to the top component JScrollPane/JTable to invade.

I know this exact case can be solved simply using GridLayout(2,1) instead of GridBagLayout (or may be other solutions), however I am fan of GridBagLayout and I want to use most of it. Also if I want to add three components instead of two and I want to make them share the vertical area by percentage for example (%25, %25, 50%) I can use GridBagConstraints#weighty = (0.25, 0.25, 0.5) which is easily applicable with GridBagLayout.

So, in this case how to make components evenly share the vertical area of JPanel container with GridBagLayout on resizing?. Or, in other words; how to enforce components to respect GridBagConstraints#weighty = 0.5; setting on resizing which is applied to both?

Code in SSCCE format:

import java.awt.Dimension;  import java.awt.GridBagConstraints;  import java.awt.GridBagLayout;  import javax.swing.JFrame;  import javax.swing.JPanel;  import javax.swing.JScrollPane;  import javax.swing.JTable;  import javax.swing.JTextArea;  import javax.swing.table.DefaultTableModel;    public class GridBagFluidFill {        private static JPanel createFormPanel() {            JPanel containerPanel = new JPanel(new GridBagLayout());          containerPanel.setPreferredSize(new Dimension(350, 200));          JScrollPane scrollableTextArea;          JScrollPane scrollableTable;            JTextArea textArea = new JTextArea();          scrollableTextArea = new JScrollPane(textArea);            DefaultTableModel model = new DefaultTableModel(new String[]{"Column1", "Column2", "Column3"}, 0);          JTable table = new JTable(model);          scrollableTable = new JScrollPane(table);            GridBagConstraints c = new GridBagConstraints();          c.gridy = 0;          c.weightx = 1.0;          // I expect this to reserve 50% of the height all time.          c.weighty = 0.5;          c.fill = GridBagConstraints.BOTH;          c.anchor = GridBagConstraints.PAGE_START;          containerPanel.add(scrollableTextArea, c);            c = new GridBagConstraints();          c.gridy = 1;          c.weightx = 1.0;          // I expect this to reserve 50% of the height all time.          c.weighty = 0.5;          c.fill = GridBagConstraints.BOTH;          c.anchor = GridBagConstraints.PAGE_END;          containerPanel.add(scrollableTable, c);            return containerPanel;      }        public static void main(String[] args) {          javax.swing.SwingUtilities.invokeLater(() -> {              JPanel formPanel = createFormPanel();              JFrame frame = new JFrame("GridBagFluidFill");              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);              frame.getContentPane().add(formPanel);              frame.pack();              frame.setVisible(true);          });      }  }  

pyQt5 not displaying progressbar

Posted: 04 Dec 2021 07:16 AM PST

I want to start the progress bar on click of pushButton but the Widgets are not displaying in the QMainWindow. I don't know why this is happening? This is happening in my main code actually, here I am showing a small example of that.

Button is also not displayed , only a blank screen is coming.

from PyQt5.QtCore import pyqtSlot, pyqtSignal, QObject, QThread  from PyQt5 import QtWidgets, QtCore  from sys import exit, argv  from time import sleep  import sys  from random import randint    class PopUpProgressBar(QtWidgets.QWidget):        def __init__(self):          super().__init__()            ## To remove title bar          self.setWindowFlags(QtCore.Qt.Window | QtCore.Qt.CustomizeWindowHint | QtCore.Qt.Tool)          layout = QtWidgets.QVBoxLayout()                    self.widget = QtWidgets.QWidget(self)          layout.addWidget(self.widget)            self.label = QtWidgets.QLabel("Another Window % d" % randint(0,100))          layout.addWidget(self.label)            self.widget.setStyleSheet('QWidget { color: rgb(255, 100, 255); border: someborder; border: 20px solid green;}')            self.setWindowTitle('WORK IN PROGRESS, PLEASE WAIT ...!')          self.setWindowFlag(QtCore.Qt.WindowCloseButtonHint, False)          # self.setWindowFlag(QtCore.Qt.WindowTitleHint, False)          self.setLayout(layout)          self.setGeometry(700, 500, 650, 100)          def start_progress(self):  # To restart the progress every time          self.show()      class AppDemo(QtWidgets.QWidget):      def __init__(self):          super().__init__()          self.setWindowTitle('Progress Bar Demo')          self.resize(500, 100)            self.pushButton = QtWidgets.QPushButton()          self.pushButton.clicked.connect(self.push)            self.popup = PopUpProgressBar()        def push(self):          self.popup.start_progress()        #     self.progressBar = QProgressBar(self)      #     self.progressBar.setGeometry(25, 25, 300, 40)      #     self.progressBar.setMaximum(100)      #     self.progressBar.setValue(0)        #     timer = QTimer(self)      #     timer.timeout.connect(self.Increase_Step)      #     timer.start(1000)        # def Increase_Step(self):      #     self.progressBar.setValue(self.progressBar.value() + 1)    app = QtWidgets.QApplication(sys.argv)    demo = AppDemo()  demo.show()    sys.exit(app.exec_())  

Remove rows from recursive query

Posted: 04 Dec 2021 07:15 AM PST

When I run this query in my database I get the following:

WITH RECURSIVE series AS (      SELECT CONCAT( a.title) as str, a.prequelID      FROM ( Prequels NATURAL JOIN Books) AS a      UNION      SELECT CONCAT(t.title, ' -> ', str) as str, t.prequelID  FROM (Books NATURAL JOIN Prequels) as t   INNER JOIN series AS s ON s.prequelID = t.bookID  )  SELECT str as series FROM series  ORDER BY series;  

This is the result :

enter image description here

I don't want any duplicates, only the full string that shows the whole series. How do I do this?

UPDATE:

I updated the query because I realised I was missing the first book in the series.

WITH RECURSIVE series AS (      SELECT CONCAT( a.title) as str, a.prequelID      FROM ( Prequels NATURAL JOIN Books) AS a      UNION      SELECT CONCAT(t.title, ' -> ', str) as str, t.prequelID  FROM (Books NATURAL JOIN Prequels) as t   INNER JOIN series AS s ON s.prequelID = t.bookID  )  SELECT CONCAT(a.title, ' -> ',a.str) as series  FROM (  SELECT Books.title, series.str  FROM series JOIN Books ON series.prequelID = Books.bookID  WHERE NOT EXISTS(          SELECT prequelID          FROM Prequels          WHERE series.prequelID = Prequels.bookID  )   ) a  ORDER BY series;  

The result is still a bit off, since I only want the complete string of the series: enter image description here

How do I fix this?

Tables:

CREATE TABLE Books  (bookID integer PRIMARY KEY,  title varchar(100),  pages integer);      CREATE TABLE Prequels  (bookID INTEGER REFERENCES Books(bookID),  prequelID INTEGER REFERENCES Books(bookID),  PRIMARY KEY (bookID,prequelID));  

Sample data of the Game of Thornes series:

INSERT INTO BOOKS (bookID,title,pages) VALUES (80429,'A Game of Thrones',292);  INSERT INTO BOOKS (bookID,title,pages) VALUES (41121,'A Clash of Kings',160);  INSERT INTO BOOKS (bookID,title,pages) VALUES (29287,'A Storm of Swords',160);  INSERT INTO BOOKS (bookID,title,pages) VALUES (17696,'A Feast for Crows',292);  INSERT INTO BOOKS (bookID,title,pages) VALUES (3947,'A Dance with Dragons',101);      INSERT INTO Prequels (bookID,prequelID) VALUES (41121,80429);  INSERT INTO Prequels (bookID,prequelID) VALUES (29287,41121);  INSERT INTO Prequels (bookID,prequelID) VALUES (17696,29287);  INSERT INTO Prequels (bookID,prequelID) VALUES (3947,17696);    

Need to exclude few words from logs using grok

Posted: 04 Dec 2021 07:16 AM PST

Consider the below string

date 00:00 1.1.1.1 POST test.com hello-world

How could I print only the date totaltime and URL(test.com) using grok?

Blank White Screen after adding Firebase to flutter

Posted: 04 Dec 2021 07:15 AM PST

After i add Firebase to my flutter project both android and IOS app not working . here is the error ,

Note-IOS does installing the app , but shows only white blank screen

Android

e: /Users/capt.nizam/.gradle/caches/transforms-2/files-2.1/00446b2c2a7eae3f618598721af19725/jetified-firebase-analytics-ktx-20.0.0-api.jar!/META-INF/java.com.google.android.libraries.firebase.firebase_analytics_ktx_granule.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.  

FAILURE: Build failed with an exception.

  • What went wrong: Execution failed for task ':app:compileDebugKotlin'.

Compilation error. See log for more details

  • Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

  • Get more help at https://help.gradle.org

BUILD FAILED in 12s Exception: Gradle task assembleDebug failed with exit code 1

And IOS APP

Debug service listening on ws://127.0.0.1:61461/6M_23sVQpSg=/ws  

Syncing files to device iPhone 13 Pro Max... [VERBOSE-2:ui_dart_state.cc(209)] Unhandled Exception: Null check operator used on a null value #0 MethodChannel.binaryMessenger (package:flutter/src/services/platform_channel.dart:121:86) #1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:146:36) #2 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:329:12) #3 MethodChannel.invokeListMethod (package:flutter/src/services/platform_channel.dart:342:41) #4 MethodChannelFirebase._initializeCore (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:31:37) #5 MethodChannelFirebase.initializeApp (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:73:13) #6 Firebase.initializeApp (package:firebase_core/src/firebase.dart:42:47) #7 main (package:ipqb/main.dart:7:18) #8 _runMainZoned.. (dart:ui/hooks.dart:145:25) #9 _rootRun (dart:async/zone.d<…>

I followed everything in the docs. i tried multiple time , even checked in a new project i am facing same error !

Automatically Update Python source code (imports)

Posted: 04 Dec 2021 07:16 AM PST

We are refactoring our code base.

Old:

from a.b import foo_method  

New:

from b.d import bar_method  

Both methods (foo_method() and bar_method()) are the same. It just changed the name an the package.

Since above example is just one example of many ways a method can be imported, I don't think a simple regular expression can help here.

How to refactor the importing of a module with a command line tool?

A lot of source code lines need to be changed, so that an IDE does not help here.

Why I get "UnhandledPromiseRejectionWarning: Error: Undefined type error. Make sure are providing an explicit type" even after I have specified type?

Posted: 04 Dec 2021 07:16 AM PST

create method is working well. No errors. But I need a way to insert a large number of records at once. That's why I'm trying to use the createQueryBuilder.

What is the reason for it to say Undefined type error? I have already defined the type as Boolean.

This is my resolver

  @Resolver(() => Vehicle)  export class VehicleResolver {    constructor(private vehicleService: VehicleService) {}      @Mutation(() => Vehicle, { name: 'createVehicle' })    create(@Args('vehicleInput') vehicle: VehicleCreateDTO) {      return this.vehicleService.create(vehicle);    }      @Mutation(() => Boolean, { name: 'createVehicleBulk' })    async createVehicleBulk(@Args('vehiclesInput') vehicles: [VehicleCreateDTO]) {      const res = await this.vehicleService        .createBulk(vehicles)        .catch((err) => console.log(err));      if (res) return true;      else return false;    }  }  

This is my service

  @Injectable()  export class VehicleService {    constructor(      @InjectRepository(Vehicle) private vehicleRepo: Repository<Vehicle>,    ) {}      create(vehicle: VehicleCreateDTO): Promise<Vehicle> {      const vcl = this.vehicleRepo.create(vehicle);      return this.vehicleRepo.save(vcl);    }      async createBulk(vehicles: VehicleCreateDTO[]): Promise<InsertResult> {      const res = await this.vehicleRepo        .createQueryBuilder()        .insert()        .into('vehicle')        .values(vehicles)        .execute();      return res;    }  }    

I want to save an array of objects of type VehicleCreateDTO. But I get the following error.

(node:11464) UnhandledPromiseRejectionWarning: Error: Undefined type error. Make sure you are providing an explicit type for the "createBulk" (parameter at index [0]) of the "VehicleResolver" class.      at Object.reflectTypeFromMetadata (E:\COL\backend\vehicle-service-insert\node_modules\@nestjs\graphql\dist\utils\reflection.utilts.js:15:15)       at E:\COL\backend\vehicle-service-insert\node_modules\@nestjs\graphql\dist\decorators\args.decorator.js:17:78      at E:\COL\backend\vehicle-service-insert\node_modules\@nestjs\graphql\dist\schema-builder\storages\lazy-metadata.storage.js:36:44      at Array.forEach (<anonymous>)      at LazyMetadataStorageHost.load (E:\COL\backend\vehicle-service-insert\node_modules\@nestjs\graphql\dist\schema-builder\storages\lazy-metadata.storage.js:36:26)      at GraphQLSchemaFactory.<anonymous> (E:\COL\backend\vehicle-service-insert\node_modules\@nestjs\graphql\dist\schema-builder\graphql-schema.factory.js:37:57)      at Generator.next (<anonymous>)      at E:\COL\backend\vehicle-service-insert\node_modules\@nestjs\graphql\node_modules\tslib\tslib.js:117:75      at new Promise (<anonymous>)      at Object.__awaiter (E:\COL\backend\vehicle-service-insert\node_modules\@nestjs\graphql\node_modules\tslib\tslib.js:113:16)  (Use `node --trace-warnings ...` to show where the warning was created)  (node:11464) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)  (node:11464) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.      

How to use the ternary operator in react using javascript styled components?

Posted: 04 Dec 2021 07:15 AM PST

I have a piece code for which i am not understanding what this ternary operator means.

below is my code,

const mobileWidth = '800'px;  const Width = '1200'px;  const Wrapper = styled.div`      width: ${props =>          props.theme.isMobile              ? props.theme.isPortrait                  ? 'calc(100% - 162px)'                  : mobileWidth              : Width};  `;  

could someone help me understand this. thanks.

No comments:

Post a Comment