Tuesday, September 14, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Is there a workaround for adding too much .h?

Posted: 14 Sep 2021 08:20 AM PDT

I'm currently making a game with "multiple choices" which means a lot of questions. My thoughts first are making each question in a single .h file and then call the content inside the main file.

which means, I will have included hundreds of header file. I don't know if this is okay as I'm new to programming. Is there any solution to this?

Here is an example on one of my headers.

void questionOne() {    **Code here**    }  

passing values between methods, Python OOP, Method not getting

Posted: 14 Sep 2021 08:20 AM PDT

I am learning about classes and methods, trying to modify a simple python code so I can pass an attribute value using a method. I could pass the attribute for the setyear() method. However, I am unable to use it and perform a simple mathematical operation (e.g, age calculation) as in the agecalc() method. Wonder if you can please point out why am I getting 0 instead of 10?

class Dog:      def __init__(self, name, born, breed):          self.name = name          self.born = born     # year born          self.breed = breed          self.year = 0          self.age=0                def setyear(self, year):          #self.year = year-self.born               self.year = year            def agecalc(self, year):          self.age = self.year - self.born  ##*** keeps giving me 0??              mydog1 = Dog (name = "Lassy", born = 2015, breed = "Husky")     mydog1.setyear(2025) # setting the year we wish to calculate the dog's age at         # The following is sub ideal.   print ("dog age =", mydog1.year - mydog1.born)    # looking replace the above line with the agecalc method i.e. print (agecalcl(2025))      # Tried the following one as well and it keeps giving me `None`  print (mydog1.agecalc(2025))  

How to resolve execution timeout expired issue occuring in a stored procedure

Posted: 14 Sep 2021 08:19 AM PDT

Facing timeout expired issue in a code developed. Shared below is the stored procedure where timeout occurs. Purpose of the code : Dates being passed from frontend (using a forloop in Windows application vb.net code) for 10 lakh cases for which date difference needs to be calculated basis the date received.

create procedure sp_getdatediff    @strd1 date = null,  @strd2 date = null,  @strd3 date = null,  @strd4 date = null,  @strd5 date = null,  @strd6 date = null,  @strd7 date = null,  @strd8 date = null,  @strd9 date = null,  @strd10 date = null,  @strd11 date = null  as  begin    declare @vardatediff1 int  declare @vardatediff2 int  declare @vardatediff3 int  declare @vardatediff4 int  declare @vardatediff5 int    set @vardatediff1 = [fn_getdiff](@strd1,@strd2,@strd3) ----- input parameters are dates passed from frontend  set @vardatediff2 = [fn_getdiff](@strd2,@strd4,@strd5)  set @vardatediff3 = [fn_getdiff](@strd4,@strd5,@strd6)  set @vardatediff4 = [fn_getdiff](@strd5,@strd7,@strd8)  set @vardatediff5 = [fn_getdiff](@strd9,@strd10,@strd11)    update tbl_Scheduler set col_dif1 = @vardatediff1 , col_dif2 = @vardatediff2 ,   col_dif3 = @vardatediff3 , col_dif4 = @vardatediff4 , col_dif5 = @vardatediff5  where id = @id    end  

Function code :

create function [fn_getdiff]  (  @startdate date = null,  @enddate date = null,  @ccode varchar(10) = null  )  returns integer      as  begin  declare @count integer   declare @tdaycount integer   if (@startdate is null or @startdate = '')  begin      set @count = 0  end  else if (@enddate is null or @enddate = '')  begin      set @count = 0  end  else  begin        select @tdaycount = count(distinct(convert(date,tdays))) from tbl_holidays with (nolock) where (convert(date,tdays,105) >= convert(date,@startdate,105))      and (convert(date,tdays,105) <= convert(date,@enddate,105)) and tcode in (select id from tbl_code with (nolock) where id = @ccode)        select @count  = datediff(@startdate,@enddate)            set @count = @count - @tdaycount         end  return @count     end  

Is there optimization required in this code to eliminate timeout issue? How can same be done?

How to get real p value rather than just 0 in R (

Posted: 14 Sep 2021 08:19 AM PDT

I'm trying to perform Kruskal-Wallis ANOVA test followed by pairwise Dunn's test with Šidák's adjustment for post-hoc analysis. I would like to see real p-value rather than just 0(or 0.0000).

Here is my result from R. Kruskal-Wallis chi-squared = 131.7343, df = 2, p-value = 0 List of pairwise comparisons: Z statistic (adjusted p-value)

1 - 2 : 8.440001 (0.0000)* 1 - 3 : 11.16992 (0.0000)* 2 - 3 : 0.261792 (0.9912)

I really appreciate it if someone let me know how to show real value instead of just 0.

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'prompt')

Posted: 14 Sep 2021 08:19 AM PDT

I am trying to use the App Install Prompt with webpack 5 but I get the following error:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'prompt')

window.addEventListener('beforeinstallprompt', (e) => {      e.preventDefault();      deferredPrompt = e;      // showInstallPromotion();      console.log("beforeinstallprompt: ", e);  });    document.querySelector('#component-1').addEventListener('click', async (e) => {      e.preventDefault();      // hideInstallPromotion();      deferredPrompt.prompt();      const {outcome} = await deferredPrompt.userChoice;      console.log("outcome: ", e, outcome);      deferredPrompt = null;  });  

Generate array from type without infering

Posted: 14 Sep 2021 08:19 AM PDT

I need to generate real JS code based on TS type, so I can prevent doubling code and creating the chaos.

export interface TypesInfo extends BaseServiceTypesInfo {      mysqlDatabases:    "db1" | "db2" | "db9";  }    //    export class Service extends BaseService<TypesInfo> {      protected static $SetInfo(info: MutableServiceInfo) {          info.$name           = "examplename";            info.$systems        = {    /*instead of true, it has to be TypesInfo.mysqlDatabases converted to array, so ["db1", "db2", "db9"];*/              mysql: true, // ["db1", "db2", "db9"] instead of true              mongodb: true          };      }  }  

Infering the type from array won't work for me, because you can't put array inside interface, because interface isn't runtime.

Basically TypesInfo.mysqlDatabase type should also works as enabler, not only for type checking.

Connect to sftp server using proxy and private key in Python

Posted: 14 Sep 2021 08:19 AM PDT

I am trying to connect to sftp server which allows key based authentication and I need to use the proxy over HTTP to connect to the sftp server. I have tried the below code using paramiko

import paramiko  import socks  host_proxy='proxy.b.net'  proxy_port = 8080  proxy_user = 'test'  proxy_pass = 'test'  server_name = 'sftp.server.com'  sock = socks.socksocket()  sock.set_proxy(socks.PROXY_TYPE_HTTP, host_proxy,      proxy_port, True, proxy_user,       proxy_pass)    sock.connect((host_proxy, proxy_port))  transport = paramiko.Transport(sock)  transport.connect(username = 'user1',pkey='private_key.ppk')    sftp = paramiko.SFTPClient.from_transport(transport.get_transport())  sftp.listdir(path='.')    sftp.close()  transport.close()  

I am getting error as below in transport.connect(), Please note that our proxy server only allows to use only HTTP. Can you please help in fixing this issue as we are stuck in proceeding further

Exception: Indecipherable protocol version "        <TBODY>"  Traceback (most recent call last):    File "/app/test/anaconda3/envs/test/lib/python3.7/site-packages/paramiko/transport.py", line 2039, in run      self._check_banner()    File "/app/test/anaconda3/envs/test/lib/python3.7/site-packages/paramiko/transport.py", line 2222, in _check_banner      raise SSHException('Indecipherable protocol version "' + buf + '"')  paramiko.ssh_exception.SSHException: Indecipherable protocol version "        <TBODY>"    ---------------------------------------------------------------------------  SSHException                              Traceback (most recent call last)  <ipython-input-8-d1fdf3269bfc> in <module>  ----> 1 transport.connect(username = 'user1',pkey='private_key.ppk')    /app/test/anaconda3/envs/test/lib/python3.7/site-packages/paramiko/transport.py in connect(self, hostkey, username, password, pkey, gss_host, gss_auth, gss_kex, gss_deleg_creds, gss_trust_dns)     1289         )     1290   -> 1291         self.start_client()     1292      1293         # check host key if we were given one    /app/test/anaconda3/envs/test/lib/python3.7/site-packages/paramiko/transport.py in start_client(self, event, timeout)      658                 e = self.get_exception()      659                 if e is not None:  --> 660                     raise e      661                 raise SSHException("Negotiation failed.")      662             if event.is_set() or (    /app/test/anaconda3/envs/test/lib/python3.7/site-packages/paramiko/transport.py in run(self)     2037                     "Local version/idstring: {}".format(self.local_version),     2038                 )  # noqa  -> 2039                 self._check_banner()     2040                 # The above is actually very much part of the handshake, but     2041                 # sometimes the banner can be read but the machine is not    /app/test/anaconda3/envs/test/lib/python3.7/site-packages/paramiko/transport.py in _check_banner(self)     2220             self._log(DEBUG, "Banner: " + buf)     2221         if buf[:4] != "SSH-":  -> 2222             raise SSHException('Indecipherable protocol version "' + buf + '"')     2223         # save this server version string for later     2224         self.remote_version = buf    SSHException: Indecipherable protocol version "        <TBODY>"  

Convert tibble form

Posted: 14 Sep 2021 08:19 AM PDT

I have the following table. I want to convert from 10 x 2 to 10 x 4. How do I do this conversion?

# A tibble: 10 x 2     ...1[,1]   [,2] ...2[,1]   [,2]        <dbl>  <dbl>    <dbl>  <dbl>   1  0.0123  0.0814  -0.315  0.135    2 -0.0265  0.0722  -0.222  0.140   

How to remove duplicates in a data frame with a different format?

Posted: 14 Sep 2021 08:19 AM PDT

So, I'm going through a dataset I saw on the internet, and I noticed lots of duplicates but with different formatting. For example, in the name column, some people started typing their name in LN, FN, MI, while some people typed their name in FN, MI, LN format. How can I remove these duplicates? Thank you!

Below is an example of a column in the data frame.

Name
Doe, John D.
John D. Doe

Compact nested for loop's

Posted: 14 Sep 2021 08:19 AM PDT

the following is Python code. How can the same be done in R?

CODE

from itertools import product     mean_ops      = ['Zero', 'Constant', 'AR']     variance_ops  = ['arch', 'garch', 'gjr', 'figarch', 'aparch', 'har']    dist_ops    = ['normal', 't', 'skewt', 'ged']      for mean, variance, dist in product(mean_ops, variance_ops, dist_ops):  

OUTPUT

Zero arch normal  Zero arch t  Zero arch skewt  Zero arch ged  Zero garch normal  Zero garch t  Zero garch skewt  Zero garch ged  Zero gjr normal  Zero gjr t  Zero gjr skewt  (...)  

In total there are 72 combinations (3 mean_opc X 6 variance_opc X 4 dist_opc)

Thank you

recompiling next.js in container is very slow

Posted: 14 Sep 2021 08:19 AM PDT

docker pull m986883511/nextjs-debug:latest    docker run --rm -it -p 3000:3000 -v $current_dir:/app m986883511/nextjs-debug:latest  

you can download my images

recompiling is about 40 seconds

ElasticSearch config lowercase analyser

Posted: 14 Sep 2021 08:19 AM PDT

I try to create an indexer with a lowercase analyzer, like below:

{    "settings": {       ....  "analysis": {    "analyzer": {      "default": {        "tokenizer": "keyword",        "filter": "lowercase"      }    }  }   },    "mappings": {  "dynamic_templates": [      ....  ],  "properties": {    // Properties list       }     }  }  

But when I search with kibana, the lowercase doesn't work, it still case sensitive

My Query like:

GET A_INDEXER/_search  {       "query": {         "bool": {         "must": [            { "match": { "property1":   "jack"}}            ]        }       }  }  

Can I make this countdown work in only one function?

Posted: 14 Sep 2021 08:19 AM PDT

This code works fine (It is a countdown for a project I'm doing), but i want to do it with only one function. It is possible?

function workingCountdown(){      //Set an interval that call the countdown function every second      window.variableCountdown = setInterval(countdown, 1000)  }  function countdown(){      //CHECK IF SECONDS IS BIGGER THAN ONE      if(seconds>1){          //IF YES          //Substract 1 to the seconds variable          window.seconds--          //Change the countdown text according to seconds left          document.getElementById("countdown").innerHTML = "You have " + seconds + " seconds left"      } else {          //IF NO          //Notify the user that they ran out of time by changing the countdown text          document.getElementById("countdown").innerHTML = "You have 0 seconds left"          //Let pass fifty miliseconds so the countdown text can change before the alert is played          setTimeout(function(){cpsTestFinish()}, 50)           //Stop the countdown repeat          clearInterval(variableCountdown)      }  }  

Is the equality relation of pointers after round-trip conversion guaranteed to be transitive?

Posted: 14 Sep 2021 08:19 AM PDT

This question is similar to "Are all pointers guaranteed to round-trip through void * correctly?" but slightly deeper.

Given:

#include <stdint.h>  
{      int i;      int *ip1 = &i;      void *vp1 = ip1;      intptr_t x = (intptr_t)vp1;      void *vp2 = (void *)x;      int *ip2 = vp2;  

then vp1 == vp2 is guaranteed to be true (even though they might not share the same binary representation), but is ip1 == ip2 guaranteed to be true? I.e., is the equality relation transitive in this case?

How to calculate age from Json Birtdate in JS

Posted: 14 Sep 2021 08:19 AM PDT

{"firstname":"Dummy0","surname":"User0","birthdate":"1997-12-04","email":"dummy.user0@mockup.data","avatar":""}

Stuck in a calculating age from Json Birtdate... Can you please help me?

Terraform for loop inside for_each argument

Posted: 14 Sep 2021 08:19 AM PDT

Can someone please explain what a for loop inside a for_each argument does in Terraform? I am trying to create an AWS SSL certificate. I've seen other code like the below but I don't understand it:

 resource "aws_acm_certificate" "nonprod_cert" {      domain_name       = var.phz_domain_name      validation_method = "DNS"  }     resource "aws_route53_record" "nonprod_cert_record" {      for_each = {        for dvo in aws_acm_certificate.nonprod_cert.domain_validation_options : dvo.domain_name => {          name   = dvo.resource_record_name          record = dvo.resource_record_value          type   = dvo.resource_record_type      }    }      zone_id = var.phz_id      name    = each.value.name      type    = each.value.type      records = [each.value.record]      ttl     = 60  }    resource "aws_acm_certificate_validation" "nonprod_cert_validated" {    certificate_arn         = aws_acm_certificate.nonprod_cert.arn    validation_record_fqdns = [for record in aws_route53_record.nonprod_cert_record : record.fqdn]    depends_on = [      aws_acm_certificate.nonprod_cert,      aws_route53_record.nonprod_cert_record    ]  }  

The specific line that I don't understand is the one in the route53 record. I get that a for_each argument can be used to create multiple resources from a single block, but I can't find anywhere that explains what this for loop is doing inside of it. If someone could explain that would be great!

The person that wrote the code has left so I can't ask them either.

working of to_string() and stringstream class

Posted: 14 Sep 2021 08:20 AM PDT

this is my code code for the countAndSay problem on leetcode. Now in this code i am using to_string() to convert integer into string but it is not working . When i am trying it on debuggur then the pointer is not moving past the to_string() function .Are there any mistake in my usage of to_string()?

#include<bits/stdc++.h>  using namespace std;    string countandsay(int n) {      string s="1";      if(n==1)          return s;                        for(int i=2;i<=n;++i)      {          int m=s.size();          string  temp="",str;          int count=1;          int j=0;          for(j=0;j<m-1;++j)          {              if(s[j]==s[j+1])              {                  count++;              }              else              {                  str=to_string(count);                  temp+=str;                  str=to_string(s[j]);                  temp+=str;                  count=1;              }          }                       str=to_string(count);                  temp+=str;                  str=to_string(s[j]);                  temp+=str;                    s=temp;      }      return s;  }    int main(){      int n=4;      cout<<countandsay(n);      return 0;  }  

then i tried using stringstream class but it was even more unexpected .

            stringstream ss;                ss <<count;              ss >> str;              temp+=str;                            ss <<s[j];              ss >> str;                             temp+=str;  

in this code instead of to_string() but the stringstream object was only working for using first time ( only storing count but not s[j]). Is it related to stringstream class then please explain its working

after that I trying using declaring a separate stringstream object for every conversion

            stringstream ss;              ss <<count;              ss >> str;              temp+=str;                            stringstream yy;              yy <<s[j];              yy >> str;                             temp+=str;  

this approach is giving correct output
please explain the reason for above happenings.
link->https://leetcode.com/problems/count-and-say
Thanks You for helping

How to get a unit of measurement as a singular noun?

Posted: 14 Sep 2021 08:20 AM PDT

I'm trying to represent running pace in my app - let's say 5min/km.

For voice over, I'd love this to be read as five minutes per kilometer.

I know I can get kilometers like that:

let measurementFormatter = MeasurementFormatter()  measurementFormatter.unitStyle = .long  measurementFormatter.string(from: UnitLength.kilometers)  

but would it be possible to get the singular form (and take advantage of the already localized units)?

Given an array of integers, how do I find the sum of its elements with some simple constraints in JavaScript?

Posted: 14 Sep 2021 08:19 AM PDT

To find the sum of array's elements I have tried this approach however the output comes undefined instead of an integer

constraints are array.length > 0 && array[i] <= 1000

function simpleArraySum(ar) {      let acc = 0;      for (let i = 0; ar.length; i++) {          if (ar.length > 0 && ar[i] <= 1000) {              acc += ar[i]          } else {              return          }      }      return acc;  }  

Any help would be appreciated.

Access value in nested JSON recieved by ActiveCollab REST API using Python

Posted: 14 Sep 2021 08:19 AM PDT

I got this by REST-API form ActiveCollab:

{  "time_records": [          {              "id": 122,              "class": "TimeRecord",              "url_path": "\/projects\/89\/time-records\/122",              "is_trashed": false,              "trashed_on": null,              "trashed_by_id": 0,              "billable_status": 1,              "value": 1.0,              "record_date": 1645847200,              "summary": "example",              "user_id": 12365,              "user_name": "Fred Coal",              "user_email": "fredc@example.com",              "parent_type": "Project",              "parent_id": 89,              "created_on": 1628497959,              "created_by_id": 17,              "created_by_name": "Fred Coal",              "created_by_email": "fredc@example.com",              "updated_on": 1635784512,              "updated_by_id": 17,              "job_type_id": 1,              "source": "unknown",              "original_is_trashed": false          },             ],  }  

I want to get the value of "value".

But I don't get how to access this property.

I am using Python for this.

import requests  import json  startdate = "2021-08-01"  enddate = "2021-08-31"  fromto = "?from="+startdate+"&to="+enddate  #--------------   def ac_rq(endpoint):      token ='*'      url = "https://*/api/v1/"+endpoint      resp = dict(requests.get(url, headers={'X-Angie-AuthApiToken': token}))      print(resp)      return resp  #--------------  a = ac_rq('projects/129/time-records/filtered-by-date'+str(fromto))  b = json.loads(a.text)  for i in b:      print(i['time_records'][0]['value'])    input("press enter to exit")  

I get this Error:

TypeError: string indices must be integers

call dictionary

Posted: 14 Sep 2021 08:19 AM PDT

I'm stuck with a problem when I'm working with a dictionary in VBA. The reason why I want to work with a dictionary and a do-while loop is because I have variables with different length, that I want to loop through. First I want to give the dic keys and and items. The reason why I skip one col for each loop is because each series has a col with dates and then a col with prices. If it is possible I want to capture the dates that match the prices in the same dictionary.

Sub opg1(dicSPX As Object)        Dim i As Integer, m As Integer      Dim varColLeng As Variant        Set dicSPX = CreateObject("Scripting.Dictionary")        m = 10        Sheets("Data").Activate            ReDim intCol(1 To nCol)     'opretter dictionary      ReDim n(1 To m)      Do While n <> ""          For i = 1 To mn  '            redim preserve IntColLen              dicSPX.Add Cells(1, 2 + ((i - 1) * 2)).Value, Range(Cells(9, 2 + ((i - 1) * 2)), Cells(n, 2 + ((i - 1) * 2))).Value          Next i      Loop  End Sub  

then I want to execute a procedure for all keys in my dic. I want to compute returns in different time series. However, when I call the dic, to the sub Returns() I get an error (Compile error: Variable not defined). I'm new to dictionaries and I probably missed a small detail.

Sub Returns()        Call opg1(dicSPX)            Dim dicSPX As New Scripting.Dictionary      Dim varKey As Variant, varArr As Variant            For Each varKey In dicSPX          varArr = dicSPX(varKey)          For i = LBound(varArr, 1) To UBound(varArr, 1)              For j = LBound(varArr, 2) To UBound(varArr, 2)  '                varReturns(i,j) = compute  the return here              Next          Next      Next  

Any suggestions? I hope the question is clear.

Thank you

IOS Apply a slow motion effect to a video while shooting

Posted: 14 Sep 2021 08:19 AM PDT

Is it possible to apply slow motion effect while recording video?

This means that the recording has not finished yet, the file has not been saved, but the user sees the recording process in slow motion.

Multi-variate Linear Regression using Gradient Descent

Posted: 14 Sep 2021 08:19 AM PDT

I've been trying to write a code for Linear Regression using Gradient Descent formula:

def gradient_descent(X, y, step_size, precision):      beta = np.zeros(X.shape[1])        N = float(len(y))      beta_old = np.ones(X.shape[1]) * 10      t = 0       error = 0        while abs(np.sqrt(np.linalg.norm(-2 / N * X.T@(y-X@beta)))) > precision:          error = 1 / N * np.sum((y-X@beta) ** 2)            for i in range(X.shape[0]):              beta = beta + 2 * step_size / N * X[i] * (y[i] - X[i]@beta)                t = t + 1          return beta, t, error  

Where I defined my convergence as "do while $||\nabla(f(x))||$<precision", ($||\nabla(f(x))|| is square root of norm of gradient descent) but my code doesn't seems to converge. Norm of gradient descent doesn't seems to go below 11.56. Can anyone please help? If there is any code mistake or logical mistake.

What is the AWS SDK library for signin in Cognito (from backend without using Amplify)?

Posted: 14 Sep 2021 08:20 AM PDT

I have implemented user signup using @aws-sdk/client-cognito-identity-provider but not able to find the module or API from AWS SDK to implement sign in to cognito

When is it preferable to use rand() vs a generator + a distribution? (e.g. mt19937 + uniform_real_distribution) [closed]

Posted: 14 Sep 2021 08:20 AM PDT

After going through the rabbit hole that is learning about rand() and how it's not very good at generating uniform pseudorandom data based on what I've dug into based on this post: Random float number generation. I am stuck trying to figure out which strategy would yield better balance of performance and accuracy when iterated a significant number of times, 128*10^6 for an example of my use case.

This link is what led me to make this post, otherwise I would have just used rand(): rand() considered harmful

Anyway, my main goal is to understand whether rand() is ever preferable to use over the generator + distribution method. There doesn't seem to be very good info even on cppreference.com or cplusplus.com for performance or time complexity for either of the two strategies.

For example, between the following two random number generation strategies is it always preferable to use the 2nd approach?

  1. rand()
  2. std::mt19937 and uniform_real_distribution

Here is an example of what my code would be doing:

int main(){        int numIterations = 128E6;        std::vector<float> randomData;        randomData.resize(numIterations);                for(int i = 0; i < numIterations; i++){            randomData[i] = float(rand())/float(RAND_MAX);        }  }  

vs.

#include<random>  int main(){      std::mt19937 mt(1729);      std::uniform_real_distribution<float> dist(0.0, 1.0)      int numIterations = 128E6;      std::vector<float> randomData;      randomData.resize(numIterations);            for(int i = 0; i < numIterations; i++){          randomData[i] = dist(mt);      }  }  

Csv column unnamed headers being written. How do I stop that, it adds the row number on the left whenever I run the program, offsetting index writing

Posted: 14 Sep 2021 08:19 AM PDT

I am trying to replace a certain cell in a csv but for some reason the code keeps adding this to the csv:

 ,Unnamed: 0,User ID,Unnamed: 1,Unnamed: 2,Balance  0,0,F7L3-2L3O-8ASV-1CG4,,,5.0  1,1,YP2V-9ERY-6V3H-UG1A,,,4.0  2,2,9FPM-879N-3BKG-ZBX8,,,0.0  3,3,1CY4-47Y8-6317-UQTK,,,5.0  4,4,H9BP-5N77-7S2T-LLMG,,,100.0  

It should look like this:

User ID,,,Balance  F7L3-2L3O-8ASV-1CG4,,,5.0  YP2V-9ERY-6V3H-UG1A,,,4.0  9FPM-879N-3BKG-ZBX8,,,0.0  1CY4-47Y8-6317-UQTK,,,5.0  H9BP-5N77-7S2T-LLMG,,,100.0  

My code is:

equations_reader = pd.read_csv("bank.csv")          equations_reader.to_csv('bank.csv')          add_e_trial = equations_reader.at[bank_indexer_addbalance, 'Balance'] = read_balance_add + coin_amount  

In summary, I want to open the CSV file, make a change and save it again without Pandas adding an index and without it modifying empty columns.

Why is it doing this? How do I fix it?

How to take user input and store in variable using tkinter?

Posted: 14 Sep 2021 08:20 AM PDT

This is a college enquiry chatbot, I want to get users name and display in the chat window.

Click here to view the output window

On the output window, I want the student's name instead of "Student". I have added only some code that I think is important. If you want full code comment below, I'll edit the question

def _on_enter_pressed(self, event):      msg = self.msg_entry.get()      self._insert_message(msg,"Student")        def _insert_message(self, msg, sender):      if not msg:          return            self.msg_entry.delete(0, END)      msg1 = f"{sender}: {msg}\n\n"      self.text_widget.configure(state=NORMAL)      self.text_widget.insert(END, msg1)      self.text_widget.configure(state=DISABLED)            msg2 = f"{bot_name}: {get_response(msg)}\n\n"      self.text_widget.configure(state=NORMAL)      self.text_widget.insert(END, msg2)      self.text_widget.configure(state=DISABLED)            self.text_widget.see(END)  

Two conflicting long lived process managers

Posted: 14 Sep 2021 08:19 AM PDT

Let assume we got two long lived process managers. Both sagas operates over 10 milion items for example. First saga adds something to each item. Second saga removes it from each item. Given both process managers need few minutes to complete its job if I run them simultaneously I get into troubles.

Part of those items would hold the value while rest of them not. The result is close to random actually and depends on command order that affect particular item. I wondered if redispatching "Remove" command in case of failure would solve the problem. I mean if you try remove non existing value you should wait for the first saga to add the value. But while process managers are working someone else may dispatch "Remove" or "Add" command. In such case my approach would fail.

How may I solve such problem? :)

"No Ad Config." on onAdFailedToLoad() Method While trying to Load Ads

Posted: 14 Sep 2021 08:20 AM PDT

I am trying to load interstitial advertisements for my app. Whenever I try to load these ads I get a Error saying "No Ads Config" from Domain "com.google.android.gms.ads".

Here is the code:

My AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>  <manifest xmlns:android="http://schemas.android.com/apk/res/android"      package="com.ayush.torch">          <application            android:allowBackup="true"          android:icon="@drawable/ic_ico"          android:label="@string/app_name"          android:supportsRtl="true"          android:theme="@style/AppTheme">          <activity android:name=".main">              <intent-filter>                  <action android:name="android.intent.action.MAIN"/>                  <category android:name="android.intent.category.LAUNCHER"/>              </intent-filter>          </activity>          <meta-data              android:name="com.google.android.gms.ads.APPLICATION_ID"              android:value="i_have_put_my_app_id_here"/>             </application>        <uses-permission android:name="android.permission.INTERNET" />      <uses-permission android:name="android.permission.CAMERA" />      <uses-permission android:name="android.permission.FLASHLIGHT" />    </manifest>  

onCreate() in main.java

                  // Creating the InterstitialAd and setting the adUnitId.          interstitialAd = new InterstitialAd(this);          interstitialAd.setAdUnitId("i have also put my interstitial ad id here");             interstitialAd.setAdListener(new AdListener() {             @Override             public void onAdLoaded() {                 Toast.makeText(main.this, "Ad Loaded", Toast.LENGTH_SHORT).show();             }               @Override             public void onAdFailedToLoad(LoadAdError loadAdError) {                 String error = String.format("domain: %s, code: %d, message: %s", loadAdError.getDomain(), loadAdError.getCode(), loadAdError.getMessage());                 Toast.makeText(main.this, "onAdFailedToLoad() with error: " + error, Toast.LENGTH_SHORT).show();             }         });  

When I load my ad in a on function it gives me error "No Ad Config."

                    Log.d("[Ads]","Ad Load State For on(): " + interstitialAd.isLoaded());                      if (interstitialAd.isLoaded())                       {                          interstitialAd.show();                      }  

sum last n days quantity using sql window function

Posted: 14 Sep 2021 08:20 AM PDT

I am trying to create following logic in Alteryx and data is coming from Exasol database.

Column "Sum_Qty_28_days" should sum up the values of "Qty " column for same article which falls under last 28 days.

My sample data looks like:

enter image description here

and I want following output:

enter image description here

E.g. "Sum_Qty_28_days" value for "article" = 'A' and date = ''2019-10-8" is 8 because it is summing up the "Qty" values associated with dates (coming within previous 28 days) Which are: 2019-09-15 2019-10-05 2019-10-08 for "article" = 'A'.

Is this possible using SQL window function? I tried myself with following code:

SUM("Qty") OVER (PARTITION BY "article", date_trunc('month',"Date")               ORDER BY "Date")  

But, it is far from what I need. It is summing up the Qty for dates falling in same month. However, I need to sum of Qty for last 28 days.

Thanks in advance.

No comments:

Post a Comment