Saturday, August 21, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Flask background thread execution

Posted: 21 Aug 2021 07:54 AM PDT

I have the code below that starts a thread. If executed as a script, it will work just fine and the worker will sleep for 10 seconds every iteration. However, if started as a background thread in Flask, the worker will sleep for varying time intervals of fewer than 10 seconds. How is it so?

import datetime  import threading      class Worker:        def __init__(self):          pass        def execute(self):          while True:              print(int(datetime.datetime.now().timestamp()))              time.sleep(10)      class ThreadWrapper():            def __init__(self, interval=1):          self.worker = Worker()            thread = threading.Thread(target=self.worker.execute, args=())          thread.daemon = False                           # Daemonize thread          thread.start()                                  # Start the execution    if __name__ == '__main__':      ThreadWrapper()  

MVC Project, from view to controller, NULL model

Posted: 21 Aug 2021 07:54 AM PDT

In an MVC project I have a very complex model, part of the class is below: (the class is BIG, I simplify a lot, leaving only one property)

[Serializable]  public class SimulazioneModelComplete : SimulazioneModel  {     public string Title { get; set; }  }  

I put some properties on a form, like this:

@using (Html.BeginForm("CreaEsito", "Simulazioni", FormMethod.Post, new { id = "CreaEsito", name = "CreaEsito", enctype = "multipart/form-data" }))  {     Title:     @Html.TextBoxFor(m => m.Title)   }  

I put a simple submit button

<input type="submit" value="SUBMIT" />  

And in the controller I have a method expecting a "SimulazioneModelComplete" model

[HttpPost]  public ActionResult CreaEsito(SimulazioneModelComplete model)  {  }  

but when i click submit "model" is ALWAYS NULL. I don't see some properties null, the whole model is null. I dont place the full code of class and form because they are BIG, and would be unreadable.

Someone can suggest reasons for a NULL model?

Aws polly decode json audio stream on client

Posted: 21 Aug 2021 07:54 AM PDT

I launched NodeJS server with AWS Polly, on request it returns to me this:

AudioStream:  {      "0": 123,      "1": 34,      "2": 116,      "3": 105,  ... and hundreds more  },  ContentType: "application/x-json-stream"  RequestCharacters: 40  

I could get MP3 or other formats, but because of "speechmarks," JSON is the only option.

Is that possible to convert this x-json-stream to audio in the browser?

How to set cookies with ```react-cookie``` inside none react function

Posted: 21 Aug 2021 07:53 AM PDT

So I am trying to set authentication with react-cookie I am using redux ass well so the problem is I dont know how to set cookie outside a none react functional component

here is my login code

export const login = (email, password) => async (dispatch) => {    try {      dispatch({        type: USER_LOGIN_REQUEST,      });      const config = {        headers: {          "Content-type": "application/json",        },      };      const { data } = await client.post(        "SOME_URL",        {          username: email,          password: password,        },        config      );        dispatch({        type: USER_LOGIN_SUCCESS,        payload: data,      });      //here I want to set cookie    } catch (error) {      dispatch({        type: USER_LOGIN_FAIL,        payload:          error.response && error.response.data.details            ? error.response.data.details            : error.details,      });    }  };    

and I want to get the cookie with the initialState inside my store.js

here is my code for store.js

  const reducer = combineReducers({    ...    userLogin: userLoginReducers,    ...    });    const userInfoFromCookies = () => {       //want to get the cookie    }      const initialState = {    ...    userLogin: { userInfo: userInfoFromCookies },    ...  };    const middleware = [thunk];    const store = createStore(    reducer,    initialState,    composeWithDevTools(applyMiddleware(...middleware))  );    export default store;    

in case you need reducer

here is the login reducer

export const userLoginReducers = (state = {}, action) => {    switch (action.type) {      case USER_LOGIN_REQUEST:        return { loading: true };      case USER_LOGIN_SUCCESS:        return { loading: false, userInfo: action.payload };        case USER_LOGIN_FAIL:        return { loading: false, error: action.payload };        case USER_LOGOUT:        return {};      default:        return state;    }  };        

Are materialized views read only in Postgresql?

Posted: 21 Aug 2021 07:53 AM PDT

According to the official documentation of create view (https://www.postgresql.org/docs/9.2/sql-createview.html):

Currently, views are read only: the system will not allow an insert, update, or delete on a view.

In the official documentation of create materialized view (https://www.postgresql.org/docs/9.3/sql-creatematerializedview.html) it is not mentioned if a materialized view is read only or not.

So are materialized views in Postgresql read only?

What is the best way to host a MERN Stack App in AWS

Posted: 21 Aug 2021 07:53 AM PDT

I have learnt, developed and ready to deploy my first MERN (MongoDB, Express, React & NodeJS) application. Based on an internet search my understanding is AWS is a good choice for it.

I am having trouble deciding which would be more economical & better option. Kindly help.

  1. Deploying everything in an EC2 instance.
  2. Deploying the React App in S3+CloudFront, NodeJS app in Elastic Beanstalk and use AWS MongoDB for the Database.

For some context, my app is somewhat like a university intranet.

Your time is highly appreciated and thank you very much in advance.

How can i do this effect with canvas?

Posted: 21 Aug 2021 07:54 AM PDT

I need to do a canvas with a bar with dynamic width, and some string inside this bar, and i want to change color os part of string that is above bar to a color with better contrast, something like image bellow. Anyone know if it's possible do this with canvas? And if possible, how can i do this?

Image Example

document.getElementById().innerText integer is saved as zero [duplicate]

Posted: 21 Aug 2021 07:55 AM PDT

I'm trying to read the content of an <input> component, save it as an Integer and eventually post it to the server. The problem is, that the integer that is entered inside the 'pageNum' variable turns to be zero. This is the code -

render() {        ......      return (      ......      <input className="text" id="pageNum" type="text" name="page" placeholder="page number"/>      .......}          requestPage = () =>{      const element = document.getElementById("pageNum");      if(element!=null){          var pageNum: number = +element.innerText;          if(pageNum!=null)              this.grabTicketsAsyncFunc(pageNum);      }            }  

After a little research, I came across this question and solution - The property 'value' does not exist on value of type 'HTMLElement'

But when im implementing this on my code, I get another error. Here is a link to the code and error image - enter image description here

Any help will be very much appriciated :)

Unhandled Exception: NoSuchMethodError: Class 'Future<dynamic>' has no instance method '[]' when getting data from openweathermap

Posted: 21 Aug 2021 07:54 AM PDT

I am building a weather app using OpenWeatherMap API.

Whenever I am passing latitude and longitude then I am getting the data correctly:

Future<dynamic> getWeatherData(double latitude, double longitude) async{      Network network = Network();      var weatherData = await network.getJson("https://api.openweathermap.org/data/2.5/weather?lat=$latitude&lon=$longitude&appid=$APP_ID&units=metric");      return weatherData;    }  

I am using weatherData like this:

void updateWeather(dynamic weatherData){      Weather weather = Weather();      setState(() {        if (weatherData == null){          temperature = 0;          temperatureIcon = "💔";          temperatureText = "Can't find weather, make sure GPS is on";          return;        }        temperature = weatherData["main"]["temp"];        int condition = weatherData["weather"][0]["id"];        temperatureIcon = weather.getWeatherIcon(condition);        temperatureText = weather.getMessage(temperature);      });  

I am using temperatureIcon and temperatureText in Text() widgets below.

Now I was adding the feature to get weather by searching city name:

var cityName = await Navigator.push(context, MaterialPageRoute(                          builder: (context){                            return Search();                          }                        ));                        if (cityName != null && cityName.toString().isNotEmpty){                          Weather weather = Weather();                          var weatherData = weather.getWeatherDataCity(cityName);                          updateWeather(weatherData);                        }  

getWeatherDataCity():

Future<dynamic> getWeatherDataCity(String cityName) async{      Network network = Network();      var weatherData = await network.getJson("https://api.openweathermap.org/data/2.5/weather?q=$cityName&appid=$APP_ID&units=metric");      return weatherData;    }  

but when I run this code I get this exception:

E/flutter ( 3250): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: NoSuchMethodError: Class 'Future<dynamic>' has no instance method '[]'.  E/flutter ( 3250): Receiver: Instance of 'Future<dynamic>'  E/flutter ( 3250): Tried calling: []("main")  E/flutter ( 3250): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)  E/flutter ( 3250): #1      WeatherScreenState.updateWeather.<anonymous closure> (package:clima/screens/weather_screen.dart:39:32)  E/flutter ( 3250): #2      State.setState (package:flutter/src/widgets/framework.dart:1088:30)  E/flutter ( 3250): #3      WeatherScreenState.updateWeather (package:clima/screens/weather_screen.dart:32:5)  E/flutter ( 3250): #4      WeatherScreenState.build.<anonymous closure> (package:clima/screens/weather_screen.dart:86:25)  E/flutter ( 3250): <asynchronous suspension>  

Why am I getting this exception?

The JSON data received is the same when I put city name or latitude and longitude.

Network.getJson():

class Network{      Future<dynamic> getJson(String url) async{      Response response = await get(Uri.parse(url));      print(response.body);      return response.statusCode >= 200 ? jsonDecode(response.body) : null;    }  }  

How to write a test to confirm that a perl script waits (or doesn't wait) for interactive user input (based on supplied options)

Posted: 21 Aug 2021 07:54 AM PDT

I have a perl script for which I would like to write a couple tests. If the perl script gets supplied a specific option, the user is allowed to paste or type out multi-line input and end their input using control-d.

I wrote a test that confirms input was received (it works by the parent test script printing to the child's input handle and the child modifies and prints that input back out), but that test doesn't wait for an end of input signal (e.g. control-d). So in other words, I can confirm it receives input, but I don't know how to confirm that it waits for the user to end the input entry. I.e. How do I know that the input consumption won't stop until the user types control-d?

Here's what I have so far. I wrote a 3rd little IO::Pipe::Consumer module to be able to send input to the child process that I'm testing and I wrote a toy example of the script that allows input on STDIN from a tty.

Here is a toy version of the script I'm testing:

>perl -e 'while(<STDIN>){print("*$_")}'  test  *test  ^d  

And here is the toy test code (that I want to improve) for the above script:

>perl -e 'use IO::Pipe::Consumer;$obj = new IO::Pipe::Consumer;$si = $obj->getSubroutineConsumer(sub {while(<STDIN>){print("*$_")}});print $si "test\n"'  *test  >  

I thought the parent would have to print an "end-of-input" (e.g. "control-d") character to end the input in the test, but the test ends immediately even though I'm not sending any such end-of-input character. I can see that it's getting, modifying, and printing the input. Is that sufficient to confirm that the script will wait for user input (and that the user will be able to intentionally end the input) or is there something else I should do to confirm it waits for all user input until the user intends to end it?

Even if modified input spit back out is sufficient proof of "waiting for input", I also wish to test that a script doesn't wait for input (when the interactive option isn't provided) - but since it doesn't seem to wait even when I do send it input without an end-of-input signal, how would I test that the script wouldn't hang waiting for input? Note, the script has other options for consuming redirected or piped input, so my intent is specifically to know if it's waiting on input from the tty. All of the STDIN consumption options (whether from the tty or via redirect/pipe) are optional, which is why I want to write these tests.

My manual testing shows everything works as intended. I would just like some tests to assure that behavior for the future.

I feel like the thing I'm missing is not relevant to IO::Pipe::Consumer, so WRT that, I'll just describe it instead of paste in 30 or so lines of code... All it does is it sets a file handle to the child's STDIN and gives that handle back to the parent when you call getSubroutineConsumer.

IO::Pipe::Consumer is basically the opposite of IO::Pipe::Producer (a module I published on cpan looong ago, say 2001-ish, when I was new to perl, or programming for that matter). The main difference, aside from swapping STDIN for STDOUT and Reader with Writer (and vice versa), is that the open is open(STDIN,"<",\${$stdin_pipe}).

How to handle onError for img tag in react?

Posted: 21 Aug 2021 07:53 AM PDT

i am simply don't know how many images will there on cdn folder so i am looping whenever i get onerror for image i will stop the adding the images tag. but even a(as variable) changing to true loop is looping till 13 not stoping over 10 because there are only 10 images in folder. i also want to add pop up for each so adding num but only last index attaching on images.

componentDidMount() {      let images = [];      let src = [];      var a = false;      let commonPath = filesPath + "companyImages/";      let num = 1;      let companyId = this.props.tab.Id;      while (a !== true && num < 13) {          if (a == true) {              alert("I am breaking")              break;          }          let imageFolder = `${companyId}/${companyId}_00${num}.jpg`;          let fullPath = `${commonPath}${imageFolder}`;          let tag = <img src={fullPath} height={140} key={num} id={'image' + num} width={200} className="image" onClick={() => this.openImage(num)} onError={a = true} onLoad={() => { console.log(num,"yup")}}></img>;                   images.push(tag);          src.push(fullPath);          num++;        }           this.setState({allImages:images,allSrcs:src});  }  

Can't ignore Content Description on new app

Posted: 21 Aug 2021 07:53 AM PDT

I have developed two other apps and was able to drop the Content Description when they run. However, a new app I am working on will not drop it.

android:contentDescription="@null"  android:importantForAccessibility="no"  tools:ignore="ContentDescription"  

I've tried the above in all combinations, and Content Description still showing.

Segmentation fault at 'FeedForward()'

Posted: 21 Aug 2021 07:53 AM PDT

I am working on making a simple perception model in C and I had decided that I wanted to have some sort of abstraction using opaque pointers. Code bellow could give more clues to the problem

perceptron.h

  #ifndef __PERCEPTRON_H__  #define __PERCEPTRON_H__    typedef struct _Perceptron _perceptron;    typedef struct{    //public      float * input;      float * weigths;      int size;  //private       void * m_perceptron;    }Perceptron;    Perceptron * InitPerceptron();  void FreePerceptron(Perceptron * instance);  void FeedForward(float input[],float weights[],int size,Perceptron * perceptron);    

No comments:

Post a Comment