Read CSV and transform html table with barcode

I’m very newbie on javascript and html, i’m sorry for elementar question.
I have a csv that I would like to read and transform into an html table and the values of the first column transform them into barcodes and insert them into the table, here is the code, unfortunately I have incorrectly set the parse of the rows inside the csv, but I can not see where. Please can you help me, I know I am a beginner and I apologize for the silly question.

<!DOCTYPE HTML>
<html>
<head>
 <meta charset="UTF-8">
<style>
<!-- qui il css per la tabella -->
</style>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/[email protected]/dist/JsBarcode.all.min.js"></script>
<script>
function createSVG() {
    var svg = document.createElementNS("http://www.w3.org/2000/svg", 'svg');
    svg.setAttribute('id', 'barCode');
    document.body.appendChild(svg);
}
function myFunction() {
  createSVG();
  var x = document.createElement("TR");
  x.setAttribute("id", "myTr");
  document.getElementById("myTable").appendChild(x);

  var y = document.createElement("TD");
  var el = document.getElementById("barCode");
  var barcode = document.createElementNS("http://www.w3.org/2000/svg", "svg");
  barcode += JsBarcode("#barCode", "ciao");
  y.appendChild(barcode);
  document.getElementById("myTr").appendChild(y);
}
</script>
<script>
function Upload() {
    function createSVG() {
    var svg = document.createElementNS("http://www.w3.org/2000/svg", 'svg');
    svg.setAttribute('class', 'barCode');
    document.body.appendChild(svg);
    }
    var fileUpload = document.getElementById("fileUpload");
        var regex = /^([a-zA-Z0-9s_\.-:])+(.csv|.txt)$/;
        if (regex.test(fileUpload.value.toLowerCase())) {
            if (typeof (FileReader) != "undefined") {
                var reader = new FileReader();
                reader.onload = function (e) {
                        var table = document.createElement("table");
                    const tR = document.createElement("tr");
                    const tD = document.createElement("td");
                    table.setAttribute("id", "mytable");
                                    var rows = e.target.result.split("n");  
                     for (var i = 0; i < rows.length; i++) {
                                var cells = rows[i].split(";", 5);  
                            var cellsq = rows[2].split(";", 5); <!-- questo è il mio dataset pulito dalle ultime colonne prende solo la riga 2 
                                                    var cellsw = rows[3].split(";", 5); <!-- prende solo la riga 3 
                                var cella = rows[a].split(";", 5);  
                            if (cells.length > 1) {
                            var row = table.insertRow(-1);
                                const tDt = document.createElement("td");
                                                        const cellsText = document.createTextNode(cells);
                                tDt.appendChild(cellsText);
                                                        tR.appendChild(tDt);
                            document.body.appendChild(tDt);
                            createSVG();    
                                var tDb = document.createElement("td");
                                                        var elb = document.getElementById("barCode");
                                                        var barcode = document.createElementNS("http://www.w3.org/2000/svg", "svg");
                            var barcodE = "<svg class='barCode' >" + JsBarcode(".barCode", cells[0].split(",")) + "</svg>"; 
                                                        tDb.append(barcodE);
                            tR.appendChild(tDb);  
                                                        
                          for (var j = 0; j < cells.length; j++) {
                
                                 var cell = row.insertCell(-1);
                             cell.innerHTML = cells[j]; 
                                }
                        }   
                    }       
                    var dvCSV = document.getElementById("dvCSV");
                    dvCSV.innerHTML = "";
                    dvCSV.appendChild(table);
                    document.body.appendChild(table);                   
                }
                reader.readAsText(fileUpload.files[0]);
            } else {
                alert("This browser does not support HTML5.");
            }
        } else {
            alert("Please upload a valid CSV file.");
            }
    }
</script>
</head>
<body>
  <p>Click the button to create a TR and a TD element.</p>

  <button onclick="myFunction()">Try it</button>

  <input type="file" id="fileUpload" />
  <input type="button" id="upload" value="Upload" onclick="Upload()" />
  <hr />
  <div id="dvCSV"></div>                    
  <table id="mytable"></table>
</body>
</html>

my goal would be to generate a table of the type where the last column is populated by the individual barcodes of the first values

react website not loading with firebase. What am I doing wrong?

I looked at the suggestions online for how to fix firebase, but they didn’t work. I tried setting my firebase.json hosting feature where says “public” to “build”, but that didn’t work so what else should I do? I don’t get errors when I compile it, but the website is blank when I run “npm start”. Here is the relevant javascript code:

import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';

const firebaseApp = firebase.initializeApp({ 
    apiKey: "AIzaSyBl_kNHH8oIn17VrR2mcKQqOn3eAZo-Osw",
    authDomain: "instagram-clone-react-82ab7.firebaseapp.com",
    projectId: "instagram-clone-react-82ab7",
    storageBucket: "instagram-clone-react-82ab7.appspot.com",
    messagingSenderId: "562669348604",
    appId: "1:562669348604:web:ae6a7cee3832803e761979",
    measurementId: "G-6PENZ2M8LS"
});

const db = firebaseApp.firestore();
const auth = firebase.auth();
const storage = firebase.storage();

export { db, auth, storage };

export default db;

App.js file code:

import React, { useState, useEffect } from 'react';
import './App.css';
import Post from './Post';
import { db } from './firebase';

function App() {
  const [posts, setPosts] = useState([]);
  
  //useEffect: Runs a piece of code based on a specific condition

  useEffect(() => {
    //this is where the code runs
    db.collection('posts').onSnapshot(snapshot => {
      //Everytime a new post is added, this line of code activates
      setPosts(snapshot.docs.map(doc => doc.data()))
    })   //"posts" inside of firebase also everytime a document gets modified inside of post it takes a screenshot

  }, [] );   //conditions go here and there just variables 



  return (
    <div className="App">

      <div className="app__header">
        <img 
          className="app__headerImage"
          src="https://www.instagram.com/static/images/web/mobile_nav_type_logo.png/735145cfe0a4.png" 
          alt="instagram_text"
        />
      </div>

      <h1>Hello clever programmers let's build a react app!!!</h1>
      
      {
        posts.map(post => (
          <Post username={post.username} caption={post.caption} imageUrl={post.imageUrl} />
        ))
      }
    </div>
  );
}

export default App;

JavaScript/JQuery how can I get id of the caller to the new view

I have two links and both links redirect to the same new url (View) .

But depending on which href link was clicked, I need to show or hide buttons on the new view.

My question is there a way to know the id of the event/caller that redirected to current/new view?

I tried looking into jquery history method but wasn’t successful.

Thank you

Read Text input .docx .pdf File

I want to read text in .docx .pdf File in JS environment.

but No exist Reading Text Example from input File Object.
Some Other question’s that Reading Text from File on path.

This is my code

// template

<v-file-input @change="uploadFile" />

// script

async uploadFile(file) {
  if (file != null) {
    // Extract file ext
    this.test_file = file;
    const ext = this.test_file.name.substring(this.test_file.name.lastIndexOf('.') + 1, this.test_file.name.length).toLowerCase();

    // Process by ext
    switch (ext) {
      case 'txt':
        let text = await this.test_file.text();
        this.file_text = text;
        break;
      case 'docx':
        // How can I process docx file
        break;
      case 'pdf':
        // How can I process pdf file
        break;
      default:
        break;
    }
  } else {
    this.file_text = '';
  }
}

Cannot GET when providing url parameters [duplicate]

I’ve created simple React application which uses React-Router-Dom. It’s basically a single-page application, however, I’m using routing in order to change value of variables in some rare cases and change the interface slightly for presentation purposes.

Here is the code I use, which allows the user to enter custom values ​​in the url. It works in local environment like it should.

<Router>
  <Routes>
    <Route path="/" element={<App />} />
    <Route path="/:exampleone/:exampletwo/:examplethree" element={<App />} />
  </Routes>
</Router>

Url examples:

http://localhost:3000/

http://localhost:3000/65/45/35

However, when I’m deploying the application (which runs in Azure, AzureWebsites.net) normal version works perfectly, but if I try to add url parameters error popups “Cannot GET (url parameters)”.

Does anyone have an idea how to fix this? Please ask if something else from the code is needed, I’m not sure what else I should provide here.

Jest: Failed prop type: Invalid prop `source` supplied to `Image`, expected one of type [number]

I am using jest with react-native to run unit test cases. And whenever it encounters Image it throws the following warning

 Warning: Failed prop type: Invalid prop `source` supplied to `Image`, expected one of type [number].
          at Component (~/.../node_modules/react-native/jest/mockComponent.js:28:18)
          at SummaryTile (~/.../src/components/home/SomeComponent.tsx:18:3)

      23 |   >
      24 |     {backgroundImg || (
    > 25 |       <Image
         |       ^
      26 |         source={require('images/cloud.png')}
      27 |       />

I tried to replace the code to

<Image src={{uri: require('images/cloud.png')}} />

as suggested in https://stackoverflow.com/a/36460928/3855179 but it started throwing the following warning and the application breaks

Warning: Failed prop type: Invalid prop `source` supplied to `Image`, expected one of type [string, number].
    at Image (http://expo_url:19000/node_modules/expo/AppEntry.bundle?platform=android&dev=true&hot=false&strict=false&minify=false:76209:43)
Jest Version: 26.6.3
React Native version: 0.64.3
Node Version: 16.14.2

Any idea how this can be handled?

how to gather data from different page

Here I have created a filter functionality in which user will select multiple checkbox and based on these selected checkbox ajax will get product data and will show on main page however, my problem is whenever I select collection name it shows only one pages data so could you help me to show multiple pages data based on checkbox selection any help would be appreciated Thanks.

  $('.vendor_filter_item input[type="checkbox"]').click(function(){

    var checkboxes = document.querySelectorAll('.vendor_filter_item input[type="checkbox"]:checked');

    for (var i = 0; i < checkboxes.length; i++) {

      var check_value = checkboxes[i].value;

          $.ajax({
            url:check_value,
            type:'GET',   
            success: function(data) {
              var content =  $('<div>').append(data).find('.collection_all_product #product-grid ');       
            
              if($('.CollectionInner__data').html() == ""){
                $('.CollectionInner__data').html($('.js_inner_product').html());          
              }
              $('.js_inner_product').html("");
              $('.js_inner_product ').append( content );  
              $('.js_inner_product').show();
              $('.collection_all_product').hide();
            }
          }); 
        
     

    }

  });

In Vue, setting props default value to computed property

  props: {
    rules: {
        type: Array,
        required: false,
        default: () => [
            (file) => !file
                || file.size < 10000000
                || this.getJsonDataByLocale.less_than_10mb_message,
            (file) => !file
                || ACCEPTED_FILE_TYPES.includes(file.type)
                || this.getJsonDataByLocale.wrong_file_message,
        ],
    }
}

This is generic component. I’m trying to set rules default to a computed property. ‘this.getJsonDataByLocale’ is a getter computed property.

It seems to be like as Vue life cycle renders props earlier than the computed property so it doesn’t know how to fetch the data from the computed property.

I really need to use ‘this.getJsonDataByLocale’, as this error msg needs to be a dynamic value.

Anyone can give me some advices?

Can’t get Plaid Link to Open using Javascript and python

When the plaid link handler is called it spins and then goes away. I can’t get the link dialog box to show completely to get access token. Setup using flask for the python server on port 5000 and using the plaid api for calls in python. Using javascript on the client side.

I can see the requests going through but nothing happens or seems to post to the client:

127.0.0.1 - - [05/Apr/2022 21:53:31] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [05/Apr/2022 21:54:10] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [05/Apr/2022 21:54:10] "POST /create_link_token HTTP/1.1" 200 -

Javascript:


    <!DOCTYPE html>
    <html>
      <head>    
      </head>
      <body>
        <button id="link-button">Link Account</button>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.plaid.com/link/v2/stable/link-initialize.js"></script>
    <script type="text/javascript">
    (async function($) {
      var handler = Plaid.create({
        // Create a new link_token to initialize Link
        token: (await $.post('/create_link_token')).link_token,
        receivedRedirectUri: window.location.href,
        onLoad: function() {
          // Optional, called when Link loads
        },
        onSuccess: function(public_token, metadata) {
          // Send the public_token to your app server.
          // The metadata object contains info about the institution the
          // user selected and the account ID or IDs, if the
          // Account Select view is enabled.
          $.post('/exchange_public_token', {
            public_token: public_token,
          });
        },
        onExit: function(err, metadata) {
          // The user exited the Link flow.
          if (err != null) {
            // The user encountered a Plaid API error prior to exiting.
          }
          // metadata contains information about the institution
          // that the user selected and the most recent API request IDs.
          // Storing this information can be helpful for support.
        },
        onEvent: function(eventName, metadata) {
          // Optionally capture Link flow events, streamed through
          // this callback as your users connect an Item to Plaid.
          // For example:
          // eventName = "TRANSITION_VIEW"
          // metadata  = {
          //   link_session_id: "123-abc",
          //   mfa_type:        "questions",
          //   timestamp:       "2017-09-14T14:42:19.350Z",
          //   view_name:       "MFA",
          // }
        }
      });
      $('#link-button').on('click', function(e) {
        handler.open();
      });
    })(jQuery);
    </script>
      </body>
    </html>

Python server.py:


    # source /Users/tnappy/node_projects/quickstart/python/bin/activate
    # Read env vars from .env file
    from plaid.exceptions import ApiException
    from plaid.model.payment_amount import PaymentAmount
    from plaid.model.payment_amount_currency import PaymentAmountCurrency
    from plaid.model.products import Products
    from plaid.model.country_code import CountryCode
    from plaid.model.recipient_bacs_nullable import RecipientBACSNullable
    from plaid.model.payment_initiation_address import PaymentInitiationAddress
    from plaid.model.payment_initiation_recipient_create_request import PaymentInitiationRecipientCreateRequest
    from plaid.model.payment_initiation_payment_create_request import PaymentInitiationPaymentCreateRequest
    from plaid.model.payment_initiation_payment_get_request import PaymentInitiationPaymentGetRequest
    from plaid.model.link_token_create_request_payment_initiation import LinkTokenCreateRequestPaymentInitiation
    from plaid.model.item_public_token_exchange_request import ItemPublicTokenExchangeRequest
    from plaid.model.link_token_create_request import LinkTokenCreateRequest
    from plaid.model.link_token_create_request_user import LinkTokenCreateRequestUser
    from plaid.model.asset_report_create_request import AssetReportCreateRequest
    from plaid.model.asset_report_create_request_options import AssetReportCreateRequestOptions
    from plaid.model.asset_report_user import AssetReportUser
    from plaid.model.asset_report_get_request import AssetReportGetRequest
    from plaid.model.asset_report_pdf_get_request import AssetReportPDFGetRequest
    from plaid.model.auth_get_request import AuthGetRequest
    from plaid.model.transactions_get_request import TransactionsGetRequest
    from plaid.model.transactions_get_request_options import TransactionsGetRequestOptions
    from plaid.model.identity_get_request import IdentityGetRequest
    from plaid.model.investments_transactions_get_request_options import InvestmentsTransactionsGetRequestOptions
    from plaid.model.investments_transactions_get_request import InvestmentsTransactionsGetRequest
    from plaid.model.accounts_balance_get_request import AccountsBalanceGetRequest
    from plaid.model.accounts_get_request import AccountsGetRequest
    from plaid.model.investments_holdings_get_request import InvestmentsHoldingsGetRequest
    from plaid.model.item_get_request import ItemGetRequest
    from plaid.model.institutions_get_by_id_request import InstitutionsGetByIdRequest
    from plaid.model.transfer_authorization_create_request import TransferAuthorizationCreateRequest
    from plaid.model.transfer_create_request import TransferCreateRequest
    from plaid.model.transfer_get_request import TransferGetRequest
    from plaid.model.transfer_network import TransferNetwork
    from plaid.model.transfer_type import TransferType
    from plaid.model.transfer_user_in_request import TransferUserInRequest
    from plaid.model.ach_class import ACHClass
    from plaid.model.transfer_create_idempotency_key import TransferCreateIdempotencyKey
    from plaid.model.transfer_user_address_in_request import TransferUserAddressInRequest
    from plaid.api import plaid_api
    from flask import Flask
    from flask import render_template
    from flask import request
    from flask import jsonify
    from datetime import datetime
    from datetime import timedelta
    import plaid
    import base64
    import os
    import datetime
    import json
    import time
    from dotenv import load_dotenv
    from werkzeug.wrappers import response
    import pyodbc 
    
    load_dotenv()
    
    
    app = Flask(__name__)
    
    cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                          "Server=DESKTOP-DJCMSVCMJBOURQUIN_SQL;"
                          "Database=MyBudget;"
                          "Trusted_Connection=yes;")
    
    cursor = cnxn.cursor()
    cursor.execute('SELECT * FROM Accounts')
    for row in cursor:
        print('row = %r' % (row,))
    vals = ("SOMETHING")
    data = "UPDATE Accounts Set API_ID = 'SOMETHING' WHERE Id = 1"
    cursor.execute(data)
    cursor.commit();
    
    access = "THAT THING"
    cursor = cnxn.execute('UPDATE Accounts Set API_ID = ? WHERE Id = ?', [access,1])
    cursor.commit();
    
    
    # Fill in your Plaid API keys - https://dashboard.plaid.com/account/keys
    PLAID_CLIENT_ID = os.getenv('PLAID_CLIENT_ID')
    PLAID_SECRET = os.getenv('PLAID_SECRET')
    # Use 'sandbox' to test with Plaid's Sandbox environment (username: user_good,
    # password: pass_good)
    # Use `development` to test with live users and credentials and `production`
    # to go live
    PLAID_ENV = os.getenv('PLAID_ENV', 'sandbox')
    # PLAID_PRODUCTS is a comma-separated list of products to use when initializing
    # Link. Note that this list must contain 'assets' in order for the app to be
    # able to create and retrieve asset reports.
    PLAID_PRODUCTS = os.getenv('PLAID_PRODUCTS', 'transactions').split(',')
    
    # PLAID_COUNTRY_CODES is a comma-separated list of countries for which users
    # will be able to select institutions from.
    PLAID_COUNTRY_CODES = os.getenv('PLAID_COUNTRY_CODES', 'US').split(',')
    
    products = []
    for product in PLAID_PRODUCTS:
        products.append(Products(product))
    
    def empty_to_none(field):
        value = os.getenv(field)
        if value is None or len(value) == 0:
            return None
        return value
    
    host = plaid.Environment.Sandbox
    
    if PLAID_ENV == 'sandbox':
        host = plaid.Environment.Sandbox
    
    if PLAID_ENV == 'development':
        host = plaid.Environment.Development
    
    if PLAID_ENV == 'production':
        host = plaid.Environment.Production
    
    # Parameters used for the OAuth redirect Link flow.
    #
    # Set PLAID_REDIRECT_URI to 'http://localhost:3000/'
    # The OAuth redirect flow requires an endpoint on the developer's website
    # that the bank website should redirect to. You will need to configure
    # this redirect URI for your client ID through the Plaid developer dashboard
    # at https://dashboard.plaid.com/team/api.
    PLAID_REDIRECT_URI = empty_to_none('PLAID_REDIRECT_URI')
    
    configuration = plaid.Configuration(
        host=host,
        api_key={
            'clientId': PLAID_CLIENT_ID,
            'secret': PLAID_SECRET,
            'plaidVersion': '2020-09-14'
        }
    )
    
    api_client = plaid.ApiClient(configuration)
    client = plaid_api.PlaidApi(api_client)
    
    @app.route('/')
    def index():
      return render_template('index.html')
    
    @app.route('/my-link/')
    def my_link():
      print ('I got clicked!')
    
      return 'Click.'
    
    @app.route("/create_link_token", methods=['POST'])
    def create_link_token():
        # Get the client_user_id by searching for the current user
            request = LinkTokenCreateRequest(
                products=products,
                client_name="Budgetary",
                country_codes=list(map(lambda x: CountryCode(x), PLAID_COUNTRY_CODES)),
                language='en',
                user=LinkTokenCreateRequestUser(
                    client_user_id=str(time.time())
                )
            )
            if PLAID_REDIRECT_URI!=None:
                request['redirect_uri']=PLAID_REDIRECT_URI
        # create link token
            response = client.link_token_create(request)
            return jsonify(response.to_dict())
    
    @app.route('/exchange_public_token', methods=['POST'])
    def exchange_public_token():
        global access_token
        public_token = request.form['public_token']
        request = ItemPublicTokenExchangeRequest(
          public_token=public_token
        )
        response = client.item_public_token_exchange(request)
        access_token = response['access_token']
        item_id = response['item_id']
    
        cursor = cnxn.execute('UPDATE Accounts Set API_ID = ? WHERE Id = ?', [access_token,1])
        cursor.commit();
    
        return jsonify(response.to_dict())
    
    if __name__ == '__main__':
      app.run(debug=True)

Why does the presence/absence of a leading zero in the Date() javascript constructor make a difference of 16 or 17 hours? [duplicate]

I’m trying to understand the Javascript Date() constructor function, and I can’t figure why the output of new Date(xxxx-0a-0b) differs from new Date(xxxx-0a-b) and new Date(xxxx-a-0b) by 16 or 17 hours. I briefly did some testing in the console, which showed me that this occurs with all years, and that apparently dates prior to around Mar 15 lead to a 16-hour difference while dates after Mar 15 lead to a 17-hour difference (I say “around” because the exact date seems to vary from year to year).

I would have been able to understand if the constructor function just crashed if it only accepts dates in the xxxx-xx-xx format, but 1) what’s the significance of the 16- and 17-hour differences; 2) why would a missing leading zero result in these differences; and 3) why does the number of hours also change always around Mar 15? Thanks for any clarification.

When replacing the body element via fetch, what is required to get the script to load?

I’m trying to learn PHP for authentication; and attempting to POST the username and password to a PHP script via fetch and, if successful, pass page content back to the client to replace the <body> element. It may be a stupid method; I don’t enough about it yet to know.

It works except the script in the body doesn’t load. I can see the script in the developer tools inspector but it isn’t working. The CSS file works.

Could you please tell me how to get the script to run? Thank you.

  "use strict";
  function postit() {
    var fd;
    try {
      fd = new FormData();
      fd.append("username", i[0].value);
      fd.append("passwd", i[1].value);

      fetch('login.php', {
        method: 'POST',
        body: fd
      })
      .then( response => {
        if ( !response.ok ) {
          throw new Error( 'Network response was not ok.' );
        } else {
          const contentType = response.headers.get('content-type');
          if (!contentType || !contentType.includes('text/html')) {
            throw new TypeError("Oops, we haven't got html.");
          }
        }
        return response.text();
      } )
      .then( data => {
         let p = new DOMParser(),
             b = p.parseFromString( data, 'text/html' );
        document.querySelector("head").appendChild( b.head.lastElementChild );
        document.body.parentNode.replaceChild( b.body, document.body );
      })
      .catch( error => {
        console.error('Error:', error);
      })
      .finally( () => {
      });
    } catch (err) {
      console.log( "Error in postit(); reason below.");
      console.log(err);
    } finally {
      fd = null;
    }
  }

  var i = document.querySelectorAll("input");

value not being assigned to the right one

When I input a value that is less than 3 and run my code, the cost is 5.00 instead of 2.50. What is the mistake and how do I fix it?

if (weight < 3)   {
    cost = 2.50
    total = weight * cost
}
if (3 < weightOfPackage < 9)   {
    cost = 5.00
    total = weight * cost
}