Monday, July 18, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


How to send traffic over a specific external network interface from node.js?

Posted: 18 Jul 2022 02:58 AM PDT

I have 2 network interfaces on a MacOS machine: "ZTE Mobile Broadband" and "Ethernet". Both can be used to access the Internet. Is it possible to influence how a specific URL will be requested from node.js? E.g. got('https://ifconfig.co', {/* something to mark traffic to make the OS send this specific request over eth or zte */})?

I know you can add routes to request specific destinations over specific interfaces, and that you can mark traffic from a certain process id and then make all traffic from this process go over specific interface, but what about single requests from a process?

Getting this Warning message in my browser console

Posted: 18 Jul 2022 02:58 AM PDT

Error: You should call navigate() in a React.useEffect(), not when your component is first rendered. I am getting this warning in my browser console every time as I am new to react I am not getting how to remove that warning message if any one can help I am thankful to them.

PaymentScreen.js :

import React, { useState } from 'react'  import { useDispatch, useSelector } from 'react-redux';  import { useNavigate } from 'react-router-dom';  import { savePaymentMethod } from '../actions/cartActions';  import CheckoutSteps from '../components/CheckoutSteps'    export default function PaymentScreen(props) {        const history = useNavigate();      const cart = useSelector((state) => state.cart);      const {shippingAddress} = cart;      if(!shippingAddress.address){          history('/shipping');//getting console message for this line      }        const [paymentMethod, setPaymentMethod] = useState('Paypal');        const dispatch = useDispatch();        const submitHandler = (e)=>{          e.preventDefault();          dispatch(savePaymentMethod(paymentMethod));          history('/placeorder');      }    return (      <div>          <CheckoutSteps step1 step2 step3></CheckoutSteps>          <form className='form' onSubmit={submitHandler}>              <div>                  <h1>Payment Method</h1>              </div>              <div>                  <div>                      <input type="radio" id="paypal" value="PayPal" name ="paymentMethod" required checked onChange={(e)=> setPaymentMethod(e.target.value)}></input>                      <label htmlFor='paypal'>PayPal</label>                  </div>              </div>              <div>                  <div>                      <input type="radio" id="stripe" value="Stripe" name ="paymentMethod" required onChange={(e)=> setPaymentMethod(e.target.value)}></input>                      <label htmlFor='stripe'>Stripe</label>                  </div>              </div>              <div>                  <button className='primary' type='submit'>Continue</button>              </div>          </form>      </div>    )  }  

CartAction.js:

import Axios from "axios";  import { CART_ADD_ITEM, CART_REMOVE_ITEM, CART_SAVE_PAYMENT_METHOD, CART_SAVE_SHIPPING_ADDRESS } from "../constants/cartConstants";    export const addToCart = (productId,qty)=> async( dispatch, getState)=>{      const {data} = await Axios.get(`/api/products/${productId}`);        dispatch({          type: CART_ADD_ITEM,          payload: {              name: data.name,              image: data.image,              price: data.price,              countInStock: data.countInStock,              product: data._id,              qty,          }      });      localStorage.setItem('cartItems', JSON.stringify(getState().cart.cartItems));  };      export const removeFromCart = (productId) => (dispatch,getstate) =>{      dispatch({type : CART_REMOVE_ITEM, payload: productId});      localStorage.setItem('cartItems', JSON.stringify(getstate().cart.cartItems))  }    export const saveShippingAddress=(data)=>(dispatch)=>{      dispatch({type: CART_SAVE_SHIPPING_ADDRESS, payload : data});      localStorage.setItem('shippingAddress',JSON.stringify(data));  }    export const savePaymentMethod=(data)=>(dispatch)=>{      dispatch( {type : CART_SAVE_PAYMENT_METHOD, payload:data});  }  

Altering a variable within a .tflite model in Xcode?

Posted: 18 Jul 2022 02:57 AM PDT

I'm trying to implement the Neural Style Transfer model by https://arxiv.org/pdf/1610.07629.pdf in an iOS app. The paper uses this conditional instance norm layer to allow a single model to learn multiple styles and also combine the styles.

Here is my code for it:

class ConditionalInstanceNorm(tf.keras.layers.Layer):    def __init__(self, scope_bn, y1, y2, alpha):      super(ConditionalInstanceNorm, self).__init__()      self.scope_bn = scope_bn      self.y1 = y1      self.y2 = y2      self.alpha = alpha        def build(self, input_shape):      self.beta = self.add_weight(name="beta"+self.scope_bn, shape=(self.y1.shape[-1], input_shape[-1]), initializer=betaInitializer, trainable=True)      self.gamma = self.add_weight(name="gamma"+self.scope_bn, shape=(self.y1.shape[-1], input_shape[-1]), initializer=gammaInitializer, trainable=True)        def call(self, inputs):      mean, var = tf.nn.moments(x=inputs, axes=[1,2], keepdims=True)      beta1 = tf.matmul(self.y1, self.beta)      gamma1 = tf.matmul(self.y1, self.gamma)      beta2 = tf.matmul(self.y2, self.beta)      gamma2 = tf.matmul(self.y2, self.gamma)      beta = self.alpha*beta1 + (1. - self.alpha)*beta2      gamma = self.alpha*gamma1 + (1. - self.alpha)*gamma2      x = tf.nn.batch_normalization(x=inputs, mean=mean, variance=var, offset=beta, scale=gamma, variance_epsilon=1e-10)      return x  

It requires me to pass in 3 hyper-parameters: y1, y2, and alpha. Each style has a unique y value (y1 and y2 are the different styles to allow combining of styles). Alpha determines the strength of influence of each style.

In python, the way I switch between different combinations of styles is by accessing each layer, identify the conditional instance norm layers then change the y1, y2, and alpha values stored:

  for layer in filter(lambda x: "conditional_instance_norm" in x.name, model.layers):      layer.y1 = y1      layer.y1 = y2      layer.alpha = alpha  

How can I do this with a .tflite model in swift? Right now I can run the model but it is stuck with the y1, y2, and alpha values it was initialised with.

Getting an error while adding FCM API Key to Azure Notification Hub

Posted: 18 Jul 2022 02:57 AM PDT

I have created a Azure Notification hub namespace, I'm trying to configure the Google FCM section of it by entering the API Key, but when I do that it is giving me this error

Error updating notification hub {"error":{"code":"BadRequest","message":"Invalid Firebase credentials."}}

The Key I added it from the google-services.json file

But when I send a notification from FCM console, I'm able to send it and receive the notification.

Any inputs would be appreciated

How to read a csv file from url using pandas

Posted: 18 Jul 2022 02:57 AM PDT

I would like to load a csv into a pandas dataframe and the data is available on a remote server.

The goal is to read it directly to a dataframe without writing the data to disk.

url = https://dev.azure.com/tankerkoenig/tankerkoenig-data/_git/tankerkoenig-data?path=/prices/2022/07/2022-07-01-prices.csv

I am thinking about an approach like this:

import requests  import pandas as pd    r = requests.get(url)  df = pd.read_csv(r.content)  

Does anyone know if something like this is possible?

Getting access denied error while uploading file to amazon s3 using tranferutility

Posted: 18 Jul 2022 02:57 AM PDT

Getting the following error

D/com.amazonaws.request: Received error response: com.amazonaws.services.s3.model.AmazonS3Exception: Access Denied (Service: null; Status Code: 403; Error Code: AccessDenied; Request ID: ZFW34X6QRZEBNR23), S3 Extended Request ID: cCcs8EOdirUSRRd9MyoUcMWDTjEvFLN/cqSYbAT3NCLR/hDSjxI/ATNX63Y9cbyDNABi8MnTauY=

Without using tranfer utility code works fine.Kindly find the code here

            getApplicationContext().startService(new Intent(getApplicationContext(), TransferService.class));      AWSMobileClient.getInstance().initialize(getApplicationContext(), new Callback<UserStateDetails>() {          @Override          public void onResult(UserStateDetails result) {              Log.i("AWSMobile Clinet","initialised awsmobile client");              TransferUtility transferUtility=TransferUtility.builder().context(getApplicationContext())                      .awsConfiguration(AWSMobileClient.getInstance().getConfiguration())                      .s3Client(new AmazonS3Client(AWSMobileClient.getInstance()))                      .build();              try {                  File exampleFile = new File("/data/data/com.dieto.app/databases/user.db");                  TransferObserver uploadObserver=transferUtility.upload( "dietodata144832-                dev",number+".db",exampleFile);                }              catch (Exception e){                  Log.e("File load","File load failed"+e.toString());              }  

Deploy Angular Microfrontends on Wildfly

Posted: 18 Jul 2022 02:57 AM PDT

I am trying to deploy Microfrontends built on angular on Wildfly, the issue is the sub-applications are loading normally on there URL paths but are failing to load in the main Microfrontend container

HOC inside react hook, causes infinite rerenders

Posted: 18 Jul 2022 02:57 AM PDT

Im attempting to return a HOC component from within the hook.

Let's say I have a top level component as...

function Component(props){    //do something with props;    return <h1>Hello {props.title}</h1>  }  

And a hook which knows some props, and wants to free the user from providing those props

function useHook(){    //somehow get prop values at runtime(say title)    const title = //get from API call;    return (props) => <Component title={title} {...props}/>  }  

Any idea why infinite rerendering happens here? Should I be using useCallback?

How to access a variable outside of a function (access from a loop)?

Posted: 18 Jul 2022 02:57 AM PDT

I am working on accessing a variable outside of a function. Here is part of my code:

def main():      trigger_gmm() = 0      log = []      def spatter_tracking_cb(ts, clusters):          global trigger_gmm          for cluster in clusters:              log.append([ts, cluster['id'], int(cluster['x']), int(cluster['y']), int(cluster['width']),                          int(cluster['height'])])               if cluster['width'] >= 200:                   trigger_gmm = 1               else:                   trigger_gmm = 0               print(trigger_gmm)  while True:      print(trigger_gmm)      if trigger_gmm == 1:          print("print something")    if __name__ == "__main__":      main()  

I get the output like this:

NameError: name 'trigger_gmm' is not defined  

Any ideas would be much appreciated!

Remove The Object from Json

Posted: 18 Jul 2022 02:58 AM PDT

Please I Have 'active:1' In My Json But I Want To Remove "active:" and i want the output // 1

    [      {          "active": 1 // I Want This Result 1 Without active      }  ]  

// Output 1

This My Code

  return  Category::where('active' , $request -> active)->get('active'); // Output 1  

Guidance on the best way to create an API

Posted: 18 Jul 2022 02:58 AM PDT

I am looking on guidance for the best method or tools complete this task. I need to build an application that replaces all negative numeric values in a csv file with 0 and then return the modified CSV(I have already done this in Python)

But it needs to be accessible via a HTTP api interface where a user can upload a CSV file and then provide the user with the CSV output. Does anyone know the best set of tools or even the best programming languages to do these last two steps in?

Thanks for any help

How to add additional information into LSTM to predict future value?

Posted: 18 Jul 2022 02:59 AM PDT

When using LSTM to predict future value, it's easy to use past value as input and set future value as output.

Taking traffic flow prediction as an example, let's say that our sampling frequency is 20/hour, that is to measure the traffic flow every 3 mins.

We could use past 60 points(3-hour past data) to predict future value, just construct the data set and then fit into LSTM, and things would be done.

However, in this case, traffic flow prediction, besides past value, time is also an important features(i.e. what time it is).

Let's take another example, prediction of passenger flow. In this case, we could use past data to predict future passenger flow. In addition, I believe that features such as whether it's holiday, whether it's weekend, would have impact on future values.

So, in general:

I know some information about the specific future time/day

I also want to predict some quantity of that specific future time/day

How can I utilize that part of information, i.e., how to use information of future, along with the past data, to predict future quantity?

ValueError: Input 0 of layer "sequential_40" is incompatible with the layer: expected shape=(None, 5, 31, 10), found shape=(5, 31, 10)

Posted: 18 Jul 2022 02:58 AM PDT

I'm having issues setting up my model. Context: I have data on people that answered a certain survey and I need to classify them according to personal information (age, gender, etc) + answer pattern and I don't have any previous classes to work on. I am using It is as follows:

train_index <- sample(dim(dados_norm)[1], dim(dados_norm)[1] * .75, FALSE)  test_index <- seq(1, dim(dados_norm)[1], 1)[-train_index]    train_data <- dados_norm[train_index,]  test_data <- dados_norm[test_index,]    train_data <- to_categorical(train_data)    m0 <- keras_model_sequential()    m0 |>     layer_dense(units = 8, activation = "relu", input_shape = c(5, 31, 10))    m0 |> compile(    loss = 'categorical_crossentropy',    optimizer = 'adam',    metrics = 'accuracy'  )    m0 |> fit(    train_data,     train_data,    epochs = 200,     batch_size = 5,     validation_split = 0.2  )  

However, I'm getting the following error:

Traceback (most recent call last):    File "C:\Users\Hektor\AppData\Local\R-MINI~1\envs\R-RETI~1\lib\site-packages\keras\utils\traceback_utils.py", line 67, in error_handler      raise e.with_traceback(filtered_tb) from None    File "C:\Users\Hektor\AppData\Local\Temp\__autograph_generated_filesy5qz62i.py", line 15, in tf__train_function      retval_ = ag__.converted_call(ag__.ld(step_function), (ag__.ld(self), ag__.ld(iterator)), None, fscope)  ValueError: in user code:        File "C:\Users\Hektor\AppData\Local\R-MINI~1\envs\R-RETI~1\lib\site-packages\keras\engine\training.py", line 1051, in train_function  *          return step_function(self, iterator)      File "C:\Users\Hektor\AppData\Local\R-MINI~1\envs\R-RETI~1\lib\site-packages\keras\engine\training.py", line 1040, in step_function  **          outputs = model.distribute_strategy.run(run_step, args=(data,))      File "C:\Users\Hektor\AppData\Local\R-MINI~1\envs\R-RETI~1\lib\site-packages\keras\engine\training.py", line 1030, in run_step  **          outputs = model.train_step(data)      File "C:\Users\Hektor\AppData\Local\R-MINI~1\envs\R-RETI~1\lib\site-packages\keras\engine\training.py", line 889, in train_step          y_pred = self(x, training=True)      File "C:\Users\Hektor\AppData\Local\R-MINI~1\envs\R-RETI~1\lib\site-packages\keras\utils\traceback_utils.py", line 67, in error_handler          raise e.with_traceback(filtered_tb) from None      File "C:\Users\Hektor\AppData\Local\R-MINI~1\envs\R-RETI~1\lib\site-packages\keras\engine\input_spec.py", line 264, in assert_input_compatibility          raise ValueError(f'Input {input_index} of layer "{layer_name}" is '        ValueError: Input 0 of layer "sequential_40" is incompatible with the layer: expected shape=(None, 5, 31, 10), found shape=(5, 31, 10)  

What could be causing the error?

Implement the equation in Derivative function code(PLECS)

Posted: 18 Jul 2022 02:57 AM PDT

I am currently solving trying to implement the non linear equation in Plecs software in Derivative function code. Could anyone help me that how to write this equation in Derivative function code? I am attaching the image of the equation.

Till here I wrote the equation code

v_ds = (2.*v_ab*cos_0 + v_bc*(cos_0+sqrt(3.)*sin_0))*(1/3.);  v_qs = -(2.*v_ab*sin_0 + v_bc*(sin_0-sqrt(3.)*cos_0))*(1/3.);    plambda_md = (    (r_kd/L_lkd - r_s/L_ls) * i_ds    + w_r * i_qs    + (r_kd/L_lkd - r_fdr/L_lfdr) * i_fdr    - r_kd*L_md_inv/L_lkd * lambda_md    + w_r/L_ls * lambda_mq    + 1./L_ls * v_ds    + 1./L_lfdr * v_fdr    ) / (L_md_inv + 1./L_ls + 1./L_lfdr + 1./L_lkd);    plambda_mq = (    - w_r * i_ds    + (r_kq/L_lkq - r_s/L_ls) * i_qs    - w_r/L_ls * lambda_md    - r_kq*L_mq_inv/L_lkq * lambda_mq    + 1./L_ls * v_qs    ) / (L_mq_inv + 1./L_ls + 1./L_lkq);    pi_ds = (    - r_s * i_ds    + L_ls*w_r * i_qs    + w_r * lambda_mq    + v_ds    - plambda_md    ) / L_ls;    pi_qs = (    - L_ls*w_r * i_ds    - r_s * i_qs    - w_r * lambda_md    + v_qs    - plambda_mq    ) / L_ls;        pi_fdr = (    - r_fdr * i_fdr    + v_fdr    - plambda_md    ) / L_lfdr;  

Displaying images with JavaScript and HTML [closed]

Posted: 18 Jul 2022 02:57 AM PDT

I am doing Wallboard for our company and im having problems printing images.

I will get exact number from database currently still testing this with random number.

So what i want is a javascript function that will basically take the random number and display that many car images/icons. For example if random number is 3 i want it to print 3 images etc. Another problem is that i want the images to random scale based on how big the random number is i want it to fill in fullscreen always i don't want to scroll down because the program will run on TV.

Would love any help or tips.

I have tried multiple javascript functions etc i found on google and this is the closest one i found that works and does kinda what i need. This prints 1 image only tho. I have tried for looping window.onload with the randomNum variable and it never seemed to work. With this code i have also added <img src="" width="305" height="312" id="myPicture" alt="some image"> to my HTML document you can see down below.

window.onload = choosePic;    var myPix = new Array("slikaAvto.png");    function choosePic() {      var randomNum = Math.floor(Math.random() * 10);      document.getElementById("myPicture").src = myPix;        }  

.body {    background-color: #898787;    width: 100%;    height: 100%;  }    section.sredina {    text-align: center;  }    .div_visina {    height: 100%;  }    article {    position: absolute;    top: 50%;    left: 50%;    transform: translate(-50%, -50%);    width: 100%;    padding: 20px;  }    .container2 {    display: table;    width: 100%;    height: 100%;  }    .leva_triglav {    background-color: #ffffff;    position: absolute;    left: 0px;    width: 20%;  }    .desna_triglav {    background-color: #898787;    position: absolute;    right: 0px;    width: 80%;  }    .logo {    position: relative;    width: 100%;  }    .leva_avto {    background-color: #ffffff;    position: fixed;    left: 0;    width: 40%;  }    .desna_avto {    background-color: #898787;    position: fixed;    right: 0;    width: 60%;  }    .avto_slika {    height: 100%;    left: 0px;    width: 100%;  }    .moto_avto {    position: relative;    transform: rotate(-90deg);    left: -50%;    color: #3f3c3c;    font-size: 27px;    font-weight: 200;    letter-spacing: 2px;  }    .besedilo_normal {    font-family: Arial, Helvetica, sans-serif;    font-size: 40px;    font-weight: 200;    letter-spacing: 2px;    text-align: center;    text-shadow: 1px 1px 1px #3f3c3c;    color: #ffffff;  }    .kilometri {    font-family: Arial, Helvetica, sans-serif;    font-size: 45px;    font-weight: 200;    letter-spacing: 1px;    text-shadow: 1px 1px 1px #3f3c3c;    color: #3f3c3c;    padding-bottom: 15%;  }    .besedilo_rdece {    font-family: Arial, Helvetica, sans-serif;    font-size: 70px;    font-weight: 200;    letter-spacing: 5px;    text-align: center;    text-shadow: 1px 1px 1px #3f3c3c;    color: #3f3c3c;  }    .sredinsko {    display: table;    height: 100%;    width: 100%;    text-align: center;    padding: 50px;  }    .crta {    width: 75%;    border: 2px solid #ffffff;  }
<html>    <head>    <link rel="stylesheet" href="style.css">    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>    </head>    <body class="body">    <section class="container2 sredina">      <div class="leva_avto div_visina">        <img src="slikaAvto.png" class="avto_slika">      </div>      <div class="desna_avto div_visina">        <article>          <div class="sredinsko">            <p class="besedilo_normal"> Cars sold tonight: </p>            <p class="besedilo_rdece"> Display images based on number of vehicles sold tonight </p>          </div>          <hr class="crta">          <div class="sredinsko">            <p class="besedilo_normal"> Cars sold this month: </p>            <p class="besedilo_rdece"> Display images based on number of vehicles sold tonight </p>            </div>        </article>      </div>    </section>    </body>    </html>

Is there a step-by-step explanation of ML.NET model builder generated code? [closed]

Posted: 18 Jul 2022 02:57 AM PDT

I am learning ML.NET and specifically the model builder feature. It's very simple to use but I am interested in understanding how the code it generates works. When searching online it only gives rewrites of original Microsoft guide on how to use the model builder, but not how the generated code works. Maybe there is someone who made it and it's just very hard to find. If possible I am particularly interested in Image Classification model builder code.

Reduce of empty array with no initial value, how to sort function with two parameters from highest to lowest value

Posted: 18 Jul 2022 02:58 AM PDT

I am running npm test for my code and I am failing the third test out of six test. I've tried to sort it with the following :

sumAll.sort(function(min,max)) {      return max - min;  }        

But it's not working. I tried to add conditionals in the code by using 'if (min > max )... else if ( min < max )' but it still don't work too. I tried adding '0' on the reducer variable 'accumulator + currentValue, 0' but still it's not working. Is there any way how can I sort the sumAll function so it's still working even if it use a higher 'min' arguments than the 'max' argument ? Please help.

const sumAll = function( min, max ) {      let fullArr = [];      let sum = 0;         const reducer = (accumulator, currentValue) => accumulator + currentValue;         // let highestToLowest =        for ( let i = min; i <= max; i++) {          fullArr.push(i);      }        // sumAll.sort(function(min,max)) {      //     return max - min;      // }                // // let lowestToHighest = fullArr.sort((a, b) => a - b);      // let highestToLowest = fullArr.sort((min, max) => max-min);        sum = fullArr.reduce(reducer);        return sum;  }    sumAll(1,4);  sumAll(123, 1);        <----------  I failed on this function call saying it 'Reduce                                       of empty array with no initial value....   

---------------------------- Jest code --------------------------

const sumAll = require('./sumAll')    describe('sumAll', () => {    test('sums numbers within the range', () => {      expect(sumAll(1, 4)).toEqual(10);    });    test('works with large numbers', () => {      expect(sumAll(1, 4000)).toEqual(8002000);    });    test('works with larger number first', () => {      expect(sumAll(123, 1)).toEqual(7626);    });    test.skip('returns ERROR with negative numbers', () => {      expect(sumAll(-10, 4)).toEqual('ERROR');    });    test.skip('returns ERROR with non-number parameters', () => {      expect(sumAll(10, "90")).toEqual('ERROR');    });    test.skip('returns ERROR with non-number parameters', () => {      expect(sumAll(10, [90, 1])).toEqual('ERROR');    });  });  

How to replace only first instance of a value in a list which consists of multiple groups?

Posted: 18 Jul 2022 02:58 AM PDT

I have 2 lists and I want to change the elements of 2nd list based on groups of 1st list. Example I have:-

a=[1,1,1,2,2,2,2,3,3,3,4,4,4,5,5]  b=['','','l2','22','','','','','l3','l5','','l4','','','']  

Both the lists have same number of elements. For every group of elements in 'a list I only want to replace the value in list b at index 1 of each group present in list a.

Conditions : Only replace the value in list b if the element at that index(of list a) is empty or '' in list b.

If the first value in list b with respect to group of values in list a at index 1 is not empty dont change the further values i.e If the list b has already some value present at index 1 dont replace any value of that group with respect to indexes in list a.

For example: a=[1,1,1,1,2,2,2,2]=b['','','l2,'l3','l4,'','',''] then expected output is b=['value','','l2','l3','l4','','','']

Expected Output:

['value', '', 'l2', 'l3', '', '', '', 'value', 'l3', 'l5', 'value', 'l4', '', 'value', '']  

Approach that I got suggested earlier by @Chris (which is correct) but now I have a different requirement:

a=[1,1,1,2,2,2,2,3,3,3,4,4,4,5,5]  b=['','','l2','l3','','','','','l3','l5','','l4','','','']    from itertools import groupby  g = groupby(a)    i = 0  for group,data in g:      n = len(list(data))      b[b[i:i+n].index('')+i] = 'value'      i+=n                print(b)  

Output I'm getting:

['value', '', 'l2', 'l3', 'value', '', '', 'value', 'l3', 'l5', 'value', 'l4', '', 'value', '']  

How to exclude Weekend and compare current dates in MYSQL

Posted: 18 Jul 2022 02:57 AM PDT

I'm comparing data with current date - 1 and -2 dates in my table. Sample Data :

Name  cnt  Dates  Mills 20    2022-07-15  Mills 15    2022-07-14  Mills 10    2022-07-13  

I have written query where it compares current date - 1 and Current date - 2

SELECT Name,Date,`T-2`,`T-1`,Diff      FROM (  SELECT  T.Name  ,T.Date,T.`T-1`,TT.`T-2`,TT.`T-2` - T.`T-1`  AS Diff FROM   (select  Name, Date, cnt AS 'T-1' from Acct where date = curdate() - 1 )T  INNER JOIN   (select  Name, Date, cnt AS 'T-2' from Acct where date = curdate() - 2)TT  ON T.Name = TT.Name )T  

Now when I execute this query Current date (2022-07-18) it is taking -1 as 2022-07-17 and -2 as 2022-07-16. I want to exclude weekends and compare those with Friday and Thursday .

Out put :

Name   T-1   T-2  DIFF   Mills   20   15    5  

TypeError: Attempting to change the setter of an unconfigurable property. phantomjs + vue 3

Posted: 18 Jul 2022 02:57 AM PDT

My project is in vuejs. I have written simple script to take screenshot of login page using phantomjs. But, No luck :-(

I have been searching solution for the above error from last 4 days.

Code :

'use strict'    var page = require("webpage").create();    page.open("http://localhost:8080/login", function () {    setTimeout(() => {      page.render("login.png");      phantom.exit();    }, 5000);  });    

Result :

As result, I am getting a blank image with a loading symbol.

I am using ubuntu 20.04 phantomjs version is 2.1.1

Please help me to resolve this error. Thanks in advance :-)

SQL Exception while saving to database - Spring MySQL Auto Generated Id

Posted: 18 Jul 2022 02:58 AM PDT

I have created a table. I want its id to increment automatically with every record. So, i selected id as Auto Incremental while creating table in MySQL.

Here my table is:

Groups Table

But it gives error while saving to database. The error is : "could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet"

My entity class:

@Entity  @Data  @Table(name="groups")  public class GroupsEntity {    @Id  @GeneratedValue(strategy = GenerationType.IDENTITY)  @Column(name = "GROUP_ID")  private int groupId;    @Column(name = "GROUP_NAME")  private String groupName;    @Column(name = "GROUP_ICON")  private String groupIcon;    @Column(name = "USER_ID")  private int userId;  }  

My Service class:

    public GroupsResponse setGroups(GroupsRequest request){      int userId = request.getUserId();      GroupsEntity groupsEntity = new GroupsEntity();      groupsEntity.setUserId(userId);      groupsEntity.setGroupIcon(request.getGroupIcon());      groupsEntity.setGroupName(request.getGroupName());      GroupsResponse response = new GroupsResponse();      try{          groupsRepository.save(groupsEntity);      } catch (Exception e){          log.error("There is an error while saving groups to Groups table. userId: " + userId);          response.setStatus(false);          response.setMessage(e.getMessage());          return response;        }      response.setStatus(true);      response.setMessage("SUCCESS");      return response;  }  

My repository class:

@Repository  public interface GroupsRepository extends JpaRepository<GroupsEntity, Integer> {    List<GroupsEntity> findByUserId(int userId);  }  

And my request is below:

{      "groupName": "abc",      "groupIcon": "",      "userId": 123  }  

Auto generation for id is working when i insert new rows with insert into query manually. But not working with Spring.

It says "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'groups (group_icon, group_name, user_id) values (' ', 'abc', 123)" in logs.

How can i fix this? Thank you.

EDIT:

I have solved the problem.

There was a warning in logs: "SQL Error: 1064, SQLState: 42000". That means column names or table name may be reserved words in MySQL.

My table's name was "groups" which is a reserved word in MySQL too. When i changed the name as "groups_table", it worked.

How to set a page its state from a React Component?

Posted: 18 Jul 2022 02:58 AM PDT

On a React page I have:

<a      data-tab="settings"      onClick={() =>          this.setState({ active_tab: "settings" })      }  >      <i style={{ backgroundImage: "url(/icons/settings.svg)" }} />      <span>To settings</span>  </a>  

How can I convert this to a Component?

On the React page I replaced the above code block with:

import MyButton from "../components/MyButton/";  MyButton({      tab: "settings",      icon: "/icons/settings.svg",      label: "To settings",  })  

And I created the Component:

import React from "react";    const MyButton = (props) => {      const { tab, icon, label } = props;        return (          <div className="tab-button">              <a                  data-tab={tab}                  // next line doesn't work...                  onClick={() =>                      this.setState({ active_tab: {tab} })                  }              >                  <i style={{ backgroundImage: `url(${icon})` }} />                  <span> {label} </span>              </a>          </div>      );  };    export default MyButton;  

It correctly displays the icon and the label.

But it doesn't change the state of active_tab on the React page. Clicking on the link generates the error _this is undefined.

What am I doing wrong? How can I change the state on the React page from this Component?


Update: I've tried it with a Class setup:

On React page:

import React, { Component, Fragment } from "react";  import MyButton from "../components/MyButton/";    return (      <Fragment>          ...          {              isAdmin ? (                  <MyButton                      tab="settings"                      icon="/icons/settings.svg"                      label="To settings"                  />              ) : ("")          }          ...      </Fragment>  

Component:

class MyButton extends Component {      constructor(props) {          super(props);          this.state = {              tab: props.tab,              icon: props.icon,              label: props.label,          };      }      render() {          const { tab, icon, label } = this.state;          return (              <div className="tab-button">                  <a                      data-tab={tab}                      onClick={() =>                          this.setState({ active_tab: {tab} })                      }                  >                      <i style={{ backgroundImage: `url(${icon})` }} />                      <span>{label}</span>                  </a>              </div>          )      }  }    export default MyButton;  

The result is still the same: the label and icon show up, but clicking on it doesn't work. This time it doesn't generate an error but just nothing happens, meaning the state on the Page hasn't changed.


I've also tried it with a Hook setup:

On React page:

import MyButton from "../components/MyButton/";    MyButton({      tab: "settings",      icon: "/icons/settings.svg",      label: "To settings",  })  

React Component file:

import React, { useState } from "react";    const MyButton = (tab, icon, label) => {      // "data" is 'starting' position.      const [active_tab, setActive_tab] = useState("data");      return (          <button              data-tab={ tab }              // next line should change the local state on the page for 'active_tab'              onClick={ () => setActive_tab({ tab }) }          >              <i style={{ backgroundImage: `url(${icon})` }} />              <span> { label } </span>      );  };    export default MyButton;  

This generates two errors:

  • Invalid hook call. Hooks can only be called inside of the body of a function component.
  • 'active_tab' is declared but its value is never read.ts

I need to fix checkbox selection issue in antd tree component

Posted: 18 Jul 2022 02:57 AM PDT

I am using an antd tree component I have customized some of the code according to my use case I have a child list under one parent checkbox what happens if I select parent all under that parent list get checks but I am also shown count of list present under it in every parent list of the child so if I select Watchlists every check box get selected but child check box list count not get updated if I click that particular child Data List then count will get an update but if I uncheck parent Watchlists then only Data List not get uncheck I need to make like if I click on parent then under that all list will update with that child count for both cases right now I don't have any idea how I can fix this if anybody knows anyway, also I added a complete code sandbox link below...

onCheck function I am some conditions that I am using to update data the first case is I have one search bar after search in the search bar if I select or unselect any list that remaining count will update accordingly list present that I am setting for the count I am not doing anything in for search state in that mean whatever change will be done in check function need to check if I select parent all child under that parent get selected and if any one child I unselect that parent check also get updated both that case need to check if onCheck function need to updated for also search bar case

this is my oncheck code that perform check uncheck     const onCheck = React.useCallback(      (checkedKeysValue, e) => {        if (e.checked) {          if (e.node?.children?.length) {            setCheckedKeys(              _.union(                checkedKeys,                _.cloneDeep([...e.node.children.map((child) => child.key)])              )            );          } else {            setCheckedKeys(_.union(checkedKeys, [e.node.key]));          }        } else {          if (e.node?.children?.length) {            setCheckedKeys(              _.union(                checkedKeys.filter((item) => {                  return (                    item !== e.node.key &&                    !e.node.children.filter((child) => child.key === item).length                  );                })              )            );          } else {            setCheckedKeys(              _.cloneDeep(checkedKeys.filter((item) => item !== e.node.key))            );          }        }      },      [checkedKeys, setCheckedKeys]    );  
const Demo = ({ alterCountsCalculation = {} }) => {    const [expandedKeys, setExpandedKeys] = useState([]);    const [checkedKeys, setCheckedKeys] = useState([]);    const [selectedKeys, setSelectedKeys] = useState([]);    const [autoExpandParent, setAutoExpandParent] = useState(true);    const [searchValue, setSearchValue] = useState("");    const [checkedKeysCount, setCheckedKeysCount] = useState(0);    const [tree, setTree] = useState(treeData);      const onExpand = (expandedKeysValue) => {      console.log("onExpand", expandedKeysValue); // if not set autoExpandParent to false, if children expanded, parent can not collapse.      // or, you can remove all expanded children keys.        setExpandedKeys(expandedKeysValue);      setAutoExpandParent(false);    };    React.useEffect(() => {      let alteredCount = 0;      let count = checkedKeys.filter((item) => {        if (Object.keys(alterCountsCalculation).includes(item)) {          alteredCount = alteredCount + alterCountsCalculation[item];          return false;        }        return !treeData.filter((node) => node.title == item).length;      }).length;      setCheckedKeysCount(count + alteredCount);    }, [checkedKeys, treeData, alterCountsCalculation]);      const onCheck = React.useCallback(      (checkedKeysValue, e) => {        if (e.checked) {          if (e.node?.children?.length) {            setCheckedKeys(              _.union(                checkedKeys,                _.cloneDeep([...e.node.children.map((child) => child.key)])              )            );          } else {            setCheckedKeys(_.union(checkedKeys, [e.node.key]));          }        } else {          if (e.node?.children?.length) {            setCheckedKeys(              _.union(                checkedKeys.filter((item) => {                  return (                    item !== e.node.key &&                    !e.node.children.filter((child) => child.key === item).length                  );                })              )            );          } else {            setCheckedKeys(              _.cloneDeep(checkedKeys.filter((item) => item !== e.node.key))            );          }        }      },      [checkedKeys, setCheckedKeys]    );      const onSelect = (selectedKeysValue, info) => {      console.log("onSelect", info);      setSelectedKeys(selectedKeysValue);    };    React.useEffect(() => {      const checked = [];        treeData.forEach((data) => {        data.children.forEach((item) => {          if (item.checked) {            checked.push(item.key);          }        });      });      setCheckedKeys(checked);    }, []);    function sleep(ms) {      return new Promise((resolve) => setTimeout(resolve, ms));    }    React.useEffect(() => {      if (searchValue) {        const filteredData = filteredTreeData(          treeData,          searchValue,          checkedKeys,          setExpandedKeys        );        setTree([...filteredData]);      } else {        setTree(treeData);      }    }, [searchValue, checkedKeys]);      return (      <div>        {JSON.stringify(checkedKeysCount)}        <Search          style={{ marginBottom: 8 }}          placeholder="Search"          onChange={(e) => {            setSearchValue(e.target.value);          }}        />        <Tree          checkable          onExpand={onExpand}          titleRender={(nodeData) => {            const index = nodeData.title              .toLowerCase()              .indexOf(searchValue.toLowerCase());            const beforeStr = nodeData.title.substr(0, index);            const afterStr = nodeData.title.substr(index + searchValue?.length);            const searchedString = nodeData.title.substr(              index,              searchValue?.length            );            let countSelectedChilds = 0;            if (nodeData.children?.length) {              nodeData.children.forEach((child) => {                if (checkedKeys?.includes(child.key)) {                  countSelectedChilds++;                }              });            }            return index > -1 ? (              <span>                {beforeStr}                <span className="site-tree-search-value">                  {searchedString}                </span>{" "}                {afterStr}{" "}                {countSelectedChilds ? <span>({countSelectedChilds})</span> : ""}              </span>            ) : (              <span>{nodeData.title}</span>            );          }}          autoExpandParent={true}          onCheck={onCheck}          checkedKeys={checkedKeys}          expandedKeys={expandedKeys}          treeData={tree}        />      </div>    );  };  

CodeSandBox Link

JAX Tridiagonal Jacobians

Posted: 18 Jul 2022 02:59 AM PDT

What is the most efficient implementation of a scalable autonomous tridiagonal system using JAX?

import jax as jx  import jax.numpt as jnp  import jax.random as jrn  import jax.lax as jlx    def make_T(m):      # Create a psuedo-random tridiagonal Jacobian and store band      T = jnp.zeros((3,m), dtype='f8')      T = T.at[0, 1:  ].set(jrn.normal(jrn.PRNGKey(0), shape=(m-1,)))      T = T.at[1,  :  ].set(jrn.normal(jrn.PRNGKey(1), shape=(m  ,)))      T = T.at[2,  :-1].set(jrn.normal(jrn.PRNGKey(2), shape=(m-1,)))      return T    def make_y(m):      # Create an pseudo-random state array      y = jrn.normal(jrn.PRNGKey(3), shape=(m  ,))      return y    def calc_f_base(y, T):      # Calculate the rate given the current state      f = T[1,:]*y      f = f.at[ 1:  ].set(f[ 1:  ]+T[0, 1:  ]*y[  :-1])      f = f.at[  :-1].set(f[  :-1]+T[2,  :-1]*y[ 1:  ])      return f    m = 2**22 # potentially exhausts resources  T = make_T(m)  y = make_y(m)    calc_f = ft.partial(calc_f_base, T=T)    

Using jax.jacrev or jax.jacfwd will generate a full Jacobian which limits the size of the system.

One attempt to overcome this limitation is as follows

def calc_jacfwd_trid(calc_f, y):      # Determine the Jacobian (forward-mode) tridiagonal band        def scan_body(carry, i):          t, T = carry          t = t.at[i-1].set(0.0)          t = t.at[i  ].set(1.0)                    f, dfy = jx.jvp(calc_f, (y,), (t,))                    T = T.at[2,idx-1].set(dfy[idx-1])          T = T.at[1,idx  ].set(dfy[idx  ])          T = T.at[0,idx+1].set(dfy[idx+1])            return (t, T), None        # Initialise      m = y.size      t = jnp.zeros_like(y)      T = jnp.zeros((3,m), dtype=y.dtype)        # Differentiate wrt y[0]      t = t.at[0].set(1.0)      f, dfy = jx.jvp(calc_f, (y,), (t,))      idxs = jnp.array([1,0]), jnp.array([0,1])      T = T.at[idxs].set(dfy[0:2])        # Differentiate wrt y[1:-1]      (t, T), empty = jlx.scan(scan_body, (t,T), jnp.arange(1,m-1))        # Differentiate wrt y[-1]      t = t.at[m-2:].set(jnp.array([0.0,1.0]))      f, dfy = jx.jvp(calc_f, (y,), (t,))      idxs = jnp.array([2,1]), jnp.array([m-2,m-1])      T = T.at[idxs].set(dfy[-2:])        return T    

which permits

T = jacfwd_trid(calc_f, y)    df = jrn.normal(jrn.PRNGKey(4), shape=y.shape)  dx = jlx.linalg.tridiagonal_solve(*T,df[:,None]).flatten()    

Is there a better approach and/or can the time complexity of calc_jacfwd_trid be reduced further?

How can I attach a file outside the package to my Python package

Posted: 18 Jul 2022 02:58 AM PDT

I have a web application that displays the ABOUT.md file of the project. The project has the following file tree:

project_folder/    main_package/      assets/icon.png      __init__.py      app.py    .gitignore # And other files    README.md    ABOUT.md    setup.cfg    setup.py  

In app.py I have a webserver that renders and provides the contents of the file README.md. It has a code like this:

from main_package import __file__ as mpfile    # First parent is just the folder where __init__.py is located.  ABOUT_MD = Path(mpfile).parent.parent / 'ABOUT.md'  

This works without building, but if I build the wheel and install it in other environment, it stops working.

I modified the config in setup.cfg so it includes the ABOUT.md

[options.package_data]  main_package =     ../ABOUT.md    assets/*  

But this copies the file to the root of site_packages, which I think is a bit dirty.

I want to keep the ABOUT.md file available in the root folder, so it remains very accessible through GitHub, but I also want to be able to build and publish my package.

Idea:

Modify the build system to copy the ABOUT.md from the root to main_package/assets/ABOUT.md while creating the wheel. Then, add an if inside app.py that loads the correct file depending on where it is. The problem is that I don't know how to make the build system copy the file to this path.

Update 2022-07-18: Why not linking?

In response to @Leander

If we use a Hard Link, that info is not propagated through the version control system (git), so It will appear to be two different files in every other computer, and we would have to sync the data somehow (with hooks or any kind of system), plus it would take double space in disk.

If we use a Symlink, the used space is reduced, but the web view of the repositories can't follow symlinks, so the ABOUT.md ends unusable (it just displays the plaintext path of the symlink).

Cloud Tasks are stuck in queue and are not executed

Posted: 18 Jul 2022 02:58 AM PDT

I am using Cloud Functions to put tasks into Cloud Tasks Queue and invoke a service (worker) function. Both the task generator and task Handler functions are deployed to Cloud Functions. This is my createTask.js:

const {CloudTasksClient} = require('@google-cloud/tasks');  const client = new CloudTasksClient();    exports.createTask = async (req, res) =>  {      const location = 'us-central1';    const project = 'project-id';    const queue = 'queueid';    const payload = 'Hello, World!';    const parent = client.queuePath(project, location, queue);  const task = { appEngineHttpRequest: {                        httpMethod: 'POST',              relativeUri : '/log_payload'},    const [ response ] = await tasksClient.createTask({ parent: queuePath, task })      if (payload) {      task.appEngineHttpRequest.body = Buffer.from(payload).toString('base64');    }    let inSeconds = 0 ;    if (inSeconds) {      // The time when the task is scheduled to be attempted.      task.scheduleTime = {        seconds: inSeconds + Date.now() / 1000,      };    }      console.log('Sending task:');    console.log(task);    // Send create task request.    const request = {parent: parent, task: task};    const [response] = await client.createTask(request);    const name = response.name;    console.log(`Created task ${name}`);    res.send({message : "Ok"});  }  

server.js

const express = require('express');  const app = express();  app.enable('trust proxy');  app.use(bodyParser.raw({type: 'application/octet-stream'}));  app.get('/', (req, res) => {    // Basic index to verify app is serving    res.send('Hello, World!').end();  });  app.post('/log_payload', (req, res) => {    // Log the request payload    console.log('Received task with payload: %s', req.body);    res.send(`Printed task payload: ${req.body}`).end();  });  app.get('*', (req, res) => {    res.send('OK').end();  });  app.listen(3000 , () => {    console.log(`App listening on port`);    console.log('Press Ctrl+C to quit.');  });   

When I run trigger the task generator function via HTTP trigger in Postman, the task is added to the queue but it stays there forever. The queue looks like this:

enter image description here

The logs of the handler task show it was never triggered. The task in the queue cannot reach its handler. The logs of task in queue looks like this:

enter image description here

The task is failed and is in the queue: enter image description here

Telethon receive location from user

Posted: 18 Jul 2022 02:57 AM PDT

What is a proper way to listen to "send location" messages from the user? My solution is to filter out messages by type of their media (process_location):

@bot.on(events.NewMessage(pattern=commands('/start')))  async def send_welcome(event: events.NewMessage.Event):      await event.respond("Hello, I'm your helper bot!", buttons=[          Button.request_location('Send location to detect timezone', resize=True),      ])      @bot.on(events.NewMessage(func=lambda e: isinstance(e.media, MessageMediaGeo)))  async def process_location(event: events.NewMessage.Event):      geo_data = event.media      ...  

But is there a better way to distinguish location messages? Couldn't find it in the docs.

How can I make the live serve to be faster?

Posted: 18 Jul 2022 02:57 AM PDT

After upgrading to Angular 6, the ng serve in watch mode is very slow. Here is how I am running it locally

ng serve --c=dev --watch  

It is taking forever to build and serve simple changes in single files. It is as if it is doing a regular ng build --prod

Did anyone face this issue? Am I doing anything wrong?

How can I get woocommerce order number using email or phone number?

Posted: 18 Jul 2022 02:59 AM PDT

Currently I am using

$order = new WC_Order($order_id);   

(using a web form)for fetching customer details related to that order id. I just want to be able to fetch customer details like billing and shipping address using customer's billing email or billing phone from database. thank you in advance. :)

Running a single test in maven -> No tests were executed

Posted: 18 Jul 2022 02:59 AM PDT

When I run a single test in Maven with this command:

mvn test -Dtest=InitiateTest  

I'm getting the following result:

No tests were executed!  

It worked a couple of minutes ago, but now it stopped working for some reason. I tried running mvn clean a couple of times before running the test, it doesn't help.

The test looks like this:

import org.openqa.selenium.*;  import org.openqa.selenium.firefox.FirefoxDriver;  import org.openqa.selenium.support.ui.Select;  import org.junit.After;  import org.junit.Before;  import org.junit.Test;    public class InitiateTest {        public static FirefoxDriver driver;        @Before          public void setUp() throws Exception {              driver = new FirefoxDriver();      }        @Test      public void initiateTest() throws Exception {              driver.get("http://localhost:8080/login.jsp");              ...      }        @After      public void tearDown() throws Exception {          driver.close();      }  }  

UPDATE:

It's caused by adding this dependency to POM:

<dependency>     <groupId>org.seleniumhq.selenium</groupId>     <artifactId>selenium</artifactId>     <version>2.0b1</version>     <scope>test</scope>  </dependency>  

When I remove it, everything works fine. Everything works fine even when I add these two dependencies instead of the previous one:

<dependency>     <groupId>org.seleniumhq.selenium</groupId>     <artifactId>selenium-support</artifactId>     <version>2.0b1</version>     <scope>test</scope>  </dependency>  <dependency>     <groupId>org.seleniumhq.selenium</groupId>     <artifactId>selenium-firefox-driver</artifactId>     <version>2.0b1</version>     <scope>test</scope>  </dependency>  

This is weird.

No comments:

Post a Comment