Wednesday, June 9, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Adding integers in a list iteratively to another list

Posted: 09 Jun 2021 08:34 AM PDT

I am trying to do the following (composites applications): I have a list of names which I would like to add integers in string form to the end of each name. This is the desired outcome:

List of names: Name1_, Name2_, Name3_

List of integers: [45,90,45,0]

Desired outcome: Name1_45, Name2_90, Name3_45, Name4_0

Instead, this is what I'm getting:

Name1_45, Name2_45, Name3_45, Name4_45

Name1_90, Name2_90, Name3_90, Name4_90

Name1_45, Name2_45, Name3_45, Name4_45

Name1_0, Name2_0, Name3_0, Name4_0

Here's my code:

import csv  name_list_a = []  name_list_b = []  name_angle_a = []  lam_a = 'Lam1_'  lam_b = 'Lam2_'  for i in range(1,10,1):      name_list_a.append([lam_a + str(i) + '_'])      # print(name_list_a)  stack_seq = [45,90,45,0]  for j in stack_seq:      for z in name_list_a:          name_angle_a.append([z + [str(j)]])      print(name_angle_a)    file = open('names.txt', 'w+', newline='')  with file:      write = csv.writer(file)      write.writerows(name_angle_a)  

How can I do this (if at all)

Thanks in advance!

HTTP test fails when testing images

Posted: 09 Jun 2021 08:34 AM PDT

  • Laravel Version: 8.45.1
  • PHP Version: 8.0.7
  • Database Driver & Version: MySQL 8.0.25

I am trying to create a test to check the response status for an image.

The image works fine in browser: https://mydomain.test/storage/images/j2L3G12eel9sqsuNSGOYmcdqwUdchZtsfFGMeY90.jpg

/**   * @runInSeparateProcess   */   public function test_can_see_image()   {       $this->get('https://mydomain.test/storage/images/j2L3G12eel9sqsuNSGOYmcdqwUdchZtsfFGMeY90.jpg')->assertOk();   }  

The test fails.

Response status code [404] does not match expected 200 status code. Failed asserting that false is true.

Block pull request if last build of source branch failed Azure Devops

Posted: 09 Jun 2021 08:34 AM PDT

In Azure DevOps, I know I can protect a branch with Build Validation, so when there's a pull request initiated, a build will run on the merged commit.

However, I would like to block the possibility to initiate a pull request if the last build of the source branch was failed. Is that possible?

File upload to Jersey from Quarkus

Posted: 09 Jun 2021 08:34 AM PDT

I need to upload a file from Quarkus application to jesrey 2 rest service which is expecting two params like

@FormDataParam("file") InputStream uploadFileInputStream,  @FormDataParam("file") FormDataContentDisposition fileMetaData  

Used below code in Quarkus to send file

public class MultipartBody {        @FormParam("file")      @PartType(MediaType.APPLICATION_OCTET_STREAM)      public InputStream file;        @FormParam("fileName")      @PartType(MediaType.TEXT_PLAIN)      public String fileName;  }    @RegisterRestClient  public interface MultipartService {        @POST      @Consumes(MediaType.MULTIPART_FORM_DATA)      @Produces(MediaType.TEXT_PLAIN)      String sendMultipartData(@MultipartForm MultipartBody data);    }  

I'm getting 500 error while calling the service. In service side logs, it says fileMetaData is null

How do I extract data from Json_response to be used in python

Posted: 09 Jun 2021 08:34 AM PDT

I am trying to integrate two APIs

  1. from metering platform that should send notifications via sms.
  2. API is an sms platform to deliver the messages.

Python Code;

import africastalking  import requests  import json    # Initialize SDK  username = "sandbox" # use 'sandbox' for development in the test environment  # use your sandbox app API key for development in the test environment  api_key = "auth_key"  africastalking.initialize(username, api_key)      # Initialize a service e.g. SMS  sms = africastalking.SMS    url = "https://nay-bokani.sparkmeter.cloud/api/v0/sms/outgoing"    payload = json.dumps({    "mark_delivered": False  })  headers = {    'Content-Type': 'application/json',    'Authentication-Token': 'auth_key'  }    response = requests.request("GET", url, headers=headers, data=payload)    # print()  json_response = response.json()    if json_response['status'] == 'success':    if json_response["messages"][0]["timestamp"] == max("timestamp"):      for s in range(len(json_response['messages'])):        response = sms.send(json_response['messages']['text'], [json_response['messages']['phone_number']])      print(response)    print(response.text)  

json response

{    "error": null,    "messages": [       {        "id": "46186176-ba91-4072-a93e-0fc089dea750",        "phone_number": "+2348000000000",        "text": "You've just been credited with N10.00 worth of energy",        "timestamp": "2021-06-09T10:14:10.795818"      },      {        "id": "6709099c-22c8-4df5-88e1-24284d8ff61f",        "phone_number": "+2348111111111",        "text": "You've just been credited with N500.00 worth of energy",        "timestamp": "2021-06-09T10:32:11.885605"      }    ],    "status": "success"  }  

I need to be able to extract the phone number and text and use it to send an auto sms using the sms API. I tried to use parse using the recent timestamp, but that will be a problem when multiple json data is returned.

Pointer arithmetic on memory returned from allocator

Posted: 09 Jun 2021 08:34 AM PDT

I'm aware that this question has already been asked and somewhat answered in the past.
However, I've a doubt on a detail that hasn't been cleared out yet (or at least for which I couldn't find a QA).

Consider the following code:

T *mem = allocator_traits::allocate(allocator, 10);  allocator_traits::construct(allocator, mem+1, params...);  

I'm constructing an object at mem[1] even if the object at mem[0] doesn't exist yet. As far as I understand, pointer arithmetic is well defined over a created array of not-constructed objects. However, this QA doesn't answer this specific case:

I should have stated that when I said storage + i will be well-defined under P0593, I was assuming that the elements storage[0], storage[1], ..., storage[i-1] have already been constructed. Although I'm not sure I understand P0593 well enough to conclude that it wouldn't also cover the case where those elements hadn't already been constructed.

In other terms, the author says that this could be UB. On the other side, it would make it impossible for an std::vector implementation to do something like this:

buf_end_size = newbuf + sizeof(T) * size();  

Since I expect it to be valid code (and I've seen this in some implementations), it would mean that pointer arithmetic is well defined for any value of i also when objects aren't constructed.

So, my question is: is this UB or I can safely do pointer arithmetic on the pointer returned by allocate in any case, for example if I want to construct the element at position 1 before that at position 0? Also, does the answer change between C++17 and C++20?

Axios get data is undefined

Posted: 09 Jun 2021 08:34 AM PDT

 axios   .get(     "http://localhost:3089/balance/"+username   )   .then((response) => {     console.log("Response: " + response.data.balance);   });  

the printout says undignified. When I use the url in a normal browser window I get [{"balance":0,"username":"krammy39"}]

why wont my code return the balance?

Two active links at the same time on wordpress

Posted: 09 Jun 2021 08:34 AM PDT

I have this "problem" with my website that is, when i am at the Home Page i have another link of my menu that is not a page, who stays active because i used an anchor on that link.

Basicaly i added the https://dama.ci/notre-histoire url to that link so when i'm on another page of my website i can actually click on the link and go back to the home page where the anchor is attached and this is what causes the problem.

So my question is, since that link on the menu isn't a page what could i actually do to have the link activated only when it's clicked ?

Is there another way to achieve what i'm trying to have on the website ?

If you want to check the site here is the URL

Would be great to see what the most code efficient method of writing this would be - educational purposes

Posted: 09 Jun 2021 08:34 AM PDT

#include <iostream>  using namespace std;    int max = 100, min = 0;  int a = 0;  int b = 0;    int main()  {        cout << "Person A, please guess a number between 0 and 100:";      cin >> a;        if (a > 100) {          cout << "Person A, play by the rules and please pick another number between 0 and 100:";          cin >> a;      }        cout << "Person B, please guess Person A's number - It's between 0-100:";      cin >> b;        if (b > 100) {          cout << "Person B, play by the rules and please pick another number between 0 and 100:";          cin >> b;      }        while (a != b) {          if (a > b) {              cout << "INCORRECT - The guess is too low" << endl;              cout << "Please guess again:";              cin >> b;          }            else if (a < b) {              cout << "INCORRECT - The guess is too high" << endl;              cout << "Please guess again:";              cin >> b;          }      }      while (a == b) {          cout << "Correct! You have guessed Person A's number." << endl;          break;      }        return 0;  }  

I'm new to C++, and whilst learning the basics; I always feel I'm writing too much. So it would be great to see what a c++ expert views how efficiently this code could be written. So yeah, any help would be greatly appreciated.

Mouse Over function not working in React JS

Posted: 09 Jun 2021 08:33 AM PDT

I have a div that should show react-player controls when i move my mouse over the player but it is not.

<div ref={videoControls} className={classes.controlWrapper}        style={{visibility: (mouseOver && mouseMove) ? 'visible' : 'hidden'}}>  ...  </div>  

The mouseOver works fine but mouseMove does not work.

This is my mouseMove function

const [mouseMove, setMouseMove] = useState(false)     const onMouseMove = () => {          setMouseMove(true)          if(!timeout.current)          timeout.current = setTimeout(() => {              setMouseMove(false)              clearTimeout(timeout.current)              timeout.current = null          }, 6000);      }    useEffect(() => {          if (!props.session) return          if (props.session.room) dispatch(setRoom(props.session.room))          console.log("Session live view mount")          window.addEventListener('mousemove', onMouseMove)          return () => {              dispatch(setRoom(null))              console.log("Session live view umount")              window.removeEventListener('mousemove', onMouseMove)          }      }, [props.session])  

ASP.Net Core 3.1 MVC Error while using stored procedures

Posted: 09 Jun 2021 08:34 AM PDT

The client wants all communication with the database to be done through stored procedures. To do this in ASP I am using FromSqlRaw like so:

_context.Visit.FromSqlRaw("exec VisitApi_RecordVisit @User", userParam)  

The stored procedure does its job and the visits are recorded. However every time it triggers an error is thrown in the console:

System.InvalidOperationException: The required column 'Id' was not present in the results of a 'FromSql' operation.  

While researching this error I found that this error is because the table it is recording to has a primary key. To fix this problem I would have to drop the primary key column and then add it back with the "Identity Specification" set to "No". I have also tried adding .HasNoKey(); to the table and tried to update the database. However, when I do it tells me I need to drop the column and add it back again. The problem is that there is already ~200,000 visits already recorded and I don't want to lose the Ids that are already tied to each row. Is there any way for me to get rid of this error without dropping the column and or deleting existing data?

How to display the latest records from the another table if not available then at least display the left table data

Posted: 09 Jun 2021 08:34 AM PDT

I have two table

  1. tbl_register
  2. tbl_societyMyprofile

What I am doing is, I have to display the records from the tbl_register table and I have to display the latest record from the tbl_societyMyprofile table.

I have a tried the below query.

SELECT *  FROM   tbl_register AS r         LEFT JOIN tbl_societymyprofile AS m                ON r.reg_id = m.reg_id  WHERE  r.reg_id =(SELECT Max(secretary_id) AS c_id                     FROM   tbl_societymyprofile                     WHERE  reg_id = 17                     GROUP  BY reg_id DESC)         AND r.is_active = 1   

Also if the records are not available in the tbl_societymyprofile then at least display the records from the tbl_register table.

reg_id id is the primary id. As of now I have the records in the tbl_register table but don't have the records in the tbl_societymyprofile and i am getting the empty records

Data step merge without using BY(id)

Posted: 09 Jun 2021 08:33 AM PDT

I need to merge two datasets like the ones below using a data step:

Data have1;  x=1; output;  x=2; output;  x=3; output;  Run;    Data have2;  y = 'A';  z = 'B';  Run;    Data want;  Merge have1 have2;  Run;  

The result should be the following:

x   y   z  1   A   B  2   A   B  3   A   B  

However when I run the merge SAS only merges the first row and gives me the following:

x   y   z  1   A   B  2     3     

I know this can be done using a left join, however in order to process the variables in the full dataset I would prefer doing it via a merge. Can anyone help please?

How to limit my decimal value to 2 places on my <td>

Posted: 09 Jun 2021 08:34 AM PDT

I'm making a query to my database to return a value of double precision. This value in my database goes up to 17 decimal places but I only want to display 2 decimal places on the web page.

This is my html with the table. The value of the decimal goes into the {{savings_percent}}

 <table class="table text-light text-end">                                          <thead>                                              <tr>                                                                                                    <th scope="col">CHW</th>                                                                                       </tr>                                          </thead>                                          <tbody class="text-end">                                              <tr id="decimal">                                                  <th scope="row">%</th>                                                  {{#with chw}}                                                  <td class='rounded'>{{savings_percent}}</td>                                                  {{/with}}                                                                                        </tbody>                                      </table>  

This is how I'm trying to grab the value, convert it to decimal and then give it a fixed number of two decimals. The console is giving me $(...).val(...).toFixed is not a function. Does anyone have a solution on how I can fix this?

let decimal = parseFloat($("#decimal .rounded").text())            window.onload = () => {            $('.rounded').val(decimal).toFixed(2)            console.log(decimal)         };  

when i deploy Airmed Foundation - Node.js Terminal, I always have the following problems

Posted: 09 Jun 2021 08:34 AM PDT

Here is the code error

This is the address of the open source project:https://github.com/the-chain/airmedfoundation-terminal

when i use code

node ./node_modules/sails/bin/sails.js l --redis --safe  

to run the server, An error occurred,but i don't know the reason.

my node verison: v8.15.0 hyperledger version: v1.4.3 Can someone help me?

How to generate a tensor representing, for each pair of rows in a matrix, whether elements at the same position both = 1?

Posted: 09 Jun 2021 08:34 AM PDT

I'm trying to compare every row in a matrix to every other row in the same matrix, yielding, for each pair, a row showing whether each element of those two rows both equal 1.

Example: if I have this matrix as input:

[[1,0,1],   [0,1,1],   [0,0,0]]  

I'd want to get this tensor:

[[[1,0,1],    [0,0,1],    [0,0,0]],   [[0,0,1],    [0,1,1]    [0,0,0]],   [[0,0,0],    [0,0,0],    [0,0,0]]]  

Alternatively, if it's easier, my eventual goal is to reduce this tensor down to a matrix where each row represents whether ANY elements in a pair of rows from the original matrix both =1. So, the tensor above would get reduced to:

[[1,1,0],   [1,1,0],   [0,0,0]]  

If it's easier to go straight to that without going through the intermediate tensor, let me know.

Difference b/w std::vector<int> V(N) and std::vector<int> V[N]?

Posted: 09 Jun 2021 08:34 AM PDT

Are these 2 statements std::vector<int> V(N) and std::vector<int> V[N] equivalent??

Also what do they mean?

search for keywords in file directory

Posted: 09 Jun 2021 08:34 AM PDT

I'm having difficulties to find the filenames that contain a keyword from a predetermined list. I manage to find all files from the directory and subdirectories, however finding keywords is not functioning. I would like to list all the files in my directory that contain a keyword in it's name:

path = ':O drive'  keywords = ['photo', 'passport', 'license']  files = [] # list of all files in directory  result = []  # list store our results    #list all files  for root, directories, file_path in os.walk(path, topdown=False):          for name in file_path:              files.append(os.path.join(root, name))    #find keywords in files              for filename in files:      for keyword in keywords:          if keyword in filename:              result[keyword].os.path.join(path, filename)    print(result)  

Validation not working and form submisstion

Posted: 09 Jun 2021 08:33 AM PDT

I am new to PHP and want to create a simple form as below and want to validate it and submit forms using SubmitForm.php

I am facing issue with phone validation, Phone validates even when i enter characters, i want to validate numbers and + sign for example +1 12345678, +91 1234123123

and i want to submit form only when all validation passed "SubmitForm.php"

        <div class="col-md-12 mb-3">            <input class="form-control" type="text" name="name" placeholder="Full Name" required>            <div class="valid-feedback">Username field is valid!</div>            <div class="invalid-feedback">Username field cannot be blank!</div>          </div>            <div class="col-md-12 mb-3">            <input class="form-control" type="email" name="email" placeholder="E-mail Address" required>            <div class="valid-feedback">Email field is valid!</div>            <div class="invalid-feedback">Email field cannot be blank!</div>          </div>            <div class="col-md-12 mb-3">            <input class="form-control" type="tel" name="tel" placeholder="Phone" required>            <div class="valid-feedback">Phone field is valid!</div>            <div class="invalid-feedback">Phone field cannot be blank!</div>          </div>            <div class="col-md-12 mb-3">            <textarea name="message" id="message" placeholder="Your Message"></textarea>          </div>            <div class="col-md-12 mt-3">            <label class="mb-3 mr-1" for="gender">I am interested in : </label>              <input type="radio" class="btn-check" name="gender" id="male" autocomplete="off" required>            <label class="btn btn-sm btn-outline-secondary" for="male">Call Back</label>              <input type="radio" class="btn-check" name="gender" id="female" autocomplete="off" required>            <label class="btn btn-sm btn-outline-secondary" for="female">Brochure</label>              <input type="radio" class="btn-check" name="gender" id="secret" autocomplete="off">            <label class="btn btn-sm btn-outline-secondary" for="secret">Price details</label>          </div>            <div class="form-button mt-3">            <button id="submit" type="submit" class="btn btn-primary">Submit</button>          </div>        </form>      </div>    </div>  </div>   </div> </div>  

(function () {  'use strict'  const forms = document.querySelectorAll('.requires-validation')  Array.from(forms)    .forEach(function (form) {      form.addEventListener('submit', function (event) {        if (!form.checkValidity()) {          event.preventDefault()          event.stopPropagation()        }          form.classList.add('was-validated')      }, false)    })  })()
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;700;900&display=swap');    *, body {      font-family: 'Poppins', sans-serif;      font-weight: 400;      -webkit-font-smoothing: antialiased;      text-rendering: optimizeLegibility;      -moz-osx-font-smoothing: grayscale;  }    html, body {      height: 100%;      background-color: #152733;      overflow: hidden;  }      .form-holder {        display: flex;        flex-direction: column;        justify-content: center;        align-items: center;        text-align: center;        min-height: 100vh;  }    .form-holder .form-content {      position: relative;      text-align: center;      display: -webkit-box;      display: -moz-box;      display: -ms-flexbox;      display: -webkit-flex;      display: flex;      -webkit-justify-content: center;      justify-content: center;      -webkit-align-items: center;      align-items: center;      padding: 60px;  }    .form-content .form-items {      border: 3px solid #fff;      padding: 40px;      display: inline-block;      width: 100%;      min-width: 540px;      -webkit-border-radius: 10px;      -moz-border-radius: 10px;      border-radius: 10px;      text-align: left;      -webkit-transition: all 0.4s ease;      transition: all 0.4s ease;  }    .form-content h3 {      color: #fff;      text-align: left;      font-size: 28px;      font-weight: 600;      margin-bottom: 5px;  }    .form-content h3.form-title {      margin-bottom: 30px;  }    .form-content p {      color: #fff;      text-align: left;      font-size: 17px;      font-weight: 300;      line-height: 20px;      margin-bottom: 30px;  }      .form-content label, .was-validated .form-check-input:invalid~.form-check-label, .was-validated .form-check-input:valid~.form-check-label{      color: #fff;  }    .form-content input[type=text], .form-content input[type=password], .form-content input[type=email], .form-content select {      width: 100%;      padding: 9px 20px;      text-align: left;      border: 0;      outline: 0;      border-radius: 6px;      background-color: #fff;      font-size: 15px;      font-weight: 300;      color: #8D8D8D;      -webkit-transition: all 0.3s ease;      transition: all 0.3s ease;      margin-top: 16px;  }      .btn-primary{      background-color: #6C757D;      outline: none;      border: 0px;       box-shadow: none;  }    .btn-primary:hover, .btn-primary:focus, .btn-primary:active{      background-color: #495056;      outline: none !important;      border: none !important;       box-shadow: none;  }    .form-content textarea {      position: static !important;      width: 100%;      padding: 8px 20px;      border-radius: 6px;      text-align: left;      background-color: #fff;      border: 0;      font-size: 15px;      font-weight: 300;      color: #8D8D8D;      outline: none;      resize: none;      height: 120px;      -webkit-transition: none;      transition: none;      margin-bottom: 14px;  }    .form-content textarea:hover, .form-content textarea:focus {      border: 0;      background-color: #ebeff8;      color: #8D8D8D;  }    .mv-up{      margin-top: -9px !important;      margin-bottom: 8px !important;  }    .invalid-feedback{      color: #ff606e;  }    .valid-feedback{     color: #2acc80;  }
<div class="form-body">                 <div class="row">              <div class="form-holder">                  <div class="form-content">                      <div class="form-items">                          <h3>Register you interest</h3>                          <p>Fill in the data below, we will get back to you!</p>                          <form class="requires-validation" action="SubmitFORM.php" method="POST" novalidate>                                <div class="col-md-12 mb-3">                                 <input class="form-control" type="text" name="name" placeholder="Full Name" required>                                 <div class="valid-feedback">Username field is valid!</div>                                 <div class="invalid-feedback">Username field cannot be blank!</div>                              </div>                                <div class="col-md-12 mb-3">                                  <input class="form-control" type="email" name="email" placeholder="E-mail Address" required>                                   <div class="valid-feedback">Email field is valid!</div>                                   <div class="invalid-feedback">Email field cannot be blank!</div>                              </div>                               <div class="col-md-12 mb-3">                                   <input class="form-control" type="tel" name="tel" placeholder="Phone" required>                                    <div class="valid-feedback">Phone field is valid!</div>                                   <div class="invalid-feedback">Phone field cannot be blank!</div>                             </div>                               <div class="col-md-12 mb-3">                                <textarea name="message" id="message" placeholder="Your Message"></textarea>                             </div>                                 <div class="col-md-12 mt-3">                              <label class="mb-3 mr-1" for="gender">I am interested in : </label>                                <input type="radio" class="btn-check" name="gender" id="male" autocomplete="off" required>                              <label class="btn btn-sm btn-outline-secondary" for="male">Call Back</label>                                <input type="radio" class="btn-check" name="gender" id="female" autocomplete="off" required>                              <label class="btn btn-sm btn-outline-secondary" for="female">Brochure</label>                                <input type="radio" class="btn-check" name="gender" id="secret" autocomplete="off" >                              <label class="btn btn-sm btn-outline-secondary" for="secret">Price details</label>                              </div>                                             <div class="form-button mt-3">                                  <button id="submit" type="submit" class="btn btn-primary">Submit</button>                              </div>                          </form>                      </div>                  </div>              </div>          </div>            </div>   

VB.NET If statement based on Arduino Serial Output

Posted: 09 Jun 2021 08:34 AM PDT

I am building a VB.NET Win Forms app that is reading the serial output of an Arduino and I want the VB.Net app to do something based on what it reads from the Arduino. The problem I am encountering is that even though I can read from the Arduino I can't seem to write it into an if statement.

The Arduino is a simple 3 button schematic. A red, yellow, and green button attached to digital pins 2,3, and 4. When one button is pressed the Arduino outputs the text "Red Button On", "Yellow Button On", or "Green Button On" depending on which button is pressed.

In the VB.Net app I have a label named lblHintRequest. I can load the arduino serial output onto this label. However, once I load the arduino serial output onto this label I can't seem to do anything with it. What I need is an if statement that will read which button is pressed and then do something depending on the button pressed. I have also tried adding a timer that ticks ever 500 ms that would read the label and this still did not work. The vb.net app just keeps skipping over the if statement.

The last thing I can think of trying is to use a textbox instead of a label and maybe that would help? But I really want this to be a label.

VB.NET Code

Imports System.IO.Ports  Public Class frmRoom    Private Sub frmRoom_Load(sender As Object, e As EventArgs) Handles MyBase.Load   SerialPort1.Open()  End Sub     Private Sub SerialPort1_DataReceived(sender As Object, e As SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived        'Searching for data input      Dim ReadCode As String      ReadCode = SerialPort1.ReadLine        'Print the button press      lblHintRequest.Invoke(New MethodInvoker(Sub() lblHintRequest.Text = ReadCode), Nothing)      'This code will not run even though when I invoke the lblhintrequest it shows re button on      If lblHintRequest.Text = "Red Button On" Then           lblHintRequest.ForeColor = Color.Red      End If    'This if statement does not work either      If lblHintRequest.Invoke(New MethodInvoker(Sub() lblHintRequest.Text = ReadCode), Nothing) = "Red Button On" Then          MsgBox("hit")      End If      End Sub  End Class  

Arduino Code

const int RedButton = 2;  const int YellowButton = 3;  const int GreenButton = 4;  const int ledpin = 13;    int buttonstateRed =0;  int buttonstateYellow =0;  int buttonstateGreen =0;    void setup() {    // put your setup code here, to run once:    Serial.begin(9600);  pinMode(ledpin,OUTPUT);  pinMode(RedButton, INPUT);  }    void loop() {    // put your main code here, to run repeatedly:  buttonstateRed = digitalRead(RedButton);  if (buttonstateRed == HIGH){    digitalWrite(ledpin, HIGH);    Serial.println("Red Button On");  }    buttonstateYellow = digitalRead(YellowButton);  if (buttonstateYellow == HIGH){    digitalWrite(ledpin, HIGH);    Serial.println("Yellow Button On");  }      buttonstateGreen = digitalRead(GreenButton);  if (buttonstateGreen == HIGH){    digitalWrite(ledpin, HIGH);    Serial.println("Green Button On");  }    if (buttonstateRed == LOW && buttonstateYellow == LOW && buttonstateGreen == LOW){    digitalWrite(ledpin, LOW);    //Serial.println("No Button Pressed");  }    Serial.flush();  delay(500);    //Serial.println("Hello");  //delay(250);  }  

Android Studio gradle doesn't show run configurations

Posted: 09 Jun 2021 08:34 AM PDT

I need to get the SHA-1 key for Firebase authentication for my app. But I am not able to find the 'run configurations' menu anywhere to run the signing report. However, in another one of my projects that was created in a friend's system, I can see it. Here's the image of my project

Here's the image of what is supposed to show

Mod Rewrite - HTTPS Redirect Causing 404 Errors

Posted: 09 Jun 2021 08:34 AM PDT

I have an issue where my htaccess file is causing 404 errors with the URLs that are supposed to be rewritten when the HTTPS condition and rules are added. Everything works fine with the rules when the HTTPS condition and rule are removed. Can anyone point me in the right direction please?

Here is my .htaccess file.

RewriteEngine ON    # All Projects Rule    RewriteRule ^projects/?$ all-projects.php [NC,QSA,L]    # Add Project Rule    RewriteRule ^projects/add/?$ add-new-project.php [NC,QSA,L]    # Assigned Projects Rule    RewriteRule ^projects/assigned/?$ assigned-projects.php [NC,QSA,L]    # Single Project Rule    RewriteRule ^projects/([^/]+)/([^/]+)/?$ single-project.php?id=$1&section=$2 [NC,QSA,L]    # Single Project Subfolders    RewriteRule ^(projects)/([^/]+)/([^/]+)/(.*)/?$ $1/$2/$3/?subfolder=$4 [NC,QSA,L]    # All Users Rule    RewriteRule ^users/([^/]+)/([^/]+)/?$ all-users.php?sort=$1&direction=$2 [NC,QSA,L]    # Add User Rule    RewriteRule ^users/add-user/?$ add-new-user.php [NC,QSA,L]    # Add Client Rule    RewriteRule ^users/add-client/?$ add-new-client.php [NC,QSA,L]    # Force HTTPS    <If "%{HTTP_HOST} == 'example.com'">      RewriteCond %{HTTPS} !=on      RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]  </If>  

Also, here are a few examples of raw URLs and what they become after the rules are applied

  1. all-projects.php?id=2&section=documents becomes /projects/2/documents/

  2. add-new-user.php becomes /users/add-user/

  3. all-users.php?sort=id&direction=asc becomes /users/id/asc

Finding a substring of a string with recursion using only the next Methods of class String : charAt(),substring(),length()

Posted: 09 Jun 2021 08:34 AM PDT

The header if the method should be ONLY (String a, String b), no overloading!

examples : a = welcome b = come output : true.

a = hi b = hi output : false.

a = goal b = gl output : false.

This is the code I got to write so far, but the problem is that it returns true in the case of : a = "subtring", b = string. because it keeps moving forward until it finds the t and goes until the end and returns true. I'm stuck about thinking how do I return to the original string if I encountered the wrong letter, recursively of course. My code :

 public static boolean isSubstring (String s1, String s2){      //checking if s2 is a substring of s1   if(s2.length()>=s1.length())    return false;   if(s2.length()==0)    return true;   if(s1.length()==0)    return false;   if(s1.charAt(0)==s2.charAt(0)){       return isSubstring(s1.substring(1),s2.substring(1));  }  //if letters are not equal   return isSubstring(s1.substring(1),s2);  }  

How to write same axios call using redux-api-middleware?

Posted: 09 Jun 2021 08:34 AM PDT

How can I rewrite this axios call using the redux-api-middleware?

axios('https://localhost:8080/api/getRegistrationApplication', {    responseType: 'blob',    headers: {      Authorization: `Bearer ${token}`,    },  })  .then(response => {    const file = new Blob(      [response.data],      { type: 'application/pdf' });    const fileURL = URL.createObjectURL(file);    setData(fileURL)    setPopupState({ loaded: true, retry: -1 });        })  .catch(error => console.log(error));  

When I try to write the same call using the redux-api-middleware I get payload as undefined:

getRegistrationApplication: () => {    return {      [RSAA]: {        endpoint: `https://localhost:8080/api/getRegistrationApplication`,        method: "GET",        headers: {          "Content-Type": "application/pdf"        },        types: [          REGISTRATION_APPLICATION_GET_REQUEST,          REGISTRATION_APPLICATION_GET_SUCCESS,          REGISTRATION_APPLICATION_GET_FAILURE,        ],      }    }  }  

I am trying to read pdf file form the backend which only seems to be working when I write my action using the axios call above.

How to queue requests using react/redux?

Posted: 09 Jun 2021 08:34 AM PDT

I have to pretty weird case to handle.

We have to few boxes, We can call some action on every box. When We click the button inside the box, we call some endpoint on the server (using axios). Response from the server return new updated information (about all boxes, not the only one on which we call the action).

Issue: If user click submit button on many boxes really fast, the request call the endpoints one by one. It's sometimes causes errors, because it's calculated on the server in the wrong order (status of group of boxes depends of single box status). I know it's maybe more backend issue, but I have to try fix this on frontend.

Proposal fix: In my opinion in this case the easiest fix is disable every submit button if any request in progress. This solution unfortunately is very slow, head of the project rejected this proposition.

What we want to goal: In some way We want to queue the requests without disable every button. Perfect solution for me at this moment:

  • click first button - call endpoint, request pending on the server.
  • click second button - button show spinner/loading information without calling endpoint.
  • server get us response for the first click, only then we really call the second request.

I think something like this is huge antipattern, but I don't set the rules. ;)

I was reading about e.g. redux-observable, but if I don't have to I don't want to use other middleware for redux (now We use redux-thunk). Redux-saga it will be ok, but unfortunately I don't know this tool. I prepare simple codesandbox example (I added timeouts in redux actions for easier testing).

I have only one stupid proposal solution. Creating a array of data needs to send correct request, and inside useEffect checking if the array length is equal to 1. Something like this:

const App = ({ boxActions, inProgress, ended }) => {    const [queue, setQueue] = useState([]);      const handleSubmit = async () => {  // this code do not work correctly, only show my what I was thinking about         if (queue.length === 1) {        const [data] = queue;        await boxActions.submit(data.id, data.timeout);        setQueue(queue.filter((item) => item.id !== data.id));    };    useEffect(() => {      handleSubmit();    }, [queue])        return (      <>        <div>          {config.map((item) => (            <Box              key={item.id}              id={item.id}              timeout={item.timeout}              handleSubmit={(id, timeout) => setQueue([...queue, {id, timeout}])}              inProgress={inProgress.includes(item.id)}              ended={ended.includes(item.id)}            />          ))}        </div>      </>    );  };  

Any ideas?

DatePickerDialog buttons have a disable style

Posted: 09 Jun 2021 08:34 AM PDT

I'm working on a ToDo list, and I include a DatePickerDialog to select the limit date but when I click on the EditText element and shows the DatePickerDialog, the Cancel and Ok buttons are showed as diabled but still you can select any of those and see the date in the EditText.

enter image description here

This is the code of my EditText

<EditText      android:id="@+id/dateTask"      style="@style/text_element"      android:layout_width="wrap_content"      android:layout_height="wrap_content"      android:layout_marginStart="28dp"      android:layout_marginTop="40dp"      android:focusable="false"      android:hint="@string/date_hint"      app:layout_constraintStart_toStartOf="parent"      app:layout_constraintTop_toBottomOf="@+id/description" />  

And this is the code of the DatePickerDialog

val date = DatePickerDialog.OnDateSetListener { view, year, month, dayOfMonth ->          myCalendar.set(Calendar.YEAR, year)          myCalendar.set(Calendar.MONTH, month)          myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth)          updateDate()      }        dateTask.setOnClickListener {          context?.let { view ->              DatePickerDialog(view, date, myCalendar.get(Calendar.YEAR),                       myCalendar.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH)).show()          }      }  

I was reading about the themes, but I'm not sure that there could be a problem. But here it is:

<resources xmlns:tools="http://schemas.android.com/tools">  <!-- Base application theme. -->  <style name="Theme.SimpleToDo" parent="Theme.MaterialComponents.DayNight.DarkActionBar">      <!-- Primary brand color. -->      <item name="colorPrimary">@color/baby_blue</item>      <item name="colorPrimaryVariant">@color/blue_grotto</item>      <item name="colorOnPrimary">@color/navy_blue</item>      <!-- Secondary brand color. -->      <item name="colorSecondary">@color/blue_grotto</item>      <item name="colorSecondaryVariant">@color/teal_700</item>      <item name="colorOnSecondary">@color/white</item>      <!-- Customize your theme here. -->  </style>    <style name="Theme.SimpleToDo.NoActionBar">      <item name="windowActionBar">false</item>      <item name="windowNoTitle">true</item>  </style>    <style name="fragment_toolbar">      <item name="android:background">@color/navy_blue</item>  </style>    <style name="text_element">      <item name="android:textColor">@color/blue_grotto</item>  </style>    <style name="background_list">      <item name="android:background">@color/baby_blue</item>  </style>    <style name="Theme.CardDemo.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />    <style name="Theme.CardDemo.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />  

ValueError: invalid literal for int() with base 10: '$16.10' (I fixed the question I just need some help to lay off my question ban)

Posted: 09 Jun 2021 08:34 AM PDT

The code below is my current code

class Money(object):      def __init__(self, dollars=0, cents=0):          self.dollars = dollars + cents//100          self.cents = cents %100      def __radd__(self, other):          if isinstance(other, Money):              other = other.cents + other.dollars * 100          elif isinstance(other, int):              other = other * 100          elif isinstance(other, float):              other = int(other * 100)          money = int(other) + float(self.cents + self.dollars * 100)          self.dollars = money // 100          self.cents = money % 100          return "$%d.%2d" %(self.dollars,self.cents)  def money_text_2():      m1 = Money(3, 50)      m2 = Money(2, 60)      print(m1 == m2)      print(m1 + m2)      print(10 + m1 + m2)  money_text()  

But it keeps getting this error:

money = int(other) + float(self.cents + self.dollars * 100)  ValueError: invalid literal for int() with base 10: '$16.10'  

I spent the past 30 minutes trying to find a solution with no results

Can someone point it out for me?

JavaScript seconds to time string with format hh:mm:ss

Posted: 09 Jun 2021 08:34 AM PDT

I want to convert a duration of time, i.e., number of seconds to colon-separated time string (hh:mm:ss)

I found some useful answers here but they all talk about converting to x hours and x minutes format.

So is there a tiny snippet that does this in jQuery or just raw JavaScript?

Get IP address of an interface on Linux

Posted: 09 Jun 2021 08:34 AM PDT

How can I get the IPv4 address of an interface on Linux from C code?

For example, I'd like to get the IP address (if any) assigned to eth0.

Show a one to many relationship as 2 columns - 1 unique row (ID & comma separated list)

Posted: 09 Jun 2021 08:34 AM PDT

I need something similar to these 2 SO questions, but using Informix SQL syntax.

My data coming in looks like this:

id     codes    63592  PELL  58640  SUBL  58640  USBL  73571  PELL  73571  USBL  73571  SUBL  

I want to see it come back like this:

id     codes     63592  PELL  58640  SUBL, USBL  73571  PELL, USBL, SUBL  

See also group_concat() in Informix.

No comments:

Post a Comment