How to create multiples of of one object?

beginner coder with an assignment due soon and I cannot figure out how to incorporate for() loop in my code so that I will have more than one quad shape that can appear using if (mouseIsPressed) conditional. Here is my code:

//stars in the sky
      if (mouseIsPressed){
  starMorning = color(214,198,214);
  starEvening = color(255,255,225);
  //star colours transition from background colour to pale yellow
  starColours = lerpColor(starMorning,starEvening,mouseX/width);
  noStroke();
  fill(starColours);
  quad(55,40,50,45,55,50,60,45);
  }

This will create one quad shape in the left corner of the screen that slowly appears as you press on your left mouse button and move it horizontally across the screen. Now I want, say, 50 of these quad things all over the screen. How do I do that? Do I need to build classes and then use the for() loop? I’ve tried following so many tutorials but I just can’t seem to apply the logic to my code. Help please!!!

Google analytics track multiple custom variables

I’m tring to use google analytics to monitor activities on my laravel site, as you can see i managed to record the events by $user_name witch is great however how to i associate this user name with another variable for example $project_id so i can see data for each user and on each different project.

enter image description here

enter image description here

any idea how i can achieve this? here is my code:

<script>
$(document).ready(function(){
$(document).mousemove(function(){

  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-9YXX', {
  'custom_map': {'dimension<Index>': 'user_id'}
});

gtag('event', 'user_name', {'user_id': '{!!$user_name!!}'});

});

});

</script>

What is difference between let , const and var in case of variable shadowing /re declaration in different scope? [duplicate]

Please check below 2 code snippets the difference is redeclaring as const/let and var in foo function.

for var, it executes but for const and let it throughs error.

Please tell me why it behaves differently.

Below code does not through any error as a is declared as var
var a=12; //Global variable
foo(); //hoisting 
function foo() {
    console.log("a="+a);
    var a=13;
    console.log("a="+a);
    if(true) {
        const a=89;
        console.log("in block="+ a);
    }
    var a=90;    //no error
    console.log("a="+a);    
}

Below code throughs variable declaration error “a has already been declared”

var a=12; //Global variable
foo(); //hoisting 
function foo() {
    console.log("a="+a);
    var a=13;
    console.log("a="+a);
    if(true) {
        const a=89;
        console.log("in block="+ a);
    }
    let a=90;    //Or const a :: error
    console.log("a="+a);    
}

Position returned data results in App Lab (code.og)

We simply can’t find an answer this anywhere in the official documentation.

We are getting data on the screen like this…

var theStore = getText("searchlist");

readRecords("games", {store:theStore}, function(records) {
    if (records.length>0) {
        for (var i =0; i < records.length; i++) {
        write("-> " + records[i].title);
        }
    }
});

…which does get data, but the problem is that write() is not really the correct function to use, as it just returns all the data starting at the top of the screen and eventually rendering off screen, which absolutely no way to control it.

So how on earth can I just display the results in a way I can control the position? At the very least, I would be happy if the results were displayed in a textarea element.

Jenkins one_at_a_time hash – trying to Make Python Code reproduce JavaScript code

I borrowed this code from another post recently, and it works great for my needs…
But I’m trying to reproduce the same results from Python code so the two language functions agree, and I’ve been struggling… These two so far do NOT produce the same results like I need… I suspect it’s an issue with the unsigned integers in Python vs JavaScript.

JavaScript Code:

//Credits (modified code): Bob Jenkins (http://www.burtleburtle.net/bob/hash/doobs.html)
//See also: https://en.wikipedia.org/wiki/Jenkins_hash_function
//Takes a string of any size and returns an avalanching hash string of 8 hex characters.
function jenkinsOneAtATimeHash(keyString)
{
  let hash = 0;
  for (charIndex = 0; charIndex < keyString.length; ++charIndex)
  {
    hash += keyString.charCodeAt(charIndex);
    hash += hash << 10;
    hash ^= hash >> 6;
  }
  hash += hash << 3;
  hash ^= hash >> 11;
  //4,294,967,295 is FFFFFFFF, the maximum 32 bit unsigned integer value, used here as a mask.
  return (((hash + (hash << 15)) & 4294967295) >>> 0).toString(16)
};

Python code:

def calcuulateChecksum(keyString: str):
    # Credits(modified code): Bob Jenkins (http://www.burtleburtle.net/bob/hash/doobs.html)
    # See also: https://en.wikipedia.org/wiki/Jenkins_hash_function
    # Takes a string of any size and returns an avalanching hash string of 8 hex characters.
    hash = 0
    # for (charIndex = 0; charIndex < keyString.length; ++charIndex):
    for char in keyString:
        hash += ord(char.encode("utf-8"))
        hash &= 0xFFFFFFFF
        hash += hash << 10
        hash &= 0xFFFFFFFF
        hash ^= hash >> 6
        hash &= 0xFFFFFFFF
    hash += hash << 3
    hash &= 0xFFFFFFFF
    hash ^= hash >> 11
    hash &= 0xFFFFFFFF
    hash += hash << 15
    hash &= 0xFFFFFFFF
    # # 4,294,967,295 is 0xffffffff, the maximum 32 bit unsigned integer value, used here as a mask.
    return hex((hash & 4294967295))

Any help on making the Python code match the JavaScript function would be appreciated…
On the other hand, I believe the Python code matches results shown in the Wiki, so why doesn’t the JavaScript code?

Javascript boolean logic (comparing double bang with truthy/falsy values)

I’m inspecting some code and I found something I’d like to run by Javascript veterans. I feel pretty comfortable with Javascript but I’ve always manage to run into something that makes me say, “I didn’t know that about Javascript!”

I’m hoping this is one of those situations:

if (this.props.referralId != prevProps.referralId ||
    this.props.referralValidationStatus != prevProps.referralValidationStatus ||
    this.props.customerName != prevProps.customerName &&
    !!prevProps.personId != !this.props.personId) {
   // perform whatever logic is here...
}

My questions:

  1. Does JS know how to automatically identify the mixture of || and &&? Or is this code missing parenthesis’s around the || comparison?
  2. Just as it’s explained here, is it fair and should I expect the obvious behavior when comparing a boolean against a truthy/falsy value?

I’m baffled on what the logic should be here. If I were to rewrite this I would do like so:

if ((this.props.referralId !== prevProps.referralId ||
    this.props.referralValidationStatus !== prevProps.referralValidationStatus ||
    this.props.customerName !== prevProps.customerName)
    && (!!prevProps.personId === !!this.props.personId)) {
   // Perform logic
}

However, I’d like to confirm and make sure I’m not missing something I might have missed about JS.

Thank you in advance for confirming my hunch or educating my on something new when it comes to JS. Looking forward to your comments and/or answers.

Adding decimal separators to a YouTube view count retrieved via API

I’m trying to retrieve a YouTube view count for a specific video on my WordPress site. I’m not a coder but I’ve managed to get it working using this code:

<div id="viewCount" style="display: inline-block;"></div>
 <script>
       let getviewCount = () => {
        fetch(`https://www.googleapis.com/youtube/v3/videos?part=statistics&id=Cemk32wKN_k&key=XXXXXXXXXXXXXXXXXXXXXXXXXXXXX`)
        .then(response => {
            return response.json()
        })
        .then(data => {
            console.log(data);
            viewCount.innerHTML = data["items"][0].statistics.viewCount;
        })      
    }
    getviewCount(); 
    </script>

The final touch I’d like to add is decimal separators so instead of the number looking like this:

13526897

It looks like this:

13,526,897

Based on some research here I think I need to use a function similar to this:

function numberWithCommas(x) {
    return x.toString().replace(/B(?=(d{3})+(?!d))/g, ",");
}

But I don’t know how to code, so combining these two ideas is beyond my ability right now.

If anyone wouldn’t mind showing me how to do it, I’d be extremely grateful!

Thanks

Function doesn’t wait react hooks

I’m trying to add items in shopping cart. It works, but after adding items when I want to calculate number of items to show on the shopping cart. Second function (calculate()) doesn’t wait items hooks. Because of that, it shows the correct count after adding second item.

Below code is my functions. As you can see, in the end of first function I’m calling the calculate() function to keep it continue.

const [testArray, setTestArray] = useState([]);
const [total, setTotal] = useState(0);
const [cartCount, setCartCount] = useState(0);

function addToTest(product, quantity = 1) {
    const ProductExist = testArray.find((item) => item.id === product.id);
    if (ProductExist) {
      setTestArray(
        testArray.map((item) => {
          if (item.id === product.id) {
            return { ...ProductExist, quantity: ProductExist.quantity + 1 };
          } else {
            return item;
          }
        })
      );
    } else {
      product.quantity = 1;
      setTestArray([...testArray, product]);
    }

    calculate();
  }
  

  function calculate() {
    let resultCount = 0;
    testArray.map((item) => {
      console.log("map func works!");
      setCartCount(cartCount + item.quantity);
    });
  }

Here is my codesandbox project, I kept it very simple to not bother you.

https://codesandbox.io/s/react-template-forked-u95qt?file=/src/App.js

The possible problem occurs due to synchronise functions. Because of that, when I try to async/await, I’m getting error about parameters, because the first function has parameter.

This is my first try for async/await:

async function calculate(product) {
    await addToTest(product);
    let resultCount = 0;
    testArray.map((item) => {
      console.log("map func works!");
      setCartCount(cartCount + item.quantity);
    });
  }

As other solution I tried to use useEffect by taking the reference setArray hooks. However, in this case, the count number increases exponentially like 1,3,9…

useEffect(()=>{
    let resultCount = 0;
    testArray.map((item) => {
      console.log("map func works!");
      setCartCount(cartCount + item.quantity);
    });
  },[testArray])

I wonder where is the problem? Because when I use the the upper code in Angular/Typescript, it works properly. I think this happens due to react hooks, but I couldn’t understand the problem.

React Redux and state after refresh

I have a problem with understanding why my app works kinda odd. When I try to reach any site on my page by clicking a link button in navbar, it navigates me there without any problems, like when I click “My account”, the URL changes to “http://localhost:3000/my_account” and everything works just fine. In this place I have to mention that “/my_account” is a protected route – user has to be logged in to reach it, when he is not logged in – he gets send to the homepage. So now the problem is that when user is logged in and tries to reach the protected route like “http://localhost:3000/my_account” by entering this URL and loading page – he is treated like a non-logged user and gets redirected to the homepage. And after he is redirected there and tries to reach this site by clicking the navbar link, he can enter this page – he is logged in. My expected result is that user can enter any URL on the site and react should check PROPRERLY if he is logged in in both cases – either when clicking a link on site or by providing a url. Can anyone tell me where do I make mistake?

UserAccount (/my_account) is a simple component:

import React, { Component } from 'react'

export class UserAccount extends Component {
    render() {
        return (
            <div>
                UserAccount
            </div>
        )
    }
}

export default UserAccount

In router in App.js I declare this route as:

<PrivateRoute path="/my_account" exact component={UserAccount}></PrivateRoute>

And the PrivateRoute is a functional component:

import React from 'react'
import {Route, Redirect} from 'react-router-dom'
import {connect} from 'react-redux'


const PrivateRoute = ({component : Component, auth, ...rest}) => (
    <Route {...rest} render={props => {
        if(auth.isLoading){
            return <h2>LOADING ...</h2>
        }
        else if(!auth.isAuthenticated){
            return <Redirect to="/login"></Redirect>
        }
        else{
        return <Component {...props}/>
        }
    
    }}></Route>
)
    


const mapStateToProps = state =>({
auth: state.auth
})

export default connect(mapStateToProps,null)(PrivateRoute);

My state in auth.js (reducer):

const initialState = {
    access: localStorage.getItem('access'),
    refresh: localStorage.getItem('refresh'),
    isAuthenticated: null,
    isLoading : false,
    user: null,
    requestSent: false,
    payload: null,
    message: null
}

And after successful login, state changes as follows:

    switch(type){
        case AUTHENTICATED_SUCCESS:
            return {
                ...state,
                isAuthenticated: true
            } 
        case LOGIN_SUCCESS:
            localStorage.setItem('access', payload.access);
            return{
                ...state,
                isAuthenticated: true,
                access: payload.access,
                refresh: payload.refresh
            }

And login function from auth.js actions:

export const login = (email, password) => async dispatch =>{
    const config = {
        headers: {
            'Content-Type': 'application/json'
        }
    };
    
    const body = JSON.stringify({email, password});

    try{
        const res = await axios.post(`${process.env.REACT_APP_API_URL}/auth/jwt/create/`, body, config);
        dispatch({
            type: LOGIN_SUCCESS,
            payload: res.data
        })
        dispatch(load_user());
        dispatch(createMessage({logged_in_successfully: "You are now logged in."}))
    } catch (err) {
        dispatch({
            type: LOGIN_FAIL,
            payload: err
        })
        const errors =  {msg: err.response.data, status: err.response.status}
        dispatch({
            type:GET_ERRORS,
            payload: errors
        })
    }
};

Thanks for your time reading that and I am hoping for some help.

Javascript – How to prevent functions from multiplying themselves [closed]

I’m struggling.
I’m doing some work to make navigation fully accessible by mouse over, keyboard and click, depending on the resolution.

I am looking for that in mobile, only the click works.
And hover, click, keyboard for higher resolutions.

It only works perfectly when I load the page at the correct resolution (low or high).
BUT, if I resize live, my functions multiply by themselves by the number of resizes done.

I tried a lot of thing like e.stopPropagation , bubble, return, split functions, all in one…without success.

  • Here is a example of the problem with a factice code, shorter (maybe it could be suffisant to understand the solution with your help) :
    Need to reduce and maximize screen and click the button for testing.
    https://codepen.io/TanGo21/pen/RwLNWey

  • Here is, a part of my “real” code :
    Go under 770px, then maximize, and look the console when you go over item “THREE” who contains a submenu.
    https://codepen.io/TanGo21/pen/oNGgxBK

Angular: utils/util.js -> Uncaught ReferenceError: process is not defined

I feel like this should be resolved simply, but after several attempts, I’m just not coming to a resolution.

Here is the error I’ve received:

Uncaught ReferenceError: process is not defined
38509 @ [PathToProject]node_modulesutilutil.js:109

This is getting triggered when I instantiate web3 into a clean/new site (there’s two other ‘test’ components, one link one button)

I’ve searched and found numerous bits of information suggesting that

  • process is a server side ‘node’ var, and I can set this to be available client-side by adding to my webpack.config.js, which I have done.
  • I might be able to resolve by just declaring a global angular var in my app.component.ts, but it seems this dependency project .js file is not accessing it.

I’ve also tried just updating the dependency project directly, but even with a compile, it seems that my changes are not being distributed into the webpack build /dist/ result.

I think this probably has a blatantly simple solution, but I’m just overlooking it. I’m just spinning my tires here and could use a little help, but I’m the first in my circle to venture into web3 and don’t have a close friend to bounce this off of. Can someone here provide some insight or an alternative resolve this issue?

Relevant bits of code:

webpack.config.js

var webpack = require('webpack');
const path = require('path');


module.exports = {
    module: {
      rules: [
        {
          test: /.(sass|less|css|ts)$/,
          use: [
            'ts-loader'
          ],
        }
      ],
    },
    plugins: [
        new webpack.DefinePlugin({
          'process.env.NODE_ENV': 'develop',
        })
    ],
    entry: './src/main.ts',
    output: {
      filename: 'main.js',
      path: path.resolve(__dirname, 'dist'),
    },
    resolve: {
      extensions: [ '.js', '.ts', '.html' ],
      modules: [
          path.resolve(__dirname, 'node_modules/'),
          path.resolve("", "src")
      ],
      alias: {
          Environments: path.resolve(__dirname, 'src/environments/'),
      },
      fallback: {
        "fs": false,
        "tls": false,
        "net": false,
        "path": false,
        "zlib": false,
        "http": require.resolve("stream-http"),
        "https": require.resolve("https-browserify"),
        "stream": false,
        "crypto": require.resolve("crypto-browserify"),
        "crypto-browserify": require.resolve('crypto-browserify'),  
    }, 
    }
}

global-constants.ts

export class GlobalConstants {
    public static process: any  = {
        env: {
            NODE_ENV: 'development'
        }
    }
}

app.component.ts

import { Component } from '@angular/core';
import{ GlobalConstants } from './common/global-constants';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'Cool Title';
  process = GlobalConstants.process;
}

Relevant bit of utils/util.js (line 106-116)

var debugs = {};
var debugEnvRegex = /^$/;

if (process.env.NODE_DEBUG) {
  var debugEnv = process.env.NODE_DEBUG;
  debugEnv = debugEnv.replace(/[|\{}()[]^$+?.]/g, '\$&')
    .replace(/*/g, '.*')
    .replace(/,/g, '$|^')
    .toUpperCase();
  debugEnvRegex = new RegExp('^' + debugEnv + '$', 'i');
}

Any help is genuinely appreciated.

Why this switch statement isn’t work perfectly?

const number = prompt("Enter your number");
const txt = "You result is : ";

switch (number) {
  case (number >= 80 && number <= 100):
    document.write(`${txt} A+`);
    break;
  case (number >= 70 && number <= 80):
    document.write(`${txt} A gread`);
    break;
  case (number >= 60 && number <= 70):
    document.write(`${txt} B gread`);
    break;
  case (number >= 50 && number <= 60):
    document.write(`${txt} C gread`);
    break;
  case (number >= 33 && number <= 50):
    document.write(`${txt} D gread`);
    break;
  case (number >= 0 && number <= 33):
    document.write(`${txt}  Field !`);
    break;
  case (number > 100 || number < 0):
    document.write(`It's not a valid number. Please input any valid number.`);
    break;
  default:
    document.write(`Not input any number. Please input any number .`);
    break;
}

Vercel error trying to access segment route: Must use import to load ES Module

To put my problem as simply as possible, I’m using Vercel for hosting my project. Vercel allows you to easily create your own REST server by basically creating an api folder at your project root and then you can make requests to any files in that directory which will call serverless functions that perform specific functionality via simply calling the route and filename (so if I wanted to make a request to my user.js file, I’d simply make a request to /api/user).

I have several different folders and files in my api folder that all work as expected when making AJAX calls to them. When I make a request to the index.js file in my blog folder by simply making a request to /api/blog, everything works fine, however, when trying to make get request to /api/blog/someId (someId can be any string) I get the following error:

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: 
C:UsersMeDocumentseatsleepcode.orgapiblog[id].js
require() of ES modules is not supported.
require() of C:UsersBrettDocumentseatsleepcode.orgapiblog[id].js from 
C:UsersMeAppDataRoamingnpmnode_modulesvercelnode_modules@vercelnodedistlauncher.js 
is an ES module file as it is a .js file whose nearest parent package.json contains "type": 
"module" which defines all .js files in that package scope as ES modules.
Instead rename [id].js to end in .cjs, change the requiring code to use import(), or remove 
"type": "module" from C:UsersBrettDocumentseatsleepcode.orgpackage.json.

I simply just want the someId portion of the /api/blog/someId url, which I was told you access by making a file with this naming syntax [randomParameter].js and properly route to it (/api/blog/someParameter).

Also, my package.json has "type":"module" defined in it, before anyone suggests the obvious.

Always getting redirected to “/” on refresh from any route in app

So, everything works great I am redirected to homepage after login, the problem is when i refresh the page from any route i am always getting redirected to “/”, if i am in “/products” and refresh the page i m redirected to “/”

my App.js:

import Sidebar from "./components/sidebar/Sidebar";
import Topbar from "./components/topbar/Topbar";
import "./App.css";
import Home from "./pages/home/Home";
import { BrowserRouter as Router, Switch, Route, Redirect } from "react-router-dom";
import UserList from "./pages/userList/UserList";
import User from "./pages/user/User";
import NewUser from "./pages/newUser/NewUser";
import ProductList from "./pages/productList/ProductList";
import Product from "./pages/product/Product";
import NewProduct from "./pages/newProduct/NewProduct";
import Login from "./pages/login/Login";
import { userRequest } from "./requestMethods";

function App() {

  const [admin, setAdmin] = useState(null)

  useEffect(() => {
    const verifyUser = async () => {
      try {
        const res = await userRequest.get('/verify')
        setAdmin(res.data)
      } catch (error) {
        console.log(error)
      }
    }
    verifyUser()
  }, [])

  return (
    <div>
    <Router>
      <Switch>
        <Route path="/login">
            {admin ? <Redirect to="/" /> : <Login/> }
          </Route>
      { admin !== null ? (
       <>
       <Topbar />
      <div className="container">
        <Sidebar />
          <Route exact path="/">
            <Home />
          </Route>
          <Route path="/users">
            <UserList />
          </Route>
          <Route path="/user/:userId">
            <User />
          </Route>
          <Route path="/newUser">
            <NewUser />
          </Route>
          <Route path="/products">
            <ProductList />
          </Route>
          <Route path="/product/:productId">
            <Product />
          </Route>
          <Route path="/newproduct">
            <NewProduct />
          </Route>
          
      </div> </>) : <Redirect to="/login"/>}
        </Switch>
    </Router>
    </div>
  );
}

export default App;

i try to use {admin !== null && (the routes here)} and it works but when i logout the application im not redirect to the login page “/login” and still in the page that i logged out.

can someone help me please?