Monday, May 2, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Querying using website field for Companies - Marketo REST API

Posted: 02 May 2022 12:31 AM PDT

I am unable to query company from Marketo using website field as a key in Marketo REST API.

rest/v1/companies.json?fields=id&filterType=Website&filterValues=www.mcd.in

Documentation - https://developers.marketo.com/rest-api/lead-database/companies/

I am getting invalid filterType error. Is there any way I can query using website field as a key ?

Why Getting 404 error in my golang code? I'm having trouble in writing API

Posted: 02 May 2022 12:31 AM PDT

userGroup.PUT("/update", user.UserUpdate)

func (u UserController) UserUpdate(c *gin.Context) { log.Println("UserUpdate(): START")

// Find users    var userForm forms.User  if err := c.BindJSON(&userForm); err != nil {      c.JSON(http.StatusBadRequest, gin.H{"message": "Invalid request payload", "error": err.Error()})      return  }    // Update User  user, err := userModel.DbUserUpdate(userForm)  if err != nil {      log.Println("There was an error while updating the user", err)      c.JSON(http.StatusInternalServerError, gin.H{"message": "Error creating user. Please try later", "error": err.Error()})      c.Abort()      return  }    log.Println("UserCreate(): END")  c.JSON(http.StatusOK, gin.H{"message": "User Updated Successfully!", "user": user})  

}

func (h User) DbUserUpdate(userForm forms.User) (*User, error) { log.Println("UserUpdate() START: id =", userForm.Id)

db := db.GetDB()    // Update  var users []User  if err := db.Where(&users, "id = ?", userForm.Id).Updates(User{Name: userForm.Name}).Error; err != nil {      log.Println("Error while deleting the user", err)      return nil, err  }    log.Println("DbUserUpdate(): END")  return (*User)(&userForm), nil  

}

Can I install Oracle Database ( enterprise edition or express edition) on my laptop which has processor - Intel(R) Core(TM) i7-1165G7?

Posted: 02 May 2022 12:31 AM PDT

Can I install Oracle Database ( enterprise edition or express edition) on my laptop which has processor - Intel(R) Core(TM) i7-1165G7 ? My os is Windows 11. I tried installing 19c and 21c several times but it is not getting installed.

TypeError: Cannot read properties of undefined (reading 'endsWith')

Posted: 02 May 2022 12:31 AM PDT

I am trying to print out all countries which end with 'land' from the countries array below:

const countries = [    'Albania',    'Bolivia',    'Canada',    'Denmark',    'Ethiopia',    'Finland',    'Germany',    'Hungary',    'Ireland',    'Japan',    'Kenya'  ]    newArr = [];    for (let i = 0; i <= countries.length; i++){    console.log(countries[i])    if (countries[i].endsWith('land') === true){      newArr.push(countries[i])    }    else{      continue    }  }  

However, I am having a TypeError: Cannot read properties of undefined (reading 'endsWith)

turi create and label studio, error join annotation with photo

Posted: 02 May 2022 12:31 AM PDT

I just start digging into Machine Learning, Turi Create and Label Studio.

I'm try to implement a model of Object Detecting using Turi Create. For simplicity I just use 1 photo which is locate in my Desktop, inside a folder CondaMLProject.

Using the software Label Studio I place the label on this photo and export the csv file annotation

I notice that the csv file is like:

pic

as you can see the image column report a wrong link to the photo, is not my desktop link.

when I run the python script of turi create to join the the image to the annotation I'm getting error

import turicreate as tc      path = "Spikosmall"  pathAnnotation = "Spikosmall/annotation.csv"  images = tc.load_images(path, with_path=True)    annotation = tc.SFrame(pathAnnotation)  data = images.join(annotation)  

Error:

Columns image and image do not have the same type in both SFrames  

How can I solve this issue? Not so smart in python .. looking for some code to iterate inside the column image and change the link to match the photo folder..

Is there any other solution? Thanks

How do I add a rarefaction curve with extrapoation using rarefaction function from package 'mobr' in R?

Posted: 02 May 2022 12:30 AM PDT

I ended up calculating a spatial sample-based rarefaction in which species are accumulated by including spatially proximate samples first, using the rarefaction function from the mobr package.

I can easily plot this in base r, but can't figure out how to add a curve to my plot, complete with a 95% CI extrapolation for the species richness. A good example of this can be seen in the iNEXT package https://cran.r-project.org/web/packages/iNEXT/vignettes/Introduction.html.

Can anyone please help me out?

Semi Circle Donut Chart with Altair

Posted: 02 May 2022 12:30 AM PDT

I'm new to Altair. Could you help me to figure out how to plot something like this?

enter image description here

Obtaining an item count from a list in a Django template

Posted: 02 May 2022 12:29 AM PDT

I am trying to get the object count on a 'list' using the length filter in the Django template and it is returning the number of characters. It looks like my list is not a real list but rather a long string. My mixin looks like this:

class ItemObjectMixin:  model = None  template_name = None  my_filter = ItemFilter    def get(self, request):      items = self.model.objects.all()      items_count = items.count()        itemsFilter = ItemsFilter(request.GET, queryset=items)      items = itemsFilter.qs      remaining = items.count()        return render(request, self.template_name, locals())  

And my class-based view looks like:

class MyItemsListView(ItemObjectMixin, ListView):  model = Items  template_name = "Items/myItems.html"  

My template has the following partial code:

      <tbody>          {% for item in items %}          <tr>              <td><a href="/item/{{ item.slug }}">{{ item.title }}</a></td>              <td>{{ item.id }}</td>              {% if item.group_of_items %}              <td>{{ item.group_of_items|length }}</td>              {% endif %}              <td>{{ item.group_of_items }}</td>          </tr>          {% endif %}      </tbody>  

The code {{ item.group_of_items|length }} gives the number of characters for each instance of 'group_of_items'. I understand why this is happening but would like a solution where the for loop gives a list of objects rather than a string. Any takers? Cheers.

better algorithm to find the biggest annulus without points in it in

Posted: 02 May 2022 12:29 AM PDT

I have a BST whose sorting is based on radius and phase of the Cartesian points. Here's the implementation:

 public class BST {        private BinNode root;      private int size;          public BST() {          this.root = null;          size = 0;      }              private double getRadius(double x, double y) {          return Math.sqrt(x*x+y*y);      }         public double getRadius(BinNode t) {                 if (t == null) return -1;                    return getRadius(t.getCoordinates()[0],t.getCoordinates()[1]);      }        private double getPhase(double x, double y) {           return Math.atan2(y,x);      }        private double getPhase(BinNode t){          return getPhase(t.getCoordinates()[0],t.getCoordinates()[1]);      }                   private BinNode BST_insert_aux(double x, double y, double r, double p, BinNode t) {                    double tr = getRadius(t);          double tp = getPhase(t);                                                  if (t.left == null && t.right != null) { //has only the right child                                                    if (r < tr) {                                                   t.setLeft(new BinNode(x, y)); return t.getLeft();                             }                            else if (r == tr) {                                                                    if (p < tp) {                                                 t.setLeft(new BinNode(x, y)); return t.getLeft();                   }                                    else if (p == tp) {                   return null; }                                    else if (p > tp) {                                                               return BST_insert_aux(x, y, r, p, t.getRight());                  }              }                            else if (r > tr) {                                    return BST_insert_aux(x, y, r, p, t.getRight());              }          }                              else if (t.left != null && t.right == null) { //has only the left child                            if (r < tr) {           return BST_insert_aux(x, y, r, p, t.getLeft()); }                    else if (r == tr) {                                                            if (p < tp) {                   return BST_insert_aux(x, y, r, p, t.getLeft()); }                                    else if (p == tp) {                   return null; }                                    else if (p > tp) {                    t.setRight(new BinNode(x, y)); return t.getRight(); }              }                        else if (r > tr) {            t.setRight(new BinNode(x, y)); return t.getRight(); }                }                              else if (t.left == null && t.right == null) { //leaf                                          if (r < tr) {                t.setLeft(new BinNode(x, y)); return t.getLeft(); }                                    else if (r == tr) {                                                          if (p < tp) {                    t.setLeft(new BinNode(x, y)); return t.getLeft(); }                                    else if (p == tp) {                    return null; }                                    else if (p > tp) {                   t.setRight(new BinNode(x, y)); return t.getRight(); }              }                            else if (r > tr) {               t.setRight(new BinNode(x, y)); return t.getRight(); }                    }                              else { //has both childs                                                if (r < tr) {               return BST_insert_aux(x, y, r, p, t.getLeft()); }                            else if (r == tr) {                                                                if (p < tp) {                   return BST_insert_aux(x, y, r, p, t.getLeft()); }                                    else if (p == tp) {                   return null; }                                    else if (p > tp) {                   return BST_insert_aux(x, y, r, p, t.getRight()); }              }                            else if (r > tr) {               return BST_insert_aux(x, y, r, p, t.getRight()); }          }                    return null;      }              public BinNode BST_insert(double x, double y) {                      if (root == null) {              root = new BinNode(x, y);              return root;          }                                 return BST_insert_aux(x, y, getRadius(x,y), getPhase(x,y), root);       }        private void print(BinNode t, int level, char pos) {                   if (t==null) return;          for (int i = 0; i < level - 1; i++) {              System.out.print("   ");          }            if (level > 0) {              System.out.print(" "+pos+":--");          }            System.out.println("coordinate: ("+ t.getCoordinates()[0]+","+t.getCoordinates()[1]+"); radius="               + getRadius(t) + " ; phase=" + getPhase(t) );            print(t.getLeft(), level + 1,'l');          print(t.getRight(), level + 1,'r');      }            public void BST_print() {          if (root!=null)              print(this.root, 0,' ');      }  

I am sorry if the code is too long, but I am new to Stack Overflow so I do not know if omitting part of the code for the sake of brevity would be better. Anyway, I have to write a method to find the area of ​​the maximum annulus that has no points inside it (those on the border, so with a radius equal to one of the two radius of the annulus are fine). Obviously the annulus must be of finite size, so there must exist in the plane at least one point with a radius greater than or equal to that of the big radius of the annulus. To do this I wrote an auxiliary method Annulus(double r1, double r2) that count how many points in the BST have a radius between r1 and r2. Here is the code:

  public int Annulus(double r1, double r2) {                System.out.println("RANGE QUERY: from " + r1 + " to " + r2);              if (r2 < r1) { System.out.println("r2 must be >= r1"); return -1; }        int[] cont = new int[1];                cont[0] = 0;                Annulus_aux(r1, r2, root, cont);            return cont[0];    }                  private void Annulus_aux(double r1, double r2, BinNode t, int[] cont) {                if (t == null) {               return;           }                else {                    double tr = getRadius(t);          double tp = getPhase(t);                                                  if (r1 >= tr) {                                    Annulus_aux(r1, r2, t.getRight(), cont);              }                            else {                                    Annulus_aux(r1, r2, t.getLeft(), cont);                                    if (r2 > tr) {                                        cont[0]++;                                        Annulus_aux(r1, r2, t.getRight(), cont);                  }                                                  }                    }            }  

The problem is in the following methods:

  public double maxAnnulus() {                LinkedList<BinNode> nodes = new LinkedList<>();                    collectNodes(nodes, root);                    double maxArea = 0;                    for (BinNode e: nodes) {                            if (Annulus(0, getRadius(e)) == 0)  { //r1 = origin                                double currentArea = area(0, getRadius(e));                                if (currentArea > maxArea) {                      System.out.println("\n\n");                       maxArea = currentArea;                  }              }                                          for (BinNode ne: nodes) {                                double r1 = getRadius(e);                  double r2 = getRadius(ne);                                if (Annulus(r1, r2) == 0)  {                                        double currentArea = area(r1,r2);                                    if (currentArea > maxArea) {                                          System.out.println("\n\n");                          maxArea = currentArea;                      }                  }              }                    }                       return maxArea;      }              private void collectNodes(LinkedList<BinNode> nodes, BinNode t) {                if (t != null) {                    collectNodes(nodes, t.getLeft());                    nodes.add(t);                        collectNodes(nodes, t.getRight());          }      }                      private double area(double r1, double r2) {           System.out.println("a1 = " + Math.PI * Math.pow(r1, 2));      System.out.println("a2 = " + Math.PI * Math.pow(r2, 2));            System.out.println("a2-a1 = " + Math.PI * (Math.pow(r2,2) - Math.pow(r1,2)));            System.out.println("\n\n");            return Math.PI * (Math.pow(r2,2) - Math.pow(r1,2));               }  }        

maxAnnulus() calculates the area of ​​the maximum annulus. To do this, it calls the collectNodes (nodes, root) method which inserts the nodes of the BST in a linkedlist. Then for each element of the linkedlist it calculates the area between its radius and the radius of every other element of the linkedlist (plus the origin), but only if the number of internal points between the two radius is 0. Then comparing the various areas, I find the largest one.

I am absolutely sure there are so many better ways to solve this problem.

C compiler] @flags doesn't work on my bash

Posted: 02 May 2022 12:31 AM PDT

I'm using Cygwin terminal bash on Windows Terminal App; and gcc doesn't recognize about @flags. It tells: "cannot find @flags: No such file or directory"

my process on Terminal>

  • $ touch flags && echo "-Werror -g" > flags
  • $ gcc main.c @flags
  • /usr/lib/gcc/x86_64-pc-cygwin/11/../../../../x86_64-pc-cygwin/bin/ld: cannot find out: No such file or directory

how to fix it? or is there another way i don't know to do @flags?

Libarchive - Creating a single .zip archive with some files encrypted(PKzip) and few other files not encrypted

Posted: 02 May 2022 12:31 AM PDT

I am trying out libarchive to try to find out whether it is useful for my purpose.

I have a .zip file, with few files encrypted (PKzip) and few other files un-encrypted. I am able to successfully extract my .zip file using libarchive without a problem.

But when I try to create such an archive, I am not able to do it. Any guidance is appreciated.

[Working Fine] Extraction

void Extract()  {  // In      archive *ina = archive_read_new();      archive_entry *entry;        archive_read_support_format_zip(ina);      archive_read_set_passphrase_callback(ina, &count, ReadPasswordCallback); // ReadPasswordCallback - Supplies nullptr/emptry string for extracting files with no password, and give appropriate password for extracting files with password      archive_read_open_filename(ina, "test.zip", 10240); // ARCHIVE_OK received here    // Out      archive *ext = archive_write_disk_new();      archive_write_disk_set_options(ext, flags);    // Extraction      for(;;)      {          archive_read_next_header(ina, &entry); // ARCHIEVE_OK received here          archive_write_header(ext, entry); // ARCHIEVE_OK received here          copy_data(ina, ext); // copy_data  ** defined at the bottom **                    // Completion of write entry          archive_write_finish_entry(ext);      }    // Close and Cleanup      archive_read_close(ina);      archive_read_free(ina);            archive_write_close(ext);      archive_write_free(ext);  }  

**[NOT WORKING] Cloning - Read the same zip file and create a copy (with few files as encrypted, few others as un-encrypted as per the original zip file) and **

void Clone()  {  // In      archive *ina = archive_read_new();      archive_entry *entry;        archive_read_support_format_zip(ina);      archive_read_set_passphrase_callback(ina, &count, ReadPasswordCallback); // ReadPasswordCallback - Supplies nullptr/emptry string for extracting files with no password, and give appropriate password for extracting files with password      archive_read_open_filename(ina, "test.zip", 10240); // ARCHIVE_OK received here    // Out      archive *oua = archive_write_new();      archive_write_set_format_zip(oua);      archive_write_set_options(oua, "zip:encryption=traditional");      archive_write_set_passphrase_callback(oua, nullptr, WritePasswordCallback); // WritePasswordCallback - Supplies nullptr/empty string for writing files with no password, and give appropriate password for writings files with password      archive_write_open_filename(oua, testNEW.zip");    // Cloning      for(;;)      {          archive_read_next_header(ina, &entry); // ARCHIEVE_OK received here          archive_write_header(oua, entry); // ARCHIEVE_OK received here          copy_data(ina, oua); // copy_data ** defined at the bottom **            // Completion of write entry          archive_write_finish_entry(oua);      }    // Close and Cleanup      archive_read_close(ina);      archive_read_free(ina);            archive_write_close(oua);      archive_write_free(oua);  }  

ReadPasswordCallback is called once per entry, hence I am able to decrypt files independently by supplying the file's corresponding password. For non-encrypted files, supplying nullptr works fine.

Whereas, with the write, the behaviour is different with the WritePasswordCallback invocation. The WritePasswordCallback is getting called "only once", not once per entry as ReadPasswordCallback. Hence I am not able to supply independent encryption key for the files. Also supplying a nullptr throws an error saying encryption key is necessary for encryption, hence I am not able to have few files as unencrypted

Is this a limitation of Libarchive library? Please help, and thanks in advance!

static int  copy_data(struct archive *ar, struct archive *aw)  {      int r;      char buff[1024];            do      {          r = archive_read_data(ar, buff, sizeof(buff)); // Receives 0/EOF at the last read          if (r == 0 || r == ARCHIVE_EOF)            return (ARCHIVE_OK);                    // Copy          r = archive_write_data(aw, buff, r); // Receive ARCHIVE_OK      } while (r > 0);      return ARCHIVE_FATAL;  }  

JS Object comes out as undefined

Posted: 02 May 2022 12:31 AM PDT

When I write onto the document the object comes out as undefined and I don't know why. Any help you be greatly appreciated. P.S I'm relatively new to JS so I am still learning.

function car(make, model, year, color, passengers, convertible, mileage) {    this.make = make;    this.model = model;    this.year = year;    this.color = color;    this.passengers = passengers;    this.convertible = convertible;    this.mileage = mileage;  }    var carParams = {    make: "Toyota",    model: "Prius",    year: 2012,    color: "red",    passengers: 1,    convertible: false,    mileage: 3403,  };  var toyota = new car(carParams);  document.write(    "The " +    toyota.make +    " " +    toyota.model +    " is a really fast car because it is " +    toyota.color +    "."  );

Merging DataFrame based on conditions in Pandas

Posted: 02 May 2022 12:31 AM PDT

I have two different DataFrames, one with some values of revenue in zero because I don't have the data and a second one with the data I am missing in the other dataframe.

enter image description here

df1=pd.DataFrame([[2020-01,2020-02,2020-03,2020-04],[1,1.2,1.4,1.8],[0.6,1.4,1.6,0],[0.8,1.3,0,0],[0.7,0,0,0]],      columns=['Date', "Day 1","Day 7","Day 14","Day 30"])  

enter image description here

df2=pd.DataFrame([[2020-02,2020-03],[0.6,1.4,1.6,2],[0.8,1.3,1.7,2.2]], columns=['Date', "Day 1","Day 7","Day 14","Day 30"])  

What I want to do is to automatically remove the cells that are empty if they are matching the same date, remove it from the first dataframe and concat the whole second dataframe so it is complete.

Is there any way to do this? I have tried to remove the lines with zeros, but as I have more rows with zeros, it is removing cells I want to maintain.

This would be the final output:

enter image description here

Thanks!

How to check missing values in each row of dataframe

Posted: 02 May 2022 12:29 AM PDT

I have a dataframe with 100's of columns and millions of rows and would like to check the missing values in each row of dataframe.

Code :

df.isna().sum()  

Currently, i'm analzing with above code which helps me with missing values in each column. How we can get the missing values w.r.t each row.

Also, distribution plot of [column of rows] vs [number of missing values].

Jekyll Kramdown # (H1) not formatting as heading

Posted: 02 May 2022 12:31 AM PDT

I am new to Jekyll and kramdown, so I might need help asking my question.

I am having trouble with the H1 heading: so the following in a post:

# H1 looks like this  ## H2 looks like this  ### H3 looks like this  #### H4 looks like this  ##### H5 looks like this  ###### H6 looks like this  Normal text looks like this  

Generates this:

enter image description here

H2-H6 look fine, but I don't know what is wrong with H1, but I would like it to format correctly.


Gemfile

source "https://rubygems.org"    gem "jekyll", ">= 3.8.5"    group :jekyll_plugins do    gem "jekyll-feed", "~> 0.12"    gem "jekyll-paginate", "~> 1.1.0"    gem "jekyll-sitemap"  end    platforms :mingw, :x64_mingw, :mswin, :jruby do    gem "tzinfo", "~> 1.2"    gem "tzinfo-data"  end    gem "wdm", ">= 0.1.1" if Gem.win_platform?    gem "webrick"  

_config.yml file

# Build settings  markdown: kramdown  permalink: pretty    highlighter: rouge  kramdown:    input: GFM    auto_ids: true    syntax_highlighter: rouge      

Can we set State during navigation from one page to other? - React router DOM V6

Posted: 02 May 2022 12:29 AM PDT

I am working with a protected route component, so if a user tries to access a user page without being logged in, a popup log in component should activate, which is done using react state.

The Login check is made during the react routing, so if the user has already logged in, then either gets redirected to the user page or gets redirected to the last page while at the same time activating the state to popup the login component.

How create an edge of a circular arc with div and css?

Posted: 02 May 2022 12:29 AM PDT

I try to create an element like this one:

enter image description here

I can't create a piece of arc of a circle according to a diameter, by playing with the edge of the angles, it doesn't look how I wish. My result:https://codepen.io/yoan-dev/pen/rNJNPPN

.main {    bottom: 0px;    width: 100%;    height: 70px;    background-color: blue;    border-top-left-radius: 100% 80px;    border-top-right-radius: 100% 80px;  }
<a href="#">    <div class="main"></div>  </a>

Project build error.Non resolvalbe parent POM in pom.xml in java

Posted: 02 May 2022 12:30 AM PDT

I am getting below error in pom.xml in java. I changed java version ,springboot version but error remains same. what should I do?

enter image description here

below is my pom.xml

<?xml version="1.0" encoding="UTF-8"?>  <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">      <modelVersion>4.0.0</modelVersion>      <parent>          <groupId>org.springframework.boot</groupId>          <artifactId>spring-boot-starter-parent</artifactId>          <version>2.5.13</version>          <relativePath/> <!-- lookup parent from repository -->      </parent>      <groupId>com.example</groupId>      <artifactId>demo</artifactId>      <version>0.0.1-SNAPSHOT</version>      <name>demo</name>      <description>Demo project for Spring Boot</description>      <properties>          <java.version>11</java.version>      </properties>      <dependencies>          <dependency>              <groupId>org.springframework.boot</groupId>              <artifactId>spring-boot-starter</artifactId>          </dependency>      </dependencies>        <build>          <plugins>              <plugin>                  <groupId>org.springframework.boot</groupId>                  <artifactId>spring-boot-maven-plugin</artifactId>              </plugin>          </plugins>      </build>    </project>  

I saw some of the answers and played with relativePath but did not work what should I do?

Why is the state always jumping out in this verilog code?

Posted: 02 May 2022 12:29 AM PDT

I am writing some verilog code and using a state machine to control what the ALU needs to do.

The following code is about the state machine:

      // Definition of states      parameter IDLE = 3'd0;      parameter MUL  = 3'd1;      parameter DIV  = 3'd2;      parameter AND = 3'd3;      parameter AVG = 3'd4;      parameter OUT  = 3'd5;        // Todo: Wire and reg if needed      reg  [ 2:0] state, state_nxt;  ...          always @(*) begin          case(state)              IDLE: begin                  if (valid)                       case(mode)                          2'd0 : state_nxt = MUL; //MUL = 1                          2'd1 : state_nxt = DIV;                          2'd2 : state_nxt = AND;                          2'd3 : state_nxt = AVG;                      endcase                  else                      state_nxt = IDLE;              end              MUL :                  if (counter != 5'd31) begin                       state_nxt = MUL;                  end                  else state_nxt = OUT; //OUT = 5              DIV :                  if (counter != 5'd31) state_nxt = DIV;                  else state_nxt = OUT;              AND : state_nxt = OUT;              AVG : state_nxt = OUT;              OUT : state_nxt = IDLE;          endcase      end  ...    always @(posedge clk or negedge rst_n) begin          if (!rst_n) begin              state <= IDLE;          end          else begin              $display("state:", state);              state <= state_nxt;              ...              if(counter == 5'd31) begin                  assign ready = 1;              end          end      end  

I expect the MUL state to persist for 31 clocks and then jump to OUT. However, the console prints out:

state:0  state:1  state:5  state:0  state:0  state:0  

What's the problem in this code? I'll be so appreciated if anyone could help.

the kubernetes pod shows Back-off restarting failed container when every thing goes fine

Posted: 02 May 2022 12:31 AM PDT

Today I found the kubernetes pod shows log:

Back-off restarting failed container  

and the pod always did not ready and could not serve the request, but when I check the pod log:

 release git:(main) kubectl logs admin-service-5bdf47b85c-bdqdw -n reddwarf-pro  ➜  release git:(main)  

there is no message output. why did this happen? what should I do to fix this problem? This is the Dockerfile:

# to reduce the docker image size  # build stage  FROM rust:1.54-alpine as builder  WORKDIR /app  COPY . /app  RUN rustup default stable  RUN apk update && apk add --no-cache libpq musl-dev pkgconfig openssl-dev postgresql-dev  RUN cargo build --release  # RUN cargo build    # Prod stage  FROM alpine:3.15  WORKDIR /app  ENV ROCKET_ADDRESS=0.0.0.0  # ENV ROCKET_PORT=11014  RUN apk update && apk add --no-cache libpq curl  COPY --from=builder /app/.env /app  COPY --from=builder /app/settings.toml /app  COPY --from=builder /app/target/release/reddwarf-admin /app/  COPY --from=builder /app/Rocket.toml /app  CMD ["./reddwarf-admin"]  

could not login into docker container by any ways. when I using describe command:

➜  release git:(main) kubectl describe pod admin-service-745dc87489-j647l -n reddwarf-pro    Name:         admin-service-745dc87489-j647l  Namespace:    reddwarf-pro  Priority:     0  Node:         k8smasterone/172.29.217.209  Start Time:   Mon, 02 May 2022 14:19:10 +0800  Labels:       app=admin-service                pod-template-hash=745dc87489  Annotations:  cni.projectcalico.org/containerID: 41763a38ee120ae7c85cd11fda699f30205a06fe9a5b6175736390d503c26bd3                cni.projectcalico.org/podIP: 10.97.196.208/32                cni.projectcalico.org/podIPs: 10.97.196.208/32  Status:       Running  IP:           10.97.196.208  IPs:    IP:           10.97.196.208  Controlled By:  ReplicaSet/admin-service-745dc87489  Containers:    admin-service:      Container ID:   containerd://406e183d166b861448aa2d3597d3d190ccd5432e92b031721cae356ab00b59b2      Image:          registry.cn-hongkong.aliyuncs.com/reddwarf-pro/reddwarf-admin:f1e71525c1996a711f67ca85715d190bafcee07d      Image ID:       registry.cn-hongkong.aliyuncs.com/reddwarf-pro/reddwarf-admin@sha256:b39bebf332bc53318e29c8f697592bf76eb9e1676b74017d87c109a74ad3f235      Port:           80/TCP      Host Port:      0/TCP      State:          Waiting        Reason:       CrashLoopBackOff      Last State:     Terminated        Reason:       Error        Exit Code:    139        Started:      Mon, 02 May 2022 14:22:02 +0800        Finished:     Mon, 02 May 2022 14:22:03 +0800      Ready:          False      Restart Count:  5      Limits:        cpu:     50m        memory:  60Mi      Requests:        cpu:     20m        memory:  6Mi      Environment:        DATABASE_URL:        <set to the key 'database_url' of config map 'admin-service-pro-config'>        Optional: false        MUSIC_DATABASE_URL:  <set to the key 'music_database_url' of config map 'admin-service-pro-config'>  Optional: false        QUARK_DATABASE_URL:  <set to the key 'quark_database_url' of config map 'admin-service-pro-config'>  Optional: false        DICT_DATABASE_URL:   <set to the key 'dict_database_url' of config map 'admin-service-pro-config'>   Optional: false        ENV:                 <set to the key 'env' of config map 'admin-service-pro-config'>                 Optional: false      Mounts:        /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-6gfdl (ro)  Conditions:    Type              Status    Initialized       True    Ready             False    ContainersReady   False    PodScheduled      True  Volumes:    kube-api-access-6gfdl:      Type:                    Projected (a volume that contains injected data from multiple sources)      TokenExpirationSeconds:  3607      ConfigMapName:           kube-root-ca.crt      ConfigMapOptional:       <nil>      DownwardAPI:             true  QoS Class:                   Burstable  Node-Selectors:              <none>  Tolerations:                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300s                               node.kubernetes.io/unreachable:NoExecute op=Exists for 300s  Events:    Type     Reason     Age                    From               Message    ----     ------     ----                   ----               -------    Normal   Scheduled  4m8s                   default-scheduler  Successfully assigned reddwarf-pro/admin-service-745dc87489-j647l to k8smasterone    Normal   Pulled     2m42s (x5 over 4m7s)   kubelet            Container image "registry.cn-hongkong.aliyuncs.com/reddwarf-pro/reddwarf-admin:f1e71525c1996a711f67ca85715d190bafcee07d" already present on machine    Normal   Created    2m42s (x5 over 4m7s)   kubelet            Created container admin-service    Normal   Started    2m41s (x5 over 4m7s)   kubelet            Started container admin-service    Warning  BackOff    2m16s (x10 over 4m5s)  kubelet            Back-off restarting failed container  

when I pull the image into local MacBook Pro, it works fine. By the way, the server running containerd not using docker.

Print out a message with empty lines [closed]

Posted: 02 May 2022 12:30 AM PDT

Write a program that prints the following text:

WE NEED TO

LEARN JAVA

AS QUICKLY AS POSSIBLE Hint: do not forget to print the empty lines! How to print those empty lines?

Group split data in timeline data in to one in PostgreSQL

Posted: 02 May 2022 12:29 AM PDT

I have data which is shown below.

stationName startTime endTime status
A normal 09:00 09:10
A normal 09:10 09:20
B normal 09:30 09:40
A normal 09:30 09:40
B normal 09:40 09:45
A warning 09:40 09:45
B warning 09:45 09:55
A alert 09:45 09:55
B normal 09:55 10:05
A alert 09:55 10:05
B normal 10:05 10:15
A normal 10:05 10:15
B normal 10:15 10:25
A normal 10:15 10:25
B normal 10:25 10:35
A normal 10:25 10:35

and I want to query data into this structure

stationName status startTime endTime
A normal 09:00 09:40
A warning 09:40 09:45
A alert 09:45 10:05
A normal 10:05 10:35
B normal 09:30 09:45
B warning 09:45 09:55
B normal 09:55 10:35

My data timeline data is split into many parts, but I want to group it into one.

The sample rate of my sound card changes slightly. Counteract?

Posted: 02 May 2022 12:31 AM PDT

I read this thread because I also wanted to find out if the sample rate of my sound card is always the same or if the value fluctuates. I downloaded the Soundcheck programme recommended in the thread. According to the Windows settings, my sound card is set as follows:
Sample rate: 48000 Hz
Channels: 2
Resolution: 24 bits.

I wrote an application a long time ago that does a Fourier transform and displays the audio signal spectrographically.

I have recorded a video for you because it is difficult for me to explain the problem. As you can see, according to Soundcheck, the bytes per second are changing all the time. I have also seen larger value deviations (up to ±1 %). I claim that this problem is the reason why the bars in the Fourier transformation programme jump up and down a bit, especially those that should not be visible at all.

Please note that due to the video editing programme it seems as if the played 2000 Hz test tone trills, but it does not. It is always the same volume.


Is there anything that can be done to get the true sample rate of the sound card, or is the code for getting the audio bytes not good enough?
I will delete the video in a few days.

This is the VB.NET source code to get the audio data (minimal example). You must download NAudio from Visual Studio's own NuGet package manager.

Imports Microsoft.VisualBasic.ControlChars  Public NotInheritable Class FormMain      Private continue_ As Boolean = True        ''' <summary>      ''' sample rate of the soundcard in Hertz      ''' </summary>      Private Samplerate As Integer = 48000      ''' <summary>      ''' 1024      ''' </summary>      Private ReadOnly BufferSize As Integer = CInt(Math.Pow(2, 10)) ' 1024      Private bwp As NAudio.Wave.BufferedWaveProvider = Nothing      ''' <summary>      ''' 21.333 ms      ''' </summary>      Private usedMilliseconds As Double      Private cnt As Integer = 0      ''' <summary>      ''' to hold the latest soundcard data which we will graph. <para></para>      ''' Größe dieses Arrays wird BufferSize ÷ 2 , also 512.      ''' </summary>      Private DataArray As Double()        Private Sub AudioDataAvailable(ByVal sender As Object, e As NAudio.Wave.WaveInEventArgs)          bwp.AddSamples(e.Buffer, 0, e.BytesRecorded)      End Sub        Private Sub Start_Listening()          Dim wi As New NAudio.Wave.WaveIn()          wi.DeviceNumber = 1          wi.WaveFormat = New NAudio.Wave.WaveFormat(Samplerate, 16, 1)          wi.BufferMilliseconds = CInt(CDbl(BufferSize) / CDbl(Samplerate) * 1000.0)          usedMilliseconds = CDbl(BufferSize) / CDbl(Samplerate) * 1000.0          AddHandler wi.DataAvailable, AddressOf AudioDataAvailable          bwp = New NAudio.Wave.BufferedWaveProvider(wi.WaveFormat)          bwp.BufferLength = BufferSize * 2          bwp.DiscardOnBufferOverflow = True            Try              wi.StartRecording()          Catch ex As NAudio.MmException              MessageBox.Show($"Could not record from audio device!{NewLine}{NewLine}{ex.Message}",                              "",                              MessageBoxButtons.OK,                              MessageBoxIcon.Error)          End Try      End Sub        Public Sub GetLatestData()          Dim audioBytes As Byte() = New Byte(BufferSize - 1) {}          bwp.Read(audioBytes, 0, BufferSize)          If audioBytes.Length = 0 Then Return          'If audioBytes(BufferSize - 2) = 0 Then Return          Dim BYTES_PER_POINT As Integer = 2          Dim PointCount As Integer = audioBytes.Length \ BYTES_PER_POINT          DataArray = (New Double(PointCount - 1) {})            For i As Integer = 0 To PointCount - 1 Step 2              DataArray(i) = CDbl(BitConverter.ToInt16(audioBytes, i * BYTES_PER_POINT))          Next      End Sub        Private Async Sub ButtonStart_Click(sender As Object, e As EventArgs) Handles ButtonStart.Click          Start_Listening()          continue_ = True          While continue_              Await Task.Run(Sub() FT())              Await Task.Run(Sub() Plot())          End While      End Sub        Private Sub ButtonStop_Click(sender As Object, e As EventArgs) Handles ButtonStop.Click          continue_ = False          PictureBox1.Image = Nothing          GC.Collect()      End Sub        Private Sub Plot()          ' plot the bars      End Sub        Private Sub FT()          GetLatestData()          If DataArray Is Nothing Then              Return          End If          ' do a fourier transform here      End Sub        Private Sub NumericUpDown_Samplerate_ValueChanged(sender As Object, e As EventArgs) Handles NumericUpDown_Samplerate.ValueChanged          Me.Samplerate = CInt(NumericUpDown_Samplerate.Value)      End Sub  End Class  

ASP.NET Core 6 - Cookie gets returned but not stored in browser

Posted: 02 May 2022 12:29 AM PDT

I am struggling with Cookie Authentication in Asp.Net Core 6.0

I have implemented and configured the Cookie Authentication and the problem I am facing is the following.

When sending POST request to the login Endpoint which is at <domain>/api/account/login the login returns a 200 OK response and the correct cookie.

However, the Cookie is not getting stored in the browser.

The Cookie Configurations

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)      .AddCookie(options =>      {        options.Cookie.Name = "Affito.Identity";        options.Cookie.HttpOnly = true;        options.Cookie.SecurePolicy = CookieSecurePolicy.None;        options.Cookie.SameSite = (SameSiteMode) (-1);        options.SlidingExpiration = true;        options.Cookie.Domain = ".affito.ch";        options.ExpireTimeSpan = TimeSpan.FromMinutes(3);        options.Cookie.IsEssential = true;      });      services.Configure<CookiePolicyOptions>(options =>    {      options.MinimumSameSitePolicy = (SameSiteMode)(-1);      options.HttpOnly = HttpOnlyPolicy.None;      options.Secure = CookieSecurePolicy.None;    });  

since I have multiple subdomains that need to work with the same cookie I have the .domain attribute in options.Cookie.Domain.

This is the response from the Network Tab in the browser after sending the login request enter image description here

However, the Cookie is getting returned but it is not getting stored in the browser for future requests.

I am sending a simple fetch request from the React-App:

const response = await fetch(BASEURL + "/account/login", {    method: "POST",    body: JSON.stringify(loginData),    headers: {      "Content-Type": "application/json",    },  });    console.log(response);  

};

Am I missing something or why does it not store the cookie in the browser. I have consulted the docs but could not figure that out.

Swagger: When sending the request from swagger, it returns the same cookie and stores it correctly in the browser. enter image description here

I guessed it had something to do with the 'SameSite' Restriction that's why I took it out but it still does not work when sending the request from stage."domain"

Which route is to write for same method on every page [closed]

Posted: 02 May 2022 12:30 AM PDT

Currenty developing a project in Laravel and want to now which route should I write when for example the search bar appears in the navigation bar on every page. It would be great if I get any advice here.

Thanks!

Command timed out errors while RabbitMQ is running on Azure container instance

Posted: 02 May 2022 12:31 AM PDT

I'm using rabbitmq:3-management docker image on Azure container instance with the following path mounted on Azure storage account /var/lib/rabbitmq/mnesia

Sometimes the following error is received:

[38;5;160m2022-04-27 10:39:14.916059+00:00 [error] <0.366.0> Command timed out: '/usr/bin/df -kP /var/lib/rabbitmq/mnesia/rabbit@localhost'[0m  [38;5;160m2022-04-27 10:39:14.931111+00:00 [error] <0.366.0> ** Generic server rabbit_disk_monitor terminating[0m  [38;5;160m2022-04-27 10:39:14.931111+00:00 [error] <0.366.0> ** Last message in was update[0m  [38;5;160m2022-04-27 10:39:14.931111+00:00 [error] <0.366.0> ** When Server state == {state,"/var/lib/rabbitmq/mnesia/rabbit@localhost",[0m  [38;5;160m2022-04-27 10:39:14.931111+00:00 [error] <0.366.0>                                50000000,5497558073344,100,10000,[0m  [38;5;160m2022-04-27 10:39:14.931111+00:00 [error] <0.366.0>                                #Ref<0.942492558.3792175105.38974>,false,true,[0m  [38;5;160m2022-04-27 10:39:14.931111+00:00 [error] <0.366.0>                                10,120000}[0m  [38;5;160m2022-04-27 10:39:14.931111+00:00 [error] <0.366.0> ** Reason for termination ==[0m  [38;5;160m2022-04-27 10:39:14.931111+00:00 [error] <0.366.0> ** {function_clause,[0m  [38;5;160m2022-04-27 10:39:14.931111+00:00 [error] <0.366.0>        [{lists,reverse,[{error,timeout}],[{file,"lists.erl"},{line,147}]},[0m  [38;5;160m2022-04-27 10:39:14.931111+00:00 [error] <0.366.0>         {string,tokens,2,[{file,"string.erl"},{line,1934}]},[0m  [38;5;160m2022-04-27 10:39:14.931111+00:00 [error] <0.366.0>         {rabbit_disk_monitor,parse_free_unix,1,[0m  [38;5;160m2022-04-27 10:39:14.931111+00:00 [error] <0.366.0>             [{file,"rabbit_disk_monitor.erl"},{line,262}]},[0m  [38;5;160m2022-04-27 10:39:14.931111+00:00 [error] <0.366.0>         {rabbit_disk_monitor,internal_update,1,[0m  [38;5;160m2022-04-27 10:39:14.931111+00:00 [error] <0.366.0>             [{file,"rabbit_disk_monitor.erl"},{line,216}]},[0m  [38;5;160m2022-04-27 10:39:14.931111+00:00 [error] <0.366.0>         {rabbit_disk_monitor,handle_info,2,[0m  [38;5;160m2022-04-27 10:39:14.931111+00:00 [error] <0.366.0>             [{file,"rabbit_disk_monitor.erl"},{line,166}]},[0m  [38;5;160m2022-04-27 10:39:14.931111+00:00 [error] <0.366.0>         {gen_server,try_dispatch,4,[{file,"gen_server.erl"},{line,695}]},[0m  [38;5;160m2022-04-27 10:39:14.931111+00:00 [error] <0.366.0>         {gen_server,handle_msg,6,[{file,"gen_server.erl"},{line,771}]},[0m  [38;5;160m2022-04-27 10:39:14.931111+00:00 [error] <0.366.0>         {proc_lib,init_p_do_apply,3,[{file,"proc_lib.erl"},{line,226}]}]}[0m  [38;5;160m2022-04-27 10:39:14.931111+00:00 [error] <0.366.0> [0m  [38;5;160m2022-04-27 10:39:14.970878+00:00 [error] <0.366.0>   crasher:[0m  [38;5;160m2022-04-27 10:39:14.970878+00:00 [error] <0.366.0>     initial call: rabbit_disk_monitor:init/1[0m  [38;5;160m2022-04-27 10:39:14.970878+00:00 [error] <0.366.0>     pid: <0.366.0>[0m  [38;5;160m2022-04-27 10:39:14.970878+00:00 [error] <0.366.0>     registered_name: rabbit_disk_monitor[0m  [38;5;160m2022-04-27 10:39:14.970878+00:00 [error] <0.366.0>     exception error: no function clause matching[0m  [38;5;160m2022-04-27 10:39:14.970878+00:00 [error] <0.366.0>                      lists:reverse({error,timeout}) (lists.erl, line 147)[0m  [38;5;160m2022-04-27 10:39:14.970878+00:00 [error] <0.366.0>       in function  string:tokens/2 (string.erl, line 1934)[0m  [38;5;160m2022-04-27 10:39:14.970878+00:00 [error] <0.366.0>       in call from rabbit_disk_monitor:parse_free_unix/1 (rabbit_disk_monitor.erl, line 262)[0m  [38;5;160m2022-04-27 10:39:14.970878+00:00 [error] <0.366.0>       in call from rabbit_disk_monitor:internal_update/1 (rabbit_disk_monitor.erl, line 216)[0m  [38;5;160m2022-04-27 10:39:14.970878+00:00 [error] <0.366.0>       in call from rabbit_disk_monitor:handle_info/2 (rabbit_disk_monitor.erl, line 166)[0m  [38;5;160m2022-04-27 10:39:14.970878+00:00 [error] <0.366.0>       in call from gen_server:try_dispatch/4 (gen_server.erl, line 695)[0m  [38;5;160m2022-04-27 10:39:14.970878+00:00 [error] <0.366.0>       in call from gen_server:handle_msg/6 (gen_server.erl, line 771)[0m  [38;5;160m2022-04-27 10:39:14.970878+00:00 [error] <0.366.0>     ancestors: [rabbit_disk_monitor_sup,rabbit_sup,<0.228.0>][0m  [38;5;160m2022-04-27 10:39:14.970878+00:00 [error] <0.366.0>     message_queue_len: 0[0m  [38;5;160m2022-04-27 10:39:14.970878+00:00 [error] <0.366.0>     messages: [][0m  [38;5;160m2022-04-27 10:39:14.970878+00:00 [error] <0.366.0>     links: [<0.365.0>][0m  [38;5;160m2022-04-27 10:39:14.970878+00:00 [error] <0.366.0>     dictionary: [][0m  [38;5;160m2022-04-27 10:39:14.970878+00:00 [error] <0.366.0>     trap_exit: false[0m  [38;5;160m2022-04-27 10:39:14.970878+00:00 [error] <0.366.0>     status: running[0m  [38;5;160m2022-04-27 10:39:14.970878+00:00 [error] <0.366.0>     heap_size: 10958[0m  [38;5;160m2022-04-27 10:39:14.970878+00:00 [error] <0.366.0>     stack_size: 29[0m  [38;5;160m2022-04-27 10:39:14.970878+00:00 [error] <0.366.0>     reductions: 93242225[0m  [38;5;160m2022-04-27 10:39:14.970878+00:00 [error] <0.366.0>   neighbours:[0m  [38;5;160m2022-04-27 10:39:14.970878+00:00 [error] <0.366.0> [0m  [38;5;160m2022-04-27 10:39:14.989350+00:00 [error] <0.365.0>     supervisor: {local,rabbit_disk_monitor_sup}[0m  [38;5;160m2022-04-27 10:39:14.989350+00:00 [error] <0.365.0>     errorContext: child_terminated[0m  [38;5;160m2022-04-27 10:39:14.989350+00:00 [error] <0.365.0>     reason: {function_clause,[0m  [38;5;160m2022-04-27 10:39:14.989350+00:00 [error] <0.365.0>                 [{lists,reverse,[0m  [38;5;160m2022-04-27 10:39:14.989350+00:00 [error] <0.365.0>                      [{error,timeout}],[0m  [38;5;160m2022-04-27 10:39:14.989350+00:00 [error] <0.365.0>                      [{file,"lists.erl"},{line,147}]},[0m  [38;5;160m2022-04-27 10:39:14.989350+00:00 [error] <0.365.0>                  {string,tokens,2,[{file,"string.erl"},{line,1934}]},[0m  [38;5;160m2022-04-27 10:39:14.989350+00:00 [error] <0.365.0>                  {rabbit_disk_monitor,parse_free_unix,1,[0m  [38;5;160m2022-04-27 10:39:14.989350+00:00 [error] <0.365.0>                      [{file,"rabbit_disk_monitor.erl"},{line,262}]},[0m  [38;5;160m2022-04-27 10:39:14.989350+00:00 [error] <0.365.0>                  {rabbit_disk_monitor,internal_update,1,[0m  [38;5;160m2022-04-27 10:39:14.989350+00:00 [error] <0.365.0>                      [{file,"rabbit_disk_monitor.erl"},{line,216}]},[0m  [38;5;160m2022-04-27 10:39:14.989350+00:00 [error] <0.365.0>                  {rabbit_disk_monitor,handle_info,2,[0m  [38;5;160m2022-04-27 10:39:14.989350+00:00 [error] <0.365.0>                      [{file,"rabbit_disk_monitor.erl"},{line,166}]},[0m  [38;5;160m2022-04-27 10:39:14.989350+00:00 [error] <0.365.0>                  {gen_server,try_dispatch,4,[0m  [38;5;160m2022-04-27 10:39:14.989350+00:00 [error] <0.365.0>                      [{file,"gen_server.erl"},{line,695}]},[0m  [38;5;160m2022-04-27 10:39:14.989350+00:00 [error] <0.365.0>                  {gen_server,handle_msg,6,[0m  [38;5;160m2022-04-27 10:39:14.989350+00:00 [error] <0.365.0>                      [{file,"gen_server.erl"},{line,771}]},[0m  [38;5;160m2022-04-27 10:39:14.989350+00:00 [error] <0.365.0>                  {proc_lib,init_p_do_apply,3,[0m  [38;5;160m2022-04-27 10:39:14.989350+00:00 [error] <0.365.0>                      [{file,"proc_lib.erl"},{line,226}]}]}[0m  [38;5;160m2022-04-27 10:39:14.989350+00:00 [error] <0.365.0>     offender: [{pid,<0.366.0>},[0m  [38;5;160m2022-04-27 10:39:14.989350+00:00 [error] <0.365.0>                {id,rabbit_disk_monitor},[0m  [38;5;160m2022-04-27 10:39:14.989350+00:00 [error] <0.365.0>                {mfargs,{rabbit_disk_monitor,start_link,[50000000]}},[0m  [38;5;160m2022-04-27 10:39:14.989350+00:00 [error] <0.365.0>                {restart_type,{transient,1}},[0m  [38;5;160m2022-04-27 10:39:14.989350+00:00 [error] <0.365.0>                {shutdown,300000},[0m  [38;5;160m2022-04-27 10:39:14.989350+00:00 [error] <0.365.0>                {child_type,worker}][0m  

If I'm trying to connect to the container and running the command /usr/bin/df -kP /var/lib/rabbitmq/mnesia/rabbit@localhost by myself I'm getting the following result immediately:

command result

Any help understanding this error and resolving it will be appreciated.

Convert TensorFlow Keras python model to Android .tflite model

Posted: 02 May 2022 12:31 AM PDT

I am working on an image recognition project using TensorFlow and Keras, that I would like to implement to my Android project. And I am new to Tensorflow...

I would like to find the closest match between an image to a folder with +2000 images. Images are similar in background and size, like so:

enter image description here

For now I have this following Python code that works okay.

from tensorflow.keras.preprocessing import image  from tensorflow.keras.applications.vgg16 import VGG16, preprocess_input  from tensorflow.keras.models import Model  import numpy as np  from PIL import Image    base_model = VGG16(weights='imagenet')  model = Model(inputs=base_model.input, outputs=base_model.get_layer('fc1').output)    def extract(img):      img = img.resize((224, 224)) # Resize the image      img = img.convert('RGB') # Convert the image color space      x = image.img_to_array(img) # Reformat the image      x = np.expand_dims(x, axis=0)      x = preprocess_input(x)      feature = model.predict(x)[0] # Extract Features      return feature / np.linalg.norm(feature)    # Iterate through images and extract Features  images = ["img1.png","img2.png","img3.png","img4.png","img5.png"...+2000 more]  all_features = np.zeros(shape=(len(images),4096))    for i in range(len(images)):      feature = extract(img=Image.open(images[i]))      all_features[i] = np.array(feature)    # Match image  query = extract(img=Image.open("image_to_match.png")) # Extract its features  dists = np.linalg.norm(all_features - query, axis=1) # Calculate the similarity (distance) between images  ids = np.argsort(dists)[:5] # Extract 5 images that have lowest distance  

Now I am a bit lost to where to go from here. To my understanding I need to create a .h5 file with all extracted image features and a .tflite file containing the model.

UPDATE after answer

I can convert the model with:

# Convert the model.  base_model = VGG16(weights='imagenet')  model = Model(inputs=base_model.input, outputs=base_model.get_layer('fc1').output)  converter = tf.lite.TFLiteConverter.from_keras_model(model)  tflite_model = converter.convert()    # Save the model.  with open('model.tflite', 'wb') as f:      f.write(tflite_model)  

But how can I get the extracted features to my Android project? Also, the file size of the model is +400 mb so Android doesnt allow to import it.

Hope you can help me, thanks.

Invariant Violation: withNavigation can only be used on a view hierarchy of a navigator

Posted: 02 May 2022 12:31 AM PDT

Here is package.json file. As seen below, react is 16.9. But they say I have to downgrade react version to fix the error. Here is reference which says to downgrade react version:

https://github.com/react-navigation/react-navigation/issues/4416

@destpat mentioned changing react version.

How can I do that? I mean what version should be considered to downgrade it to?

Here is the error I got when running the app on android emulator.

Invariant Violation: withNavigation can only be used on a view hierarchy of a navigator. The wrapped component is unable to get access to navigation from props or context.    This error is located at:  in withNavigation(NavigationEvents) (at OrderMapView/index.js:717)  in RCTView (at View.js:34)  in View (at createAnimatedComponent.js:165)  in AnimatedComponent (at createAnimatedComponent.js:215)  in ForwardRef(AnimatedComponentWrapper) (at OrderMapView/index.js:714)  in OrderMapView (created by Connect(OrderMapView))  in Connect(OrderMapView) (at Home/index.js:102)  in StaticContainer (at SceneComponent.js:11)  in RCTView (at View.js:34)  in View (at SceneComponent.js:10)  in SceneComponent (created by ViewPager)  in RNCViewPager (at ViewPager.js:150)  in ViewPager (at createAnimatedComponent.js:165)  in AnimatedComponent (at createAnimatedComponent.js:215)  in ForwardRef(AnimatedComponentWrapper) (at react-native-scrollable-tab-view/index.js:253)  in RCTView (at View.js:34)  in View (at react-native-scrollable-tab-view/index.js:396)  in ScrollableTabView (at Home/index.js:86)  in RCTView (at View.js:34)  in View (at Home/index.js:109)  in Home (at WithBackgroundTimer.js:70)  in WithBackgroundTimer (at WithAppStateAndLocation.js:207)  in WithAppStateAndLocation (created by Connect(WithAppStateAndLocation))  in Connect(WithAppStateAndLocation) (at navigationStore.js:319)  in Wrapped (at SceneView.js:31)  in SceneView (at CardStack.js:412)  in RCTView (at View.js:34)  in View (at CardStack.js:411)  in RCTView (at View.js:34)  in View (at CardStack.js:410)  in RCTView (at View.js:34)  in View (at createAnimatedComponent.js:165)  in AnimatedComponent (at createAnimatedComponent.js:215)  in ForwardRef(AnimatedComponentWrapper) (at Card.js:26)  in Card (at PointerEventsContainer.js:55)  in Container (at CardStack.js:454)  in RCTView (at View.js:34)  in View (at CardStack.js:383)  in RCTView (at View.js:34)  in View (at CardStack.js:382)  in CardStack (at CardStackTransitioner.js:97)  in RCTView (at View.js:34)  in View (at Transitioner.js:192)  in Transitioner (at CardStackTransitioner.js:49)  in CardStackTransitioner (at StackNavigator.js:60)  in Unknown (at createNavigator.js:52)  in Navigator (at createNavigationContainer.js:210)  in NavigationContainer (at SceneView.js:31)  in SceneView (at CardStack.js:412)  in RCTView (at View.js:34)  in View (at CardStack.js:411)  in RCTView (at View.js:34)  in View (at CardStack.js:410)  in RCTView (at View.js:34)  in View (at createAnimatedComponent.js:165)  in AnimatedComponent (at createAnimatedComponent.js:215)  in ForwardRef(AnimatedComponentWrapper) (at Card.js:26)  in Card (at PointerEventsContainer.js:55)  in Container (at CardStack.js:454)  in RCTView (at View.js:34)  in View (at CardStack.js:383)  in RCTView (at View.js:34)  in View (at CardStack.js:382)  in CardStack (at CardStackTransitioner.js:97)  in RCTView (at View.js:34)  in View (at Transitioner.js:192)  in Transitioner (at CardStackTransitioner.js:49)  in CardStackTransitioner (at StackNavigator.js:60)  in Unknown (at createNavigator.js:52)  in Navigator (at createNavigationContainer.js:210)  in NavigationContainer (at SceneView.js:31)  in SceneView (at DrawerScreen.js:40)  in DrawerScreen (at withCachedChildNavigation.js:66)  in withCachedChildNavigation(DrawerScreen) (at DrawerNavigator.js:106)  in Unknown (at createNavigator.js:52)  in Navigator (at DrawerView.js:215)  in RCTView (at View.js:34)  in View (at DrawerLayoutAndroid.android.js:204)  in AndroidDrawerLayout (at DrawerLayoutAndroid.android.js:223)  in DrawerLayoutAndroid (at DrawerView.js:195)  in DrawerView (at DrawerNavigator.js:127)  in Unknown (at createNavigator.js:52)  in Navigator (at createNavigationContainer.js:210)  in NavigationContainer (at SceneView.js:31)  in SceneView (at CardStack.js:412)  in RCTView (at View.js:34)  in View (at CardStack.js:411)  in RCTView (at View.js:34)  in View (at CardStack.js:410)  in RCTView (at View.js:34)  in View (at createAnimatedComponent.js:165)  in AnimatedComponent (at createAnimatedComponent.js:215)  in ForwardRef(AnimatedComponentWrapper) (at Card.js:26)  in Card (at PointerEventsContainer.js:55)  in Container (at CardStack.js:454)  in RCTView (at View.js:34)  in View (at CardStack.js:383)  in RCTView (at View.js:34)  in View (at CardStack.js:382)  in CardStack (at CardStackTransitioner.js:97)  in RCTView (at View.js:34)  in View (at Transitioner.js:192)  in Transitioner (at CardStackTransitioner.js:49)  in CardStackTransitioner (at StackNavigator.js:60)  in Unknown (at createNavigator.js:52)  in Navigator (at createNavigationContainer.js:210)  in NavigationContainer (at Router.js:70)  in App (at Router.js:91)  in Router (created by Connect(Router))  in Connect(Router) (at navigator/index.js:266)  in _default (at src/index.js:67)  in Provider (at src/index.js:66)  in RCTView (at View.js:34)  in View (at src/index.js:60)  in App (at renderApplication.js:45)  in RCTView (at View.js:34)  in View (at AppContainer.js:106)  in RCTView (at View.js:34)  in View (at AppContainer.js:132)  in AppContainer (at renderApplication.js:39)  [Sat Dec 18 2021 06:41:35.575]  ERROR    TypeError: undefined is not an object (evaluating 'this.map.setNativeProps')  
{    "name": " ",    "version": "0.0.1",    "private": true,    "scripts": {      "start": "node node_modules/react-native/local-cli/cli.js start",      "test": "jest",      "lint": "eslint .",      "lint:fix": "eslint . --fix",      "prettier": "prettier --write '*.js'",      "format-code": "yarn run prettier"    },    "dependencies": {      "@mapbox/polyline": "^1.0.0",      "@ptomasroos/react-native-multi-slider": "^0.0.14",      "@react-native-community/art": "^1.2.0",      "@react-native-community/async-storage": "^1.12.1",      "@react-native-community/cli-platform-ios": "3.0.0",      "@react-native-community/geolocation": "^2.0.2",      "@react-native-community/netinfo": "^4.4.0",      "@react-native-community/picker": "^1.8.1",      "@react-native-community/viewpager": "^4.1.6",      "@react-native-picker/picker": "^1.9.2",      "apisauce": "^0.14.3",      "async": "^2.6.0",      "axios": "^0.21.0",      "base-64": "^0.1.0",      "lodash": "^4.17.10",      "moment": "^2.22.1",      "prop-types": "^15.6.1",      "react": "16.9.0",      "react-devtools": "^4.8.2",      "react-native": "0.63.2",      "react-native-a-beep": "^1.0.6",      "react-native-actionsheet": "^2.4.2",      "react-native-background-timer": "2.0.0",      "react-native-beep-tone": "^1.0.2",      "react-native-clean-project": "^3.4.0",      "react-native-cli": "^2.0.1",      "react-native-datepicker": "^1.7.2",      "react-native-firebase": "^5.6.0",      "react-native-gesture-handler": "^1.7.0",      "react-native-htmlview": "^0.13.0",      "react-native-image-picker": "^0.26.10",      "react-native-image-placeholder": "^1.0.14",      "react-native-image-progress": "^1.1.1",      "react-native-image-resizer": "^1.0.0",      "react-native-intl-phone-input": "^1.2.26",      "react-native-iphone-x-helper": "^1.0.3",      "react-native-keyboard-manager": "^4.0.13-7",      "react-native-linear-gradient": "^2.4.0",      "react-native-loading-spinner-overlay": "^1.1.0",      "react-native-maps": "0.27.1",      "react-native-message-bar": "^2.0.10",      "react-native-modal": "^6.0.0",      "react-native-notification-sounds": "^0.5.2",      "react-native-openanything": "^0.0.6",      "react-native-picker-select": "^8.0.2",      "react-native-progress": "^4.1.2",      "react-native-progress-bar-animated": "^1.0.6",      "react-native-progress-timer": "^1.0.1",      "react-native-push-notification": "^8.1.1",      "react-native-reanimated": "^1.13.0",      "react-native-router-flux": "4.0.0-beta.27",      "react-native-safe-area-context": "^3.3.2",      "react-native-safe-area-view": "^1.1.1",      "react-native-screens": "^2.10.1",      "react-native-scrollable-tab-view": "^1.0.0",      "react-native-search-box": "^0.0.18",      "react-native-simple-toast": "^1.1.2",      "react-native-sound": "^0.11.0",      "react-native-sounds-beep": "0.0.1",      "react-native-star-rating": "^1.0.9",      "react-native-svg": "10.0.0",      "react-native-swipeout": "^2.3.3",      "react-native-swiper": "^1.6.0-nightly.3",      "react-navigation": "^4.4.0",      "react-redux": "^5.0.7",      "redux": "^4.0.0",      "redux-logger": "^3.0.6",      "redux-saga": "^0.16.0",      "redux-storage": "^4.1.2",      "redux-storage-decorator-filter": "^1.1.8",      "redux-storage-engine-reactnativeasyncstorage": "^1.0.5",      "remote-redux-devtools": "^0.5.12",      "remotedev": "^0.2.9",      "remotedev-server": "^0.3.1",      "reselect": "^3.0.1",      "seamless-immutable": "^7.1.3",      "victory-native": "30.0.0"    },    "devDependencies": {      "babel-core": "^7.0.0-bridge.0",      "babel-jest": "24.3.1",      "jest": "24.3.1",      "metro-react-native-babel-preset": "0.53.0",      "react-test-renderer": "16.6.3"    },    "jest": {      "preset": "react-native"    }  }  

package javax.servlet does not exist | package jakarta.servlet does not exist

Posted: 02 May 2022 12:31 AM PDT

javac -classpath "/opt/tomcat/lib/servlet-api.jar" /opt/tomcat/webapps/ROOT/WEB-INF/classes/NewServlet.java  

I have tried replacing the javax.servlet with "jakarta.servlet". It still throws the same error with "package jakarta.servlet" does not exist.

I have included the servlet-api.jar while compiling the program. Nothing seems to work here. I am stuck with this for 3 days now. I am a newbie to the servlet. I am not using any IDE. My tomcat is running fine and it is showing the results but the class with these packages are not getting compiled and hence unable to process the following page.

I am using tomcat 10 and linux mint 20.1 .

React doesn't render autocomplete off

Posted: 02 May 2022 12:31 AM PDT

How do I make react render it?

<input      id={field.name}      className="form-control"      type="text"      placeholder={field.name}      autocomplete="off"      {...field}/>  

No comments:

Post a Comment