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

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.

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.

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?

Webpack is not compatible with react router dom v6?

Some hours ago, i posted a question about, why my routes weren’t working in my module-federation/react application, some people tried to help me, but they couldn’t.

I was using webpack so i can use microfronteds as components with react, and with TS, but, i had a big problem with my routes.

( This is the link to the post My routing with React router dom, <Route /> not working ).

Then i said, you know what, i’ll do this with pure JS, i’m pretty sure there was a problem with ts config or something like that.

Then, after migrating everything everything to simple JS, my routes with react-router-dom are not working as before.

Is there a posibility that, the new version of react-router-dom ( https://reactrouter.com/docs/en/v6/getting-started/overview ) and webpack do not match ? This sounds weird, but i don’t see other way to figure this out.

Recursion function in JavaScript

I have a simple recursion function that returns the sum of the first n elements of the array. I’m a little bit struggling with understanding: when the function calls itself through return return sum(arr, n-1) + arr[n-1]; what actually this sum(arr, n-1) does as it is not added to the final sum eventually and why it’s not been calculated.

Here’s the whole function, really appreciate any explanation.

    function sum(arr, n) {
if (n === 0) {return 0}
else if (n >= 1) {
  return sum(arr, n-1) + arr[n-1];
}
}

Javascript function return http response as null

While console.log("result ="+req.responseText); can output actual content, if(response == null) console.log("response null"); gets executed as well.
How can I return http response correctly?

var response = callSvc(textContent);
if(response == null) console.log("response null");

function callSvc(text){
var cleanUrl = "http://localhost:8080/api/mock";
var body={
    "text":text,
    "user":contentId
}
var contentId = generateContentId();
var req = new XMLHttpRequest();
    req.open("POST", cleanUrl);
    req.setRequestHeader("Content-Type", "application/json; charset=utf8");
    var json = JSON.stringify(body);
    req.send(json);
    req.onreadystatechange = function() {
        if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
            var data = JSON.parse(req.responseText);
            console.log("result ="+req.responseText);
            return data;              
        } else {
            return error => {
                  console.error(error);
                }
        }
    }
}

Is there a way to use a fields value in the Model to set a style attribute dynamically?

I have created a CSHTML email template file to send alerts when a specific event is about to end (i.e. sends an alert 10-minutes before end, then at 5-minutes before end, etc.). I want to highlight the type of event (since there can be more than one) by color to differentiate the messages. What I currently have is this:

<strong style="color: {event color}">@alert.event</strong> is scheduled to end: <strong>@endEasternTime

I would like to be able to set the {event color} based on the value in @alert.event, but I’m not sure that I can. I tried to create a script in the file, but I’m not sure how to get its return value into the style tag:

<script>
    // Get the root element
    var r = document.querySelector(':root');

    // Create a function for getting a variable value
    function getEventColor(event) {
        // Get the styles (properties and values) for the root
        var rs = getComputedStyle(r);

        // Get the color associated with the event (default is the border color)
        return (event === "event1"
            ? rs.getPropertyValue('--evt1Color')
            : (event === "event2"
                ? rs.getPropertyValue('--evt2Color')
                : (event === "event3"
                    ? rs.getPropertyValue('--evt3Color')
                    : rs.getPropertyValue('--bdrColor')
                    )
                )
            );
    }
</script>

Note that I have created HTML variables in the file to match up the colors to other styles in the file (such as border-color) — for space considerations and clarity, I’m not going to show that here.

Is there a way to do this? If not using the inline CSS above, can I update a class or id on the fly using something like the script method above and, if so, what’s the best way. I appreciate any help.