Wednesday, May 12, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


How to increase character limit in "fast-two-sms" for sending SMS using Node JS

Posted: 12 May 2021 07:57 AM PDT

I'm using fast-two-sms for sending SMS via my Node JS app. Now the thing is when character count is greater than 221 the message is getting cropped and only the message with 221 characters is sent . Below is my code for sending the SMS

const fast2smsAuth = process.env.FAST_TWO_SMS;  const fast2sms = require("fast-two-sms");    function sendSMS(){     var options = {         authorization: fast2smsAuth,         message: "message with character greater than 221",         numbers: ["+918888888888"],  };  fast2sms.sendMessage(options);   }  

Here in above case the SMS recieved by 8888888888 is getting trimmed upto 221 characters only. They've mentioned on their page that when character count exceeds the threshold it'll be counted as new SMS but SMS won't be trimmed (FAQ fast-two-sms) . Already thanks for the help ;)

PLSQL bitmask values

Posted: 12 May 2021 07:57 AM PDT

I am in this situation, I cannot validate the bit for the print permission. Unfortunately I can't have a bitmask with a single bit lit. Can you give me some suggestions?

SELECT     DECODE(BITAND(00000000100000100000000000000001, 1), 1, '1', '0') AS READ,    DECODE(BITAND(00000000100000100000000000000001, 131072), 131072, '1', '0') AS COPY,    DECODE(BITAND(00000000100000100000000000000001, 8388608), 8388608, '1', '0') AS PRINT    FROM   DUAL  

The result is the following

R C P  - - -  1 1 0  

Exception in HostFunction: Malformed calls from JS: field sizes are different Exception?

Posted: 12 May 2021 07:57 AM PDT

I know there are lots of answers on stackoverllow but this problem is mostly but it's same name but different error problem. Let me know if my error has been answered yet

const [address, setAddress] = useState('');  const [phone, setPhone] = useState('');  

case 1:

i got data address from location and i has changed to //setAddress('23 street') //

and then i delete address into ' '

this time it show error

case 2:

phone = '' and i type some character then i showed error

 <TextInput   onChangeText={(onChangePhone) => setPhone(onChangePhone)}  />  

Inversing a complicated regex statement

Posted: 12 May 2021 07:56 AM PDT

I have been trying to implement a regex that will allow me to identify everything in a given .cpp file that is not a function call so that I can replace it with an empty string. so far I have managed to create a regex that can identify the function calls, linked here: https://regex101.com/r/oupnbe/1

But, when I try to inverse the function in the same way as I've done with other expressions it does not work as expected, linked here: https://regex101.com/r/SrEMjY/1

Trying to validate username and password in javascript but not getting alert and desired output

Posted: 12 May 2021 07:56 AM PDT

please check the code

username:
password:
Submit

function validate(){

        var name= document.getElementById("name");           var pwd=document.getElementById("pwd");          if ( name==null || name==""){                alert("Name can't be blank");                return false;                }else if(pwd.length <6){                        alert("Password must be at least 6 characters long.");                        return false;                    }        }  

Page’s settings blocked the loading of a resource at inline (“default-src”). Unable to revert config changes

Posted: 12 May 2021 07:56 AM PDT

Here is an image to show better the network tab and console details

I inadvertently clicked a few wrong buttons and now my Content-Security Policy has changed and I am unable to make any GET calls on localhost. It refuses to load any information at all.

I have tried to find a solution but nothing seems to work.

I am using the Firefox browser. I can provide further information. However, I am stuck at this point with these changes.

The following are my current Content Security Policy settings.

java.lang.IllegalArgumentException: URI is not absolute exception is occurred while mocking restTemplate

Posted: 12 May 2021 07:56 AM PDT

@Mock  RestTemplate restTemplate;    @Test  public void testMethod() {  Mockito.when(restTemplate.exchange(Mockito.anyString(),Mockito.any(),Mockito.any(), Mockito.eq(SomeClassName.class))).thenReturn(responseEntity);    assertEquals(currencyList,service.getCurrencyList());  }    

when service.getCurrencyList() method is called, i need to return the responseEntity. But instead it shows the URI is not absolute exception.

How to monitor accuracy with CTC loss function and Datasets? (runnable code included)

Posted: 12 May 2021 07:56 AM PDT

I've been trying to speed up training of my CRNN network for optical character recognition, but I can't get the accuracy metric working when using TFRecords and tf.data.Dataset pipelines. I previously used a Keras Sequence and had it working. Here is a complete runnable toy example showing my problem (tested with Tensorflow 2.4.1):

import random  import numpy as np  import tensorflow as tf  import tensorflow.keras.backend as K  from tensorflow.python.keras import Input, Model  from tensorflow.python.keras.layers import Dense, Layer, Bidirectional, GRU, Reshape, Activation  from tensorflow.python.keras.optimizer_v2.adam import Adam    AUTOTUNE = tf.data.experimental.AUTOTUNE  CHAR_VECTOR = "ABC"  IMG_W = 10  IMG_H = 10  N_CHANNELS = 3      class CTCLayer(Layer):      def __init__(self, name=None):          super().__init__(name=name)          self.loss_fn = K.ctc_batch_cost        def call(self, y_true, y_pred, label_length):          # Compute the training-time loss value and add it          # to the layer using `self.add_loss()`.          batch_len = tf.cast(tf.shape(y_true)[0], dtype="int64")          input_length = tf.cast(tf.shape(y_pred)[1], dtype="int64")          input_length = input_length * tf.ones(shape=(batch_len, 1), dtype="int64")            loss = self.loss_fn(y_true, y_pred, input_length, label_length)          self.add_loss(loss)            # At test time, just return the computed predictions          return y_pred      def get_model():      n_classes = len(CHAR_VECTOR) + 1        input = Input(name='image', shape=(IMG_W, IMG_H, N_CHANNELS), dtype='float32')      label = Input(name='label', shape=[None], dtype='float32')      label_length = Input(name='label_length', shape=[None], dtype='int64')        x = Reshape(target_shape=(IMG_W, np.prod(input.shape[2:])), name='reshape')(input)      x = Dense(24, activation='relu', name='dense1')(x)      x = Bidirectional(GRU(24, return_sequences=True, name="GRU"), merge_mode="sum")(x)      x = Dense(n_classes, name='dense2')(x)      y_pred = Activation('softmax', name='softmax')(x)        output = CTCLayer(name="ctc")(label, y_pred, label_length)        m = Model(inputs=[input, label, label_length], outputs=output)      return m      def image_feature(value):      """Returns a bytes_list from a string / byte."""      return tf.train.Feature(bytes_list=tf.train.BytesList(value=[tf.io.encode_jpeg(value).numpy()]))      def float_feature_list(value):      """Returns a list of float_list from a float / double."""      return tf.train.Feature(float_list=tf.train.FloatList(value=value))      def int64_feature(value):      """Returns an int64_list from a bool / enum / int / uint."""      return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))      def create_example(image, label, label_length):      feature = {          "image": image_feature(image),          "label": float_feature_list(label),          "label_length": int64_feature(label_length),      }      return tf.train.Example(features=tf.train.Features(feature=feature))      def parse_tfrecord_fn(example):      feature_description = {          "image": tf.io.FixedLenFeature([], tf.string),          "label": tf.io.VarLenFeature(tf.float32),          "label_length": tf.io.FixedLenFeature([1], tf.int64),      }      example = tf.io.parse_single_example(example, feature_description)      example["image"] = tf.image.convert_image_dtype(tf.io.decode_jpeg(example["image"], channels=3), dtype="float32")      example["label"] = tf.sparse.to_dense(example["label"])        return example      def generate_tfrecords(n):      with tf.io.TFRecordWriter(filename) as writer:          for i in range(n):              random_img = np.random.random((IMG_W, IMG_H, N_CHANNELS))              label_length = random.randint(1, max_text_len)              label = np.random.randint(0, len(CHAR_VECTOR), max_text_len)              example = create_example(random_img, label, label_length)              writer.write(example.SerializeToString())      class DataGenerator(tf.keras.utils.Sequence):      def __len__(self):          return steps_per_epoch        def __getitem__(self, index):          outputs = np.zeros([batch_size])          dataset = get_dataset()          inputs = next(iter(dataset.take(1)))          return inputs, outputs      def get_dataset():      generate_tfrecords(batch_size * epochs * steps_per_epoch)      dataset = (          tf.data.TFRecordDataset(filename, num_parallel_reads=AUTOTUNE)          .map(parse_tfrecord_fn, num_parallel_calls=AUTOTUNE)          .batch(batch_size)          .prefetch(AUTOTUNE)      )      return dataset      if __name__ == "__main__":      batch_size = 9      epochs = 7      steps_per_epoch = 8      max_text_len = 5      filename = "test.tfrec"      use_generator = False      data = DataGenerator() if use_generator else get_dataset()        model = get_model()      '''This fails when use_generator == False, removing the        metric solves it'''      model.compile(optimizer=Adam(), metrics=["accuracy"])      model.fit(data, epochs=epochs, steps_per_epoch=steps_per_epoch)    

Set use_generator = False or remove metrics=["accuracy"] and it will run without error.

As you can see the DataGenerator uses the same data from the TFRecords, but it also returns some zeros, and for whatever reason this seems to be the magic sauce:

class DataGenerator(tf.keras.utils.Sequence):      def __len__(self):          return steps_per_epoch        def __getitem__(self, index):          outputs = np.zeros([batch_size])          dataset = get_dataset()          inputs = next(iter(dataset.take(1)))          return inputs, outputs  

I also noticed that this Keras example suffers from the same problem (it crashes if you edit the code to monitor accuracy): https://keras.io/examples/vision/captcha_ocr/

Is there any way to mimic the behaviour of __getitem__ with the Dataset, or some other way of getting the accuracy without using a Sequence?

Issues with add and delete rows with one to many relationship

Posted: 12 May 2021 07:56 AM PDT

Both of the tables include unique constraints. I have been strugling with this for some time now. What should the command be for adding and deleting?

  • Adding a new row if the title is not existing in Movie table, add a new row if the genre is not existing in Genre table and create a link in the Association table.

  • Deleting the title from Movie table and removing the link from Association table. Do nothing for genre.

Do I need to change my model?

model.py

  Association = db.Table(      'association',      db.Column(          'movies_id',          db.Integer,          db.ForeignKey('movies.id'),          index=True,      ),      db.Column(          'genres_id',          db.Integer,          db.ForeignKey('genres.id'),          index=True,      ),    )        class Movie(db.Model):      __tablename__ = 'movies'      id = db.Column(          db.Integer,          primary_key=True,          index=True,      )      title = db.Column(          db.String(80),          index=True,          unique=True,          nullable=False,      )      genres = db.relationship(          "Genre",          secondary='association',          backref=db.backref('movies')      )        def __repr__(self):          return '{}'.format(self.title)        class Genre(db.Model):      __tablename__ = 'genres'      id = db.Column(          db.Integer,          primary_key=True,          index=True,      )      category = db.Column(          db.String(80),          index=True,          unique=True,          nullable=False,      )        def __repr__(self):          return '{}'.format(self.category)  

response undefined when using jest mock to test axios in vue

Posted: 12 May 2021 07:56 AM PDT

I have tried lots of answers to similar questions, but none of them helps. (the comments are what I have tried. attempts are separated by a blank line. I have stuck here for almost a week, trying to improve the coverage by testing the .then part of the Axios request. really cannot figure out which part goes wrong.

code here

__ mocks __/axios.js:

export default {      get: jest.fn(() => Promise.resolve({ data: {} })),      post: jest.fn(() => Promise.resolve())  }  

getInfo method to be tested:

getInfo () {        axios.get('/')          .then((response) => {            this.form.sid = response.data.data.basic_info.username            this.form.name = response.data.data.basic_info.name            this.form.tel = response.data.data.basic_info.mobile_number            this.form.email = response.data.data.basic_info.email            return response.data          }).catch(function (error) {            console.log(error)          })      }  

test code:

import { shallowMount } from '@vue/test-utils'  import InfoForm from '@/components/Form'    //attempt 1  import mockAxios from 'axios';  jest.mock('axios')    //attempt 2  // import axios from './__mocks__/axios'  // jest.mock('axios')    //attempt 3  // import axios from './__mocks__/axios'  // jest.mock("axios", () => ({  //     post: jest.fn((_url, _body) => {  //       url = _url  //       body = _body   //       return Promise.resolve()  //     }),  //     get: jest.fn(() => {  //         return Promise.resolve()  //       })  //   }))    //attempt 4  // import mockAxios from "axios"    //...  //describe part is skipped here        it('test method: getInfo', async () => {          const mockAxiosGet = jest.spyOn(mockAxios, "get")          mockAxiosGet.mockResolvedValue(() =>              Promise.resolve({                  data: {                      basic_info: {                          username: 'aName',                          name: 'aNAME',                          mobile_number: '12222222222',                          email: 'amail@em.com'                      }                  }              })      )            const response = await wrapper.vm.getInfo()          expect(response).toBeDefined() // error(plz see error message below)      })  

error message:

Ensure that a variable is not undefined.    InfoForm.vue test > test method: getInfo  -----  Error: expect(received).toBeDefined()    Received: undefined Jest  

any help is highly appreciated!

any way to change DM name? discord js 12

Posted: 12 May 2021 07:56 AM PDT

I have a DM with friends and we have a war going on right now. Can i change DM name using bot on discord js 12?

Records in bursts

Posted: 12 May 2021 07:56 AM PDT

I am staring at a weird bug where my web application (that handles logins) is looped over multiple times in a short burst. I am tracking a record in my database every time my code is run. I can see burst of 7 records where 3 columns always have the same values and those records are created in under 20 seconds. Is there a way to identify the rows that fall into this sort of pattern? I don't know if I am conveying this properly but I am hoping someone understands what I am asking for.

The results would be grouped by the 3 columns data and only display the rows where the datestamp occurs within 20 seconds of another row that has the same values in the 3 columns of data. But I can't wrap my head around how to do this at all.

a scene get back previous scene after Specified second javafx

Posted: 12 May 2021 07:56 AM PDT

i have scene 1 and and wrote below code to this scene 1 goes to another scene 2:

FXMLLoader watingLoader = new FXMLLoader();  watingLoader.setLocation(getClass().getResource("/FXMLfiles/wating.fxml"));    Parent watingParent = watingLoader.load();  Scene watingScene = new Scene(watingParent);  Stage watingStage = (Stage) ((Node) event.getSource()).getScene().getWindow();  watingStage.setScene(watingScene);  watingStage.show();  

i want to when scene 2 comes up, automaticly after 6 seconds scene 2 goes back to scene 1 without any event! but this switch scene protocol i learn needs an event at "(Node) event.getSource()" what should i do?

how to cut out a piece of a string with javascript jquery?

Posted: 12 May 2021 07:57 AM PDT

I am having a string like below and i want to cut out the T with the time from it like below:

var string = '2021-05-10T08:00,2021-05-11T08:00,2021-05-12T08:00';  

My new string should look like this:

var new_string = '2021-05-10,2021-05-11,2021-05-12';  

How can i do that?

I tried with .replace function but the problem is that the time is not always 08:00

Creating JDialog in actionperformed

Posted: 12 May 2021 07:56 AM PDT

I'm working on a swing application for reading a JSON file and then writing the same to a file. Action items will be listed in a JTable row that shows the metadata of the file and the last column of each row has a button for printing the JSON into a local file.

In the action performed, I'm planning to show a custom JDialog to prevent any operations in the UI, this is blocking all further steps, like writing the file.

Is this possible to start a thread to invoke a function for file reoperations after showing the JDialog? I tried this way using Thread, but this also got blocked.

@Override      public void actionPerformed(ActionEvent e) {          JButton printerButton = (JButton) e.getSource();          String ac = printerButton.getActionCommand();          System.out.println("ac = " + ac);                    /*           * **Start JDialog for blocking any operation on the window**            */                    /*           * **Start a thread for writing a file**           */      }  

Round Javascript Float number to 2 decimal digits [duplicate]

Posted: 12 May 2021 07:56 AM PDT

In my project, when I am subtracting 96.74 from 60, javascript is giving me 36.739999999999995 , but I need 36.74 to do further calculation.

What should I do, how do I overcome this problem??

Thanks in advance.

Parsing day of month with one digit in Java

Posted: 12 May 2021 07:56 AM PDT

I want to parse the string "OCTOBER81984" to a Java LocalDate. I'm using the following code but don't works

LocalDate.parse("OCTOBER81984",      new DateTimeFormatterBuilder()            .parseCaseInsensitive()           .appendPattern("MMMMdyyyy")           .toFormatter(Locale.US)  );  

The exception is

Exception in thread "main" java.time.format.DateTimeParseException: Text 'OCTOBER81984' could not be parsed at index 12      at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)      at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)      at java.time.LocalDate.parse(LocalDate.java:400)  

The pattern used is

MMMM --> Full month name<br>  d    --> Day of month with 1 or 2 digits<br>  yyyy --> Year<br>  

I have read the docs twice and my pattern looks fine but really doesn't work.

What am I missing?

Removing the current item I'm iterating over in a loop in Python 3.x

Posted: 12 May 2021 07:57 AM PDT

I currently have the below code in Python 3.x:-

lst_exclusion_terms = ['bob','jenny', 'michael']  file_list = ['1.txt', '2.txt', '3.txt']    for f in file_list:      with open(f, "r", encoding="utf-8") as file:          content = file.read()          if any(entry in content for entry in lst_exclusion_terms):              print(content)  

What I am aiming to do is to review the content of each file in the list file_list. When reviewing the content, I then want to check to see if any of the entries in the list lst_exclusion_terms exists. If it does, I want to remove that entry from the list.

So, if 'bob' is within the content of 2.txt, this will be removed (popped) out of the list.

I am unsure how to replace my print(content) with the command to identify the current index number for the item being examined and then remove it.

Any suggestions? Thanks

I have a xml file which is having lots of special characters which I need to find out and put the distinct list of those into a text file

Posted: 12 May 2021 07:56 AM PDT

I have a xml file. I need to find out the special characters from that xml file except A-Z, a-z, 0-9 and the following list of symbols. Is there a way to automate this or should I be looking for a utf-8 editor?

Can someone please help?

Using HTML select options to filter what is showing

Posted: 12 May 2021 07:56 AM PDT

I am wanting to use a HTML options selector to filter the posts that my site will show by subject.

For example, if the user selects the subject Computer Science in the options, it will only show posts that have a 'post_subject' value of compSci.

However currently when I click the 'filter' button, it just shows all the posts from the database.

Here is an example of a post in the database: The image shows the database tables

Edit: after trying what was suggested in the comments, when filtered (other than for all subjects) it is returning nothing even though there are posts for each subject saved in the database

<div class="post">      <form name="writeForm" method="post">          <label for="subjectView">Choose a subject:</label>          <select name="subjectView" id="subjectView">              <optgroup label="SubjectsView">                  <option value="all">All Subjects</option>                  <option value="CompSci">CompSci</option>                  <option value="Economics">Economics</option>                  <option value="Maths">Maths</option>                  <option value="Music">Music</option>                  <option value="English">English</option>              </optgroup>          </select>          <p><input type="submit" value="Filter"></p>      </form>  <?php  if ($_POST['subjectView'] = 'all') {      $sql = "SELECT * FROM tblPosts ORDER BY post_date DESC";      $result = $connect->query($sql);      if ($result->num_rows > 0) {          while($row = $result->fetch_assoc()) {              echo "<div class=\"post\"> <h2> Username: " . $row["user_name"] . "</h2></div>";              echo "<div class=\"postCont\"> <p>" . $row["post_contents"] . "</p></div>";              echo "<div class=\"post\"> <p>" . $row["post_date"] . "</p></div>";          }      } else {          echo "0 results";      }  } else {      $sql = "SELECT * FROM tblPosts ORDER BY post_date DESC WHERE post_subject = {$_POST['subjectView']}";      $result = $connect->query($sql);        if ($result->num_rows > 0) {          while($row = $result->fetch_assoc()) {              echo "<div class=\"post\"> <h2> Username: " . $row["user_name"] . "</h2></div>";              echo "<div class=\"postCont\"> <p>" . $row["post_contents"] . "</p></div>";              echo "<div class=\"post\"> <p>" . $row["post_date"] . "</p></div>";          }      } else {          echo "0 results";      }  }  

If you would like any clarification please ask :)

How to pass a value to html through javascript dynamically?

Posted: 12 May 2021 07:57 AM PDT

I have an HTML page that shows

Hi |FNAME|,  You have successfully logged in.  

So here I want to pass a value for |FNAME| using javascript. For example, I want to pass Jack to |FNAME| my output should be,

Hi Jack,  You have successfully logged in.  

Intially I have used this method,

var str = "Visit America!";  var res = str.replace("America", "Japan");  

and by console.log(res) will return

Visit Japan  

But now I want to use another method instead of replace()

Im trying to make a mysql backup script in bash, but there is a problem

Posted: 12 May 2021 07:56 AM PDT

Passing in Items as Props to be used in React Native Drop Menu

Posted: 12 May 2021 07:57 AM PDT

I have some React code to render a react-native-dropdown-picker DropMenu that looks like so:

export const DropMenu = () => {     const [open, setOpen] = useState(false);     const [value, setValue] = useState(null);     const [items, setItems] = useState([       { label: 'A', value: 'a' },       { label: 'B', value: 'c' },       { label: 'C', value: 'c' }     ]);           return (       <DropDownPicker         open={open}         value={value}         items={items}         setOpen={setOpen}         setValue={setValue}         setItems={setItems}       />     );   }  

What I'd like to do is make this re-useable by simply passing in the implementation details for the items to be used in the menu. What would that look like? Something like this, using the spread operator? I am unclear on what the syntax would look like specifically:

export const DropMenu = props => {    const [open, setOpen] = useState(false);    const [value, setValue] = useState(null);    const [items, setItems] = useState([    const [items, setItems] = useState([      {         label: [...props.items.label],         value: [...props.items.value]       }     ]);    ]);      return (      <DropDownPicker        open={open}        value={value}        items={items}        setOpen={setOpen}        setValue={setValue}        setItems={setItems}      />    );  }  

And I'd pass in props that look like this:

const items = [  ​ { label: 'A', value: 'a' },   { label: 'B', value: 'c' },   ​{ label: 'C', value: 'c' }  ];  

How can I pass in the values to be used in the DropMenu via props?

Find an object that can be in different arrays and delete it MongoDB

Posted: 12 May 2021 07:56 AM PDT

Suppose I have the following document:

{  _id: "609bcd3160653e022a6d0fd8",  companies:{     apple: [         {          product_id: "609bcd3160653e022a6d0fd7"         },         {          product_id: "609bcd3160653e022a6d0fd6"         }     ],     microsoft: [         {          product_id: "609bcd3160653e022a6d0fd5"         },         {          product_id: "609bcd3160653e022a6d0fd4"         }     ]    }  }  

How can I find and delete the object with the product_id: "609bcd3160653e022a6d0fd4".

P.S: I use MongoDB native driver for Nodejs.

Thanks a lot!

Pandas: Holding on to an output until a change happens in parameter X

Posted: 12 May 2021 07:56 AM PDT

I am trying to identify different phases in a process. What I basically need to create is the following:

  • When Parameter A > certain value: Output = Phase 1; keep this value until:
  • Parameter B reaches a certain value, then Output = Phase 2

This is of course quite easy to program with a generator, however, the tricky part here is that sometimes it can go back from phase 2 to 1 or it can also skip a phase.

I am not quite sure how to do this. Ideally the code would look at a parameter, and when it changes decide to go back or forward in the phases.

I came up with some sample code below:

  • Give an output for Phase 1 when Parameter A reaches 1.
  • Hold on to Phase 1 until Parameter B changes to >120 or parameter A >= 2.
  • Hold on until parameter A < 1.5 --> go back to Phase 1 or Hold on until parameter A > 3 --> go forward to Phase 3.

I hope this question is clear. The real dataset has 36 parameters so I simplified the case a bit to not make it any more complicated than necessary!

I hope you can help me out!

import pandas as pd    data = {    "Date and Time": ["2020-06-07 00:00", "2020-06-07 00:01", "2020-06-07 00:02", "2020-06-07 00:03", "2020-06-07 00:04", "2020-06-07 00:05", "2020-06-07 00:06", "2020-06-07 00:07", "2020-06-07 00:08", "2020-06-07 00:09", "2020-06-07 00:10"],    "Parameter A": [1, 1, 1, 1, 1.5, 2, 2.1, 2.2, 2.3, 1.6, 1.2],    "Parameter B": [100, 101, 99, 102, 101, 105, 120, 125, 122, 123, 99],    "Required output": ["Phase 1", "Phase 1","Phase 1","Phase 1","Phase 1","Phase 2","Phase 2","Phase 2","Phase 2","Phase 2","Phase 1"]  }    df = pd.DataFrame(data)  

Put array of data in local storage and again get specific data then modify it and again store modified data in localstorage array

Posted: 12 May 2021 07:57 AM PDT

addque(num, i) {      localStorage.setItem("totalque",'[]');      for (var item of this.items) {        if (i == item.Id) {          this.x[i] = this.count + parseInt(num);          console.log(this.x[i]);          localStorage.setItem("totalque", JSON.stringify(this.x[i]));          this.count = parseInt(JSON.parse(localStorage.getItem("totalque[i]")));          console.log(this.count);             }  }            

.html file

<form #frmRegister="ngForm" *ngIf="item.Id==(i+1)">     <input type="text" name="number" ngModel #number="ngModel" class="form-control" >     <button type="submit"  (click)="addque(frmRegister.value.number,i+1)">+</button>  </form>  

I need to enter some numbers in input field and click button it should store data in local storage array for every loop iteration. Then get data from local storage and again modify the data, and then store in local storage.

Why dynamic routing is not working as expected in Nuxt js when data coming from vuex or localstorage?

Posted: 12 May 2021 07:56 AM PDT

I want each question that entered by the user to be turned to a link that leads to a page to discuss and comments on this question solely. So, I have a text area that takes user input (a question ) then save it to a localstorge with previous hardcoded data. The hardcoded data are rendered properly to valid links to dynamic pages. But those from user input are not working. I checked many questions here I did not find a proper answer to this problem. I want the input of user to work as a link . They all stored together and I am looping them together , so I expect them all to be working as links properly. But those from user do not work as expected:

<table v-for="q in questions">    <td>      <tr class="border-dotted border-2 border-light-blue-200">         <nuxt-link :to="`/questions/${q.id}`"> {{ q.question }}</nuxt-link>         </tr>    </td>  </table>  

Computed property to read from vuex:

computed: {    questions() {      return this.$store.state.all;    }   }   

Any help?

First 6 questions are hardcoded and they work. The last one is from user and it is not working

The data from user is stored properly within the hardcoded data but not works as them

This link is working . It is hardcoded. I expect similar results from data coming from users

This link from user is not working

Console TypeError of undefined

Why is that strange behaviour in quasar framework select css?

Posted: 12 May 2021 07:56 AM PDT

I have a select control that I need to put on the right. I use html and css to achieve this, but there is strange behaviour when I click on the control for the first time. It breaks the options, but when navigate the options the control grows until there are not break lines:

https://codepen.io/andreschica/pen/LYWpKvJ?editors=1011

<div id="q-app">    <q-card bordered class="my-card justify-between ">        <q-card-section class="row justify-between items-center bg-grey-2 q-pa-none">        <q-item class="col-8 q-pa-none" style="background-color: #f5f5f5;">        </q-item>        <q-item class="col-4 q-pa-none" style="background-color: #f5f5f5;">          <q-item-section>            <div class="row items-center q-pa-sm col-12 justify-center ">              <label class="text-weight-bold text-primary text-h5 q-mr-sm">Evento:</label>             <q-select  v-model="model" class="col-grow" :options="listaEventos" >               </q-select>            </div>          </q-item-section>        </q-item>      </q-card-section>    </q-card>  </div>  

I need to avoid that behaviour. Thanks for your help.

Instability in second order ODE in Julia

Posted: 12 May 2021 07:56 AM PDT

I want to solve numerically a second-order ODE (see first equation below) which depends on relatively easy functions (g, g'/g and f/g are superpositions of cos,sine,cosh,sinh). The main problem is that these functions depend on a function alpha (e.g. cos(alpha*phi)), and only its derivative is known (see second equation below, sigma and d are fixed).

eqdiff

This is obviously difficult to solve, so I tried first something simpler, setting alpha=phi². My code returns the warning Warning: Automatic dt set the starting dt as NaN, causing instability. followed by Warning: NaN dt detected. Likely a NaN value in the state, parameters, or derivative value caused this outcome. The code runs, but plotting the solution gives an error ArgumentError: reducing over an empty collection is not allowed, which I assume is telling me my solution is empty.

I have found a post with a similar issue, in which the error occurred because the parameters were giving a divergent solution, but in my case all the functions in the ODE are well-defined on the interval of interest (-5,5), so I doubt this would be my case. I have three questions then:

  1. How can I know where is the NaN value exactly?
  2. How can I avoid this error?
  3. Is there a way to implement the full expression (d alpha/d phi) into an integrator?

Many thanks!

EDIT: Following the comment of @Lutz Lehmann, I tried to reduce the 2nd order ODE and solve the three equations simultaneously, but Julia tells me UndefVarError: α not defined, even though I explicitly define it as the third equation. What am I doing wrong?

EDIT2: The error disappeared after renaming the functions correctly. However, I receive the same warnings and error as before, with the addition of Warning: First function call produced NaNs. Exiting. in first instance.

EDIT3: I have now written the expression for dα is a simpler way, and corrected two mistakes in the code (sign pointed out by @Lutz Lehmann and a missing closing parenthesis). After giving a small non-zero initial value to α and A', I can see the solution blows up at time ϕ>2.12, so I guess the problem lies there.

enter image description here

using DifferentialEquations  using Plots    const global lp=1.                 const global s2=81.  const global  d=-9.0e-4  const global B=1.    # Parameter in the gaussian f(\phi) defined below  const global β =1.   # Parameter in the gaussian f(\phi) defined below  const global k=1.    # Wave number               @variables α,ϕ    # Useful functions  #α(ϕ) = ϕ^2      g1(α,ϕ) = s2^2*α^2*sinh(s2*α*ϕ)*sin(2d*α)  g2(α,ϕ) = cos(2d*α)+cosh(s2*α*ϕ)  g3(α,ϕ) = -α*s2*sin(2d*α)+2d*cos(2d*α)+2d*cosh(s2*α*ϕ)  g(α,ϕ) = exp(-2α)*g3(α,ϕ)/g2(α,ϕ)/2/lp  dgg(α,ϕ) = g1(α,ϕ)/g2(α,ϕ)/g3(α,ϕ) # Derivative of g over g    f1(α,ϕ) = -4B*lp*exp(2α)*ϕ*exp(-ϕ^2/β^2)/β^2  f2(α,ϕ) = cos(2d*α)+cosh(s2*α*ϕ)  f3(α,ϕ) = -α*s2*sin(2d*α)+2d*cos(2d*α)+2d*cosh(s2*α*ϕ)  dfg(α,ϕ) = f1(α,ϕ)*f2(α,ϕ)/f3(α,ϕ) # Derivative of f over g    α1(α,ϕ) = ϕ*s2*sin(2d*α)+2d*sinh(s2*α*ϕ)    function eom(du,u,p,ϕ)      α = u[1]      A = u[2]      dA = u[3]      du[1] = α1(α,ϕ)/g3(α,ϕ)      du[2] = dA      du[3] = -2*dgg(α,ϕ)*dA-2*dfg(α,ϕ)*dA-k^2*A/g(α,ϕ)  end   A₀ = [0.1,0.,0.1]               # initial state vector  tspan = (-5.0,5.0)                  # time interval  prob = ODEProblem(eom,A₀,tspan)  sol = solve(prob,Tsit5())  plot(sol)    # Full solution to implement in the future  # dαdϕ1(ϕ) = ϕ*s2*sin(2d*α)+2d*sinh(s2*α*ϕ)  # dαdϕ(ϕ) = dαdϕ1(ϕ)/g3(ϕ)     # Original problem  # function eom(ddu,du,u,p,ϕ)  #     ddu[1] = -2dgg(ϕ)*du[1]-2dfg(ϕ)*du[1]-k^2*u[1]/g(ϕ)  # end  # u0 = [0.]                  # initial state vector  # du0 = [0.]  # tspan = (-5.0,5.0)                  # time interval  # prob = SecondOrderODEProblem(eom,du0,u0,tspan)  # sol = solve(prob,Tsit5())  # plot(sol)  

Get Document from current user firebase swift

Posted: 12 May 2021 07:57 AM PDT

I'm trying to get the firstname from this: enter image description here

The user is logged in and I can access his uid, but I can't get the Document that belongs to that user, this is how I'm trying to do it:

    private func getDocument() {            var userID = Auth.auth().currentUser?.uid              userID = String(userID!)            var currentUser = Auth.auth().currentUser      //         Get sspecific document from current user          let docRef = db.collection("users").document("bnf2s3RURUSV2Oecng9t")            // Get data          docRef.getDocument { (document, error) in              if let document = document, document.exists {                  let dataDescription = document.data().map(String.init(describing:)) ?? "nil"                  print("Document data: \(dataDescription)")              } else {                  print("Document does not exist")              }          }      }  

If you noticed, if I put manually "bnf2s3RURUSV2Oecng9t" it will access the data, but the point is to be able to know what ""bnf2s3RURUSV2Oecng9t" is so I can put it on that hard coded variable on top. My end goal is be able to get the first name of the current user :)

No comments:

Post a Comment