Tuesday, August 24, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


AWS Node.js Lambda: Promise reject does not return custom error, resolve works

Posted: 24 Aug 2021 08:27 AM PDT

I'm running a AWS Lambda function in Node.js 14, bound to a REST API in API Gateway with LAMBDA_PROXY.

Consider this simplified Pseudo Code for index.js:

exports.handler = async function (event, context) {      if (event.body.myParam === '1') {          // Works!          return {              statusCode: 302,              headers: {                  Location: 'https://iam.aredire.ct'              }          };      } else if (event.body.myParam === '2') {          // Works! 403 - {"message":"You are not allowed to do that!"}          return {              statusCode: 403,              body: JSON.stringify({                  message: 'You are not allowed to do that!'              })          };      } else if (event.body.myParam === '3') {          const jwt = require('jsonwebtoken');          const token = 'ey...';          const pubKey = '-----BEGIN PUBLIC KEY----- ...';            // Some promise          return new Promise(function (resolve, reject) {              // Some async call              jwt.verify(token, pubKey, function (err, decoded) {                  if (err) {                      // gets logged                      console.log(err);                        // 502 - {"message": "Internal server error"}                      return reject({                          statusCode: 403,                          body: JSON.stringify({                              message: 'No valid token'                          })                      });                        // 502 - {"message": "Internal server error"}                      return reject(JSON.stringify({                          statusCode: 403,                          body: {                              message: 'No valid token'                          }                      }));                  }                  // Works! 200 - {"message":"Works!"}                  resolve({                      statusCode: 200,                      body: JSON.stringify({                          message: 'Works!'                      })                  });              });          });      }  }  

Please see the comments in the code snippets. Do you have any idea why resolve() and return work as expected but reject() always returns 502 - {"message": "Internal server error"}? I want that the requester actually gets a 403 - {"message": "No valid token"}?

I read about JSON.stringifying the whole error object, but that does not help.

Cloudwatch raises this error:

ERROR   Invoke Error      {      "errorType": "Error",      "errorMessage": "{\"statusCode\":403,\"body\":{\"message\":\"No valid token\"}}",      "stack": [          ...      ]  }  

Convert data.frame to a geo-spatial data class

Posted: 24 Aug 2021 08:27 AM PDT

I want to convert csv data.frame about global terrorism to geo-spatial data class for leaflet() work. Which code should I use?

Function Call Issues

Posted: 24 Aug 2021 08:27 AM PDT

please can anyone tell me why the showUsers() function below isn't executed? the function is supposed to output the array items in the console but nothing seems to happen when i call it. it is only executed if you call it in the addData() function.

const doubleButton = document.getElementById('double');  const showMillionaireButton = document.getElementById('show-millionaires');  const sortButton = document.getElementById('sort');  const calculateWealthButton = document.getElementById('calculate-wealth');    const nameHolder = document.querySelector('#main h2');  const netWorthHolder = document.querySelector('#main span');    let data = [];    const getRandomUser = async () => {      const res = await fetch('https://randomuser.me/api');      const data = await res.json();      const user = data.results[0];        const newUser = {          name: `${user.name.first} ${user.name.last}`,          netWorth: Math.floor(Math.random() * 1000000)      }            addData(newUser);  }    const addData = (obj) => {      data.push(obj);  }    getRandomUser();  getRandomUser();  getRandomUser();    const showUsers = () => {      data.forEach((user) => {          console.log(user)      })  }  showUsers();  

showUsers() would only run when it is added in the addData() function

Plotting a two variable function

Posted: 24 Aug 2021 08:27 AM PDT

I am trying to plot a two variable function. I saw several examples and followed exactly what they did. but I do not know how to fix this error? Any help will be appreciated. if Z.ndim != 2: AttributeError: 'Mul' object has no attribute 'ndim' here is my codes: import sympy as sp enter code here`import math import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm #(imports color map tools) r1,r2,r, labda,sigma, sigmalabda, X, Y, x, y, z, l, I, P = sp.symbols("r1,r2,r, labda,sigma, sigmalabda, x, X1, X2, y,z, l, I, P")

Kb = 1.38*10**(-23) #Boltzmann's constant  T = 293 #Room temperature(Kelvin)  labda = l  labda = 89  I = 304.4  sigma = 7.63*10**(-18)  #P = 133.322 #partial pressure of Oxygen (pascals) or (100militorr)    #density of Oxygen  n = (P/(Kb * T))  print('n: ', n)  print('pi: ', math.pi)    #Absorption coefficient  K = (1/(n*sigma))  print('K: ', K)      def f(r, P):      return (304.4)*(sp.exp((r*293*1.38*10**(-23))/(P*7.63*10**(-18))))  r = np.linspace(1, 11, 50) #from 1cm to 100cm  P = np.linspace(133.322, 66661.2, 100) #from 1Torr to 500Torr  #P = np.linspace(1, 500, 100) #from 1Torr to 500Torr  X, Y = np.meshgrid(r, P) #create an array containing all values pairs(ri, Pi)  Z = f(X, Y)  #Phi = np.array(r, P)  #Z = (304.4)*(sp.exp((r*293*1.38*10**(-23))/(P*7.63*10**(-18))))  fig = plt.figure()  ax = plt.axes(projection = "3d")  ax.plot_surface(X, Y, Z, rstride = 1, cstride = 1, cmap = "jet", edgecolor = "none")  plt.xlabel('r')  plt.ylabel('P')  ax.set_title("surface")  plt.show()  

why doesn`t work time sleep with the GUI?

Posted: 24 Aug 2021 08:27 AM PDT

it works with print("something"), but not with the GUI

def threads(): global text_00, text_10, bttn_00, bttn_80, bttn_81, bttn_texte

if bttn_80["text"] == bttn_81["text"]:      text_00.set(random.choice(bttn_texte))      time.sleep(1)      text_10.set(bttn_00["text"])      time.sleep(1)      text_80.set(bttn_00["text"])  

Cumulative variable to subtract over and over again until it reaches 0 value

Posted: 24 Aug 2021 08:27 AM PDT

I need help with loops in C++. Suppose I have 10 people, represented by a vector of length 10, each of them with a certain age. I want to select only people with age<12, and subtract to their age a fixed value age_fixed. It looks very simple with a for loop:

vector<float> diff_ages(0);  vector<float> ages {1.2, 7.3, 13.9, 17.8, 45., 72.3, 12.1, 100.3, 6.7, 88.2};  double age_fixed=8.1;    for (auto i=0;i<ages.size();i++){    if (ages[i]<12){        diff_ages.push_back(ages[i]-age_fixed);    }  }    

Now I want to complicate things:

  • if the difference between ages[i] and age_fixed is greater that 0, I want to put the difference in diff_ages, as usual;
  • if the difference is lower than 0, e.g. for ages[0], ages[1], ages[8], I want to put 0 in diff_ages, and use a cumulative variable cum_age where I sum the exceeding difference (in abs value); if this cumulative variable is greater than 0 at the end of the loop over the 10 ages (in my case cum_age=9.1 at the end of the first loop), I want to restart the loop again and again, subtracting the values accumulated in cum_age from ages[i], until cum_ages becomes 0.

Any idea on how to do that? I think I should use a while loop, but I'm not very familiar with it, I usually use for loops.

How to locate user location to map through ip address in python folium?

Posted: 24 Aug 2021 08:27 AM PDT

I am using Django REST Framework. Now I can Access User IP from the request of user using django-ipware.

from ipware import get_client_ip  def getlocation(request):      client_ip, is_routable = get_client_ip(request)  

It provides me the IP address of the request from where user is accessing. Now I want to find out latitude and longitude of that IP through which I can place the user location on the folium map.

map1 = folium.Map(location=[latitude,longitude], zoom_start=12, control_scale=True,prefer_canvas=True)    folium.CircleMarker(location = [latitude,longitude],radius = 20, popup= 'Here You Are',fill=True,fill_color="#3186cc",).add_to(map1)    folium.Marker([latitude,longitude], popup ='Your Location').add_to(map1)  

So How can I get The Latitude and Longitude??

Save correctly in PDF to Drive a Google Sheet

Posted: 24 Aug 2021 08:27 AM PDT

I am developing a script under Sheet allowing :

  • send an email with a pdf copy of the sheet attached
  • save this sheet in pdf in my Drive (defined with the id of the folder)

I succeeded without any problem for the first part of the script. For the second part, I also succeeded in making this backup. However, the information present in this one does not suit me. Indeed, the images are not transferred in the file (I have "cellimage" which appears instead) and the data do not correspond to those present in my Sheet. Indeed, they are rounded to 3 digits after the comma in my sheet while in the backup, there is no rounding.

I would have liked to have the same file as the one that is attached to the email. I searched hard but I could not find a code to save my attachment in the drive.

Here is the link to the file.

Here is the function that allows you to send the mail :

function envoiMail() {    // Déclaration des constantes    const classeur = SpreadsheetApp.getActiveSpreadsheet();    const feuille = classeur.getSheetByName('SYNTHESE');      // Déclaration des variables    var semaine = feuille.getRange('B5').getValue();    var annee = feuille.getRange('B4').getValue();      var auditeurMail = Session.getActiveUser().getEmail().split('@');    var auditeurNomPrenom = auditeurMail[0].split('.');    var auditeurPrenom = majString(auditeurNomPrenom[0]);    var auditeurNom = majString(auditeurNomPrenom[1]);    var signature = auditeurPrenom+' '+auditeurNom;      var sujet = 'test ' + semaine + ' (' + annee +')';    var corpsDuMail = '<p>Bonjour,</p>'    + '<p> Veuillez trouver ci-joint le test de la semaine ' + semaine + '-'+annee+'.</b></p><br>'    + '</p>Bonne réception,</p>'    + signature;     // Pièce jointe   var url = "https://docs.google.com/spreadsheets/d/SS_ID/export?".replace("SS_ID", classeur.getId());   var url_ext = 'exportFormat=pdf&format=pdf' + '&size=A4' + '&portrait=true' + '&fitw=true&source=labnol'               + '&sheetnames=false&printtitle=false' + '&pagenumbers=false&gridlines=false' + '&fzr=false' + '&gid=';   var token = ScriptApp.getOAuthToken();   var pdfMarge = UrlFetchApp.fetch(url + url_ext + feuille.getSheetId(),{headers : {                'Authorization' : 'Bearer ' + token }}).getBlob().setName("Marge_previsionnelle_S"+semaine+"_"+annee+".pdf");       // Fonction permettant d'envoyer le mail   MailApp.sendEmail("email@gmail.com", sujet, corpsDuMail, {   htmlBody : corpsDuMail,   attachments : [pdfMarge]   });     // Pop-up pour informer que l'envoi de mails s'est déroulé correctement   SpreadsheetApp.getUi().alert("Le mail a bien été envoyé aux personnes concernées !");  }    // Fonction permettant de mettre en majuscule la première lettre de la chaîne de caractère  function majString(a){     return (a+'').charAt(0).toUpperCase()+a.substr(1);   }  

And here is the function that allows me to archive my sheet in my drive :

function sauvegardeDrive() {    // Déclaration des variables et constantes    const classeur = SpreadsheetApp.getActiveSpreadsheet();    const feuille = classeur.getSheetByName('SYNTHESE');    var sheetName = "SYNTHESE";    var folderID = "1sRkfgLO8C4ABcrzPBonGPJm3emzWD3Ct";    var sourceSpreadsheet = SpreadsheetApp.getActive();    var sourceSheet = sourceSpreadsheet.getSheetByName(sheetName);    var folder = DriveApp.getFolderById(folderID);    var semaine = feuille.getRange('B5').getValue();    var annee = feuille.getRange('B4').getValue();    var pdfName = "test"+semaine+"_"+annee+".pdf";      //Copie de l'ensemble du Sheet    var destSpreadsheet = SpreadsheetApp.open(DriveApp.getFileById(sourceSpreadsheet.getId()).makeCopy("copieFichier", folder));     //Suppression des onglets inutiles   var sheets = destSpreadsheet.getSheets();   for (i = 0; i < sheets.length; i++) {     if (sheets[i].getSheetName() != sheetName){        destSpreadsheet.deleteSheet(sheets[i]);     }   }   var destSheet = destSpreadsheet.getSheets()[0];    var sourceRange = sourceSheet.getRange(1,1,sourceSheet.getMaxRows(),sourceSheet.getMaxColumns());   var sourcevalues = sourceRange.getValues();   var destRange = destSheet.getRange(1, 1, destSheet.getMaxRows(), destSheet.getMaxColumns());   destRange.setValues(sourcevalues);     //Sauvegarde en pdf   var theBlob = destSpreadsheet.getBlob().getAs('application/pdf').setName(pdfName);   var newFile = folder.createFile(theBlob);     //Suppression du Sheet temporaire   DriveApp.getFileById(destSpreadsheet.getId()).setTrashed(true);  }  

If you have any ideas, I'm interested.

Thank you in advance and sorry for mistakes in grammary's english (or others)

How do I aggregate object properties?

Posted: 24 Aug 2021 08:26 AM PDT

I am currently building a react application and I want to combine values of every object property together. How Would I do that? Here is my code:

  <tfoot>      {console.log(coinInfo)}      {coinInfo.map((c) => (        <tr>          <th>Total: {numberFormatter.format(c.coinValue + c.coinValue)}</th>        </tr>      ))}    </tfoot>  </table>    );  };    export default CoinList;  

React Native - Activity Recognition Permission Request in XML, still request permissions

Posted: 24 Aug 2021 08:26 AM PDT

Im using Google fit to track user steps with react-native-google-fit. After getting user permission to track Activity and Body im getting an error that I need to request permission from user of Activity Recognition.

This is the xml I added (also tried to add LOCATION):

  <uses-permission android:name="android.permission.ACTIVITY_RECOGNITION"/>    <uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION"/>   <!-- <uses-permission android:name="com.google.android.gms.permission.LOCATION"/> --> <---- tried with this as well  

This is the sdk versions in the gradle.build:

  buildToolsVersion = "28.0.3"    minSdkVersion = 21    compileSdkVersion = 28    targetSdkVersion = 29  

Also added (in gradle.build):

    implementation 'com.google.android.gms:play-services-fitness:20.0.0'      implementation 'com.google.android.gms:play-services-location:18.0.0'      implementation 'com.google.android.gms:play-services-auth:19.2.0'  

This is where the code (Google Fit) execute (HomePage.js - just after user logs in):

useEffect(() => {          const options = {              scopes: [                  Scopes.FITNESS_ACTIVITY_READ,                  Scopes.FITNESS_ACTIVITY_WRITE,                  Scopes.FITNESS_BODY_READ,                  Scopes.FITNESS_BODY_WRITE,                  Scopes.FITNESS_LOCATION_READ, <---- also tried without                  Scopes.FITNESS_LOCATION_WRITE, <---- also tried without              ],          };            GoogleFit.authorize(options)              .then(authResult => {                  if (authResult.success) {                      alert('AUTH_SUCCESS'); <------ alert success                          GoogleFit.startRecording((callback) => { <----- application crash (see attached image)                          });                                } else {                      alert('AUTH_DENIED', authResult.message);                  }              })              .catch(() => {                  alert('AUTH_ERROR');              });      }, []);    

It doesnt crash on the simulator, only on physical device. The physical device im using is android with android 10. Tho I need to accommodate version >= 8.

Any help will be greatly appreciated!

enter image description here

how to control or limit internet speed using termux?

Posted: 24 Aug 2021 08:25 AM PDT

I have a rooted phone so can I do it? it's possible on Linux and I understand not all Linux commands are available on termux.

Basic confusion in python

Posted: 24 Aug 2021 08:27 AM PDT

I am not able to understand this code and the concept behind such output. I am creating two objects but only one "Hello" is printed in console. I have tried to figure out through "id" but both the ids are different from each other:

class lol:      print("Hello")        # Output: Hello                            # 16377072 16378920  h = lol()  k = lol()  print(id(h), id(k))  

I can't get records from .net core mvc web api database

Posted: 24 Aug 2021 08:27 AM PDT

I couldn't solve it in any way, can you please help? I added web api to my .net core mvc project. I can return values as string or json, quite normally. But when it comes to the database, I have a problem. I am getting a null error. No matter how hard I searched, I couldn't figure it out. The smallest answer helps a lot. enter image description here

enter image description here

[ApiController] When I add it, my app doesn't open at all. When I make a comment line, it opens. But I can't call database methods. The same operations can be called seamlessly in the webui layer. Startup.cs

enter image description here enter image description here

enter image description here

Appsettings enter image description here

Can you please help?

Fail:

    fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]        An unhandled exception has occurred while executing the request.  System.NullReferenceException: Object reference not set to an instance of an object.     at zfc.webapi.Controllers.zfc.GetReferrer() in C:\Users\mderv\Desktop\zfc\zfc.webapi\Controllers\zfc.cs:line 26     at lambda_method(Closure , Object , Object[] )     at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)     at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)     at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()     at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)     at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()  --- End of stack trace from previous location where exception was thrown ---     at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)     at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)     at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()  --- End of stack trace from previous location where exception was thrown ---     at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)     at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)     at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)     at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)     at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)     at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)  

Csproj enter image description here

How can I add an incrementing id="" attribute to the following JavaScript generated HTML form?

Posted: 24 Aug 2021 08:26 AM PDT

I have managed to come up with the following JavaScript and HTML but now I am stuck. I want to be able to add an id="" attribute to the fields and have them numbered as I add more fields with the '+ Add' button.

I've been playing around with this but have not had any success yet. Could someone give me some suggestions or offer some solutions to this issue?

$(document).ready(function(){      var maxField = 10; //Input fields increment limitation      var addButton = $('.add_button'); //Add button selector      var wrapper = $('.field_wrapper'); //Input field wrapper      var fieldHTML = '<div><table width="100%"><tr><td><input type="text"           name="field_name[]" value="" class="form-control" style="width:98%;"           placeholder="Role"/></td><td><input type="text" name="field_name[]" value=""           class="form-control" style="width:100%;" placeholder="Name"/></td></tr></table>           <a href="javascript:void(0);" class="remove_button"><button type="button"           class="btn btn-danger btn-sm" style="margin-top:10px; margin-bottom: 18px;"> -           Remove </button></a></div>';          var x = 1; //Initial field counter is 1        //Once add button is clicked      $(addButton).click(function(){          //Check maximum number of input fields          if(x < maxField){              x++; //Increment field counter              $(wrapper).append(fieldHTML); //Add field html          }      });        //Once remove button is clicked      $(wrapper).on('click', '.remove_button', function(e){          e.preventDefault();          $(this).parent('div').remove(); //Remove field html          x--; //Decrement field counter      });  });  
  <label style="margin-top:70px;">Credits</label>  <div class="field_wrapper">      <div class="form-group">        <table width='100%'>          <tr>            <td>              <input type="text" name="field_name[]" value="" placeholder="Role" class='form-control' style="width:98%"/>            </td>            <td>              <input type="text" name="field_name[]" value="" placeholder="Name" class='form-control' style="width:100%"/>            </td>          </table>          <a href="javascript:void(0);" class="add_button" title="Add field">            <button style='margin-top:10px; margin-bottom: 10px;' type="button" class="btn btn-success btn-sm"> + Add Role </button>          </a>          </div>   </div>    

How to fix : ValueError: too many values to unpack (expected 2)

Posted: 24 Aug 2021 08:27 AM PDT

    import pathlib  datadir = "...My Google drive"   datatest = pathlib.Path(datadir)     image_count = len(list(datatest.glob('*/*.jpg')))     print("จำนวนรูป : ",image_count)    train_ds = tf.keras.preprocessing.image_dataset_from_directory(    datatest,    validation_split=0.1,    subset="training",    seed=123,    image_size=(IMG_ROWS, IMG_COLS),    batch_size=BATCH_SIZE)    val_ds = tf.keras.preprocessing.image_dataset_from_directory(    datatest,    validation_split=0.2,    subset="validation",    seed=123,    image_size=(IMG_ROWS, IMG_COLS),    batch_size=BATCH_SIZE)    (x_train, y_train), (x_test, y_test) = train_ds  

(x_train, y_train), (x_test, y_test) = train_ds

------------------------------- code error --------------------------------

ValueError                                Traceback (most recent call last)  <ipython-input-53-0219205d9ccf> in <module>()  ----> 1 (x_train, y_train), (x_test, y_test) = train_ds    ValueError: too many values to unpack (expected 2)  

How to convert a list of tibbles/dataframes into a nested tibble/dataframe

Posted: 24 Aug 2021 08:26 AM PDT

Sample Data

ex_list <- list(a = tibble(x = 1:4, y = 5:8),                  b = mtcars)  

How do I convert this list of tibbles/dataframes into a nested tibble as shown below:

# A tibble: 2 x 2    data_name data                <chr>     <list>            1 a         <tibble [4 × 2]>  2 b         <df [32 × 11]>   

Tidy solutions appreciated!

Determining trait bounds for a Rust function template ( usize or Vec<usize> )

Posted: 24 Aug 2021 08:26 AM PDT

I am trying to write a function template which I want to have the following signature

pub fn convert_to_one_hot<T>(category_id: T, num_classes: usize) -> Vec<bool> {...}

Here T can be usize or Vec<usize>. How should I determine the trait bounds for T to write such a function ?

In the following are instances of the function for the two cases :

  1. When T is usize
    pub fn convert_to_one_hot(category_id: usize, num_classes: usize) -> Vec<bool> {          let mut one_hot = Vec::<bool>::with_capacity(num_classes);          for index in 0usize..num_classes{              one_hot[index] = false;          }          one_hot[category_id] = true;          one_hot      }  
  1. When T is Vec<usize>
pub fn convert_to_one_hot(category_id: Vec<usize>, num_classes: usize) -> Vec<bool> {      let mut one_hot = Vec::<bool>::with_capacity(num_classes);      for index in 0usize..num_classes {          one_hot[index] = false;      }      for category in category_id{          one_hot[category] = true;      }      one_hot  }  

What is the correct way to use environment variables for external API?

Posted: 24 Aug 2021 08:27 AM PDT

I'm currently learning Next.js.

I have a Laravel API on http://localhost:8080/api/items and I'm calling this API using getServerSideProps():

export async function getServerSideProps() {    const res = await fetch("http://localhost:8080/api/items/", {      method: 'GET',    })    const { data } = await res.json()    return { props: { data } };  }  

How can I keep the base URL in a separate file that will also not expose the API URL? So instead of writing the entire URL I will have something like:

const res = await fetch(`${process.env.API_URL}/items/`, {      method: 'GET',    })  

I tried to do what the docs say but it's not working, I created a next.config.js file with the following:

module.exports = {      env: {          API_URL: "http://localhost:8080/api",      },  }  

But there are two problems with this:

  1. It's not working, I get TypeError: Only absolute URLs are supported, and it seems like it doesn't recognize template literals because it shows me const res = await fetch( ${process.env.API_URL}/api/products/ on the log screen
  2. I think next.config.js exposes the API URL to the public, and I want it to be private

Multivariate Time series forecasting using VAR

Posted: 24 Aug 2021 08:26 AM PDT

Details of dateset:

  1. contains more than 100k data points with seven features(Temp,dew,relative humidity,pressure,wind direction,wind speed,power generation)
  2. Hourly data starting from 2007 to 2021..For training the model I have taken from 2017 to 2021
  3. Stationary and yearly seasonal. 4.All features are auto correlated

Insights: 1.taken 90 percent data as training data and trained using simple var 2. Foretasted all 7 features (multivariate) 3. For two features forecasting is quite wrong RMSE is high compared to the mean ie wind speed and Power generated 4. Majorly Wind speed values are coming wrong and as it's cubed in the formula of wind power,it's getting affected.

Approach:

  1. To solve the problem I am trying to make linear eqn for wind speed using all its coeff(Only where p value is higher than 0.05), corresponding intercept (time lagged feature values) and constant term .
  2. Cannot able to forecast using this equation after the first value.

Is this approach correct or should we any other?

Removing duplicates from array using single loop

Posted: 24 Aug 2021 08:27 AM PDT

I want to remove duplicates from array using a single loop, it's not working, This is what I've done so far.

code.c

#include <stdio.h>    #define size 20  #define true 1  #define false 0    int main() {            int input[size] = {1, 3, 3, 3, 3, 3, 4, 3, 3, 3, 5, 6, 7, 8, 1, 1, 1, 1, 2, 2};        int current = input[0], flag = false, index = 0;            for (int x = 0; x < size; x++) {          if (current == input[x] && (flag == false)) {              flag = true;          } else if (current != input[x]) {              input[index++] = current;              current = input[x];              flag = false;          }      }            for (int foo = 0; foo < index; foo++) {          printf("%d", input[foo]);          printf((foo != index - 1) ? ", " : "");      }            return 0;  }  

input

1, 3, 3, 3, 3, 3, 4, 3, 3, 3, 5, 6, 7, 8, 1, 1, 1, 1, 2, 2  

output

1, 3, 4, 3, 5, 6, 7, 8, 1  

Is it possible to ask agents to leave an agentset without relying on their variables in NetLogo?

Posted: 24 Aug 2021 08:26 AM PDT

Although NetLogo has a good set of primitives allowing for the handy creation of agentsets, sometimes we might want to ask agents to 'manually' add themselves to an agentset as part of a procedure they're running - for instance, by using turtle-set.

Example:

globals [   good-folks   bad-folks   ]    to setup    clear-all        set good-folks (turtle-set)    set bad-folks (turtle-set)        create-turtles 50 [     ifelse (random 2 < 1)      [set good-folks (turtle-set good-folks self)]      [set bad-folks (turtle-set bad-folks self)]     ]  end    to go    ask good-folks [     do-good-things     ]        ask bad-folks [     do-bad-things     ]  end    to do-good-things end  to do-bad-things end  

The advantage of this approach above is better readability, the possibility to avoid having to create a turtles-own variable and avoid having to resort to with or if statements - as shown below:

turtles-own [   group   ]    to setup    clear-all        create-turtles 50 [     ifelse (random 2 < 1)      [set group "good folks"]      [set group "bad folks"]    ]  end    to go1    ask turtles with [group = "good folks"] [     do-good-things     ]        ask turtles with [group = "bad folks"] [     do-bad-things     ]  end    ; OR    to go2    ask turtles [     ifelse (group = "good folks")      [do-good-things]      [do-bad-things]    ]  end    to do-good-things end  to do-bad-things end  

Especially, it seems to me that the latter approach does not scale up as smoothly as the former, i.e. more groups will require more withs or ifs, instead of just being able to refer to the needed group neatly.

However, I am not aware of a way to do the exact opposite of set good-folks (turtle-set good-folks self), i.e. asking the turtle to 'manually' remove itself from the agentset.

; In this case, bad-folks try to recruit some good folks  to do-bad-things    if (random 3 < 2) [     ask one-of good-folks [       set good-folks (turtle-set good-folks - self) ; Leave the good folks <- **How to do this?**       set bad-folks (turtle-set bad-folks self) ; Join the bad folks      ]     ]  end  

I know this could be achieved by using a turtles-own variable and then updating agentsets as set <good/bad>-folks turtles with [...], but this is exactly the whole thing that I am trying to avoid in this question: less readable, more variables, more commands etc. And, perhaps equally important, it looks inconsistent with the use that can be done of turtle-set to grow the agentset by using it in combination with self. It would look easier and more consistent if existed a way to subtract self from the agentset - does it exist?

Update

Jasper's solution (i.e. using breeds instead of agentsets) works as long as the groups that I want to keep track of are mutually exclusive: agents switch from one single breed to another single breed only needing set breed ..., which will both make the agent join the new breed and leave their previous breed. However, this would not work in case I want to keep track of multiple groups with overlaps: beyond good-folks and bad-folks, I may have tall-folks and short-folks. Agents will have to belong to multiple groups simultaneously - something that agentsets can handle while breeds cannot.

How to skip certain part of a resource from being provisioned using terraform

Posted: 24 Aug 2021 08:27 AM PDT

How to skip certain parts of a resource from being provisioned using terraform.

# main.tf  resource "azurerm_api_management" "apim_demo" {    name                = var.apim_instance_name    location            = azurerm_resource_group.apim_rg.location    resource_group_name = azurerm_resource_group.apim_rg.name    publisher_name      = var.apim_publisher_name    publisher_email     = var.apim_publisher_email      sku_name = var.apim_sku_name      identity {      type = "SystemAssigned"    }    hostname_configuration {      proxy {        default_ssl_binding          = true        host_name                    = "qtech"        key_vault_id                 = "https://ssl-key-test789.vault.azure.net/secrets/my-ssl-certificate"        negotiate_client_certificate = true      }      proxy {        default_ssl_binding          = false        host_name                    = "ftech"        key_vault_id                 = "https://ssl-key-test789.vault.azure.net/secrets/my-ssl-certificate2"        negotiate_client_certificate = true        #custom                       = var.custom_block        #count                       = var.test_condition ? 1 : 0      }      }      }    
# variables.tf    variable "apim_instance_name" {}    variable "apim_publisher_name" {}    variable "apim_publisher_email" {}    variable "apim_sku_name" {}    variable "tenant_id" {    #  description "Enter Tenant ID"  }    variable "client_id" {    #  description "Enter Tenant ID"  }    variable "subscription_id" {    #  description "Enter Subscription ID"  }    variable "client_secret" {    #  description "Enter client secret"  }        variable "apim_resource_group_name" {    #  description "RG-2"  }    variable "apim_location" {    type = map(any)    default = {      location1 = "eastus"      location2 = "westus"    }  }    #variable "subnets" {  #  type = "list"  #  default = ["10.0.1.0/24", "10.0.2.0/24"]  #}      variable "test_condition" {    type    = bool    default = true  }    variable "custom_block" {    default = null  }        

From the above terraform code, I wanna avoid/skip the below (second proxy block) part of the resource from being provisioned

    proxy {        default_ssl_binding          = false        host_name                    = "ftech"        key_vault_id                 = "https://ssl-key-test789.vault.azure.net/secrets/my-ssl-certificate2"        negotiate_client_certificate = true  #      custom                       = var.custom_block  #      count                       = var.test_condition ? 1 : 0      }    

I did try to use count logic to avoid but I guess it will work on a complete resource block, not on a certain part of a resource block. Anyways got below error using count logic

Error: Unsupported argument  │   │   on apim-instance.tf line 35, in resource "azurerm_api_management" "apim_demo":  │   35:       count                       = var.test_condition ? 1 : 0  │   │ An argument named "count" is not expected here.  ╵    

I also try to use null logic to avoid but I guess it will also work on a complete resource block, not on a certain part of a resource block. Anyways got the below error using null logic.

│ Error: Unsupported argument  │   │   on apim-instance.tf line 34, in resource "azurerm_api_management" "apim_demo":  │   34:       custom                       = var.custom_block  │   │ An argument named "custom" is not expected here.  ╵      

Can anyone please help me over here?

A quick response will be appreciated.

Thanks & Regards.

How do i make my discord bot select a message from a list of phrases and send a random selected phrase from that list to a specific user?

Posted: 24 Aug 2021 08:27 AM PDT

I already have this code but it doesn't work correctly. When I change the message for a specific phrase it works but it don't work when I try to grab a random item from the list made before.


import discord  import os    client = discord.Client()      @client.event  async def on_ready():    print('We are live as {0.user}'.format(client))    @client.event  async def on_message(message):    if message.author == client.user:      return      if message.content.startswith('&hello'):      await message.channel.send('Hello There')    @client.event  async def on_message(message):      if message.author == client.user:          return                if message.author.id == 295365551499247618:        list = ["Oye callate","Quien te pregunto", "A nadie le importa", "Muerete", "Vete pa la pinga","Callate"]      await message.channel.send(random.choice(list))    client.run('TOKEN')  

Windows Folder Shortcut of an Electron App - get the path of that folder?

Posted: 24 Aug 2021 08:27 AM PDT

TL;DR

I want to open my Electron App through a Windows Folder Shortcut (right click on any folder and click Run In My Electron App), and get the folder path that initiated the app.

I managed to create the shortcut using windows Registry, but I can't find a way to get the path of the folder that initiated the app. (in the shortcut, "Temporary")

Run in my electron app enter image description here

So in the above shortcut, the goal is to know the path of F:\ePC\Libraries\Videos\Loom\Temporary inside of electron app. (and the path should always be matching the folder that initiated the app).

A real world working example: Just like when using WinRAR, you can right click on a folder and click "Add to archive..." - the WinRAR app knows the path of the folder that have been right-clicked on. (Kind of like "open file with", but "open folder with").

Another real world example that works with Electron is Visual Studio Code, you can right click on a folder and click "Open With Code". How did they do that?

My Attempt

I tried to look over the documentation of Electron but only found a way to get the path of the EXE file, but not the folder that excecated that file using the windows folder shortcut.

I tried also process.argv but it gives me the path of the exe file, and not the initiating folder.

Steps to reproduce the my attempt and test it yourself:

  1. Get the repository and clone it. (It only has 3 files: index.js, index.html and package.json).

  2. Open that folder in the command line and run npm install

  3. Export the electron app by running npm run package-win. this should export the exe file to [relative app path]/rlease-builds/windows-folder-electron-shortcut-win32-ia32/windows-folder-electron-shortcut.exe.

  4. To add the windows shortcut for the app: In the windows registry create this:

HKEY_CLASSES_ROOT\Folder\shell\Run In My Electron App\command

Here's a step by step:

  • 4 a. Open "Registry Editor" in Windows.
  • 4 b. Head over to HKEY_CLASSES_ROOT\Folder\shell and create a new folder called "Run In My Electron App"
  • 4 c. Inside the created folder, create command folder.
  • 4 d. Double click on the default value and change it to the full path of the exe file.

(In my case the default value is: C:\Users\elron\apps\windows-folder-electron-shortcut\rlease-builds\Paste Folder Icon-win32-ia32\Paste Folder Icon.exe. Make sure that the path is YOUR path of .exe file of the exported app.)

When done with step 4, It should look something like this:

enter image description here

Result:

When running the app through a folder shortcut, it will give you the path of the EXE as expected, but not the path that initiated the app as shown in this screenshot:

Run in my electron app

And now you can test it.

Any help will be appreciated!

How do I add an image to my python stock prediction web app that I am hosting locally through streamlit?

Posted: 24 Aug 2021 08:26 AM PDT

This is because I have tried using the code below but when I run my web app no image is displayed. Note that this program is written on notepad++ ,,,

    #import the libraries.      import streamlit as st      import pandas as pd        # insert Image.      from IPython.display import Image      Image("Desktop\stock.jpg")  

Python - text-adventure game if/else/elif problem [closed]

Posted: 24 Aug 2021 08:27 AM PDT

image of code and error message

I am having problems with the else/if/elif statements within my code. Im getting an indentation error but I have re-written the code a few times now and I am still getting the error.I have attached a picture for more clarity. I am coding in python3.

Edit: Please can you guys have a look at the image attached to view the code. I am very new to stack overflow, and I'm not sure how to format the code correctly.

Is there a better way to remove LastPass icon from a control where I don't have access to the underlying HTML input?

Posted: 24 Aug 2021 08:26 AM PDT

I know you can use data-lpignore="true" on an html input to tell LastPass to ignore the field, but is there a way when you're using a 3rd party control where you don't have (easy) access to the underlying input?

Generate fenced Matrix with m and n integers

Posted: 24 Aug 2021 08:26 AM PDT

How to generate a matrix with border 1's and 0's at the core when we give m and n positive integers.

Input:  4,5      Output      [1, 1, 1, 1, 1]      [1, 0, 0, 0, 1]      [1, 0, 0, 0, 1]      [1, 1, 1, 1, 1]  

I used this code.Is there any other way to get the output

import numpy as np  a=np.ones((m,n),dtype="int")  a[1:-1,1:-1]=0  

Is there way to get PostgreSQL service name?

Posted: 24 Aug 2021 08:27 AM PDT

Is there way to get PostgreSQL service name?

I mean something like SELECT @@SERVICENAME as in MS SQL Server. Or maybe it is declared in one of config files?

It's called Service ID: enter image description here

lightweight UI library for OpenGL [closed]

Posted: 24 Aug 2021 08:26 AM PDT

Like the title says, I'm looking for a library that's platform-agnostic and lightweight, for the purpose of displaying buttons, slider bars, check boxes, etc. in OpenGL. Ideally, something that is not directly coupled with OpenGL is best (ie. so that I may replace the rendering with DirectX if need be).

My 'ideal' library would have an event system that supports callbacks or something similar. This is a nice-to-have, but not absolutely required.

I looked into Qt and wxWidgets and both seem very heavy. CEGUI looks like a mess of code. Most other libraries I seen are GLUT based.

No comments:

Post a Comment