Friday, May 28, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Laravel: Request data is supposed to be integers but show up as string

Posted: 28 May 2021 07:27 AM PDT

This are the parameters I pass as POST request from postman This are the parameters I pass as POST request from postman

When $request is returned from the method. All integer gets converted to string.

public function update(Request $request){      return $request;  }  

Received response is as follows: response image

Dynamic SQL in SAP HANA Stored Procedures - Using mapping table

Posted: 28 May 2021 07:27 AM PDT

In SAP ECC we have created a mapping table containing user and organisation authorization acces. U1 : OrgA U2 : OrgB U3 : *

We have createD a SAP HANA Calculation View in SQL Analytics Privileges. And we have an authorization dynamic authorization process in place, which will filter the access to the organisation dynamically based on the reading of the mapping table.

The solution works. Expect for the management of the * value corresponding to the access to all organisation. Would you know how to adjust the source code below to manage the access to all organisation ?

PROCEDURE "_SYS_BIC"."REPORTS::CONTROLE_AUTORISATIONS_ORGANISATION" ( out OUT_FILTER VARCHAR(500) ) LANGUAGE SQLSCRIPT SQL SECURITY definer DEFAULT SCHEMA ABAP READS SQL DATA AS BEGIN

LISTES_VALEURS = SELECT USER_NAME,'organisation in (' ||'''' || STRING_AGG(RESTRICTION, ''',''' ) || '''' || ')' as RESTRICTION from table_authorization where USER_NAME = SESSION_USER group by USER_NAME;

SELECT distinct RESTRICTION into OUT_FILTER from :LISTES_VALEURS;

END;

How can we return data's from firebase queries with async await

Posted: 28 May 2021 07:27 AM PDT

Hi I have an array of document id's of a users collection. I want to retrieve a user data array with all user's data' some parameters in an object for every document of the users collection for given id's from the array of documents id's.

But with my current code the returned value is returned before the promise is solved, thus it is an empty array.

Can somebody explain me more on how to implement this asynchronous call, and what is the problem with this.

This is my code

export const getChatInfo = async chatIdsArray => {    const userData = new Array();    await chatIdsArray.forEach(async chatId => {      const documentSnapshot = await firestore()        .collection('users')        .doc(chatId)        .get();        if (documentSnapshot.exists) {        const {fname, lname, userImg} = documentSnapshot.data();        userData.push({          fname: fname,          lname: lname,          userImg: userImg,        });      }      console.log(`userdata in getchatinfo inner : ${JSON.stringify(userData)}`); // this returns correct array    });    console.log(`userdata in getchatinfo outer : ${JSON.stringify(userData)}`); // this return an empty array    return {userData};  };  

Discord.js bot was working, added one extra command and everything broke. Can anyone help me figure out why?

Posted: 28 May 2021 07:27 AM PDT

Tried to venture in to the realm of making discord bots. Followed along with a fairly simple tutorial, tweaking it along the way to fit what I was trying to make. The bot originally worked, but I went back in to add the "Mistake" command, and suddenly it's not working. I added in console.log pretty much everywhere, trying to figure out how far everything was getting.

When I start the bot, it will spit out the "Bot Online" log. When I input a command, it will spit out the "Commands" log, but it won't register the command at all. I've tried looking for any minor typos, missing brackets, etc... but I just can't seem to figure out what's gone wrong. I'm hoping that someone here can help! Thank you!

const Discord = require('discord.js');  const config = require('./config.json');    const client = new Discord.Client();    const SQLite = require('better-sqlite3');  const sql = new SQLite('./scores.sqlite');    client.on('ready', () => {    console.log('Bot Online');    const table = sql.prepare("SELECT count(*) FROM sqlite_master WHERE type='table' AND name = 'goals';").get();    if (!table['count(*)']) {      sql.prepare('CREATE TABLE goals (id TEXT PRIMARY KEY, user TEXT, guild TEXT, goals INTEGER);').run();      sql.prepare('CREATE UNIQUE INDEX idx_goals_id ON goals (id);').run();      sql.pragma('synchronous = 1');      sql.pragma('journal_mode = wal');    }      //Statements to get and set the goal data    client.getGoals = sql.prepare('SELECT * FROM goals WHERE user = ? AND guild = ?');    client.setGoals = sql.prepare('INSERT OR REPLACE INTO goals (id, user, guild, goals) VALUES (@id, @user, @guild, @goals);');  });    client.on('message', (message) => {    if (message.author.bot) return;    let goalTotal;    if (message.guild) {      goalTotal = client.getGoals.get(message.author.id, message.guild.id);      if (!goalTotal) {        goalTotal = {          id: `${message.guild.id}-${message.author.id}`,          user: message.author.id,          guild: message.guild.id,          goals: 0,        };      }    }      if (message.content.indexOf(config.prefix) !== 0) return;      const args = message.content.slice(config.prefix.length).trim().split(/ +/g);    const command = args.shift().toLowerCase();    console.log('Commands');      if (command === 'Goals') {      console.log('Goals');      return message.reply(`You Currently Have ${goalTotal.goals} Own Goals.`);    }      if (command === 'OwnGoal') {      console.log('Own Goal');      const user = message.mentions.users.first() || client.users.cache.get(args[0]);      if (!user) return message.reply('You must mention someone.');      let userscore = client.getGoals.get(user.id, message.guild.id);        if (!userscore) {        userscore = {          id: `${message.guild.id}-${user.id}`,          user: user.id,          guild: message.guild.id,          goals: 0,        };      }      userscore.goals++;      console.log({ userscore });      client.setGoals.run(userscore);        return message.channel.send(`${user.tag} has betrayed his team and now has a total of ${userscore.goals} own goals.`);    }      if (command === 'Mistake') {      console.log('Mistake');      const user = message.mentions.users.first() || client.users.cache.get(args[0]);      if (!user) return message.reply('You must mention someone.');      let userscore = client.getGoals.get(user.id, message.guild.id);        if (!userscore) {        return message.reply('This person has no Rocket Bot activity.');      }      if (userscore === 0) {        return message.reply('This player currently has no goals.');      }      if (userscore > 0) {        userscore.goals--;      }      console.log({ userscore });      client.setGoals.run(userscore);        return message.channel.send(`${user.tag} was falsely accused and now has a total of ${userscore.goals} own goals.`);    }      if (command === 'Leaderboard') {      console.log('Leaderboard');      const leaderboard = sql.prepare('SELECT * FROM goals WHERE guild = ? ORDER BY goals DESC;').all(message.guild.id);      const embed = new Discord.MessageEmbed()        .setTitle('Rocket Bot Leaderboard')        .setAuthor(client.user.username, client.user.avatarURL())        .setDescription('Total Goals Scored Against Own Team:')        .setFooter('Rocket Bot Was Coded By Ryan Kirk.', 'kirkforaday.com')        .setThumbnail('https://imgur.com/a/S9HN4bT')        .setColor('0099ff');        for (const data of leaderboard) {        embed.addFields({          name: client.users.cache.get(data.user).tag,          value: `${data.goals} goals`,          inline: true,        });      }      return message.channel.send({ embed });    }      if (command === 'RocketHelp') {      console.log('Help');      return message.reply(        'Rocket Bot Commands:' +          '\n' +          '!Goals - See How Many Goals You Have Scored Against Your Own Team' +          '\n' +          '!OwnGoal - Tag Another Player With @ To Add One To Their Total' +          '\n' +          '!Mistake - Tag Another Player With @ To Subtract One From Their Total' +          '\n' +          '!Leaderboard - Show The Current Leaderboard'      );    }  });    client.login(config.token);  

How to input a uservariable into a mysql query using express?

Posted: 28 May 2021 07:27 AM PDT

I want to execute a mysql query depending on an input from user. Then the result is returned to a html page. How I pass the from_destination variable in the WHERE clause?
airTicketsController.js

const mysql = require('mysql');    // DB connection  const connection = mysql.createConnection({      host: 'localhost',      user: 'myuser',      password: 'mypassword',      database: 'mydatabase'  });    connection.connect(function(error) {      if (!!error) console.log(error);      else console.log('CONGRATS! Database Connected!');  });    //---------------  exports.selectFlight = (req, res) => {      const from_destination = req.params.from_destination;      const to_destination = req.params.to_destination;        let sql = "SELECT * FROM flight WHERE from_destination = '" + from_destination + "'";      let query = connection.query(sql, (err, rows) => {          if (err) throw err;          res.render('air_ticketsSelect', {              title: 'Filters',              data: rows,          });      });      console.log(sql);  }  


index.js

var express = require('express');  var router = express.Router();    // Air tickets controller  const airTicketsController = require('../controllers/airTicketsController');    /* GET home page. */  router.get('/', function(req, res, next) {      res.render('home', { title: 'Express' });  });    // Air tickets page  router.get('/air_tickets', function(req, res, next) {      res.render('air_tickets', { title: 'Air tickets' });  });    router.get('/searchFlight', airTicketsController.selectFlight);  

google sheet replace regex formula

Posted: 28 May 2021 07:27 AM PDT

I want to remove any string that matches: _digitsxdigits like _8x7 and _999x1

=ArrayFormula(if((Input!A10:A=TRUE), SUBSTITUTE(Input!E10:E, REGEXEXTRACT(Input!E10:E,"[0-9]x[0-9]"),""), ""))  

I get this error, but I'm not sure how to fix it.

enter image description here

Adjoint Table Many-To-Many relationship using JPA, Can't get one of parents id

Posted: 28 May 2021 07:27 AM PDT

I'm trying to create a relationship between Items, Markets and every item may have different price on each market. So I decided to create a many-to-many relationship with additional column. So:

  1. There are more than one markets
  2. There are more than one items
  3. Each item may have different price on each market or might be null

And I'm saving the items and markets using MarketRepository() which works fine except one thing. When I add MarketItem to List of MarketItems in market object and save with repository, on database I it assigns id for item but not for market

Here are the adjustment I did:

On Market.java

@OneToMany(mappedBy = "market", cascade = CascadeType.ALL)      private List<MarketItem> items = new ArrayList<>();  

On MarketItem.java

@Entity  @Table(name = "market_item")  @Getter  @Setter  @RequiredArgsConstructor  public class MarketItem {      @Id      @GeneratedValue(strategy = GenerationType.AUTO)      private Long id;        @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)      @JoinColumn(name = "item_id")      private Item item;        @ManyToOne(fetch = FetchType.EAGER)      @JoinColumn(name = "market_id")      private Market market;        @Column(name = "price")      private Integer price;  }  

On Item.java

@Entity  @Table(name = "item")  @Getter  @Setter  @NoArgsConstructor  public class Item {      @Id      @GeneratedValue(strategy = GenerationType.AUTO)      private Long id;        @OneToMany(mappedBy = "item")      private List<MarketItem> marketItems = new ArrayList<>();        @Column(name = "fullName")      private String fullName;  }  

NUnit testing a conntroller method that returns a list

Posted: 28 May 2021 07:27 AM PDT

I am writing a test for a controller method.This method accesses the getPharmacySupply method in SupplyRepository which return a list of PharmacyMedicineSupply according to the project requirement:

[HttpPost("PharmacySupply")]          public Task<List<PharmacyMedicineSupply>> GetPharmacySupply([FromBody] List<MedicineDemand> medDemand)          {              _log4net.Info("Get Pharmacy Supply API Acessed");              return _supplyRepo.GetPharmacySupply(medDemand);  

These are my models:

 public class MedicineStock      {                   public string Name { get; set; }         public string ChemicalComposition  { get; set; }          public string TargetAilment { get; set; }          public DateTime DateOfExpiry { get; set; }          public int NumberOfTabletsInStock { get; set; }        }  

and

public class PharmacyMedicineSupply      {                    public string pharmacyName { get; set; }          public List<MedicineNameAndSupply> medicineAndSupply { get; set; }      }  

and

public class MedicineNameAndSupply      {          public string medicineName { get; set; }          public int supplyCount { get; set; }      }  

This is the test I am writing:

 public static List<MedicineDemand> mockMedicineDemand= new List<MedicineDemand>()          {                  new MedicineDemand()                  {                      Medicine = "Medcine1",                      DemandCount = 20                  },                  new MedicineDemand()                  {                      Medicine = "Medcine2",                      DemandCount = 25                  },                  new MedicineDemand()                  {                      Medicine = "Medcine3",                      DemandCount = 30                  },                  new MedicineDemand()                  {                      Medicine = "Medcine4",                      DemandCount = 35                  },                  new MedicineDemand()                  {                      Medicine = "Medcine5",                      DemandCount = 40                  }        [Test, TestCaseSource(nameof(mockMedicineDemand))]          public void Test_GetPharmacySupply(List<MedicineDemand> mockMedicineDemand)          {              Mock<ISupplyRepo> supplyMock = new Mock<ISupplyRepo>();              //supplyMock.Setup(x => x.GetPharmacySupply(mockMedicineDemand)).Returns(pharMedSup);              SupplyController sc = new SupplyController(supplyMock.Object);              var result = sc.GetPharmacySupply(mockMedicineDemand) as Task<List<PharmacyMedicineSupply>>;              var resultList = result.Result;              Assert.That(4,Is.EqualTo( resultList[0].medicineAndSupply[0].supplyCount));  

But I am getting this error Object of type 'MedicineSupplyMicroservice.Models.MedicineDemand' cannot be converted to type 'System.Collections.Generic.List`1[MedicineSupplyMicroservice.Models.MedicineDemand]'. What am I doing wrong??

How can I do server side rendering in reactjs

Posted: 28 May 2021 07:27 AM PDT

To make a website SEO friendly we have to implement Server side rendering of the application in React. I want to know what is best way to do SSR using Next.js or Express in React

How to apply a pretrained transformer model from huggingface?

Posted: 28 May 2021 07:27 AM PDT

I am interested in using pre-trained models from Huggingface for named entity recognition (NER) tasks without further training or testing of the model.

On the model page of HuggingFace, the only information for reusing the model are as follow:

from transformers import AutoTokenizer, AutoModel  tokenizer = AutoTokenizer.from_pretrained("emilyalsentzer/Bio_ClinicalBERT")  model = AutoModel.from_pretrained("emilyalsentzer/Bio_ClinicalBERT")  

Any suggestions on how to apply the model on a text for NER?

Make function in R converting daily data to monthly (xts)

Posted: 28 May 2021 07:26 AM PDT

i want to make a function to convert my daily river flow data to monthly or yearly and the return to be an xts object. i have already made my daily data to xts. Can anyone help me because i just started the r language...

Linux won't autoload kernel module

Posted: 28 May 2021 07:26 AM PDT

I created a basic kernel module that I plan to use eventually for a timing analysis. I am running a 4.14.149 mainline kernel and am building it with Yocto Zeus running on an i.MX6 target. I can't seem to get it to launch automatically.

Everything compiles fine, and I see my testmodule.ko show up in /lib/modules/4.14.149/extras/ on target. I can load it and unload it just fine with insmod and rmmod so I am pretty sure the module is ok. I also see a testmodule.conf file that contains the module name (testmodule) in /etc/modules-load.d/ but when I boot and do a lsmod I don't see it loaded. I also don't see any output in journalctl that would indicate that it loaded.

I have looked at and tried Yocto: Adding kernel module recipe to image, but it doesn't load on boot and Yocto load kernel module and have added KERNEL_MODULE_AUTOLOAD += "testmodule" in my machine configuration and I also tried it in the module recipe to no avail. I am including the module in my image recipe via IMAGE_INSTALL_append as kernel-module-test

Here is the recipe for my module:

SUMMARY = "Test kernel module"  LICENSE = "CLOSED"    inherit module    SRC_URI = "file://Makefile \              file://testmodule.c"    S = "${WORKDIR}"    KERNEL_MODULE_AUTOLOAD += "testmodule"    RPROVIDES_${PN} += "kernel-module-test"  

The module code at the moment just prints a message (it was a sample from a Yocto book I had) and that is it:

#include<linux/kernel.h>  #include<linux/init.h>  #include<linux/module.h>     /*  ** Module Init function  */  static int hello_world_init(void)  {      printk("Markem Kernel Module Inserted Successfully...\n");      return 0;  }  /*  ** Module Exit function  */  static void hello_world_exit(void)  {      printk("Markem Kernel Module Removed Successfully...\n");  }    module_init(hello_world_init);  module_exit(hello_world_exit);    MODULE_LICENSE("Proprietary");    /*  MODULE_VERSION("0.1");  MODULE_DESCRIPTION("A test module.");  MODULE_AUTHOR("Markem-Imaje Corporation");    */  

And lastly the Makefile, which is also based on the Yocto Book sample

obj-m := testmodule.o    SRC := $(shell pwd)    all:      $(MAKE) -C $(KERNEL_SRC) M=$(SRC)    modules_install:      $(MAKE) -C $(KERNEL_SRC) M=$(SRC) modules_install    clean:      rm -f *.o *~ core .depend .*.cmd *.ko *.mod.c      rm -f Module.markers Module.symvers modules.order      rm -rf .tmp_versions Modules.symvers  

If you need the recipe for my kernel or my machine conf or anything, I can get those. Everything I have read indicates that having the file in /etc/modules-load.d/ indicates it should load automatically. Is there possibly a kernel configuration I am missing or something?

Not able to remove option in cloned select

Posted: 28 May 2021 07:27 AM PDT

I have an issue with removing a cloned option that I created. I can remove the original option, but nothing is removed from the clone.

var oriFruit = $('option', '#fruit').clone();  $("#fruit").find("[value='fruit1']").remove(); // works    console.log(oriFruit.length); // = 4  oriFruit.find("option[value='fruit1']").remove(); // does not work  console.log(oriFruit.length); // = 4, I expect 3
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>  <select id="fruit" multiple="multiple" class="form-control">    <option value="fruit1">fruit1</option>    <option value="fruit2">fruit2</option>    <option value="fruit3">fruit3</option>    <option value="fruit4">fruit4</option>  </select>

What is wrong with this code? I tried several methods but still failed. Thanks for helping me.

Get trending words as a stream with Tweepy

Posted: 28 May 2021 07:27 AM PDT

What I know:

I have been using Tweepy for a long period and I know how you can create a stream to get new Tweets with a given keyword.

I also know that you can get trending keywords in a specific region from the documentation.

What I am trying to achieve:

I was wondering how I can use the trending APIs to get trending topic but in a form of a stream, so if a topic starts trending in a place, I will like a similar event to the on_data event on the stream listener to get fired and return the new trending topic.

Does anyone know how I can achieve this?

Or any hint on how I can achieve this?

How to write an array of objects through composition in another object and how to create them in main class?

Posted: 28 May 2021 07:27 AM PDT

For example, there is this program where I could write in the Book object (constructor) many Authors. The errors appear only in main, but there may be some code in other classes, which should be written differently.

```  package ex1;    public class Author {  private String name, email;  private char gender;    public Author(String name, String email, char gender) {      this.name = name;      this.email = email;      this.gender = gender;  }    public String toString() {      return "Author [name=" + name + ", email=" + email + ", gender=" + gender + "]";  }    public String getName() {      return name;  }    public void setEmail(String email) {      this.email = email;  }    public char getGender() {      return gender;  }  }  ```  

In the photo, you can see the program requirements.

```  package ex1;    import java.util.Arrays;    public class Book {  private String name;  private Author[] authors;  private Page page;  private double price;  private int qty = 1;    public Book(String name, Author[] authors, double price) {      this.name = name;      this.authors = authors;      this.price = price;  }    public Book(String name, Author[] authors, Page page, double price, int qty) {      this.name = name;      this.authors = authors;      this.price = price;      this.qty = qty;      this.page = page;  }    @Override  public String toString() {      return "Book [name=" + name + ", authors=" + Arrays.toString(authors) + ", page=" + page + ",               price=" + price + ", qty=" + qty + "]";  }    public String getName() {      return name;  }    public Author[] getAuthors() {      return authors;  }    public double getPrice() {      return price;  }    public void setPrice(double price) {      this.price = price;  }    //....  }  ```  

The class page is working at least.

```  package ex1;    public class Page {  private int pageNumber, numberOfWords;  private String footnote;    public Page(int pageNumber, int numberOfWords, String footnote) {      this.pageNumber = pageNumber;      this.numberOfWords = numberOfWords;      this.footnote = footnote;  }    @Override  public String toString() {      return "Page [pageNumber=" + pageNumber + ", numberOfWords=" + numberOfWords + ", footnote=" +               footnote + "]";  }    public int getPNr() {      return pageNumber;  }    public int getWords() {      return numberOfWords;  }    public String getFoot() {      return footnote;  }  }  ```  

So here I would like to see that I could create a Book like this or in a similar manner: Book b2 = new Book("Ac2", authors[authorAna, Kratos], 35);

```  package ex1;    import java.util.Arrays;    public class Main {  public static void main(String[] args) {      Author authors[] = new Author[2]; // this is a method but it doesn't work as intended            Author authorAna = new Author("Ana", "A@em.com", 'f');      Author Kratos = new Author("Kratos", "K@em.com", 'm');      authors[0] = authorAna;      authors[1] = Kratos;            Page p6 = new Page(6, 400, "He jumped into the haystack to hide from enemies");            Book b1 = new Book("Ac1", authors, 25);      //Book b2 = new Book("Ac2", authorAna, 35);      //Book b3 = new Book("God of War1", Kratos, 20);      //Book b4 = new Book("GoW2", , p6, 20, 40);            System.out.println(Kratos + "\n" + b1.toString());      //System.out.println(b2);      //System.out.println(b3);      //System.out.println(b4);  }  }  ```  

How to configure ESLint for TypeScript with IntelliJ Ultimate?

Posted: 28 May 2021 07:27 AM PDT

I am trying to configure ESLint for TypeScript with IntelliJ Ultimate 2020.2.

I don't see any options under "Settings -> Language & Frameworks -> TypeScript"

enter image description here

I am seeing the option only for TSLint which is deprecated. How ESLint can be configured for the (Angular) project?

How to get text value of elements in Selenium Python?

Posted: 28 May 2021 07:28 AM PDT

It's the first time I ever use Selenium. I'm trying to get the text value of these two elements: element1

element 2

Here's my code:

keto = browser.find_elements_by_tag_name("h3")[0].text  print(keto)  sheto =browser.find_element_by_xpath("//table[@class='preftable']/tbody/tr/td[@class='prefright'[0].text  print(sheto)  

I was getting the first element just fine, through the h3 tag. Now, both elements are not appearing. I can't locate through anything that uses ID as it changes quite a lot.

Any help?

How refactor a function vanilla js

Posted: 28 May 2021 07:27 AM PDT

I am trying to refactor a function but can't figure out what could be the best approach for it

let smallNumber = 50;  let mediumNumber = 40;  let groupNumber = 35;    function price() {    if (numberSelected <= 3) {      document.getElementById("total").innerHTML = "£"+(smallNumber * numberSelected).toFixed(2);    } else if (numberSelected <= 6) {      document.getElementById("total").innerHTML = "£"+(mediumNumber * numberSelected).toFixed(2);    } else if (numberSelected > 6) {      document.getElementById("total").innerHTML = "£"+(groupNumber * numberSelected).toFixed(2);    }    total.style.display = "block";    button.style.display = "block";  }  

Thanks

Listen to any field changes under nested FormGroup using valueChanges

Posted: 28 May 2021 07:27 AM PDT

I am trying to listen if any field changes or not using valueChanges by angular. Below is my code

      this.advSearchForm = this.formBuilder.group({          noCountry: this.formBuilder.group({            licenseOwnerName: [null, [Validators.maxLength(256)]],            locationAddressLine1: [null, [Validators.maxLength(256)]],            DBAName: [null, [Validators.maxLength(255)]],            locationCity: [null, [Validators.maxLength(60)]],            licenseNumber: [null, [Validators.maxLength(256)]],                    issuingAuthorityName: [null, [Validators.maxLength(256)]],          }),                  locationState: [null],          locationCountry: [null]        });          const lNumber = <FormControl>this.advSearchForm.get('noCountry.licenseNumber');        const lCountry = <FormControl>this.advSearchForm.get('locationCountry');        const lState = <FormControl>this.advSearchForm.get('locationState');        const lAddress = <FormControl>this.advSearchForm.get('noCountry.locationAddressLine1');        const lOwner = <FormControl>this.advSearchForm.get('noCountry.licenseOwnerName');        const lCity = <FormControl>this.advSearchForm.get('noCountry.locationCity');        const dName = <FormControl>this.advSearchForm.get('noCountry.DBAName');        const iAuthority = <FormControl>this.advSearchForm.get('noCountry.issuingAuthorityName');                this.subscription = this.advSearchForm.get('noCountry').valueChanges.subscribe(selectedValue  => {          if (lCountry.value == 287307 && lAddress.value == null  && lOwner.value == null  && lCity.value == null  && dName.value == null  && iAuthority.value == null  && lNumber.value == null ) {              lState.setValidators([Validators.required ]);            console.log(selectedValue);          }          else {            lState.setValidators(null);          }            lState.updateValueAndValidity();          });  

And I am trying to listen to it with

       this.advSearchForm.get('noCountry').valueChanges.subscribe(selectedValue  => { ....  

HTML

    <form (ngSubmit)="onSubmit()" [formGroup]="advSearchForm" class="search_main_form" >               <div class="form-row">        <div class="col">          <div class="form-group">            <label for="email">License Owner: </label>            <div class="controls">              <input type="text" id="licenseOwnerName" class="form-control" formControlName="licenseOwnerName" maxlength="256">                            </div>          </div>        </div>        <div class="col">          <div class="form-group">            <label for="email">Location Address Line 1: </label>            <div class="controls">              <input type="text" id="locationAddressLine1" class="form-control" formControlName="locationAddressLine1" maxlength="256">            </div>          </div>        </div>      </div>        <div class="form-row">          <div class="col">            <div class="form-group">              <label for="dba_name">DBA Name: </label>              <div class="controls">                <input type="text" id="DBAName" class="form-control" formControlName="DBAName" maxlength="255">              </div>            </div>          </div>          <div class="col">            <div class="form-group">              <label for="location_city">Location City: </label>              <div class="controls">                <input type="text" id="locationCity" class="form-control" formControlName="locationCity" maxlength="60">              </div>            </div>          </div>      </div>        <div class="form-row">          <div class="col">              <div class="form-group">              <label for="license_number">License Number: </label>              <div class="controls">                  <input type="text" id="licenseNumber" class="form-control" formControlName="licenseNumber" maxlength="256">              </div>              </div>          </div>          <div class="col">              <div class="form-group">              <label for="location_state">Location State: </label>              <div class="controls">                  <select id="locationState" formControlName="locationState" class="form-control" (change)="onChangeState($event.target.value);getStateText($event)">                    <option value="">Please select</option>                    <option *ngFor="let state of statesList" [value]="state.id">{{state.name}}</option>                  </select>                  <span class="errorMsg">{{geoError}}</span>              </div>              </div>          </div>      </div>        <div class="form-row">          <div class="col">              <div class="form-group">              <label for="issuing_authority">Issuing Authority Name: </label>              <div class="controls">                  <input type="text" id="issuingAuthorityName" class="form-control" formControlName="issuingAuthorityName" maxlength="256">              </div>              </div>          </div>          <div class="col">              <div class="form-group">              <label for="location_country">Location Country: </label>              <div class="controls">                  <select id="locationCountry" formControlName="locationCountry" class="form-control" (change)="onChangeCountry($event.target.value);getCountryText($event)">                    <option *ngFor ="let country of countriesList" [value]="country.id">{{country.name ? country.name : country.isoName}} </option>                </select>                <span class="errorMsg">{{geoError}}</span>              </div>              </div>          </div>      </div>        <div class="form-group search_btn">        <!-- <button [disabled]="!licenseOwner && !locationCity && !locationAddress && !dbaName && !licenseNumber && !stateSelected && !issuingAuthority" class="btn btn-primary" type="submit"> -->        <button [disabled]="advSearchForm.invalid" class="btn btn-primary" type="submit">          Search        </button>      </div>      </form>  

But the above is not working. What wrong I am doing here? Please suggest. Thanks

code execution is not going inside react function

Posted: 28 May 2021 07:27 AM PDT

When i try to call auth.isauthenticated(), execution flow is not going inside componentDidMount() function. It skips all code inside of componentDidMount() and goes directly to isAuthenticated function. this is the complete flow of my code.

import { Redirect, Route } from "react-router";  import auth from "./auth";    const ProtectedRoute = ({component: Component, ...rest} ) => {      return (           <Route  {...rest} render={              (props) =>{                  if(auth.isAuthenticated()){                      return <Component {...props} />                  }                  else{                      return <Redirect to='/login' />                  }              }          } />       );  }     export default ProtectedRoute;    import axios from 'axios'  import React from 'react';  import {constants} from './script/constant';    class Auth extends React.Component{        constructor(){          super();          this.state = {               authenticated: false          };      }      componentDidMount(){          axios.get(`https://jsonplaceholder.typicode.com/users`)          .then(res => {              const userData = res.data;              if(userData === ""){                  this.setState({authenticated: false});                  console.log("falseapi");              }              else{                  this.setState({authenticated:true});                    console.log("trueapi");              }                      })        };      isAuthenticated(){          return this.state.authenticated;      }    }  export default new Auth();  

Edit Text Editor SwiftUI

Posted: 28 May 2021 07:27 AM PDT

I am trying to edit the text of a binding value from another view. But text editor does not allow me to do so.

First I need to see the previous value of selectedNote.title in TextEditor and then I should be able to edit the title.

struct EditNotePageView: View {      @Binding var selectedNote: CDNoteModel!      @State var text = ""      var body: some View {          TextEditor(selectedNote.title!, text: $text)      }  }  

I also tried like this. I can see my selectedNote.title in the simulator but when I tap on it it does nothing.

 struct EditNotePageView: View {      @Binding var selectedNote: CDNoteModel!      @State var text = ""      var body: some View {          Text(selectedNote.title!)              .onTapGesture {                  text = selectedNote.title!                  TextEditor(text: $text)              }      }  }  

enter image description here

yarn fails with "Invalid URL" when fetching packages

Posted: 28 May 2021 07:27 AM PDT

For some reason when I try to install dependencies yarn fails with a "Invalid URL":

yarn install v1.22.10  [1/4] 🔍  Resolving packages...  [2/4] 🚚  Fetching packages...  error An unexpected error occurred: "Invalid URL".  info If you think this is a bug, please open a bug report with the information provided in "/Users/tomasz.mularczyk/Desktop/frontend/yarn-error.log".  info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.  

output of yarn-error.log:

Arguments:     /usr/local/Cellar/node/16.2.0/bin/node /usr/local/Cellar/yarn/1.22.10/libexec/bin/yarn.js    PATH:     /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/tomasz.mularczyk/Library/Python/3.8/bin/:/usr/local/go/bin:/Library/Apple/usr/bin    Yarn version:     1.22.10    Node version:     16.2.0    Platform:     darwin x64    Trace:     Error: Invalid URL        at module.exports.module.exports (/usr/local/Cellar/yarn/1.22.10/libexec/lib/cli.js:71821:9)        at urlParts (/usr/local/Cellar/yarn/1.22.10/libexec/lib/cli.js:31614:75)        at NpmRegistry.isRequestToRegistry (/usr/local/Cellar/yarn/1.22.10/libexec/lib/cli.js:31658:20)        at NpmRegistry.<anonymous> (/usr/local/Cellar/yarn/1.22.10/libexec/lib/cli.js:31689:31)        at Generator.next (<anonymous>)        at step (/usr/local/Cellar/yarn/1.22.10/libexec/lib/cli.js:310:30)        at /usr/local/Cellar/yarn/1.22.10/libexec/lib/cli.js:328:14        at new Promise (<anonymous>)        at new F (/usr/local/Cellar/yarn/1.22.10/libexec/lib/cli.js:5301:28)        at NpmRegistry.<anonymous> (/usr/local/Cellar/yarn/1.22.10/libexec/lib/cli.js:307:12)    npm manifest:     ...    

It does install dependencies when I remove the lock file. However, it fails with the current lock file.

I cannot tell what "invalid URL" means in my case, which URL?

The output of yarn install --verbose:

verbose 29.506520368 Performing "GET" request to "https://registry.yarnpkg.com/just-extend/-/just-extend-4.1.1.tgz".  verbose 29.519454624 Performing "GET" request to "https://registry.yarnpkg.com/path-to-regexp/-/path-to-regexp-1.8.0.tgz".  verbose 29.534487361 Performing "GET" request to "https://registry.yarnpkg.com/remark/-/remark-12.0.1.tgz".  verbose 29.550315695 Performing "GET" request to "https://registry.yarnpkg.com/unist-util-find-all-after/-/unist-util-find-all-after-3.0.1.tgz".  verbose 29.57800699 Performing "GET" request to "https://registry.yarnpkg.com/browserslist/-/browserslist-4.14.0.tgz".  verbose 29.594486458 Error: Invalid URL      at module.exports.module.exports (/usr/local/Cellar/yarn/1.22.10/libexec/lib/cli.js:71821:9)      at urlParts (/usr/local/Cellar/yarn/1.22.10/libexec/lib/cli.js:31614:75)      at /usr/local/Cellar/yarn/1.22.10/libexec/lib/cli.js:31746:29      at Array.find (<anonymous>)      at NpmRegistry.requestNeedsAuth (/usr/local/Cellar/yarn/1.22.10/libexec/lib/cli.js:31743:59)      at NpmRegistry.<anonymous> (/usr/local/Cellar/yarn/1.22.10/libexec/lib/cli.js:31689:81)      at Generator.next (<anonymous>)      at step (/usr/local/Cellar/yarn/1.22.10/libexec/lib/cli.js:310:30)      at /usr/local/Cellar/yarn/1.22.10/libexec/lib/cli.js:328:14      at new Promise (<anonymous>)  error An unexpected error occurred: "Invalid URL".  info If you think this is a bug, please open a bug report with the information provided in "/Users/tomasz.mularczyk/Desktop/frontend-platform/yarn-error.log".  info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.  verbose 29.604016293 Performing "GET" request to "https://registry.yarnpkg.com/normalize-range/-/normalize-range-0.1.2.tgz".  verbose 29.614073262 Performing "GET" request to "https://registry.yarnpkg.com/num2fraction/-/num2fraction-1.2.2.tgz".  verbose 29.653593887 Performing "GET" request to "https://registry.yarnpkg.com/clone-regexp/-/clone-regexp-2.2.0.tgz".  verbose 29.657308561 Performing "GET" request to "https://registry.yarnpkg.com/@nodelib/fs.stat/-/fs.stat-2.0.3.tgz".  verbose 29.670359986 Performing "GET" request to "https://registry.yarnpkg.com/@nodelib/fs.walk/-/fs.walk-1.2.4.tgz".  verbose 29.7046679 Performing "GET" request to "https://registry.yarnpkg.com/merge2/-/merge2-1.4.1.tgz".  

Could not find androidx.camera:camera-view

Posted: 28 May 2021 07:26 AM PDT

I am developing a basic custom camera app These are my dependency

// CameraX core library dependency  implementation "androidx.camera:camera-camera2:$camera_version"  // CameraX Lifecycle dependency  implementation "androidx.camera:camera-lifecycle:$camera_version"  // CameraX View dependency  implementation "androidx.camera:camera-view:$camera_version"  

camera_version = '1.0.0'

Getting below error, it work fine if I remove camera-view dependency, but I cannot as I need that for my custom camera app.

Could not resolve all files for configuration ':app:debugRuntimeClasspath'. Could not find androidx.camera:camera-view. Searched in the following locations: - https://dl.google.com/dl/android/maven2/androidx/camera/camera-view/1.0.0/camera-view-1.0.0.pom - https://repo.maven.apache.org/maven2/androidx/camera/camera-view/1.0.0/camera-view-1.0.0.pom Required by: project :app

post_save does not work error EmailConfirm is not create

Posted: 28 May 2021 07:27 AM PDT

https://www.online-python.com/DQeaOAu0xU at the risk of appearing stupid I want to generate a unique key so I created this function but post_save does not work correctly error EmailConfirm is not create

Trying to find Top 10 products within categories through Regex

Posted: 28 May 2021 07:27 AM PDT

I have a ton of products, separated into different categories. I've aggregated each products revenue, within their category and I now need to locate the top 10.

The issue is, that not every product have sold within a given timeframe, or some category doesn't even have 10 products, leaving me with fewer than 10 values.

As an example, these are some of the values:

  1. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,3,3,5,6,20,46,47,53,78,92,94,111,115,139,161,163,208,278,291,412,636,638,729,755,829,2673
  2. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,57,124,158,207,288,547
  3. 0,0,90,449,1590,10492
  4. 0
  5. 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,7,12,14,32,32,37,62,64,64,64,94,100,103,109,113,114,114,129,133,148,152,154,160,167,177,188,205,207,207,209,214,214,224,225,238,238,244,247,254,268,268,285,288,298,301,305,327,333,347,348,359,362,368,373,402,410,432,452,462,462,472,482,495,511,512,532,566,597,599,600,609,620,636,639,701,704,707,728,747,768,769,773,805,833,899,937,1003,1049,1150,1160,1218,1230,1262,1327,1377,1396,1474,1532,1547,1565,1760,1768,1836,1962,1963,2137,2293,2423,2448,2451,2484,2529,2609,3138,3172,3195,3424,3700,3824,4310,4345,4415,4819,4943,5083,5123,5158,5334,5734,6673,7160,7913,9298,9349,10148,11047,11078,12929,18535,20756,28850,63447
  6. 63,126

How would you get as close as possible to capturing the top 10 within a category, and how would you ensure that it is only products that have sold, that are included as a possibility? And all of this through Regex.

My current setup is only finding top 3 and a very basic setup:

  • Step 1: ^.*\,(.*\,.*\,.*)$ finding top 3
  • Step 2: ^(.*)\,.*\,.*$ finding the lowest value of the top 3 products
  • Step 3: Checking if original revenue value is higher than, or equal to, step 2 value.
  • Step 4: If yes, then bestseller, otherwise just empty value.

Thanks in advance

fastapi throws 400 bad request when I upload a large file

Posted: 28 May 2021 07:27 AM PDT

I provisioned and configured a Fedora 34 vm on VirtualBox with 2048 MB RAM to serve this FastAPI application on localhost:7070. The full application source code and dependency code and instructions are here. Below is the smallest reproducible example I could make.

main.py

import os, pathlib    import fastapi as fast  import aiofiles              ROOT_DIR = os.path.dirname(os.path.abspath(__file__))  RESULTS_DIR = pathlib.Path('/'.join((ROOT_DIR, 'results')))          app = fast.FastAPI()          @app.post('/api')  async def upload(      request: fast.Request,       file: fast.UploadFile = fast.File(...),      filedir: str = ''):                dest = RESULTS_DIR.joinpath(filedir, file.filename)      dest.parent.mkdir(parents=True, exist_ok=True)        async with aiofiles.open(dest, 'wb') as buffer:          await file.seek(0)          contents = await file.read()          await buffer.write(contents)        return f'localhost:7070/{dest.parent.name}/{dest.name}'  

start.sh the server application

#! /bin/bash  uvicorn --host "0.0.0.0" --log-level debug --port 7070 main:app  

client.py

import httpx  from pathlib import Path  import asyncio    async def async_post_file_req(url: str, filepath: Path):          async with httpx.AsyncClient(          timeout=httpx.Timeout(write=None, read=None, connect=None, pool=None)) as client:          r = await client.post(              url,               files={                  'file': (filepath.name, filepath.open('rb'), 'application/octet-stream')              }          )    if __name__ == '__main__':      url = 'http://localhost:7070'      asyncio.run(          async_post_file_req(              f'{url}/api',                          Path('~/1500M.txt')      ))  

create a 1500 MB file

truncate -s 1500M 1500M.txt  

When uploading a 1500 MB file, the current implementation of upload appears to read the whole file into memory, and then the server responds with {status: 400, reason: 'Bad Request', details: 'There was an error parsing the body.'}, and the file is not written to disk. When uploading an 825 MB file, the server responds with 200, and the file is written to disk. I don't understand why there is an error in parsing the larger file.

What's going on?

How do I upload files that are larger than the machine's available memory?

Do I have to stream the body?

How can I hand an array to my c code using a separate file? [closed]

Posted: 28 May 2021 07:27 AM PDT

First, Hello. I'm a long time reader, and this is my first time posting a question.

So I'm working on an application that will need to program a MCU from a high level(like Python or something). In the high level, I want to create an array that will be handed to my C-code, ideally as a separate file, to be used on the MCU. I've read that using data in C-headder files is not recommended, and sending data in a source.c file can cause errors.Thank you very much :)

Configuring a custom Appname in logs for log4net ext json

Posted: 28 May 2021 07:27 AM PDT

I'm using log4net.ext.json for logging in wcf class library and there is no exe. However I'd like to give appname some alias name e.g. CarService instead of /LM/W3SVC/2/ROOT-1-132599327970820414. How do I configure that?

Current config:

<log4net>    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">      <encoding value="UTF-8" type="System.Text.UTF8Encoding" />      <file type="log4net.Util.PatternString" value="C:\Logs\WcfLibrary.log" name ="RollingLogFileAppender" />      <appendToFile value="true" />      <rollingStyle value="Date" />      <countDirection value="-1"/>      <datePattern value="yyyy-MM-dd"/>      <logName value="Myapp" />      <applicationName value="BmwService" />      <staticLogFileName value="true" />      <layout type="log4net.Layout.SerializedLayout, log4net.Ext.Json">        <member value="logDateTime%date:yyyy-MM-dd HH:mm:ss:ffff" />        <decorator type="log4net.Layout.Decorators.StandardTypesDecorator, log4net.Ext.Json" />        <member value="hostName" />        <default />        <remove value="date" />        <remove value="ndc" />        <remove value="message" />        <remove value="thread" />        <remove value="exception" />        <member value="logData:messageObject" />      </layout>    </appender>    <root>      <level value="All"/>      <appender-ref ref="RollingLogFileAppender"/>    </root>  </log4net>  

I am getting below log:

{"logDateTime":"2021-03-11","hostName":"PC","level":"DEBUG","appname":"/LM/W3SVC/2/ROOT-1-132599327970820414","logger":"Service","logData":{"Message":"Service started","ClassName":"Utils","MethodName":"Start"}}  

Expected log is:

{"logDateTime":"2021-03-11","hostName":"PC","level":"DEBUG","appname":"CarService","logger":"Service","logData":{"Message":"Service started","ClassName":"Utils","MethodName":"Start"}}  

The argument type 'ShowSnackBar' can't be assigned to the parameter 'SnackBar'

Posted: 28 May 2021 07:27 AM PDT

I want to reuse my SnackBar widget but I get this error:

The argument type 'ShowSnackBar' can't be assigned to the parameter 'SnackBar'  

This is my SnackBarShow code

import 'package:flutter/material.dart';  class ShowSnackBar extends StatelessWidget{    final dynamic state;      const ShowSnackBar({this.state}) ;    @override    Widget build(BuildContext context) {      // TODO: implement build          return SnackBar(content: Text(state.message??'خطا رخ داد.',style: TextStyle(color: Colors.white),        ),          elevation: 4,          backgroundColor: Colors.deepPurple,          action: SnackBarAction(label: 'متوجه شدم', onPressed: (){            print("ok");            }),);      }    }  

This is some part of my code which use flutter_bloc library and this ShowSnacBar class.I got this error on line 4

 BlocListener<AuthenticationBloc,AuthenticationState>  (listener: (context,state){                if(state is AuthenticationError){                    _scafoldKey.currentState.showSnackBar(                      ShowSnackBar(state: state)                    );                }              },  

Thank you .

angular-cli server - how to specify default port

Posted: 28 May 2021 07:26 AM PDT

Using angular-cli with the ng serve command, how can I specify a default port so I do not need to manually pass the --port flag every time?

I'd like to change from the default port 4200.

No comments:

Post a Comment