Monday, May 30, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Getting each foreach loop in ajax

Posted: 30 May 2022 03:30 PM PDT

I'm currently looking at making a social media style site.

I have a foreach displaying a sql table of user posts.

I've looked and found how to submit to a php file without refreshing but now I'm in need of a way to have the ability to like each individual post.

Currently, if I put the ajax script at say the bottom, it likes the last post within the foreach loop. Any suggestions on how I can have it "like" the correct post? Hopefully this explains enough.

My ajax code:

$(document).ready(function(e){      e.preventDefault();      $.ajax({          url: "get_data.php",          type: "POST",          data: {postid, $postid},          success: function(data){                    });  });  

Group by using COUNT(*) OVER (PARTITION BY

Posted: 30 May 2022 03:29 PM PDT

I want to create a new column with the counts of repeated elements based on other 3 columns. When I try on the group by to add, i_count I get the following error SQL state: 42P20. I would also like to have a column with the average of the column loss from other column by name

SELECT    cst,    st,    co,    COUNT(*) OVER (PARTITION BY cst,st,co ) AS count    --mean of loss by co  FROM s.tb_st , s.tb_cst , s.tb_co , erp.tb_i  WHERE st != 'te'  GROUP  BY cst,st ,co, count  ORDER BY cst , st, co;  

input

  cst          | st              |  co               sal          | pa              |  ctr              sal          | pa              |  ctr              sal          | pa              |  est              sal          | re              |  ctr             sal          | re              |  ctr              sal          | re              |  ust              cus          | pa              |  ctr              cus          | re              |  ctr              cus          | re              |  ctr              cus          | re              |  ctr            

expected output

  cst          | st              |  co           |count | lossmeanbyco      sal          | pa              |  ctr          | 2    | 2000    sal          | pa              |  est          | 1    | 5000    sal          | re              |  ctr          | 2    | 2000    sal          | re              |  ust          | 1    | 1000    cus          | pa              |  ctr          | 1    | 2000    cus          | re              |  ctr          | 3    | 2000  

How to create a global variable for render_template()?

Posted: 30 May 2022 03:29 PM PDT

I have a simple task: to pass the same variable for different routes in the render_template() function. This value is in the base template and I need to pass it on every render_template() function. Can I set this value as a global value so that I don't have to set it in every function for different routes?

@app.route('/hello')  def hello(name=None):      return render_template('hello.html', value=value)    @app.route('/bye')  def bye(name=None):      return render_template('bye.html', value=value)```  

Dynamic text on image

Posted: 30 May 2022 03:29 PM PDT

I have an application that creates a dynamic image and writes text on it. The English language text works as advertised but other languages fail completely. The letters become boxes, etc.

package main    import (      "errors"      "fmt"      "image"      "image/color"      "image/png"      "math"      "os"        "github.com/fogleman/gg"      guuid "github.com/google/uuid"        "github.com/jimlawless/whereami"  )    type TextImage struct {      BgImgPath string      FontPath  string      FontSize  float64      Text      string  }    var sentence = make(map[string]string)  var language string    func init() {      sentence["arabic"] = "قفز الثعلب البني فوق الكلب الكسول."      sentence["english"] = "The brown fox jumped over the lazy dog."      sentence["hebrew"] = "השועל החום קפץ מעל הכלב העצלן."      sentence["hindi"] = "भूरी लोमड़ी आलसी कुत्ते के ऊपर से कूद गई।."      sentence["greek"] = "Η καφέ αλεπού πήδηξε πάνω από το τεμπέλικο σκυλί."  }    func main() {      language = "greek"      uuid := genUUID()      createFolder(uuid)      createImage(len(sentence[language]), uuid)      writeImage(sentence[language], uuid)  }    func genUUID() string {      return guuid.New().String()  }    func createFolder(p string) {      path := "./tmp/" + p      if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) {          err := os.MkdirAll(path, os.ModePerm)          if err != nil {              fmt.Println(err.Error() + " @ " + whereami.WhereAmI())          }      }  }    func writeImage(text string, path string) {      ti := TextImage{          BgImgPath: "./tmp/" + path + "/" + language + ".png",          FontPath:  "./ttf/PlayfairDisplay-Regular.ttf",          FontSize:  24,          Text:      text,      }      img, err := textOnImg(ti)      if err != nil {          fmt.Println(err.Error() + " @ " + whereami.WhereAmI())      }      err = saveImage(img, "./tmp/"+path+"/"+language+".png")      if err != nil {          fmt.Println(err.Error() + " @ " + whereami.WhereAmI())      }  }    func createImage(textlength int, path string) {      minDim := 300      scale := 30      dim := math.Sqrt(float64(textlength))      width := int(dim) * scale      height := int(dim) * scale        if width < minDim || height < minDim {          width = minDim          height = minDim      }        upLeft := image.Point{0, 0}      lowRight := image.Point{width, height}        img := image.NewRGBA(image.Rectangle{upLeft, lowRight})      //img.Bounds()      white := color.RGBA{255, 255, 255, 0xff}        // Set color for each pixel.      for x := 0; x < width; x++ {          for y := 0; y < height; y++ {              switch {              case x < width/2 && y < height/2: // upper left quadrant                  img.Set(x, y, white)              case x >= width/2 && y >= height/2: // lower right quadrant                  img.Set(x, y, color.White)              default:                  img.Set(x, y, color.White)              }          }      }        f, err := os.Create("./tmp/" + path + "/" + language + ".png")      if err != nil {          fmt.Println(err.Error() + " @ " + whereami.WhereAmI())      }      err = png.Encode(f, img)      if err != nil {          fmt.Println(err.Error() + " @ " + whereami.WhereAmI())      }  }    func deleteFolder(folder string) {      err := os.RemoveAll("./tmp/" + folder)      if err != nil {          fmt.Println(err.Error() + " @ " + whereami.WhereAmI())      }  }    func textOnImg(ti TextImage) (image.Image, error) {      bgImage, err := gg.LoadImage(ti.BgImgPath)      if err != nil {          fmt.Println(err.Error() + " @ " + whereami.WhereAmI())          return nil, err      }      imgWidth := bgImage.Bounds().Dx()      imgHeight := bgImage.Bounds().Dy()        dc := gg.NewContext(imgWidth, imgHeight)      dc.DrawImage(bgImage, 0, 0)        if err := dc.LoadFontFace(ti.FontPath, ti.FontSize); err != nil {          fmt.Println(err.Error() + " @ " + whereami.WhereAmI())          return nil, err      }        x := float64(imgWidth / 2)      y := float64((imgHeight / 2) - 80)      maxWidth := float64(imgWidth) - 60.0      dc.SetColor(color.Black)      fmt.Println(ti.Text)      dc.DrawStringWrapped(ti.Text, x, y, 0.5, 0.5, maxWidth, 1.5, gg.AlignLeft)        return dc.Image(), nil  }    func saveImage(img image.Image, path string) error {      if err := gg.SavePNG(path, img); err != nil {          fmt.Println(err.Error() + " @ " + whereami.WhereAmI())          return err      }      return nil  }    

Any recommendations hot to fix this?

How can I get this code to output a sorted list instead of "none"

Posted: 30 May 2022 03:29 PM PDT

Codecademy problem#5 "Combine Sort"

def combine_sort(lst1, lst2):    combined = lst1 + lst2    return combined.sort()    print(combine_sort([1,3,2],[3,1,2]))  

This code outputs

none

Trying to understand functions bool in C++

Posted: 30 May 2022 03:29 PM PDT

I am a beginner in C++ and I'm trying to improve my programming with functions. My problem with the exercise below is with making a code for objective number 2, where I don't understand how to return a value true or else false for the given variables (y1, x1, c1) with the use of function bool three (int) and arguments y, x and c. I just really need to see a working code for exercise below so that I can then dive into it and learn from it, understanding what everything does. It would mean alot and help me move on to other function exercises. Every help is very much appreciated.

This is the exercise:

Create a program with proper functions.

Read values for y, x and c; reading should repeat untill y is between 2 and 5 (with 2 and 5 included) and then x and c between 7 and 12 (both included).

Function three (int) shuold return value true, if the given argument (value of variable) is multiple of number 3, else is false; with this function decide a value for variable y1 for argument y and similar for x1 for argument x and c1 for argument c.

Type out values for y1, x1 and c1.

Function odd (int, int) writes out all the odd numbers between 2 given arguments y and x.

Function square (int,int,int,int&,int&) should return value, which is a sum of squares of the given arguments; over the last two arguments it should return a sum of squares of the first 2 arguments and the last 2 arguments.

With function determine value of variable yxc with arguments y, x, c, yx2 and xc2.

Write out values of yxc, yx2 and xc2

Prototypes of functions:

bool three (int);    void odd (int,int);    int square (int,int,int,int&,int&);  

How my code looks like now:

#include <iostream>  using namespace std;    bool three(int);  void odd(int, int);  int square(int, int, int, int&, int&);    int main()  {      int y, x, c;      cout << "Insert values for y, x in c." << endl;      while ((y > 5) || (y < 2)) {          cout << "Insert a value for y: ";          cin >> y;      }      while ((x > 12) || (x < 7)) {          cout << "Insert a value for x: ";          cin >> x;      }      while ((c > 12) || (x < 7)) {          cout << "Insert a value for c: ";          cin >> c;      }      three(y);  }    bool three(int y)  {      if (y % 3 == 0)          return true;      else {          return false;      }  }  

Why is Android Studio telling me my variable is not initialized?

Posted: 30 May 2022 03:28 PM PDT

I am trying to change the location of an image, and to do that I need a certain variable, which I initialized at the start of this code. I am able to call the variable multiple times with no problem, expect for the second time I call it, on line 7. The exact error is "Variable 'currentHall' must be initialized." How can I fix this?

            var currentHall: Hall              for(i in 0..11) {                  if(halls[i].name == locationHall) {                      currentHall = halls[i]                  }              }              if(currentHall.image == "segment_hori.png") {                  youAreHere.y = currentHall.yCoord                  youAreHere.x = currentHall.xCoord + locationCoords              }              if(currentHall.image == "segment_vert.png") {                  youAreHere.y = currentHall.yCoord + locationCoords                  youAreHere.x = currentHall.xCoord              }  

Rust: Mysterious impossibility of copy array

Posted: 30 May 2022 03:28 PM PDT

I wrote the following Rust code, and is giving me a error whose cause is far beyond my comprehension. And is that the array copy mechanism in lines 80 to 88, but that it is no working, and I have no idea why. Also note that I already tried with .copy.

I just want to copy the Updater's display to the Canvas view_buffer.

Why does the line 88 assert does crash?

My main.rs:

use std::cell::RefCell;  use std::rc::Rc;  use std::time::{Duration, Instant};    use iced::{      canvas::Canvas,      canvas::{Cursor, Geometry},      executor, time,      widget::canvas::{          event::{self, Event},          Program,      },      Application, Clipboard, Command, Element, Rectangle, Settings, Subscription,  };    pub const WINDOW_HEIGHT: usize = 32;  pub const WINDOW_WIDTH: usize = 64;  pub const WINDOW_SIZE: usize = WINDOW_WIDTH * WINDOW_HEIGHT;    #[derive(Debug, Clone)]  pub struct Updater {      display: [bool; WINDOW_SIZE],      redraw_required: bool,  }    impl Default for Updater {      fn default() -> Updater {          Updater {              display: [false; WINDOW_SIZE],              redraw_required: false,          }      }  }    impl Updater {      pub fn cpu_tick(&mut self) {          for i in 0..WINDOW_SIZE {              use rand::random;              self.display[i] = random();          }      }        pub fn get_display_state(&self) -> &[bool; WINDOW_SIZE] {          &self.display      }        pub fn is_redraw_required(&self) -> bool {          self.redraw_required      }        pub fn unset_redraw_required(&mut self) {          self.redraw_required = false;      }  }    #[derive(Debug)]  pub struct CanvasView {      view_buffer: [bool; WINDOW_SIZE],      updater: Rc<RefCell<Updater>>,  }    impl CanvasView {      pub fn new(program: Rc<RefCell<Updater>>) -> CanvasView {          CanvasView {              view_buffer: [false; WINDOW_SIZE],              updater: program,          }      }  }    impl Program<Message> for CanvasView {      fn update(          &mut self,          _event: Event,          _bounds: Rectangle,          _cursor: Cursor,      ) -> (event::Status, Option<Message>) {          let mut updater_instance = self.updater.borrow_mut();          if updater_instance.is_redraw_required() {              let arr = updater_instance.get_display_state();              for (v, item) in arr.iter().enumerate().take(WINDOW_SIZE) {                  self.view_buffer[v] = *item;                  assert_eq!(self.view_buffer[v], arr[v]);              }              updater_instance.unset_redraw_required();              assert_eq!(*updater_instance.get_display_state(), self.view_buffer);          }          assert_eq!(*updater_instance.get_display_state(), self.view_buffer);          (event::Status::Ignored, None)      }        fn draw(&self, _bounds: Rectangle, _cursor: Cursor) -> Vec<Geometry> {          vec![]      }  }    struct ExampleApplication {      updater_instance: Option<Rc<RefCell<Updater>>>,  }    #[derive(Debug, Clone)]  pub enum Message {      CPUTick(Instant),  }    impl Application for ExampleApplication {      type Executor = executor::Default;      type Message = Message;      type Flags = ();        fn new(_: ()) -> (ExampleApplication, Command<Self::Message>) {          (              Self {                  updater_instance: Some(Rc::new(RefCell::new(Updater::default()))),              },              Command::none(),          )      }        fn title(&self) -> String {          String::from("Test")      }        fn update(          &mut self,          message: Self::Message,          _clipbourd: &mut Clipboard,      ) -> Command<Self::Message> {          match message {              Message::CPUTick(_instant) => {                  if let Some(updater_instance) = self.updater_instance.as_mut() {                      updater_instance.borrow_mut().cpu_tick();                  }                  Command::none()              }          }      }        fn subscription(&self) -> Subscription<Self::Message> {          let cpu_tick = time::every(Duration::from_millis(1000 / 500)).map(Message::CPUTick);            Subscription::batch(vec![cpu_tick])      }        fn view(&mut self) -> Element<Self::Message> {          use iced::{Container, Length};            let content = Canvas::new(CanvasView::new(Rc::clone(              self.updater_instance.as_ref().unwrap(),          )))          .width(Length::Fill)          .height(Length::Fill);          Container::new(content)              .width(Length::Fill)              .height(Length::Fill)              .into()      }  }    pub fn main() {      env_logger::init();        ExampleApplication::run(Settings {          window: iced::Settings {              size: (64 * 15, 32 * 15),              min_size: Some((64 * 5, 32 * 5)),              max_size: Some((64 * 5, 32 * 5)),              resizable: false,              ..iced::Settings::default()          },          flags: (),          default_font: None,          default_text_size: 20,          exit_on_close_request: true,          antialiasing: true,      })      .unwrap();  }  

My Cargo.toml

[package]  name = "example"  version = "0.1.0"  edition = "2021"  [dependencies]  rand = "0.8.4"  iced = { version = "0.3" , features = ["canvas", "tokio"] }  iced_native = "0.3"  log = "0.4.16"  env_logger = "0.9.0"  

How can I pass the data from Firebase to an array of objects

Posted: 30 May 2022 03:28 PM PDT

I need to pass the data retrieved from Firebase to the "eventos" object array, I'm a beginner, how's the easiest way to do that?

var ref:DatabaseReference?  var databaseHandle:DatabaseHandle?    var eventos = [Evento]()        override func viewDidLoad() {      super.viewDidLoad()            tableView.delegate = self      tableView.dataSource = self            let ref = Database.database().reference(withPath: "Eventos")            ref.observe(.value, with: { snapshot in          // This is the snapshot of the data at the moment in the Firebase database          print(snapshot.value as Any)      })  

Is there a way do color specific dates in input, type = "date"

Posted: 30 May 2022 03:28 PM PDT

I would like to implement reservations. Because of that, some date ranges are already reserved. Is there any way to color specific dates in the pop up that comes out when I click the little calendar icon. I would like to achieve something like this picture of calendar where the red dates are already reserved I'm open for any kind of implementation

How to import and use my own function from .py file in Python Pandas?

Posted: 30 May 2022 03:29 PM PDT

In Jupyter Notebook I created my own function in my_fk.py file like below:

import pandas as pd    def missing_val(df):        df= pd.DataFrame(df.dtypes, columns=["type"])      df["missing"] = pd.DataFrame(df.isna().any())      df["sum_miss"] = pd.DataFrame(df.isna().sum())      df["perc_miss"] = round((df.apply(pd.isna).mean()*100),2)            return df  

Then when I try to import and run my function using below code:

df = pd.read_csv("my_data.csv")  import pandas as pd  import numpy as np  import my_fk fk  fk.missing_val(df)  

I have error like below. Error suggests that in my my_fk.py file there is no pandas as pd, but there IS line with code "import pandas as pd". How can I import and use my own function from python file ?

NameError: name 'pd' is not defined  

how to retrieve data from the dictionary

Posted: 30 May 2022 03:28 PM PDT

How can I get the phone number and state name of the city of Mooresville from this dictionary

{'CityName': 'Milton', 'Tel': 623-2891, 'code': '850', 'title': 'FL'}  {'CityName': 'Mooresville', 'Tel': 985-3764, 'code': '765', 'title': 'IN'}  {'CityName': 'Sunnyvale', 'Tel': 730-2231, 'code': '408', 'title': 'CA'}  

Primary key without Identity (Auto-increment column)

Posted: 30 May 2022 03:31 PM PDT

How to create an autoincrementing primary key without using the identity function? I have the following problem, when trying to make a record and this is not successful, a rollback occurs, that is, the PK column loses the sequence and this generates holes in my column

Example I have 5 records in my tables

ID - NAME

1 - zack

2 - lux

3 - zed

4 - Lucian

5 - kata

If for some reason when trying to do an insert it fails you lose the sequence ...

id - name

999 - velkoz

I want to avoid this.

How can I create a PK automatically without using INDENTITY and make it efficient to the database engine as an integer?

CREATE TABLE Students  (      student_id INT IDENTITY, -- BAD IDEA TO USE IDENTITY FUNCTION      name VARCHAR(20),      CONSTRAINT PK_STUDENT_ID PRIMARY KEY (student_id)  )  

Can we add embedding Angular page url to Azure B2C Endpoint?

Posted: 30 May 2022 03:28 PM PDT

Is it possible to embed Angular page url(with ) in Azure B2C Login Endpoint? I only see examples of embedding simple HTML page url and not angular generated HTML url. Is it technically feasible? I know there are other ways as shown in official documentation where the flows go from website to B2C i.e. we can use redirect or popup. But I need the B2C endpoint to show my embedded angular page.

calculating previous months from Date() duplicates a month

Posted: 30 May 2022 03:31 PM PDT

I am trying to 12 previous months from today, but it displays

Date to start with - Mon May 30 22:57:30 GMT+01:00 2022

Months displayed are - these are the values in the monthsArray, Month March 2022 is displayed twice

April 2022 March 2022 (DISPLAYED TWICE) March 2022 (DISPLAYED TWICE) February 2022 January 2022 December 2021 November 2021 October 2021 September 2021 August 2021 July 2021 June 2021

This is the logic to display months

  val monthsArray: ArrayList<String> = ArrayList()      val date = Date()      var i = 1      while (i <= 12) {          date.month = date.month - 1          monthsArray.add(readableSpinnerItemDate(date.time))          i++      }  

Could you please suggest what might be wrong here please

Thanks R

What data structure is typically used to support text insertion?

Posted: 30 May 2022 03:28 PM PDT

I write some text in a textbox:

Four score and seven years ago our fathers brought forth a new nation...

This textbox can be in Notepad, Microsoft Word, or in a webpage on my browser. I realize I made an omission, and I want to insert some text in the middle:

Four score and seven years ago our fathers brought forth, upon this continent, a new nation...

(in practice) What data structure is typically used to support text insertion?

How to get inputs from the user?

Posted: 30 May 2022 03:29 PM PDT

I want to make a spam bot that asks you 4 questions

  • what's your word?
  • how much delay between messages?
  • how many messages you want to send?
  • have you read the instructions?(y,n)

The problem is that it just loops asking the last question.

Here is my code:

#importing required packages  import pyautogui    import time  #defining variables  word = input("what's your word?: ")  delay = int(input("how much delay between messages?: "))  knows = 5  doesnot = 20       #loop  while True:       number = int(input("how many messages you want to send?: "))      maxnumber = int(number)      while number < maxnumber:          pyautogui.typewrite(word)          pyautogui.press("enter")          time.sleep(delay)      if number == maxnumber:          break      break  #checking if he knows what the F is he doin'  while True:      auth = input("have you read the instructions?(y,n): ")      if auth == "y":          print("you have 5 seconds to switch tabs")          time.sleep(knows)      elif auth == "n":          print("rules are simple, you have 5 seconds to switch tabs and click on the box you want to spam(if you're reading this you have 20 seconds!)")          time.sleep(doesnot)          break  

I want the bot to ask these questions and behave accordingly.

Sort string that contain date in Python

Posted: 30 May 2022 03:30 PM PDT

This code sorting dates without any issues. If I add any string to the my_dates variable can we sort similiarly? Splitting the string is the only way or any other alternative?

eg: my_dates = ['a_05112018.zip', 'a_25032017.zip', 'a_01112018.zip', 'a_07012017.zip']

from datetime import datetime  import re    pattern='Anyfile_<ddmmyyyy>.zip'  my_dates = ['05112018', '25032017', '01112018', '07012017']    result = re.search("<([dmy]{8,})>", pattern, flags=re.IGNORECASE)  if result:      date_pattern = result.group(1)      date_pattern = re.sub("dd", "%d", date_pattern, flags=re.IGNORECASE)      date_pattern = re.sub("mmm", "%b", date_pattern, flags=re.IGNORECASE)      date_pattern = re.sub("mm", "%m", date_pattern, flags=re.IGNORECASE)      date_pattern = re.sub("yyyy", "%Y", date_pattern, flags=re.IGNORECASE)    my_dates.sort(key=lambda date: datetime.strptime(date, date_pattern))  print(my_dates)  

Update Parent Data from Child Modal Data using Props in vue

Posted: 30 May 2022 03:30 PM PDT

I am working on invoice, where i want to add new client using modal and then get added data back to create invoice page (Parent Page). I have tried to follow many previous questions but still not able to figure it out, how to properly use $emit here. How to Pass data from Modal to Parent..

Here are the codes so far.

this is createInvoice.vue

<template>     <button @click="isComponentModalActive = true">         Add New Client     </button>       <b-modal        v-model="isComponentModalActive"         has-modal-card         full-screen         :can-cancel="false"      >        <client-add-form v-bind="form.clientData"></client-add-form>      </b-modal>  </template>    <script>  import ClientAddForm from '../../../components/ClientAddForm.vue';  export default {    components: { ClientAddForm },      data() {      return {        isComponentModalActive: false,        form: {          clientData: {            name: "Gaurav Kumar",            email: "imthegrv@gmail.com",            phone: "",            address: "",            city: "",            country: "",            taxCode: "",            Type: "",          },         }  }  </script>  

this is ClientAddForm.vue Modal

    <template>        <div class="modal-card" style="width: auto">          <header class="modal-card-head">            <p class="modal-card-title">Add/Modify Customer Information</p>          </header>          <section class="modal-card-body">            <b-field label="Name">              <b-input type="text" :value="name" placeholder="Name"> </b-input>            </b-field>            <b-field label="Phone">              <b-input type="phone" :value="phone" placeholder="Phone"> </b-input>            </b-field>            <b-field label="Email">              <b-input type="email" :value="email" placeholder="Email"> </b-input>            </b-field>            <b-field label="Address">              <b-input type="textarea" :value="address" placeholder="Address">              </b-input>            </b-field>            <b-field label="City">              <b-input type="text" :value="city" placeholder="City"> </b-input>            </b-field>            <b-field label="Country">              <b-input type="text" :value="country" placeholder="Country"> </b-input>            </b-field>          </section>          <footer class="modal-card-foot">            <b-button label="Close" @click="$parent.close()" />            <b-button label="Save" type="is-primary" @click="Update()"  />          </footer>        </div>     </template>                <script>      export default {        props: ["email", "phone", "name", "city", "country", "address"],              methods: {          Update(){             //Database Operations etc             this.$emit()          }        }      }   </script>  

Vue reactive object containing array of object

Posted: 30 May 2022 03:31 PM PDT

I have tried many different formats, but can only make this work:

// This works  <script setup lang="ts">  import { reactive } from 'vue'  import { IPixabayItem } from '../interfaces/IPixapayItem'  const imageList: IPixabayItem[] = []  const foundImages = reactive(      {          images: imageList      }  )  </script>  

Somehow I would like to avoid the const 'imageList' and instantiate the 'IPixabayItem[]' inside the reactive object; but cannot make this transpile.

// This dosn't work  <script setup lang="ts">  import { reactive } from 'vue'  import { IPixabayItem } from '../interfaces/IPixapayItem'  const foundImages = reactive(      {          images: IPixabayItem[] = []      }  )  </script>  

Help appreciated

React App Build Failure (sass/resolve-url-loader)

Posted: 30 May 2022 03:30 PM PDT

Creating a react app off this tutorial (https://www.youtube.com/watch?v=yqe5UB_BF7Q) and got this error when trying to apply the styles. The last step involved deleted the index.css file and replacing it with styles.scss.

I already tried npm install -g sass to no luck, anyone know what to do here?

Error output below.

Failed to compile.

Cannot find module 'sass' Require stack:

  • /Users/amarcin/web/node_modules/sass-loader/dist/utils.js
  • /Users/amarcin/web/node_modules/sass-loader/dist/index.js
  • /Users/amarcin/web/node_modules/sass-loader/dist/cjs.js
  • /Users/amarcin/web/node_modules/loader-runner/lib/loadLoader.js
  • /Users/amarcin/web/node_modules/loader-runner/lib/LoaderRunner.js
  • /Users/amarcin/web/node_modules/webpack/lib/NormalModule.js
  • /Users/amarcin/web/node_modules/webpack-manifest-plugin/dist/index.js
  • /Users/amarcin/web/node_modules/react-scripts/config/webpack.config.js
  • /Users/amarcin/web/node_modules/react-scripts/scripts/start.js WARNING in ./src/styles.scss (./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[7].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[7].use[2]!./node_modules/resolve-url-loader/index.js??ruleSet[1].rules[1].oneOf[7].use[3]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[7].use[4]!./src/styles.scss) Module Warning (from ./node_modules/resolve-url-loader/index.js): resolve-url-loader: webpack misconfiguration webpack or the upstream loader did not supply a source-map

ERROR in ./src/styles.scss (./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[7].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[7].use[2]!./node_modules/resolve-url-loader/index.js??ruleSet[1].rules[1].oneOf[7].use[3]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[7].use[4]!./src/styles.scss) Module Error (from ./node_modules/sass-loader/dist/cjs.js): Cannot find module 'sass' Require stack:

  • /Users/amarcin/web/node_modules/sass-loader/dist/utils.js
  • /Users/amarcin/web/node_modules/sass-loader/dist/index.js
  • /Users/amarcin/web/node_modules/sass-loader/dist/cjs.js
  • /Users/amarcin/web/node_modules/loader-runner/lib/loadLoader.js
  • /Users/amarcin/web/node_modules/loader-runner/lib/LoaderRunner.js
  • /Users/amarcin/web/node_modules/webpack/lib/NormalModule.js
  • /Users/amarcin/web/node_modules/webpack-manifest-plugin/dist/index.js
  • /Users/amarcin/web/node_modules/react-scripts/config/webpack.config.js
  • /Users/amarcin/web/node_modules/react-scripts/scripts/start.js

ERROR in ./src/styles.scss (./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[7].use[1]!./node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[7].use[2]!./node_modules/resolve-url-loader/index.js??ruleSet[1].rules[1].oneOf[7].use[3]!./node_modules/sass-loader/dist/cjs.js??ruleSet[1].rules[1].oneOf[7].use[4]!./src/styles.scss) Module build failed (from ./node_modules/resolve-url-loader/index.js): Error: resolve-url-loader: error processing CSS PostCSS received undefined instead of CSS string at new Input (/Users/amarcin/web/node_modules/resolve-url-loader/node_modules/postcss/lib/input.js:38:13) at encodeError (/Users/amarcin/web/node_modules/resolve-url-loader/index.js:287:12) at onFailure (/Users/amarcin/web/node_modules/resolve-url-loader/index.js:228:14)

webpack compiled with 2 errors and 1 warning

FAILED CONFIGURATION: @BeforeMethod setUp - Selenium Java TestNG

Posted: 30 May 2022 03:28 PM PDT

I am trying to execute Selenium Java Project with TestNG but I am getting the Configurations Problems related to TestNG annotations. I am using Page object model design pattern. The chromedriver gets executed successfully for each testcase and it lands on login page but after that it crashes and gives error about Failed Configurations @BeforeMethod.

I am sharing the whole code and console errors. Any Solution for this folks! Been stuck here for the long time.

Page Classes.

Base Page:

package Pages;    import org.openqa.selenium.By;  import org.openqa.selenium.WebDriver;  import org.openqa.selenium.support.ui.ExpectedConditions;  import org.openqa.selenium.support.ui.WebDriverWait;  import org.testng.Assert;    public class BasePage{    public WebDriver driver;  public WebDriverWait wait;      public BasePage(WebDriver driver, WebDriverWait wait) {            this.driver = driver;      this.wait = wait;  }    //Generic Methods    public void click(By elementlocation) {      driver.findElement(elementlocation).click();  }    public void writeText(By elementlocation, String text) {      driver.findElement(elementlocation).sendKeys(text);  }    public String readText(By elementlocation) {      return driver.findElement(elementlocation).getText();  }    public void waitVisibility(By elementlocation) {      wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(elementlocation));  }    public void waitElementToBeClickable(By elementlocation ) {      wait.until(ExpectedConditions.elementToBeClickable(elementlocation));  }    public void assertEquals (By elementlocation, String expectedText) {      waitVisibility(elementlocation);      Assert.assertEquals(readText(elementlocation), expectedText);  }        }  

Login Page with Methods:

package Pages;    import org.openqa.selenium.By;  import org.openqa.selenium.WebDriver;  import org.openqa.selenium.support.ui.WebDriverWait;    public class LoginPage extends BasePage{            public LoginPage(WebDriver driver, WebDriverWait wait) {          super(driver, wait);      }        By email = By.xpath("//input[@data-placeholder='Enter your username']");      By pwd = By.xpath("//input[@data-placeholder='Enter your Password']");      By LoginBtn = By.xpath("//button//span[text()='Login']");      By emptyLoginVerification = By.xpath("//span[contains(text(),'Both Password and user name are required.')]");      By emptyPasswordVerification = By.xpath("//span[contains(text(),'Both Password and user name are required.')]");      By emptyUserNameVerification = By.xpath("//span[contains(text(),'Both Password and user name are required.')]");        //methods      public LoginPage LoginToAMS(String username, String password) {                    writeText(email, username);                    writeText(pwd, password);                    click(LoginBtn);                            return this;      }            public LoginPage EmptyLoginVerification (String expectedText) {                    assertEquals(emptyLoginVerification, expectedText);                    return this;          }            public LoginPage EmptyPasswordVerification (String expectedText) {                    assertEquals(emptyPasswordVerification, expectedText);                    return this;              }            public LoginPage EmptyUserNameVerification (String expectedText) {                    assertEquals(emptyUserNameVerification, expectedText);                    return this;              }  }  

Below are the TestClasses Now.

BaseTest:

package tests;    import java.time.Duration;    import org.openqa.selenium.WebDriver;  import org.openqa.selenium.chrome.ChromeDriver;  import org.openqa.selenium.support.ui.WebDriverWait;  import org.testng.annotations.AfterClass;  import org.testng.annotations.AfterMethod;  import org.testng.annotations.AfterTest;  import org.testng.annotations.BeforeClass;  import org.testng.annotations.BeforeMethod;  import org.testng.annotations.BeforeTest;      public class BaseTest {            public WebDriver driver;      public WebDriverWait wait;              @BeforeMethod      public void setup() {                    System.setProperty("WebDriver.chrome.driver", "C:\\eclipse\\eclipse-workspace\\ams\\chromedriver.exe");          driver = new ChromeDriver();          wait = new WebDriverWait(driver, Duration.ofSeconds(15));          driver.manage().window().maximize();          driver.get("http://dev-ims.dplit.com/");                }            @AfterMethod      public void teardown() {          driver.close();      }  }  

And here is the actual TestClass:

package tests;    import static org.testng.Assert.assertEquals;    import java.util.concurrent.TimeUnit;    import org.openqa.selenium.By;  import org.openqa.selenium.WebDriver;  import org.openqa.selenium.chrome.ChromeDriver;  import org.testng.Assert;  import org.testng.annotations.AfterTest;  import org.testng.annotations.BeforeTest;  import org.testng.annotations.Test;    import Pages.HomePage_ListOfItems;  import Pages.LoginPage;    public class LoginTestCases extends BaseTest{            LoginPage loginpage = new LoginPage(driver, wait);            private String username = "nasir.n@planet.com";      private String password = "123456";            @Test(priority=0)      public void Valid_Login_To_AMS() {          loginpage.LoginToAMS(username, password);         }            @Test(priority=1)      public void Empty_Login_To_AMS() {          loginpage.LoginToAMS("","");          loginpage.EmptyLoginVerification("Both Password and user name are required.");      }            @Test(priority=2)      public void UserName_EmptyPassword() {          loginpage.LoginToAMS(username,"");          loginpage.EmptyPasswordVerification("Both Password and user name are required.");      }            @Test(priority=4)      public void EmptyUserName_PasswordFill( ) {          loginpage.LoginToAMS("", password);          loginpage.EmptyUserNameVerification("Both Password and user name are required.");      }    }  

The errors that I am getting are below:

[RemoteTestNG] detected TestNG version 7.4.0  SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".  SLF4J: Defaulting to no-operation (NOP) logger implementation  SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.  Starting ChromeDriver 101.0.4951.41 (93c720db8323b3ec10d056025ab95c23a31997c9-refs/branch-heads/4951@{#904}) on port 52405  Only local connections are allowed.  Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.  ChromeDriver was started successfully.  May 30, 2022 8:45:44 PM org.openqa.selenium.remote.ProtocolHandshake createSession  INFO: Detected dialect: W3C  May 30, 2022 8:45:44 PM org.openqa.selenium.devtools.CdpVersionFinder findNearestMatch  WARNING: Unable to find an exact match for CDP version 101, so returning the closest version found: a no-op implementation  May 30, 2022 8:45:44 PM org.openqa.selenium.devtools.CdpVersionFinder findNearestMatch  INFO: Unable to find CDP implementation matching 101.  May 30, 2022 8:45:44 PM org.openqa.selenium.chromium.ChromiumDriver lambda$new$3  WARNING: Unable to find version of CDP to use for . You may need to include a dependency on a specific version of the CDP using something similar to `org.seleniumhq.selenium:selenium-devtools-v86:4.1.1` where the version ("v86") matches the version of the chromium-based browser you're using and the version number of the artifact is the same as Selenium's.  Starting ChromeDriver 101.0.4951.41 (93c720db8323b3ec10d056025ab95c23a31997c9-refs/branch-heads/4951@{#904}) on port 50748  Only local connections are allowed.  Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.  ChromeDriver was started successfully.  May 30, 2022 8:46:30 PM org.openqa.selenium.remote.ProtocolHandshake createSession  INFO: Detected dialect: W3C  May 30, 2022 8:46:31 PM org.openqa.selenium.devtools.CdpVersionFinder findNearestMatch  WARNING: Unable to find an exact match for CDP version 101, so returning the closest version found: a no-op implementation  May 30, 2022 8:46:31 PM org.openqa.selenium.devtools.CdpVersionFinder findNearestMatch  INFO: Unable to find CDP implementation matching 101.  May 30, 2022 8:46:31 PM org.openqa.selenium.chromium.ChromiumDriver lambda$new$3  WARNING: Unable to find version of CDP to use for . You may need to include a dependency on a specific version of the CDP using something similar to `org.seleniumhq.selenium:selenium-devtools-v86:4.1.1` where the version ("v86") matches the version of the chromium-based browser you're using and the version number of the artifact is the same as Selenium's.  FAILED CONFIGURATION: @BeforeMethod setup  org.openqa.selenium.WebDriverException: unknown error: cannot determine loading status  from disconnected: unable to send message to renderer    (Session info: chrome=101.0.4951.67)  Build info: version: '4.1.1', revision: 'e8fcc2cecf'  System info: host: 'NASIR-S-LTP', ip: '192.168.10.18', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '17.0.1'  Driver info: org.openqa.selenium.chrome.ChromeDriver  Command: [afb96e2642d9f544c41d7d722caab5d3, get {url=http://dev-ims.dplit.com/}]  Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 101.0.4951.67, chrome: {chromedriverVersion: 101.0.4951.41 (93c720db8323..., userDataDir: C:\Users\nasir.n\AppData\Lo...}, goog:chromeOptions: {debuggerAddress: localhost:53544}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: WINDOWS, platformName: WINDOWS, proxy: Proxy(), se:cdp: ws://localhost:53544/devtoo..., se:cdpVersion: 101.0.4951.67, setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify, webauthn:extension:credBlob: true, webauthn:extension:largeBlob: true, webauthn:virtualAuthenticators: true}  Session ID: afb96e2642d9f544c41d7d722caab5d3      at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)      at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77)      at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)      at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)      at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)      at org.openqa.selenium.remote.codec.w3c.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:200)      at org.openqa.selenium.remote.codec.w3c.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:133)      at org.openqa.selenium.remote.codec.w3c.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:53)      at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:184)      at org.openqa.selenium.remote.service.DriverCommandExecutor.invokeExecute(DriverCommandExecutor.java:167)      at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:142)      at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:543)      at org.openqa.selenium.remote.RemoteWebDriver.get(RemoteWebDriver.java:312)      at tests.BaseTest.setup(BaseTest.java:29)      at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)      at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)      at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)      at java.base/java.lang.reflect.Method.invoke(Method.java:568)      at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:133)      at org.testng.internal.MethodInvocationHelper.invokeMethodConsideringTimeout(MethodInvocationHelper.java:62)      at org.testng.internal.ConfigInvoker.invokeConfigurationMethod(ConfigInvoker.java:385)      at org.testng.internal.ConfigInvoker.invokeConfigurations(ConfigInvoker.java:321)      at org.testng.internal.TestInvoker.runConfigMethods(TestInvoker.java:700)      at org.testng.internal.TestInvoker.invokeMethod(TestInvoker.java:527)      at org.testng.internal.TestInvoker.invokeTestMethod(TestInvoker.java:173)      at org.testng.internal.MethodRunner.runInSequence(MethodRunner.java:46)      at org.testng.internal.TestInvoker$MethodInvocationAgent.invoke(TestInvoker.java:824)      at org.testng.internal.TestInvoker.invokeTestMethods(TestInvoker.java:146)      at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:146)      at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:128)      at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)      at org.testng.TestRunner.privateRun(TestRunner.java:794)      at org.testng.TestRunner.run(TestRunner.java:596)      at org.testng.SuiteRunner.runTest(SuiteRunner.java:377)      at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:371)      at org.testng.SuiteRunner.privateRun(SuiteRunner.java:332)      at org.testng.SuiteRunner.run(SuiteRunner.java:276)      at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)      at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)      at org.testng.TestNG.runSuitesSequentially(TestNG.java:1212)      at org.testng.TestNG.runSuitesLocally(TestNG.java:1134)      at org.testng.TestNG.runSuites(TestNG.java:1063)      at org.testng.TestNG.run(TestNG.java:1031)      at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115)      at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)      at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)  

POM.xml

<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>    <groupId>amsdev</groupId>    <artifactId>ams</artifactId>    <version>0.0.1-SNAPSHOT</version>     <dependencies>          <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->  <dependency>      <groupId>org.seleniumhq.selenium</groupId>      <artifactId>selenium-java</artifactId>      <version>4.1.1</version>  </dependency>    <!-- https://mvnrepository.com/artifact/org.testng/testng -->  <dependency>      <groupId>org.testng</groupId>      <artifactId>testng</artifactId>      <version>7.4.0</version>      <scope>test</scope>  </dependency>          </dependencies>    </project>  

I’m trying to make an Hirschberg algorithm with python

Posted: 30 May 2022 03:29 PM PDT

I'm trying to make a Hirschberg algorithm with python. I've written the code but I don't know how to compose all alignments in the recursion. Please help me if anyone knows.

  import sys    class Assignment2022:        def __init__(self, A, B, m, d, g):          self.F = None          self.A = A          self.B = B          self.m = m          self.d = d if d < 0 else -d          self.g = g if g < 0 else -g          self.WWW = []          self.ZZZ = []            def compare(self, Ai, Bj):          if Ai == Bj:              return self.m          else:              return self.d        def NeedlemanWunsch(self, A, B):          nA = len(A)          nB = len(B)          F = [[_ * self.g for _ in range(0, nA + 1)]]          for _ in range(1, nB + 1):              row = [0] * (nA + 1)              row[0] = _ * self.g              F.append(row)            for j in range(nB + 1):              for i in range(nA + 1):                  if i == 0 and j == 0:                      F[j][i] = 0                  elif j == 0:                      F[j][i] = self.g * i                  elif i == 0:                      F[j][i] = self.g * j                  else:                      dm = F[j - 1][i - 1] + self.m if A[i - 1] == B[j - 1] else F[j - 1][i - 1] + self.d                      F[j][i] = max(F[j - 1][i] + self.g, F[j][i - 1] + self.g, dm)          self.F = F          self.WWW=[]          self.ZZZ=[]          self.EnumerateAlignments(A, B, F, W='', Z='')          return self.WWW, self.ZZZ        def EnumerateAlignments(self, A, B, F, W, Z):          i = len(A)          j = len(B)          if i == 0 and j == 0:              self.WWW.append(W)              self.ZZZ.append(Z)          elif i > 0 and j > 0:              mm = self.compare(A[i - 1], B[j - 1])                if F[j][i] == F[j - 1][i - 1] + mm:                  self.EnumerateAlignments(A[:i - 1], B[:j - 1], F, A[i-1] + W, B[j-1] + Z)          if i > 0 and F[j][i] == F[j][i - 1] + self.g:              self.EnumerateAlignments(A[:i - 1], B, F, A[i-1] + W, '-' + Z)          if j > 0 and F[j][i] == F[j - 1][i] + self.g:              self.EnumerateAlignments(A, B[:j - 1], F, '-' + W, B[j-1] + Z)        def ComputeAlignmentScore(self, A, B):          L = [0] * (len(B) + 1)          for j in range(len(L)):              L[j] = j * g          K = [0] * (len(B) + 1)          for i in range(1, len(A) + 1):              L, K = K, L              L[0] = i * g              for j in range(1, len(B) + 1):                  md = self.compare(A[i - 1], B[j - 1])                  L[j] = max(L[j - 1] + g, K[j] + g, K[j - 1] + md)          return L          def Hirschberg(self, A, B):            if len(A) == 0:              WW = ['-'] * len(B)              ZZ = B          elif len(B) == 0:              WW = A              ZZ = ['-'] * len(A)          elif len(A) == 1 or len(B) == 1:              WW, ZZ = self.NeedlemanWunsch(A, B)          else:              i = len(A) // 2              Sl = self.ComputeAlignmentScore(A[:i], B)              B_ = B[::-1]              Sr = self.ComputeAlignmentScore(A[i:][::-1], B_)              Sr.reverse()              S = [Sl[i] + Sr[i] for i in range(len(Sl))]              J = [i for i, _ in enumerate(S) if _ == max(S)]                           WW, ZZ = [], []              for j in J:                                        WWl, ZZl = self.Hirschberg(A[:i], B[:j])                  WWr, ZZr = self.Hirschberg(A[i:], B[j:], lr='r')                  WWn = WWl + WWr                  ZZn = ZZl + ZZr                                    WW.append(WWn)                  ZZ.append(ZZn)            return WW, ZZ      if __name__ == '__main__':      # args = ['-2','1' ,'-1','GACGC','ACTGACG']      # args = ['-1','1' ,'-1','GATTACA','GCATGCG']            args = ['-1', '+1', '-1', "deep end", 'depend']            solver = Assignment2022(A, B, m, d, g, t=t)      WW, ZZ = solver.Hirschberg(A, B)      print(WW)      print(ZZ)    

In the task I read the pseudocode is:

Hirschberg(A, B)  Input: A, the first sequence to be aligned  B, the second sequence to be aligned  Output: WW, all the alignments of A with B  ZZ, all the alignments of B with A corresponding to WW  1 if |A| = 0 then  2 WW ← " − " × |B|  3 ZZ ← B  4 else if |B| = 0 then  5 WW ← A  6 ZZ ← " − " × |A|  7 else if |A| = 1 or |B| = 1 then  8 (WW , ZZ) ← NeedlemanWunsch(A, B)  9 else  10 i ← ⌊|A|/2⌋  11 Sl ← ComputeAlignmentScore(A[0 . . . i], B)  12 Sr ← ComputeAlignmentScore(A ̃[i . . . |A|], B ̃)  13 S ← Sl +  ̃Sr  14 J ← Max(S)  15 WW ← CreateList()  16 ZZ ← CreateList()  17 foreach j in J do  18 (WWl, ZZl) ← Hirschberg(A[0 . . . i], B[0 . . . j])  19 (WWr, ZZr) ← Hirschberg(A[i . . . |A|], B[j . . . |B|])  20 UpdateAlignments(WW, ZZ, WWl + WWr, ZZl + ZZr)  21 return (WW, ZZ)  

My problem is how to implement the UpdateAligments function to collect all the Alignments. Please if someone has any Idea let's help me with that because I'm really stuck on that for days.

the example Inputs and outputs:

for input

args = ['-1', '+1', '-1', "deep end", 'depend']  

The alignments must be:

WW = ["deep end"]  ZZ = ["d-ep-end"]  

for input

args = ['-1','1' ,'-1','GATTACA','GCATGCG']  

The aligments must be:

WW = ["G-ATTACA", "G-ATTACA", "G-ATTACA"]  ZZ = ["GCA-TGCG", "GCAT-GCG", "GCATG-CG"]  

How to get the first audio channel from a video with ffmpeg-python?

Posted: 30 May 2022 03:27 PM PDT

I would like to get the very first audio channel from a video using ffmpeg-python.

I tried with this:

  out, _ = (          ffmpeg              .input(filename)              .output('pipe:', loglevel=0, format='s16le', acodec='pcm_s16le', ac=1, ar='8k')              .run(capture_stdout=True)      )      """ extract audio signal """      self.signal = (          np              .frombuffer(out, np.int16)        )  

but I am not sure whether this is correct.

I had a look here, but I could not find a solution: https://trac.ffmpeg.org/wiki/AudioChannelManipulation

Any suggestion? Thanks!

Is a multivalued Attribute always a week entity?

Posted: 30 May 2022 03:30 PM PDT

Can a multivalued attribute be a weak attribute? Or is it always a weak entity?

Spring Boot : Values of all attributes of DTO are null

Posted: 30 May 2022 03:30 PM PDT

I'm developing a Spring Boot application and I have a problem with my POST request. When I do the request it seems that every field in the request body is null.

Client entity

    package com.tradeManagementApp.tradeManagement.model;            import lombok.*;            import javax.persistence.*;      import java.util.List;            @Data      @Builder      @NoArgsConstructor      @AllArgsConstructor      @EqualsAndHashCode(callSuper = true)      @Table(name ="Client")      @Entity      public class Client extends AdstractEntity{                @Column(name = "nom")          private String nom;                @Column(name = "prenom")          private String prenom;                @Column(name = "photo")          private String photo;                @Embedded          private Adresse adresse;                @Column(name = "mail")          private String mail;                @Column(name = "tel")          private String tel;                @Column(name = "identreprise")          private int idEntreprise;                @OneToMany(mappedBy = "client")          private List<CommandeClient> commandeClients;      }  

Adress entity

    package com.tradeManagementApp.tradeManagement.model;            import lombok.*;            import javax.persistence.Column;      import javax.persistence.Embeddable;      import java.io.Serializable;            @Data      @NoArgsConstructor      @AllArgsConstructor      @Embeddable      public class Adresse implements Serializable {                      @Column(name = "adresee1")          private  String adresse1;                @Column(name = "adresee2")          private  String adresse2;                @Column(name = "ville")          private  String ville;                @Column(name = "pays")          private  String pays;                @Column(name = "codepostal")          private  String codepostal;      }  

Client DTO

          @Builder      @Data      public class ClientDto {                private Integer id;          private String nom;          private String prenom;          private String photo;          private AdresseDto adresse;          private String mail;          private Integer idEntreprise;          private String tel;          @JsonIgnore          private List<CommandeClientDto> commandeClients;                public static ClientDto fromEntity (Client client){              if (client == null){            //            todo throw an exception                  return null;              }                    return ClientDto.builder()                      .id(client.getId())                      .nom(client.getNom())                      .prenom(client.getPrenom())                      .photo(client.getPhoto())                      .adresse(AdresseDto.fromEntity(client.getAdresse()))                      .mail(client.getMail())                      .idEntreprise(client.getIdEntreprise())                      .tel(client.getTel())                      .build();          }                public static Client toEntity(ClientDto clientDto){              if (clientDto == null){            //            todo throw an exception                  return null;              }                    Client client = new Client();                    client.setId(clientDto.getId());              client.setNom(clientDto.getNom());              client.setPrenom(clientDto.getPrenom());              client.setPhoto(clientDto.getPhoto());              client.setMail(clientDto.getMail());              client.setTel(clientDto.getTel());              client.setIdEntreprise(clientDto.getIdEntreprise());              client.setAdresse(AdresseDto.toEntity(clientDto.getAdresse()));                    return client;          }            }  

Adress DTO

          @AllArgsConstructor      @NoArgsConstructor      @Builder      @Data      public class AdresseDto {                private  String adresse1;          private  String adresse2;          private  String ville;          private  String pays;          private  String codePostal;                public static AdresseDto fromEntity(Adresse adresse){              if (adresse == null){            //            todo throw an exception                  return null;              }              return AdresseDto.builder()                      .adresse1(adresse.getAdresse1())                      .adresse2(adresse.getAdresse2())                      .ville(adresse.getVille())                      .pays(adresse.getPays())                      .codePostal(adresse.getCodepostal())                      .build();          }                public static Adresse toEntity (AdresseDto adresseDto){              if (adresseDto == null){            //            todo throw an exception                  return null;              }                          Adresse adresse = new Adresse();                    adresse.setAdresse1(adresseDto.getAdresse1());              adresse.setAdresse2(adresseDto.getAdresse2());              adresse.setVille(adresseDto.getVille());              adresse.setPays(adresseDto.getPays());              adresse.setCodepostal(adresseDto.getCodePostal());                    return adresse;          }      }  

client validator

    public class ClientValidator {                public static List<String> validate (ClientDto clientDto){              List<String> errors = new ArrayList<>();                    if (clientDto == null){                  errors.add("veuillez renseignez le nom du client");                  errors.add("veuillez renseignez le prenom du client");                  errors.add("veuillez renseignez l'email du client");                  return errors;              }              if ( !StringUtils.hasLength(clientDto.getNom())){                  errors.add("veuillez renseignez le nom du client");              }              if ( !StringUtils.hasLength(clientDto.getPrenom())){                  errors.add("veuillez renseignez le prenom du client");              }              if ( !StringUtils.hasLength(clientDto.getMail())){                  errors.add("veuillez renseignez l'email du client");              }              if ( !StringUtils.hasLength(clientDto.getTel())){                  errors.add("veuillez renseignez le numero de telephone du client");              }                    return errors;          }      }    

Save client method in Service

    @Override          public ClientDto save(ClientDto clientDto) {              List<String> errors = ClientValidator.validate(clientDto);                    if (!errors.isEmpty()){                  log.error("Client is not Valid {}",clientDto);                  throw new InvalidEntityException("le client est invalide", ErrorCode.CLIENT_NOT_VALID, errors);              }              return ClientDto.fromEntity(                      clientRepositry.save(ClientDto.toEntity(clientDto))              );          }   

Client controller

             @PostMapping(value = CLIENT_ENDPOIND+"/", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)          @Operation(summary = "enregistrer un client", description = "cette methode permet de enregistrer un client"          )          @ApiResponses(value = {                  @ApiResponse(responseCode = "200", description = "client enregistrer avec succée"),                  @ApiResponse(responseCode = "400", description = "les informations du clients ne sont pas valides")          })          ClientDto save(@RequestBody ClientDto clientDto);  

When i do a post request using swagger UI

curl -X 'POST' \    'http://localhost:8080/tradeManagement/v1/clients/' \    -H 'accept: application/json' \    -H 'Content-Type: application/json' \    -d '{        "nom": "string",    "prenom": "string",    "photo": "string",    "adresse": {      "adresse1": "string",      "adresse2": "string",      "ville": "string",      "pays": "string",      "codePostal": "string"    },    "mail": "string",    "idEntreprise": 0,    "tel": "string"  }'  

I have an error stating that the values of all attributes of customer Dto are null.

ERROR 13948 --- [nio-8080-exec-6] c.t.t.s.i.ClientServiceImplementation    : Client is not Valid ClientDto(id=null, nom=null, prenom=null, photo=null, adresse=null, mail=null, idEntreprise=null, tel=null, commandeClients=null)  

response body

{    "httpCode": 400,    "errorCode": "CLIENT_NOT_VALID",    "message": "le client est invalide",    "errors": [      "veuillez renseignez le nom du client",      "veuillez renseignez le prenom du client",      "veuillez renseignez l'email du client",      "veuillez renseignez le numero de telephone du client"    ]  }  

Why does error No module named app keep coming up?

Posted: 30 May 2022 03:29 PM PDT

Not sure why I keep getting this error.

The app.py seems to be in the right folder and there's no virtual env folder.

Error (python.exe: No module named app)

enter image description here

It is a Flask app. This is literally all of the code (It's a school project but I don't think the error is part of it):

from flask     import Flask, render_template  import json    """  A example for creating a Table that is sortable by its header  """  app = Flask(__name__)  data = [{    "name": "bootstrap-table",    "commits": "10",    "uneven": "An extended Bootstrap table"  },   {    "name": "multiple-select",    "commits": "288",    "uneven": "A jQuery plugin"  }, {    "name": "Testing",    "commits": "340",    "uneven": "For test"  }]  # other column settings -> http://bootstrap-table.wenzhixin.net.cn/documentation/#column-options  columns = [    {      "field": "name", # which is the field's name of data key       "title": "name", # display as the table header's name      "sortable": True,    },    {      "field": "commits",      "title": "commits",      "sortable": True,    },    {      "field": "uneven",      "title": "uneven",      "sortable": True,    }  ]    #jdata=json.dumps(data)    @app.route('/')  def index():      return render_template("table.html",        data=data,        columns=columns,        title='Flask Bootstrap Table')      if __name__ == '__main__':      #print jdata    app.run(debug=True)  

enter image description here

R: What is the difference of the Lasso for variable selection between the packages glmnet and hdm

Posted: 30 May 2022 03:28 PM PDT

For my PhD I use a Lasso approach in R for variable selection. Now, I used the package glmnet and also hdm. What is the difference of the basic lasso estimator in these two packages? I read the docs and also googled a lot but the only hint that I found was this one which was not very helpful for my exact purpose.

The reason for asking is because my models converge if I use glmnet and they sometimes do not converge when I use hdm. That is why I assume that the difference is in the optimization function. Here is a minimal example:

# Delete environment  rm(list = ls())    # Packages  library(glmnet)  #> Loading required package: Matrix  #> Loaded glmnet 4.1-4  library(hdm)    # get data  data = read.table("https://pastebin.com/raw/gmXk0h2P", sep = ",", header = T)    # do the lasso  lasso_hdm = rlassologit(dep ~ ., data = data)  #> Warning: from glmnet C++ code (error code -1); Convergence for 1th lambda value  #> not reached after maxit=100000 iterations; solutions for larger lambdas returned  #> Warning in getcoef(fit, nvars, nx, vnames): an empty model has been returned;  #> probably a convergence issue  lasso_glm = glmnet(as.matrix(data[,!(names(data) %in% c("dep"))]), data$dep, family = "binomial")  

Created on 2022-05-31 by the reprex package (v2.0.1)

Additionally, please find my sessionInfo:

sessionInfo()  #> R version 4.2.0 (2022-04-22)  #> Platform: x86_64-pc-linux-gnu (64-bit)  #> Running under: Ubuntu 22.04 LTS  #>   #> Matrix products: default  #> BLAS:   /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.10.0  #> LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.10.0  #>   #> locale:  #>  [1] LC_CTYPE=en_GB.UTF-8       LC_NUMERIC=C                #>  [3] LC_TIME=de_DE.UTF-8        LC_COLLATE=en_GB.UTF-8      #>  [5] LC_MONETARY=de_DE.UTF-8    LC_MESSAGES=en_GB.UTF-8     #>  [7] LC_PAPER=de_DE.UTF-8       LC_NAME=C                   #>  [9] LC_ADDRESS=C               LC_TELEPHONE=C              #> [11] LC_MEASUREMENT=de_DE.UTF-8 LC_IDENTIFICATION=C         #>   #> attached base packages:  #> [1] stats     graphics  grDevices utils     datasets  methods   base       #>   #> loaded via a namespace (and not attached):  #>  [1] rstudioapi_0.13   knitr_1.39        magrittr_2.0.3    R.cache_0.15.0     #>  [5] rlang_1.0.2       fastmap_1.1.0     fansi_1.0.3       stringr_1.4.0      #>  [9] styler_1.7.0      highr_0.9         tools_4.2.0       xfun_0.31          #> [13] R.oo_1.24.0       utf8_1.2.2        cli_3.3.0         withr_2.5.0        #> [17] htmltools_0.5.2   ellipsis_0.3.2    yaml_2.3.5        digest_0.6.29      #> [21] tibble_3.1.7      lifecycle_1.0.1   crayon_1.5.1      purrr_0.3.4        #> [25] R.utils_2.11.0    vctrs_0.4.1       fs_1.5.2          glue_1.6.2         #> [29] evaluate_0.15     rmarkdown_2.14    reprex_2.0.1      stringi_1.7.6      #> [33] compiler_4.2.0    pillar_1.7.0      R.methodsS3_1.8.1 pkgconfig_2.0.3  

Created on 2022-05-31 by the reprex package (v2.0.1)

In the end I am interested in the theory of both packages and maybe I find a good reason to stick to the glmnet package as this converges.

Thank you so much in advance!

How do I modify a binary file in a shell script?

Posted: 30 May 2022 03:28 PM PDT

Is there a command to modify a binary file in the shell?

First, I created a file with all 0xFF values:

dd if=/dev/zero ibs=1K count=1 | tr "\000" "\377" > ./Test.img  hexdump Test.img  

Output:

0000000 ffff ffff ffff ffff ffff ffff ffff ffff  *  0000400  

Then I wanted to change some byte value like

0000000 aaaa ffff bbbb ffff cccc ffff ffff ffff  *  0000400  

How can I change that? Or is there a command in shell script?

How to install an npm package from GitHub directly

Posted: 30 May 2022 03:31 PM PDT

Trying to install modules from GitHub results in this error:

ENOENT error on package.json.

Easily reproduced using express:

npm install https://github.com/visionmedia/express throws error.

npm install express works.

Why can't I install from GitHub?

Here is the console output:

npm http GET https://github.com/visionmedia/express.git  npm http 200 https://github.com/visionmedia/express.git  npm ERR! not a package /home/guym/tmp/npm-32312/1373176518024-0.6586997057311237/tmp.tgz  npm ERR! Error: ENOENT, open '/home/guym/tmp/npm-32312/1373176518024-0.6586997057311237/package/package.json'  npm ERR! If you need help, you may report this log at:  npm ERR!     <http://github.com/isaacs/npm/issues>  npm ERR! or email it to:  npm ERR!     <npm-@googlegroups.com>    npm ERR! System Linux 3.8.0-23-generic  npm ERR! command "/usr/bin/node" "/usr/bin/npm" "install" "https://github.com/visionmedia/express.git"  npm ERR! cwd /home/guym/dev_env/projects_GIT/proj/somename  npm ERR! node -v v0.10.10  npm ERR! npm -v 1.2.25  npm ERR! path /home/guym/tmp/npm-32312/1373176518024-0.6586997057311237/package/package.json  npm ERR! code ENOENT  npm ERR! errno 34  npm ERR!  npm ERR! Additional logging details can be found in:  npm ERR!     /home/guym/dev_env/projects_GIT/proj/somename/npm-debug.log  npm ERR! not ok code 0  

No comments:

Post a Comment