Vue’s TransitionGroup doesn’t changes text like expected

I have an array of objects like this:

[ { word: 'example', guessed: false }, {word: 'another', guessed: true } ]

and this is my TransitionGroup component

<TransitionGroup
    appear
    tag="div"
    class="flex gap-y-4 gap-x-6 flex-wrap relative"
    enter-from-class="-translate-y-full opacity-0"
    leave-to-class="-translate-y-full opacity-0"
    enter-active-class="duration-500"
    leave-active-class="duration-500"
>
    <p
        v-for="each in anagramsList"
        :key="each.guessed"
        class="uppercase font-medium text-xl underline underline-offset-4 tracking-wider"
        :class="{ 'text-primary-300': !each.guessed }"
        v-text="each.guessed ? each.word : each.word.replace(/./g, '-')"
    />
</TransitionGroup>

this code is working, it shows the words side by side, if the word wasn’t guessed yet, it shows just the “—-” (dashes), if it was, shows the actual word…

Setup

Vue 3 and Tailwindcss

The problem

The transition when the word changes (from the dashes to the word) works, but they don’t change places like they were absolute position, the new word appear on the side before the dashed word disappear

the dashed word disappearing and the new word appearing should happen in the same spot in the array, but they are being added and removed normally like adding a new item to the array

My attempts

  • I’ve tried adding “mode=”out-in”” in the TransitionGroup tag
  • I’ve tried adding an “key” property in each object, with a “Symbol()” from vue
  • I’ve tried wrapping the “p” tag inside a normal “Trasition” and wrap that in a “template” tag to do the v-for

Randomize An array based on a Given seed [duplicate]

Given a array A and a seed S(number), how do I make an algorithm to randomize the array A with the seed S? (Array A is fixed but then it should rearrange the elements of A based on the seed)
Initial Attempt:

function shuffleArrayWithSeed(array, seed) {
  var getRandom = Math.floor(Math.sin(seed++) * 100)
  for (var i = 0;i<array.length;i++){
    function lowerqw(i,getRandom){
      if (Math.floor(getRandom * i)>=array.length){
        return lowerqw(i,getRandom/2);
      }else{
        return Math.floor(getRandom * i)
      }
      }
    var temporaryValue, randomIndex;
    randomIndex = lowerqw(i,getRandom);
    // Swap current element with a randomly selected element
    temporaryValue = array[i];
    array[i] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }
  console.log(array)
  return array;
}

But this doesn’t randomize the array at all. Could you please find any flaws? Or come with a better algorithm, which is not that time consuming as size of array A increases?
Note: This Question doesn’t help me as the answers here, deal with those randomizing the array at complete random.

Get All matching Substring between two characters using javascript

I am trying to extract a string from within a larger string where it get everything in between a { and a }

input I would {do} this for {every} {occurence} of a <substring> my starting

output should be [{do},{every},{occurence}]

var inputs = I would {do} this for {every} {occurence} of a <substring> my starting;
var arrStr = inputs.split(/[{}]/);
console.log(arrStr)

React native react-native-paper problem with chips inside a view

enter image description here

I’m having the following problem with the chip inside the View when it has a style.

I tried the same code on snack expo, there problem doesn’t happen.

Expo:

enter image description here

But when I try it on my physical device I get the problem seen in the picture.

Can you give me a hand?

Link: expo

import { useEffect, useState, useRef } from 'react';
import {
  ScrollView,
  View,
  StyleSheet,
  DrawerLayoutAndroid,
} from 'react-native';

import { Card, Chip } from 'react-native-paper';

const navigationView = () => <View style={{ margin: 5, marginTop: 50 }} />;

export default function App() {
  const drawer = useRef(null);

  return (
    <DrawerLayoutAndroid
      ref={drawer}
      drawerWidth={300}
      renderNavigationView={navigationView}>
      <View style={styles.container}>
        <ScrollView
          style={{
            flex: 1,
          }}>
          <Card style={{ marginBottom: 5 }}>
            <Card.Title
              title={'Title'}
              subtitle={'SubTitle'}
              subtitleNumberOfLines={2}
            />
            <Card.Content>
              <View style={{ alignItems: 'flex-end' }}>
                <Chip
                  style={{
                    backgroundColor: '#F0BF05',
                  }}>
                  Right
                </Chip>
              </View>
              <View style={{ alignItems: 'flex-start' }}>
                <Chip
                  style={{
                    backgroundColor: '#00BFFF',
                  }}>
                  Left
                </Chip>
              </View>
              <View style={{ alignItems: 'flex-end' }}>
                <Chip
                  style={{
                    backgroundColor: '#F0BF05',
                  }}>
                  Right
                </Chip>
              </View>
            </Card.Content>
          </Card>
        </ScrollView>
      </View>
    </DrawerLayoutAndroid>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: 12,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
});

Reactive function in svelte not firing when the value changes?

Entire code sample below.

The problem I have is that I know vatSuccess is actually changing successfully. However when I try to do anything with it in a reactive manner when I know it should be true it does not seem to work.

In the sample below I would expect the reactive statement console logging ‘vatSuccess’ to run twice first when it’s declared as false and then again when it becomes true.

However it only runs the first time

let vatSuccess = false
let nameSuccess = false

function handleVatValidation(): Error {
    // Vat is optional so putting nothing passes validation
    if (companyInformation.vat.length === 0) {
        vatSuccess = true
        vatError = null
        return null
    }

    if (companyInformation.vat.length < 6) {
        vatSuccess = false
        vatError = 'vat must be at least 6 characters'
        return 'vat must be at least 6 characters'
    }

    vatSuccess = true
    console.log('vatSuccess', vatSuccess) // This code runs and prints true

    vatError = null
    return null
}

$: {
    console.log('vatSuccess', vatSuccess) // This only runs once when it is false
}

I have tried to change it liek this so vatSuccess is a reactive value to begin with but the behaviour is the same.

$: vatSuccess = false

ngx-sharebuttons npm not working with angular 15

I am facing this issue with version 15 of angular
I try with the older version of ngx-sharebuttons (13,12, and 11 too) but the issue is the same there is nothing in the description about which version I have to use for angular 15

this is error
error

here is my pakege.json
pakege.json

  • i try to install older version of ngx-sharebuttons
  • I set up a fresh project for it

but the issue is the same

Get a weighted value between 0 and 1 based on zero being min value and 1 max value

Let’s set I have a set of numbers: Set(6) { 0, 2.58, 2.74, 2.75, 4.12, 5.5 }. These sum to 17.69.

I know I can get a weighted / percentage based value between 0 and 1 by dividing each number by the total, which produces:

{
  '0': 0,
  '2.58': 0.14584511023176935,
  '2.74': 0.15488976823063877,
  '2.75': 0.1554550593555681,
  '4.12': 0.2328999434708875,
  '5.5': 0.3109101187111362
}

The result I am looking for though, is more like this:

{
  '0': 0,
  '2.58': around 0.5,
  '2.74': just over 0.5,
  '2.75': just over 0.5,
  '4.12': around 0.8,
  '5.5': 1
}

So the closer a number is to the higher number in the set, the closer to 1 it is.

I’m sure I’m missing something simple here.

Issues with AR.js Location-Based Example from Documentation

I am trying to implement the location-based augmented reality functionality using AR.js library. I have been referring to the official AR.js documentation (https://ar-js-org.github.io/AR.js-Docs/) and specifically the location-based section.

I have copied the provided code into my HTML file and made the necessary changes by replacing the add-your-latitude and add-your-longitude placeholders with my actual latitude and longitude values. However, the AR object is not appearing at the specified GPS coordinates. I have also tried adding multiple markers with close positions to my location, but still no success.

I have checked the browser console for any error messages, but there are no relevant errors or warnings. I have also ensured that my browser has location permission granted to the web page (i tested on iOS – safari and chrome both).

Is there anyone who has successfully implemented the AR.js location-based functionality? Could there be any specific steps or considerations that I might be missing? Is there a working example or any additional resources available for implementing location-based AR using AR.js?

I would appreciate any guidance or insights to help resolve this issue. Thank you in advance for your assistance.

How to Add Span tag to text in WordPress?

Greetings to all friends of WordPress and Code ❤️,
This i my first post here so i hope i do it in a good way,)

How can add a span tag to a text in WordPress in one click?

What I am intending to achieve is the addition of a button to the Gutenberg editor toolbar. This button, once clicked, should surround the selected text with a tag <span data-no-translation=””></span> . I have tried various approaches using the WordPress block API, but the resulting outcome is not what I expected. All I manage to achieve is the visibility of the ‘no translate’ button.

After several attempts, the button does not function as anticipated. Either it does nothing at all, or it simply adds the tag without the selected content, or I have something better: <span class=”no-translation”>test</span>

However, what I want is: <span data-no-translation=””>test</span>

Below is the JavaScript code that I utilized for my customized button:

(function (wp) {
    var MyCustomButton = function (props) {
        return wp.element.createElement(
            wp.blockEditor.RichTextToolbarButton, {
                icon: 'editor-code',
                title: 'No Translate',
                onClick: function () {
                    props.onChange(wp.richText.toggleFormat(
                        props.value,
                        { type: 'my-plugin/my-custom-button' }
                    ));
                },
                isActive: props.isActive,
            }
        );
    }
    wp.richText.registerFormatType(
        'my-plugin/my-custom-button', {
            title: 'No Translate',
            tagName: 'span',
            className: 'no-translation',
            attributes: {
                'data-no-translation': 'true'
            },
            edit: MyCustomButton,
        }
    );
})(window.wp);

this code in my functions.php file

function mon_plugin_gutenberg() {
    wp_enqueue_script(
        'mon-plugin-gutenberg',
        get_stylesheet_directory_uri() . '/mon-plugin-gutenberg.js',
        array( 'wp-blocks', 'wp-dom', 'wp-editor', 'wp-rich-text' ),
        filemtime( get_stylesheet_directory() . '/mon-plugin-gutenberg.js' )
    );
}
add_action( 'enqueue_block_editor_assets', 'mon_plugin_gutenberg' );

I am sure it is a minor error in my code or a configuration issue, but I am unable to find the solution. If anyone could lend me a hand in resolving this issue, I would be immensely grateful.

I use this attribute to avoid translating certain links or texts, for instance for my page with TranslatePress plugin which automatically changes/translates the URLs if it is an internal URL https://translatepress.com/

For instance I added a link to my homepage (https://wikihhc.com/) in the content of my page: https://wikihhc.com/guide/hhc/ and if I don’t add <span data-no-translation=””> by going through “edit in HTML”, the link is no longer on the homepage but on https://wikihhc.com/es/

for the page translated into Spanish, for instance:https://wikihhc.com/es/guia/hhc/

In most cases this is what I want but in this particular example, no.)

Thank you in advance for your assistance and kindness as I am a beginner!

Running Javascript on Console without Screen Refresh

I have a site I want to run JS Code on through console, but not clear the console on Screen Refresh;
I have a website (I am making it) where there is a “Start” button whose id is “start-btn”. I have some code to put in the console which clicks the start button, waits 12 minutes and waits 20 minutes then reloads the page then starts the whole process again. There is a process when the button is pressed, that process takes 12 minutes, and to do the process again, there is a 20 minute delay. The problem is, the button is only available after refresh (it isn’t live); also, I don’t want to change any of my source code, because this is a new fun learning challenge for me. Also please don’t suggest me something like Userscript managers or Chrome Extension making, they don’t work out for me. So, how do I run this code persistently even after the screen refreshes? The code is down below:

I tried Chrome Extensions, Userscript managers and everything, so please don’t tell me those.

How to generate large numbers in Hebrew in JavaScript?

At first I came up with this script for generating smaller numbers up to roughly 1000:

const one = ['א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט']

const ten = ['י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ']

const hundred = ['ק', 'ר', 'ש', 'ת', 'ך', 'ם', 'ן', 'ף', 'ץ']

/**
 * Convert number to Hebrew script number.
 */

export function make(n: number) {
  const a = Math.floor(n / 100)
  const x = n % 100
  const b = Math.floor(n / 10)
  const y = x % 10

  const s = []
  if (a) {
    s.push(hundred[a - 1])
  }
  if (b) {
    s.push(ten[b - 1])
  }
  if (y) {
    s.push(one[y - 1])
  }

  return s.join('')
}

It’s probably a little incorrect. But now I would like to generate even larger numbers using the number table from here, which I have copied here:

const list = {
  1: 'א',
  2: 'ב',
  3: 'ג',
  4: 'ד',
  5: 'ה',
  6: 'ו',
  7: 'ז',
  8: 'ח',
  9: 'ט',
  10: 'י',
  11: 'יא',
  12: 'יב',
  13: 'יג',
  14: 'יד',
  15: 'ט״ו',
  16: 'ט״ז',
  17: 'יז',
  18: 'יח',
  19: 'יט',
  20: 'כ',
  30: 'ל',
  40: 'מ',
  50: 'נ',
  60: 'ס',
  70: 'ע',
  80: 'פ',
  90: 'צ',
  100: 'ק',
  200: 'ר',
  300: 'ש',
  400: 'ת',
  500: 'ך',
  600: 'ם',
  700: 'ן',
  800: 'ף',
  900: 'ץ',
  1000: "א'",
  2000: 'ב׳',
  5000: "ה'",
  10000: "י'",
  100000: "ק'",
}

So there are numbers 1-9, 10-90, 100-900, then at the end 1000 2000 5000 10000 and 100000. Say I want to generate numbers up to 100k, how can I do that effectively? You would have to do something like this perhaps? I can’t tell if I have it correct, and I don’t know enough yet to know what the expected output should be exactly, other than the letters should be laid out from left to right with the larger numbers on the left.

function make(n) {
  if (n > 100000) {
    throw new Error("Too large");
  }

  const a = Math.floor(n / 100000);
  const x = n % 100000;
  let b = Math.floor(n / 10000);
  const y = x % 10000;
  let c = Math.floor(n / 5000);
  const z = y % 5000;
  let d = Math.floor(n / 2000);
  const z2 = z % 2000;
  let e = Math.floor(n / 1000);
  const z3 = z2 % 1000;
  const f = Math.floor(n / 100);
  const z4 = z3 % 100;
  const g = Math.floor(n / 10);
  const z5 = z4 % 10;

  const s = [];
  if (b) {
    while (b--) s.push(list[10000]);
  }
  if (c) {
    while (c--) s.push(list[5000]);
  }
  if (d) {
    while (d--) s.push(list[2000]);
  }
  if (e) {
    while (e--) s.push(list[1000]);
  }
  if (f) {
    s.push(hundred[f - 1]);
  }
  if (g) {
    s.push(ten[g - 1]);
  }
  if (z5) {
    s.push(one[z5 - 1]);
  }

  return s.join("");
}

const list = {
  1: "א",
  2: "ב",
  3: "ג",
  4: "ד",
  5: "ה",
  6: "ו",
  7: "ז",
  8: "ח",
  9: "ט",
  10: "י",
  11: "יא",
  12: "יב",
  13: "יג",
  14: "יד",
  15: "ט״ו",
  16: "ט״ז",
  17: "יז",
  18: "יח",
  19: "יט",
  20: "כ",
  30: "ל",
  40: "מ",
  50: "נ",
  60: "ס",
  70: "ע",
  80: "פ",
  90: "צ",
  100: "ק",
  200: "ר",
  300: "ש",
  400: "ת",
  500: "ך",
  600: "ם",
  700: "ן",
  800: "ף",
  900: "ץ",
  1000: "א'",
  2000: "ב׳",
  5000: "ה'",
  10000: "י'",
  100000: "ק'",
};

const one = ["א", "ב", "ג", "ד", "ה", "ו", "ז", "ח", "ט"];

const ten = ["י", "כ", "ל", "מ", "נ", "ס", "ע", "פ", "צ"];

const hundred = ["ק", "ר", "ש", "ת", "ך", "ם", "ן", "ף", "ץ"];

console.log(make(11234))

Is iteration order of Typescript Map deterministic

In the code below for instance, is iteration order guaranteed to stay the same?

const m = new Map();
m.set('h', {age: 99, salary: 9000});
m.set('a', {age: 77, salary: 3000});
for (const [_, element] of m.entries()) {
  console.log(element);
}
for (const [_, element] of m.entries()) {
  console.log(element);
}
for (const [_, element] of m.entries()) {
  console.log(element);
}

Minecraft bedrock edition @minecraft/server module beforechat event

Manifest dependencies

{
    "module_name": "@minecraft/server",
    "version": "1.2.0-beta"
},

Main.js

import * as server from "@minecraft/server"

// This is the old version for listening to a chat event (1.1.0-beta):
server.world.events.beforeChat.subscribe(function (eventData) {
    let Player = eventData.sender
    let Message = eventData.message
    Player.tell($`[${Player}]: ${Message}`)
}

“server.world.events.beforeChat.subscribe” is causing the error:
TypeError: cannot read property ‘subscribe‘ of undefined

I want the server to listen to chat message events but I’m not sure how I do that with the new version. I’ve looked at the Microsoft documentation:

Microsoft has not provided any usage examples and I cannot find any other resources.

Event handler of must be added on the initial evaluation of worker script – Firebase Service Worker

I am trying to register a service worker, and it seems to be working. However, I get 3 warnings:

  1. Event handler of ‘push’ event must be added on the initial evaluation of worker script.
  2. Event handler of ‘pushsubscriptionchange’ event must be added on the initial evaluation of worker script.
  3. Event handler of ‘notificationclick’ event must be added on the initial evaluation of worker script.

I am developing a Flutter Web app, and wanted to secure my firebaseConfig. I noticed that you can view a service worker when in the developer options, so I didn’t want to place the config there. I opted for storing my firebaseConfig setup on the cloud, in the google cloud secret manager (for now, anyway).

When the user clicks to “allow” for notifications, I register the service worker, which is the famous firebase-messaging-sw.js. I do this from a async function:

firebase_messaging_manager.js

async function registerFCMServiceWorker() {
  if ('serviceWorker' in navigator) {
    await navigator.serviceWorker.register('firebase-messaging-sw.js');
  }
}

I ended up removing some code from the function, so there may not need to be async/await functionality here.

firebase-messaging-sw.js

// Event handlers
self.addEventListener('push', (event) => {
  console.log("push called");
});

self.addEventListener('pushsubscriptionchange', (event) => {
  console.log("pushsubscriptionchange called");
});

self.addEventListener('notificationclick', (event) => {
  console.log("notificationclick called");
});

// Contains the code to run getFirebaseConfig()
importScripts('assets/lib/firebase_options.js');
importScripts('https://www.gstatic.com/firebasejs/9.22.0/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/9.22.0/firebase-messaging-compat.js');

// Initialize Firebase
getFirebaseConfig().then((firebaseConfig) => {
  firebase.initializeApp(firebaseConfig.result);
  const messaging = firebase.messaging();

  messaging.onBackgroundMessage((payload) => {
    console.log('Received background message', payload);
  });

});

As you can see, all of the mentioned events are at the top of the service worker, but it doesn’t seem to matter. I know that the ‘notificationclick’ event needs to be up there, but I don’t even use the other events. My only thought is that the warning messages must be firebase related. The reason I think this, is because I don’t initialize firebase until the promise is returned. In fact, if I hard-code the initialization for messaging, the warnings disappear.

I also noticed that the warnings do not point to firebase-messaging-sw.js, they point to a file called register.ts, which is a google file:

register.ts warnings

import {
  Component,
  ComponentContainer,
  ComponentType,
  InstanceFactory
} from '@firebase/component';
import {
  onNotificationClick,
  onPush,
  onSubChange
} from '../listeners/sw-listeners';

import { GetTokenOptions } from '../interfaces/public-types';
import { MessagingInternal } from '@firebase/messaging-interop-types';
import { MessagingService } from '../messaging-service';
import { ServiceWorkerGlobalScope } from '../util/sw-types';
import { _registerComponent, registerVersion } from '@firebase/app';
import { getToken } from '../api/getToken';
import { messageEventListener } from '../listeners/window-listener';

import { name, version } from '../../package.json';

const WindowMessagingFactory: InstanceFactory<'messaging'> = (
  container: ComponentContainer
) => {
  const messaging = new MessagingService(
    container.getProvider('app').getImmediate(),
    container.getProvider('installations-internal').getImmediate(),
    container.getProvider('analytics-internal')
  );

  navigator.serviceWorker.addEventListener('message', e =>
    messageEventListener(messaging as MessagingService, e)
  );

  return messaging;
};

const WindowMessagingInternalFactory: InstanceFactory<'messaging-internal'> = (
  container: ComponentContainer
) => {
  const messaging = container
    .getProvider('messaging')
    .getImmediate() as MessagingService;

  const messagingInternal: MessagingInternal = {
    getToken: (options?: GetTokenOptions) => getToken(messaging, options)
  };

  return messagingInternal;
};

declare const self: ServiceWorkerGlobalScope;
const SwMessagingFactory: InstanceFactory<'messaging'> = (
  container: ComponentContainer
) => {
  const messaging = new MessagingService(
    container.getProvider('app').getImmediate(),
    container.getProvider('installations-internal').getImmediate(),
    container.getProvider('analytics-internal')
  );

  self.addEventListener('push', e => {
    e.waitUntil(onPush(e, messaging as MessagingService));
  });
  self.addEventListener('pushsubscriptionchange', e => {
    e.waitUntil(onSubChange(e, messaging as MessagingService));
  });
  self.addEventListener('notificationclick', e => {
    e.waitUntil(onNotificationClick(e));
  });

  return messaging;
};

export function registerMessagingInWindow(): void {
  _registerComponent(
    new Component('messaging', WindowMessagingFactory, ComponentType.PUBLIC)
  );

  _registerComponent(
    new Component(
      'messaging-internal',
      WindowMessagingInternalFactory,
      ComponentType.PRIVATE
    )
  );

  registerVersion(name, version);
  // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
  registerVersion(name, version, '__BUILD_TARGET__');
}

/**
 * The messaging instance registered in sw is named differently than that of in client. This is
 * because both `registerMessagingInWindow` and `registerMessagingInSw` would be called in
 * `messaging-compat` and component with the same name can only be registered once.
 */
export function registerMessagingInSw(): void {
  _registerComponent(
    new Component('messaging-sw', SwMessagingFactory, ComponentType.PUBLIC)
  );
}

Here’s the TL/DR section of the code that the warnings point to:

declare const self: ServiceWorkerGlobalScope;
const SwMessagingFactory: InstanceFactory<'messaging'> = (
  container: ComponentContainer
) => {
  const messaging = new MessagingService(
    container.getProvider('app').getImmediate(),
    container.getProvider('installations-internal').getImmediate(),
    container.getProvider('analytics-internal')
  );

  self.addEventListener('push', e => {
    e.waitUntil(onPush(e, messaging as MessagingService));
  });
  self.addEventListener('pushsubscriptionchange', e => {
    e.waitUntil(onSubChange(e, messaging as MessagingService));
  });
  self.addEventListener('notificationclick', e => {
    e.waitUntil(onNotificationClick(e));
  });

  return messaging;
};

I haven’t tested this yet, but the most likely solution is to instantiate firebase messaging without my configuration, then update the messaging afterwards. However, i’m not sure how to do that. I’m sure it’s not as simple as updating the messaging object. That is, if I do this, it may not work with the event ‘notificationclick’ when I send messages.

Any thoughts would be extremely helpful. Thank you all!