How can I create a color heatmap in JavaScript and CSS?

I have a value representing the +/-ity of an article which ranges from -1 to 1 with -1 being strongly negative and 1 being strongly positive.

I want to turn this into a color such that it ranges from red (strongly negative) pass through grey (neutral) and ends at green (strongly positive).

The solution that I have come up with does not fully satisfy what I am trying to achieve. I am not a color expert but for some reason any value even slightly negative e.g. -.07 is resulting in a bright red. I also expect any positive value to start looking green but what I see is actually orange.

What am I doing wrong? Is there a better way to represent what I am after?

function getAsHslHeatMap(value: number) {
    value = Math.max(-1, Math.min(1, value));
    
    let hue;
    
    if (value <= 0) {
        // Transition from red to grey | Red is 0 degrees
        hue = (1 - value) * 0;
    } else {
        // Transition from grey to green | Green is 120 degrees
        hue = value * 120;
    }
    
    // Convert hue to an integer for CSS
    hue = Math.round(hue);
    
    let saturation = 100; // Full saturation
    let lightness = 50; // Mid lightness
    
    return `hsl(${hue}, ${saturation}%, ${lightness}%)`;
}

Function defined in an `api.js` file stored in the public folder, but when that function is called within component, error claims it is not defined

I’m trying to call a fetchAPI function that is defined in my api.js file, but am continually receiving the error that it is undefined.

Below is the code within the api.js file:

const seededRandom = function (seed) {
    var m = 2 ** 35 - 31;
    var a = 185852;
    var s = seed % m;
    return function () {
        return (s = s * a % m) / m;
    };
}

const fetchAPI = function (date) {
    if (!(date instanceof Date)) {
        date = new Date(date);
    };

    let result = [];
    let random = seededRandom(date.getDate());

    for (let i = 17; i <= 23; i++) {
        if (random() < 0.5) {
            result.push(i + ':00');
        }
        if (random() < 0.5) {
            result.push(i + ':30');
        }
    }
    return result;
};
const submitAPI = function (formData) {
    return true;
};

Next is the tag I created in the index.html file:

<body>
  <script src="api.js"></script>
  <div id="root"></div>
</body>

and lastly the attempted call of the function in my component (a React component utilizing useFormik):

export function BookingForm() {
    const formik = useFormik({
        initialValues: {
            guests: '',
            date: new Date().toLocaleDateString(),
            time: 'Select Time',
            firstName: '',
            lastName: '',
            email: '',
            phone: '',
            occasion: 'Occasion',
            otherInfo: '',
            confirmButton: false,
        },
        validationSchema: Yup.object().shape({
            guests:
                Yup.number()
                    .positive('Must be a positive number')
                    .min(1, 'There must be at least one guest')
                    .max(25, 'Our maximum party size is 25, for larger groups, please contact us directly to book a private event')
                    .required('Please enter the number of guests.'),
            date: Yup.date()
                .test(
                    'date',
                    'The date you selected has already passed.',
                    function (date) { return new Date(date) >= new Date(); }
                )
                .required('Required'),
            time: Yup.string()
                .notOneOf(['Select Time'], 'Please select one of our available time slots.')
                .required('Please select one of our available time slots.'),
            firstName: Yup.string().required('Required').trim(),
            lastName: Yup.string().required('Required').trim(),
            email: Yup.string().email('Please enter a valid email address').required('Required').trim(),
            phone: Yup.string()
                .required('Required')
                .matches(/^[0-9]{10}$/, 'Please enter a valid phone number')
                .min(10, 'Please enter a valid phone number'),
            confirmButton: Yup.boolean().oneOf([true], 'You must confirm the information above is accurate to submit your booking'),
        }),
        onSubmit:
            (values, { resetForm }) => {
                if (formik.isValid) {
                    console.log('Form submitted:', values);
                    alert('Your reservation has been submitted! We will send you a confirmation email shortly.');
                    resetForm();
                } else {
                    alert('Please fill out all required fields before submitting your reservation.');
                }
            }
    });

    const availability = fetchAPI(formik.values.date);

The api.js file is stored within the public folder and referenced in a script tag in the index.html file. I have tried both the standalone function call and placing it inside a useEffect hook.

Timeout error on react-export-excel library

I’m having a problem installing the react-export-excel. For some reason the connection to git keeps getting a timeout message, and I don’t know why.

It’s an old code that suddenly stopped working with some dependencies and this one seems to be the most problematic of them.

Any advises on how to deal with this or any other library I could use instead of this one (that might not need that many changes to the code since it is used throughout a big part of my code).

> npm i react-export-excel
npm ERR! code 128
npm ERR! A git connection error occurred
npm ERR! command git --no-replace-objects ls-remote ssh://[email protected]/securedeveloper/js-xlsx.git
npm ERR! ssh: connect to host github.com port 22: Connection timed out
npm ERR! fatal: Could not read from remote repository.
npm ERR!
npm ERR! Please make sure you have the correct access rights
npm ERR! and the repository exists.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:Users0435764AppDataLocalnpm-cache_logs2024-08-22T19_13_42_855Z-debug-0.log

Problème de mise à jour de l’interface utilisateur après sélection d’une ville dans une application Angular [closed]

Je développe une application Angular où l’utilisateur peut sélectionner une ville à partir d’une liste. Lorsque l’utilisateur sélectionne une ville, l’action SetOrganisationAction est dispatchée pour mettre à jour l’organisation sélectionnée dans le store global (NgRx). Cependant, même si l’action est dispatchée avec succès, l’interface utilisateur ne se met pas à jour immédiatement. Pour voir le changement, je dois actualiser manuellement la page ou naviguer vers une autre page.

Is it good use multiple repositories in one service? [closed]

How to structure service interactions with multiple repositories in NestJS for different payment types (subscription and one-time payment)?

I’m developing a NestJS application and need to implement a quote system with two payment types: subscription and one-time payment. For each payment type, there are different repositories from another module that handle saving relevant data.

My question is:

Should I call the repositories directly within my service or inject and use the service from the imported module to perform the save operation?
Is it considered good practice to have a service that interacts with multiple repositories from another module, or should I separate the logic into different services?
I’m looking for best practices or principles that would help me maintain clean code and follow SOLID principles. Any examples would be highly appreciated.

Outlook Add-Ins Send email content in REST API POST method

I have developed Outlook Add-Ins (https://learn.microsoft.com/en-us/office/dev/add-ins/outlook/). Which reads content from E-Mail and populate the content and make another POST call to API.

For one of the requirement I wanted to send the entire email as attachment n make a POST call which will send entire email in byte array format.

Any help with code or links or examples would be really appreciated.

Where in node.js source code does the process of JIT compiling the javascript executable begin

There is a border between launching the node.js platform itself and executing .js files.

I am curious to know where is that moment in the node.js source code that starts executing the compiled code?


I found the next:

MaybeLocal<Value> BuiltinLoader::CompileAndCall(Local<Context> context,
                                                const char* id,
                                                int argc,
                                                Local<Value> argv[],
                                                Realm* optional_realm) {
  // Arguments must match the parameters specified in
  // BuiltinLoader::LookupAndCompile().
  MaybeLocal<Function> maybe_fn = LookupAndCompile(context, id, optional_realm);
  Local<Function> fn;
  if (!maybe_fn.ToLocal(&fn)) {
    return MaybeLocal<Value>();
  }
  Local<Value> undefined = Undefined(context->GetIsolate());
  return fn->Call(context, undefined, argc, argv);
}

Do I understand correctly that fn->Call(context, undefined, argc, argv) runs the compiled script code?

What is wrong with the bookmarklet that is supposed to delete some element on specific page?

The following bookmarklet should remove a specific element from web-page opened in Chrome (I plan to use it on single webpage only, so there would be no need for a more general solution; also, I am interested in solution that would not be run automatically, hence the bookmarklet):

javascript: function run() { var r = "/html/body/div/div[1]"; var e = document.getElementByXpath(r); e.parentNode.removeChild(e) }; run();

It does not work, though.

Full disclosure: I have never written a single line of JS code before (so I would appreciate both explanation of what is wrong and correction), the bookmarklet is a simplified variant of the one suggested in the accepted answer of this thread.

Ethers BNB transaction getting ALREADY_EXISTS: already known

I am currently trying to transfer BNB from wallet A to wallet B. My code will populate the transaction info and trigger the function of sendTransaction.

However, sometime I get the error message of Already Exist: already known, but my transaction is successful in bscscan and the BNB is transferred from wallet A to wallet B successfully. This error does not happen every transaction, only happens randomly.

Error Message at console

const wallet = new ethers.Wallet(formData.secretKey, provider);
 let tempErrorData = "";
 let errorLongData = "";

        const txnInfo = await wallet.populateTransaction({
            to: userProfile.wallet_address,
            value: value,
            gasLimit: 21000,
            maxFeePerGas,
            maxPriorityFeePerGas,
            timeout: 500
        }).catch(error => {
            errorLongData = error;
            console.error("Populate 1 Error", error);
            }
        });

        let tx = await wallet.sendTransaction(txnInfo)
            .catch(error => {
                errorLongData = error;
                console.error("error", error);
            });

Why isn’t an array containing strings – gathered from an element – being updated when changes are made to the element?

I have trouble understanding why adding TEXT_NODE-s (document.createTextNode('some string')) into an existing parent element does not update the number of elements when using a for loop.

Don’t get me wrong, it makes modifying the the parent element easier, I just don’t understand why the length of array isn’t being updated.

I though that when working with this kind of elements, they are ‘alive’ ie. updating with changes made.

Example:

const textarea = document.querySelector("#textarea");
const topNodes = textarea.childNodes;
for (const topNode of topNodes){
    if (topNode.nodeType === 3){
        let charCount = 0;
        const nodes = topNode.textContent.split(" ");
        for (let i = 0; i < nodes.length - 1; i++) {
            const node = nodes[i];
            if (typeof node !== 'undefined' && !node.length){
                charCount++; //in case of double space (currently irrelevant)
                continue;
            }
            charCount += node.length + 1;
            if (node === 'two'){
                appendString(charCount, topNode, 'some string');
            }
            console.log("+-------------------------+");
            console.log("| current node count: ", nodes.length - 1, " |")
            console.log("|  actual node count: ", topNode.textContent.split(" ").length - 1, " |")
        }
    }
}

function appendString(charCount, thisParentNode, string){
    const nodeText = thisParentNode.textContent;
    const before = nodeText.slice(0, charCount);
    const after = nodeText.slice(charCount);

    thisParentNode.textContent = before;
    
    if (string.charAt(string.length - 1) !== " "){
      string = string + " ";
    }

    const textNodeAfter = document.createTextNode(after);
    const textNodeAppend = document.createTextNode(string);

    thisParentNode.parentNode.insertBefore(textNodeAppend, thisParentNode.nextSibling);
    thisParentNode.parentNode.insertBefore(textNodeAfter, textNodeAppend.nextSibling);
    
    //and normalize all the way up to textarea
    const textarea = document.querySelector("#textarea");
    normalizeAll(thisParentNode, textarea);

    function normalizeAll(thisNode, topNode){
        if (thisNode !== topNode){
            thisNode.normalize();
            normalizeAll(thisNode.parentNode, topNode);
        } else {
           thisNode.normalize();
        }
    } 
}
#body{
  height: 100%
}
#textarea {
  min-height: 30%;
  border: 1px solid black;
}
<html>
  <body>
    <div id="textarea" contenteditable>one two three</div>
  </body>
</html>

Enum related error when updating from Angular v15 to v16

I recently updated from Angular 15 to 16 and some pages don’t seem to load up at all. The error I’m getting is
“Uncaught Error: Uncaught (in promise): ReferenceError: Cannot access ‘HomeModule’ before initialization
ReferenceError: Cannot access ‘HomeModule’ before initialization
at Module.HomeModule(src_app_components_signed-in_pages_promotions_home_home_module_ts.js:12:62)
at app.routing.ts:303:102”. Upon tracing back the error, we found out the modules and component using enums were giving this error. This is one of the enums defined in a separate ts file as:
PurchaseType.ts:

   export enum PurchaseType {
      Bulk = 1,
      Single = 2
    }

All of these have been exported from a single file in the format of:

export * from './objects/orderingSystem/purchasing-type/PurchaseType';

app-routing:
This is how it’s used in app-routing:

      {
        path: 'purchase-type',
        loadChildren: () =>
          import('./components/signed-in/pages/customerPurchase/mainPurchase/mainPurchase.module').then((m) => m.MainPurchaseModule),
      },

You would then used it as :

import { PurchaseType } from '@abc/orderingSystem';
    @NgModule({
  imports: [
    ABCModule.forRoot(),
    BCDModule.forRoot(),
    RouterModule.forChild([
      {
        path: 'purchased-items',
        component: PurchasedPage,
        data: { bulk: PurchaseType.Bulk, single: PurchaseType.Single},
      },
   ]),
  ],

On clicking this page, the page doesn’t load up and there are other pages having enums which show the same behavior. But if I change the path to original import from:

import { PurchaseType } from '@abc/orderingSystem';

to

import { PurchaseType } from 'dataTransferObjects/objects/purchasing-type/PurchaseType';

the routing seems to load up normally.
However, on stopping and restarting the server, the error pops up again.

I’ve tried changing the DTO to including ‘const’:

export const enum PurchaseType {
  Bulk = 1,
  Single = 2
}

and also tried exporting it as:

export enum PurchaseType {
  Bulk = '1',
  Single = '2'
}

Both of these didn’t work. Is there some configurations when updating the Angular 16 i’m missing or anyone experienced similar issues? Any help would be appreciated!

Disable submit button if any of option from the list not selected from the drop down list

I am trying to link the submit button with the option list. If there is any one item of the from the option list of both list got selected from the drop down list then only the submit button will enabled.

Example – User have to select one option from category {ABC,DEF,GHI} and one option from category {XYZ,MNO,PQR} then the tag submit will activate. If one option from these two was missing then tag submit

const dropdown1 = document.getElementById("dropdown");
const dropdown2 = document.getElementById("dropdown");
const submitbutton = document.getElementById("btn");

dropdown1.addEventListener("input", function() {
  submitbutton.disabled = dropdown1.value = dropdown2.value === "";
});
<form>
  <select id="dropdown1">
    <option>ABC</option>
    <option>DEF</option>
    <option>GHI</option>
  </select>

  <select id="dropdown2">
    <option>XYZ</option>
    <option>MNO</option>
    <option>PQR</option>
  </select>

  <input type="submit" id="btn" disabled>
</form>

willn’t activate.

Find below code.

Try with above code but not happen.

Accessing history in chromium browsers through extensions API

I’m currently developing an extension that will provide a better alternative to standard Edge history page. For accessing the history I used chrome.history, which, as I previously thought, solved my problem. However, as I increased maxResults property of the query, at some point it just stopped returning more results (around a 100, I definitely have more than 100 history items), from which I concluded that it only returns the items that were added after the last launch of the browser. I comfirmed that by restarting the browser and saw an empty result. Currently, I’m using this piece of code to get history items:

function displayHistory(items, filter, main) {
    items.processingDone = false;
    chrome.history.search(
        {
            text: filter,
            maxResults: 1000
        },
        (history) => {
            undisplayAll(items, main);
            for (const i of history) {
                displayItem(items, i, main);
            }
            items.processingDone = true;
        }
    );
}

The question is: How to access the whole history?