Is there a way to use ngx-spinner in standalone angular apps?

How do I use ngx-spinner in my standalone angular app ?

There’s no app.module to import it. I can’t import it in the component itself because I get “Component imports must be standalone components, directives, pipes, or must be NgModule” error. And if I just declare it on constructor I get “‘ngx-spinner’ is not a known element” in the template.

How do I use it in standalone apps ?

How is ‘return new Error’ different from ‘throw’

I was practicing promise and this exercise popped up. I knew the throw will immediately hop out of the the function and find the nearest .catch. However, I still don’t understand why return new Error('test'); is followed by the action of .then and not .catch.

Code snippet

function job(state) {
    return new Promise(function(resolve, reject) {
        if (state) {
            resolve('success');
        } else {
            reject('error');
        }
    });
}

let promise = job(true);

promise

.then(function(data) {
    console.log(data);

    return job(true);
})

.then(function(data) {
    if (data !== 'victory') {
        throw 'Defeat';
    }

    return job(true);
})

.then(function(data) {
    console.log(data);
})

.catch(function(error) {
    console.log(error);

    return job(false);
})

.then(function(data) {
    console.log(data);

    return job(true);
})

.catch(function(error) {
    console.log(error);

    return 'Error caught';
})

.then(function(data) {
    console.log(data);

    return new Error('test');
})

.then(function(data) {
    console.log('Success:', data.message);
})

.catch(function(data) {
    console.log('Error:', data.message);
});

The result

> "success"
> "Defeat"
> "error"
> "Error caught"
> "Success:" "test"

I have researched but I can’t seem to find any explanation on this matter. I also consulted chatGPT but it really sucked.

i’m getting following error when i refresh page

this code is run properly for first time, but when i refresh page i get this error

export default function Adminroute() {
  const [ok, setOk] = useState(false);
  const [auth] = useAuth();
  
  const authCheck = async () => {
    const resp = await axios.get(`${api_endpoint}${admin_dashboard}`);
    if (resp.data.ok) {
      setOk(true);
    } else {
      setOk(false);
    }
  };
    useEffect(async () => {
    if (auth?.token) await authCheck();
  }, [auth?.token]);
  return ok ? <Outlet /> : <SpinnerWithCouter path="/" />;
}

enter image description here

Merge multiple versions of a modified string in JS

Given three strings :

  • str0 is the initial text
  • str1 is a modified version of that text
  • str2 is an other modified version of that text

How to produce a string that combines modifications introduced by both versions?

For example:

str0 = "This is quite a short text";
str1 = "This is quite a text";
str2 = "This is QUITE a short text";
merge(str0, [str1, str2]) // should return "This is QUITE a text"

I am currently using jsdiff library to compare the source string str0 with the target strings str1 and str2. The function I am using (Diff.diffWords) returns a list of changes to be applied to str0 in order to obtain str1 or str2 (words to keep, to add, to remove).

In the example, Diff.diffWords(str0, str1) returns

[
   { value: "This is quite a " },
   { removed: true, value: "short" },
   { value: "text" }
]

And Diff.diffWords(str0, str2) returns

[
   { value: "This is " },
   { removed: true, value: "quite" },
   { added: true, value: "QUITE" },
   { value: " a short text" }
]

But I not sure how to properly merge these two lists of changes in order to build the final string. Is there a known algorithm to implement in that case?

How to make my cookie consent ad for google tag work?

With my code snippet in javascript in a wordpress website that have a google tag that links to google analytics, when I enable it, nothing happen in my google analytics, and when it’s off (the cookie consent banner) it works but want to have the cookie consent banner.

<script>
    window.dataLayer = window.dataLayer || [];
    function gtag() {
        dataLayer.push(arguments);
    }
    if (localStorage.getItem('consentMode') === null) {
        gtag("consent", "default", {
                      "ad_storage": "denied",
            "analytics_storage": "denied",
        });
    } else {
        gtag("consent", "default", JSON.parse(localStorage.getItem("consentMode")));
    }
</script>

<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-MYSECRETKEY');</script>
<!-- End Google Tag Manager -->

<script>
// Function to send consent to Google Analytics via GTM
    
    function setConsent(consent) {
        const consentMode = {
            'ad_storage': consent.ad_storage ? 'granted' : 'denied',
            'analytics_storage': consent.analytics_storage ? 'granted' : 'denied',
        };
        gtag('consent', 'update', consent);
        localStorage.setItem('consentMode', JSON.stringify(consentMode));
    }
    
    window.onload = function() {
        
        if (document.getElementById('btn_yes') != null) {
              
                    document.getElementById('btn_yes').addEventListener('click', function() {
                        setConsent({
                            ad_storage : true,
                            analytics_storage : true
                        });
                    });

                    document.getElementById('btn_no').addEventListener('click', function() {
                        setConsent({
                            ad_storage : false,
                            analytics_storage : false
                        });
                    });
        }
    }
 
</script>

I need to edit image using ai [closed]

Recently, I am building AI-Image-Generation from photo.
I tried to implement this using OpenAI API.

enter image description here

I received the generated image file, but I am not satisfied.
Maybe should I use another AI API instead of OpenAI API?
If yes, what kind of API do you recommend?
If you have a solution, please let me know.

This is my node.js snippet.
You can find my active project from my Github

const fs = require("fs");
const OpenAI = require("openai");

const openai = new OpenAI({
  apiKey: "YOUR API KEY HERE",
});

app.post("/generate", async (req, res) => {
  const { fileName, prompt, imageAmount, imageSize } = req.body;
  try {
    const image = await openai.images.edit({
      image: fs.createReadStream(`./uploads/${fileName}`),
      prompt,
      model: "dall-e-2", // I cannot use dall-e-3. opeai doe
      n: 2,
      size: "256x256",
    });
    console.log(image.data);
    return res.status(200).json({ data: image.data });
  } catch (err) {
    console.log(err);
    return res
      .status(500)
      .json({ message: "Something went wrong during generating an image" });
  }
  console.log(fileName, prompt, imageAmount, imageSize);
});

React Native: Issue with Button Component Rendering Blank in Android

I’m encountering an issue in my React Native project where the Button component appears blank on Android, despite setting the title prop. Here’s a simplified version of my code:

import React from 'react';
import { View, Button } from 'react-native';

export default function MyComponent() {
  return (
    <View>
      <Button title="Click Me" onPress={() => handlePress()} />
    </View>
  );
}

function handlePress() {
  console.log("Button clicked!");
}

I’ve checked the documentation and other resources, and it seems like I’m using the Button component correctly. However, when I run the app on an Android emulator, the button is rendering without any text. The onPress function is triggered correctly, but the text is not visible.

Has anyone encountered a similar issue or can point me in the right direction to troubleshoot and resolve this problem? Thanks for your help!

React JS usRef() hook for header also affects footer

I am completely new to React and I have an App with the following structure in App.js:

function App() {

  return (
    <Router>
      <div className="App">
        <Header />
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/portfolio" element={<Portfolio />} />
        </Routes>
        <Footer />
      </div>
    </Router>
  );
}

export default App;

And the relevant code of my Header.js is:

function Header() {
const navLinksRef = useRef();
const toggleMenu = () => {
    setMenuOpen((prevMenuOpen) => {
      const navLinks = navLinksRef.current;
      const overlay = overlayRef.current;

      if (navLinks && overlay) {
        setIsTransitionEnabled(true);
        if (!prevMenuOpen) {
          // Open menu
          navLinks.style.transform = 'translateX(0)';
          overlay.style.opacity = '1';

        } else {
          // Close menu
          navLinks.style.transform = 'translateX(100%)';
          overlay.style.opacity = '0';
        }
      }

      return !prevMenuOpen; // Toggle the menu state
    });
  };


  const closeMenu = () => {
    setMenuOpen(false);

    resetParameters()
      
    setIsTransitionEnabled(false);
  };

  const handleTransitionEnd = () => {
    setIsTransitionEnabled(false);
  };

  const resetParameters = () => {
    const navLinks = navLinksRef.current;
    const overlay = overlayRef.current;

    if (navLinks && overlay) {
      navLinks.style.transform = '';
      overlay.style.opacity = '';
    }
  };

return (
    <header className={`header ${menuOpen ? 'menu-open' : ''}`}>
      <div className="nav-container">
        <div className="menu-icon" onClick={toggleMenu}>
          <span></span>
          <span></span>
          <span></span>
        </div>
        <nav
          ref={navLinksRef}
          className={`nav-links ${isTransitionEnabled ? 'transition' : ''}`}
          onTransitionEnd={handleTransitionEnd}
        >
          <ul>
            <li><Link to="/" onClick={closeMenu}>Home</Link></li>
            <li><Link to="/portfolio" onClick={closeMenu}>Portfolio</Link></li>
            <li><Link to="/about" onClick={closeMenu}>About</Link></li>
          </ul>
        </nav>
        <div
          ref={overlayRef}
          className="overlay"
          onClick={toggleMenu}
        ></div>
      </div>
    </header>
  );
}

export default Header;

As you can see I am using navLinks.style.transform = 'translateX(0)'; and navLinks.style.transform = 'translateX(100%)'; to modify the position of “navLinks”. What I wanted to achieve here was to apply this transformation only to the navigation elements of the header. What actually happens is that my footer is affected as well. What am I doing wrong?

If it is of any help, this is the code of the footer:

function Footer() {
    return (
      <footer className="footer">
        <div className="footer-content">
          {/* Your other footer content */}
          <a
            href="https://www.instagram.com/julian.manke/"
            target="_blank"
            rel="noopener noreferrer"
            className="instagram-link"
          >
            <FontAwesomeIcon icon={faInstagram} size="2x" />
          </a>
        </div>
      </footer>
    );
  }

export default Footer;

How to compare sets in Javascript/Node.js

I am at a loss. Mozilla web docs for Set clearly lists set methods like .union, .intersection and more. But when I try to use them in a Node REPL, the sets seem to lack these methods. What do I miss?

console.log(new Set(['a', 'b', 'c']).union(new Set(['c', 'd'])));
% node
Welcome to Node.js v20.10.0.
Type ".help" for more information.
> new Set(['a', 'b', 'c']).union(new Set(['c', 'd']))
Uncaught TypeError: (intermediate value).union is not a function

Terser mangle props accessed by string vars

Is there a way to change the mangled key from string vars or prevent mangling the prop if accessed by var?

Ex:

# webpack.js
new TerserPlugin({
  parallel: false,
  terserOptions: {
    nameCache: mangleLegend,
    mangle: {
      properties: {
        regex: /^manglePrefix_/,
        keep_quoted: true,
      },
    },
  },
}),


# test.js
const someObject = {
  manglePrefix_name: 'Some name',
}

const key = 'manglePrefix_name';

console.log(someObject[key]); // either also mangle the string or prevent mangling the object altogether
console.log(someObject.hasOwnProperty(key)); // this is nice to have, but not mandatory.

I know that if I use the string directly in brackets it will work/ignore based on keep_quoted, but I’m interested in the case with the variable/enum (TypeScript)

Chartjs Legend for each bar

I’m trying to create a horizontal bar chart where both the data and labels are random. I also want to incorporate a legend for each bar, similar to a donut chart. The goal is to enable removal of a specific item by selecting its corresponding legend text.
I’m considering the option of creating multiple datasets, but I’m unsure if that is the best approach.
Im using Chart.js/2.7.2/Chart.min.js

Im expecting that i could create legend for each bar
Please suggest some good ideas without multiple datasets as well

Below code i was trying for creating new datasets based on labels and values :

const newDatasets = labels.map((label, index) => ({
label: label,
data: values[index],
}));

Here is my actual code :

const labels = category;
const values = count;

const data = {
    labels: labels,
    datasets: [{

        data: values,
        backgroundColor: getBackgroundColor(labels, reportColor[0]),
        borderWidth: 2,
        borderRadius: 19,
        borderSkipped: false,
        barPercentage: 1,
        categoryPercentage: 0.1
    }]
    
};

const config = {
    type: 'horizontalBar',
    data,
    options: {
        plugins: {
    datalabels: {
        color: 'white',
        font: {
            weight: 'bold'
        },
    },
},  
        responsive: true,
        maintainAspectRatio: false,
        indexAxis: 'y',
        legend: { display: false },
        tooltips: {
            cornerRadius: 10
        },
        scales: {
            xAxes: [{
                barThickness: 6,
                gridLines: {
                    display: false,
                    drawBorder: false
                },
                scaleLabel: {
                    display: true,
                    labelString: yAxisLabel,
                    fontSize: 20
                },
                ticks: {
                    /*beginAtZero: true,*/
                    userCallback: function(label, index, labels) {
                        if (Math.trunc(label) === label) {
                            return label;
                        }
                    }
                },
            }],
            yAxes: [{
                barPercentage: 1.0,
                barThickness: 20,
                gridLines: {
                    display: false,
                    drawBorder: false
                },
                scaleLabel: {
                    display: true,
                    labelString: xAxisLabel,
                    fontSize: 20
                },
            }]
        },
    },
};


horizontalBarChart = new Chart(
    document.getElementById("horizontalBarChart"),
    config
);

React: Accessing Updated State from Custom Hook Inside Event Handler

In a React component, I’m facing a challenge with state synchronization between an event handler and a custom hook. The event handler updates a state variable, and I need to access the latest value of another state that is derived from a custom hook depending on this updated state.

We use a custom hook, and define a state variable and an event handler.

The event handler sets the value of state variable a to variable c (which depends on the event argument) and then needs to use the latest value of b, which is returned by a custom hook that depends on a.

function MyComponent(props) {
  const [a, setA] = useState(null);
  const b = useCustomHook(a);

  const eventHandler = useCallback(async (event) => {
    try {
      const c = event.data;

      setA(c);

      if (b) { // we need to use b here, but it is stale (one step behind)
        // logic
      }
      else {
        // more logic
      }
    } catch (e) {
      console.error(`Error:`, e);
    }

  }, [b]);
}

The issue is that b is always one step behind the event handler. When running the logic in the event handler, its value has not been updated yet.

How can one access the latest value of b (which depends on a, which depends on c, which depends on event) inside of the event handler?

I have tried using only setting the state variables inside of the event handler and use an effect for the rest of the logic, but the effect does not only run when the event handler is triggered.

What solution would be in line with the React paradigm? How can I restructure my code to solve this issue?

How to share providers between app / child modules in Angular 15

I have a module which provides a config file using an injection token. The config file can be passed from the parent module using ModuleWithProviders

export class ChildModule{
  static withConfig(config: SomeConfigStructure): ModuleWithProviders<ChildModule> {
    return {
      ngModule: ChildModule,
      providers: [
        {
          provide: CONFIG_INJECTION_TOKEN,
          useValue: config.subSectionInConfig,
          deps: [APP_INITIALIZER]
        }
      ],
    };
  }
}

The module is then added to the app module like:

  imports: [  
    ChildModule.withConfig(config),
    AppRoutingModule,
    ...
  ],
  providers: [
    {
      provide: AnotherConfig,
      useFactory: ConfigFactory,
      deps: [Injector],
    },
    ...

When injecting these configs, Services provided by the ChildModule cannot seem to find AnotherConfig from the app module while other services, ChildModule or not, can’t find anything for CONFIG_INJECTION_TOKEN

In both cases the error thrown is NullInjectorError.
Am I missing a property on the provider or do my provided instances get messed up because they are only available in their respective module ?

I should probably pass AnotherConfig to the ChildModule withConfig method as well so everything is provided by one module but the problem still remains.

How do I access Firebase Tenants from a Vue app or Firebase Cloud Functions?

The Firebase multi tenant authentication docs include examples on how to work with Tenants in Node.js but I’m still learning and I don’t understand how this can be done in Cloud Functions.

function listAllTenants(nextPageToken) {
  return admin.auth().tenantManager().listTenants(100, nextPageToken)
    .then((result) => {
      result.tenants.forEach((tenant) => {
        console.log(tenant.toJSON());
      });
      if (result.pageToken) {
        return listAllTenants(result.pageToken);
      }
    });
}

listAllTenants();

How do I take this above and turn it into a Cloud Function?

The best I could do is this…

const functions = require("firebase-functions");
const admin = require("firebase-admin");
const tenantManager = admin.auth().tenantManager();
const express = require("express");
const cors = require("cors");

const app = express();

app.use(
  cors({
    origin: ["http://localhost:3000"], // Make sure to remove the trailing slash in the URL
  })
);

app.get("/getTenants", async (req, res) => {
  try {
    const tenantList = await tenantManager.listTenants();
    const tenantsArr = tenantList.tenants.map((tenant) => tenant.toJSON());
    res.status(200).send(tenantsArr);
  } catch (error) {
    console.error("Error fetching tenants:", error);
    res.status(500).send("Error fetching tenants");
  }
});

exports.getTenants = functions.https.onRequest(app);

Plus my Vue store (Vuex) file where I call the function…

import { getFunctions, httpsCallable } from "firebase/functions";
async getTenants({ commit }) {
    commit("SET_TENANTS", []); // Clearing tenants before fetching new data
    try {
      const tenantsArr = [];
      const functions = getFunctions();
      const getTenantsCallable = httpsCallable(functions, "getTenants");
      const result = await getTenantsCallable(); // Call the callable function

      tenantsArr.push(result.data);
      console.log("Tenants:", result.data);
      commit("SET_TENANTS", tenantsArr);
    } catch (error) {
      // Handle errors
      console.error("Error fetching tenants:", error);
    }
  },

But this returns a not found 404 console error:
POST https://us-central1-mysite-12432-staging.cloudfunctions.net/getTenants 404 (Not Found)