How to create Javascript WritableStream on memory (like fs.creareWriteStream)

I try to use some JS library with ServiceWorker, without access to Node.JS FileSystem functionality. That original library export result in the same way

Import * as fs from 'fs'
...
JsLib.export(result, fs.createWriteStream("res.pdf")) 

I need the same export, but export to byte array, without FileSystem. I have create array in the same way

 const Out = (Array as any).create("byte", mysize)

and if I manually fill this byte array with test data, my algorithm working fine further.
But I don’t understand how to correctly create the same stream as Node.JS created, but in memory, in my “Out” array.
There are some example in MDN with WritableStream, but I’m not sure how that examples related to this task. Maybe there is cheap solution like

JsLib.export(result, ...Out) 

Or this solution not emulated fs.createWriteStream? Directly using spread syntax is impossible “A spread argument must either have a tuple type or be passed to a rest parameter”. But how to solve this quest correctly?

How to input text from URL

I have a webpage that has a search box and button. When you enter text into the search box it returns information on the page. I would like to figure out how I can enter text into the URL and have it auto-fill the search box on the page.

For instance, on google I would enter this URL: https://www.google.com/?q=TEST. Where “TEST” is the text that I want to search for in the search box.

My webpage doesn’t have multiple URL’s associated with it, everything happens on the same page and I use javascript to update the page results (no server side).

How can I make this possible to search in the search box through my URL.

I tried implementing the code below, and it works on my Visual Studio live server, but it doesn’t work when I upload it to my domain. I get an “Internal Service Error.” It seems like it wants a “path name” after the URL, and in my domain I don’t have any path. Or maybe I’m doing it all wrong in general.

I tried implementing the code below, and it works on my Visual Studio live server, but it doesn’t work when I upload it to my domain. I get an “Internal Service Error.”

It seems like it wants a “path name” after the URL, which I provide when running in my Visual Studio Live environment. In my domain, I don’t have any path, I am just entering www.mywebsite.com/?q=TEST. Is this where the problem is or is there something code wise that needs to be done?

function getQueryParam(name) {
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get(name);
}

// Check if the "q" parameter exists in the URL
const inputTextFromURL = getQueryParam('q');
if (inputTextFromURL) {
    document.getElementById('searchInput').value = inputTextFromURL;
    startSearch(); // Perform the search operation automatically
}

Javascript download Webgl canvas image

Canvas.toDataUrl() does not work and only shows the background that was loaded at the start. When i trigger the download the content drawn on the canvas element were not saved somehow. How can i fix it?

https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL did not work.

Code:
`
const canvas = document.querySelector(“#item > div > canvas”);
const gl = canvas.getContext(‘webgl’, { preserveDrawingBuffer: true });

const dataURL = canvas.toDataURL('image/png');

const a = document.createElement('a');
a.href = dataURL;
a.download = 'canvas-image.png';
a.click();

`

Why am I getting .slice is not a function? where is the problem from

function BlogList({ blogs }) {
  const { blogsLoading, searchBlogsLoading } = useBlogsContext();
  const blogsLimit = 6;
  const { paginate, setPaginate } = useState(1 * blogsLimit);
  const paginateHandler = (value) => setPaginate(value * blogsLimit);
  if (blogsLoading || searchBlogsLoading) {
    return <Spinner animation="border" variant="light" />;
  }

  return (
    <> <div>
        {blogs.slice(paginate - 6, paginate).map((blog) => {
          return (
            <div key={blog.id}>
              <div>{blog.title}</div>
              <div>{blog.body.substring(0, 100)}...</div>
              <div><MdAddReaction />
                <span">{blog.reactions}</span>
              </div>
              <div>{blog.tags.map((tag, idx) => (
                  <span key={idx}>{tag}</span> ))}
              </div>
              <div>
                <Link
                  to={`/blog/${blog.id}`}>
                  Read More
                </Link>
              </div>
            </div>
          );
        })}
      </div>
      <Pagination noOfBlogs={blogs.length} paginateHandler={paginateHandler} />
    </>
  );
}
BlogList.propTypes = {
  blogs: PropTypes.any,
};

export default BlogList;

I also changed the prop type to array and string, but it didn’t change
The values of the blogs are received from dummy json API
The data enters the blogs correctly, but it still displays this error

Uncaught TypeError: blogs.slice is not a function

useNavigation changes URL but not does not render or display component

Consider the following code:

App.jsx:

import ContextProvider from "./provider/contextProvider";
import Routes from "./routes";
function App() {
  console.log("In App");

  return (
    <ContextProvider>
      <Routes />
    </ContextProvider>
  );
}

export default App;

Routes.jsx:

import { RouterProvider, createBrowserRouter } from "react-router-dom";
import { provideContext } from "./provider/contextProvider";
import Component1 from "./pages/Component1";
import Component2 from "./pages/Component2";
const Routes = () => {
  const { token } = provideContext();

  const router = createBrowserRouter([
    {
      path: "/Component2",
      element: <Component2 />,
    },
    {
      path: "/Component1",
      element: <Component1 />,
    },
  ]);


  return <RouterProvider router={router} />;
};

export default Routes;

pages/Component1.jsx:

const Component1 = () => {
  console.log("In Component1");

  return <div>Component1</div>;
};

export default Component1;

pages/Component2.jsx:

import { useNavigate } from "react-router-dom";
import { provideContext } from "../provider/contextProvider";

const Component2 = () => {
  const navigate = useNavigate();
  const { setToken } = provideContext();
  console.log("In Component2");
  const onClick = () => {
    setToken("Token");
    setTimeout(() => {
      navigate("/Component1");
    });
  };

  return (
    <>
      <button onClick={onClick}>Click me</button>
    </>
  );
};

export default Component2;

provider/ContextProvider.jsx:

import { createContext, useContext, useState } from "react";

const Context = createContext();

const ContextProvider = ({ children }) => {
  const [token, setToken] = useState("Initial");

  return (
    <Context.Provider value={{ token, setToken }}>{children}</Context.Provider>
  );
};

export const provideContext = () => {
  return useContext(Context);
};

export default ContextProvider;

When clicking the button in Component2, the URL changes but the UI still shows Component2.
Component 1 is not even rendered once.

Interestingly, if i remove the setTimeout() in Component2.jsx function OR remove const { token } = provideContext(); in Routes.jsx, the issue goes away. Not sure what is going.

How to add google maps markers from a json array- or how to add parameters for my array to the marker constructor

I’ve been fighting this forever I’m trying to figure out how to display google map markers from an object array generated in php, which I have JSON encoded and can access in my js file. Specifically I’m unsure how to either format my data so that the google maps marker parameters accept it, or how to define the parameters within the marker code.

Here are the important bits from the different programs:

PHP

$query = "SELECT LATITUDE as LAT, LONGITUDE as LNG, BUSINESSNAME as SHOP
     FROM mechanic 
     WHERE LATITUDE <> '' 
      AND LATITUDE IS NOT NULL 
    ";

if ($result = $conn -> query($query)) {
  while ($obj = $result -> fetch_object()) {
    // save the results to an object array on each iteration
    $objects[] = $obj;
  }
  $result -> free_result();
}
  
?>
  <script>var locations = <?php echo json_encode($objects); ?>

ARRAY IN JS

console.log(locations);
Array(3) [ {…}, {…}, {…} ]​
0: Object { LAT: "38.6152529", LNG: "-90.3559897", SHOP: "Toms Auto Care" }​
1: Object { LAT: "26.0039884", LNG: "-80.1416624", SHOP: "Sams Shop" }​
2: Object { LAT: "38.6152529", LNG: "-90.3559896", SHOP: "Mels Shop" }​
length: 3

GOOGLE MAP MARKER code sample in js that I am completely lost on getting to use the array:

locatons.forEach(([position, title], i) => {
      const marker = new google.maps.Marker({
        position,
        map,
        title: `${i + 1}. ${title}`,
        label: `${i + 1}`,
        optimized: false,
      });

I’ve been trying this for a long time, in many formats, I’m unsure if I had to make it into an object array, but I finally got that together, and now I have no idea how to get the markers constructor to use the lat lng and shop name.

AutoNumeric.js (ShinyWidgets) in Shiny DT Table

I am struggling to embed an autonumeric Input inside a DT table within a shiny app. I stumbled over this post here which made things a bit clearer for me.

However, I cant make it work for an autonumeric Input.

Here is what I have so far:

library(shiny)
library(DT)
library(shinyWidgets)

ui <- 
  tagList(
    DTOutput("dtable")
  ) 

server <- function(input, output){
  
  output$dtable <- 
    renderDT(
      {
        
        dat <- data.frame(
          select = c(
            as.character(
              autonumericInput(
                inputId = 'id_1',
                label = "Default Input 1",
                value = 1.34
              )
            )
          )
        )
        
        js <- c(
          "function(settings){",
          "  $('[id^=id_1]').autoNumeric({",
          "    minimumValue: 1,",
          "    maximumValue: 2,",
          "  });",
          "}"
        )
        
        datatable(
          dat,
          rownames = FALSE,
          escape = FALSE,
          options = list(
            initComplete = JS(js),
            preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
            drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); }')
          )
        )
      }
    )
  
}

shinyApp(ui, server)

I think the problem will probably be that the js-snippet is not correct and the initialization of the object does not work properly. However, I know close to nothing about JS and I am not sure on how to do this properly. Can anyone help me with this?

Wait datatable load to finish

in javascript i need wait to table load all data content from a string array, my approach is whit “initComplete” but table is not loading.
here is my example code:

<script>

    var myArray = [~alldata~]

    initComplete: buildTable(myArray)



    function buildTable(data){
        var table = document.getElementById('table')

        for (var i = 0; i < data.length; i++){
            var row = `<tr>
                            <td>type</td>
                            <td>${data[i].id}</td>
                            <td>${data[i].de}</td>                                              
                      </tr>`
            table.innerHTML += row


        }
    }

</script>

anyone have a sugestion?

i try the code above

Output text fields not working on wix using javascript

I am trying to take user input from dropdown boxes and text fields to carry out a calculation however I cannot seem to show the output in the boxes I want to.

Below is the code I have used to try and output the values but the boxes in the image attached don’t seem to change:

$w(“#text5”).text = (100 * (1 – Treatment1Year1)) >= 90 ? “>90%” : (100 * (1 – Treatment1Year1)) <= 10 ? “<10%” : (100 * (1 – Treatment1Year1)) + “%”;

$w("#text6").text = (100 * (1 - Treatment1Year3)) >= 90 ? ">90%" : (100 * (1 - Treatment1Year3)) <= 10 ? "<10%" : (100 * (1 - Treatment1Year3)) + "%";

$w("#text7").text = (100 * (1 - Treatment2Year1)) >= 90 ? ">90%" : (100 * (1 - Treatment2Year1)) <= 10 ? "<10%" : (100 * (1 - Treatment2Year1)) + "%";

$w("#text8").text = (100 * (1 - Treatment2Year3)) >= 90 ? ">90%" : (100 * (1 - Treatment2Year3)) <= 10 ? "<10%" : (100 * (1 - Treatment2Year3)) + "%";

enter image description here

I am new to javascript and wix so any help would be greatly appreciated 🙂

No strict mode – Why does my React component render three times when I click a button multiple times?

I have a simple React component that uses a state hook. The initial state is false, and when a button is clicked, the state is set to true. I have a console.log statement in the component to log when it renders.

Here is my code:

import { useState } from 'react';

function App() {
  const [value, setValue] = useState(false);

  function changeState() {
    setValue(true);
  }

  return (
    <>
      {console.log('rendered!')}
      <button onClick={changeState}>Click</button>
    </>
  );
}

export default App;

When I click the button multiple times, I see the message “rendered!” logged three times in the console. I expected it to be logged twice – once for the initial render, and once for the re-render after the state change. Can anyone explain why it’s being logged an extra time?

Unable to create custom transformer for UIFont using AWS style dictionary

I’m using AWS style dictionary to generate UI properties from Figma Tokens. I could not get custom transformer working.

Custom transform and my config file:

import StyleDictionary from "style-dictionary-utils";
import pkg from 'style-dictionary-utils';
const { transform } = pkg;

StyleDictionary.registerTransform({
  name: 'font/createUIFont',
  type: 'value',
  matcher: function(token) {
    return token.attributes.category === 'font';
  },
  transformer: function(token) {
    console.log("hello", token);
    const fontName = token.original.value;
    const fontSize = token.attributes.size.value;

    // Update the transformed value to return UIFont object instantiation
    return `UIFont(name: "${fontName}", size: ${fontSize}) ?? UIFont.systemFont(ofSize: ${fontSize})`;
  }
});

const config = {
  source: ["tokens/**/*tokens.json"],
  platforms: {
    "ios-swift-separate-enums": {
      "transformGroup": "ios-swift-separate",
      "buildPath": "build/ios/",
      "files": [{
          "destination": "FontTokens.swift",
          "format": "ios-swift/class.swift",
          "className": "FontTokens",
          "filter": {
            "attributes": {
              "category": "font"
            }
          },
          "transforms": [
            "font/createUIFont"
          ]
        }]
    }
  },
};

StyleDictionary
  .extend(config)
  .buildAllPlatforms();

the font token:

{
  "font": {
    "headingg": { "$size": 20, "$value": "HelveticaNeue-Bold", "$weight": "bold" }
  }
}

the output I get is:

public class FontTokens {
   public static let headingg = "HelveticaNeue-Bold"
}

What I’m trying to achieve is to create a UIFont property

public class FontTokens {
   public static let headingg = UIFont(name: "HelveticaNeue-Bold", size: 20)
}

Rotating image animation in Webflow

I am trying to achieve the same animation as the on in the second section: better for byuers/sellers/agents https://www.flyp.co/about-us in Webflow but I am not sure where to start. I would be thankful for any tips. An example solution in pure html, css, javascript is also fine

I have a slider and have achieved a smiliar effect so far I just can’t make the images rotate and appear in the same way

How do i get a discord.js bot to reply to an interaction based on what options are selected

I want my discord bot to reply to the interaction based on what options are selected for example say i have a command called favourite pet depending on what option the user choose say the options where dog and cat if the user choose dog the bot would reply with ‘my favourite pet is dog too’ or say the user choose cat the bot would reply with ‘my favourite animal is cat too’ I cant manage to figure out how to do that

if (interaction.commandName === 'favourite-pet') {
    if (interaction.options === 'dog') {
      interaction.reply(`My favourtie pet is also a dog `)
    }
if (interaction.options === 'cat') {
      interaction.reply(`my favourite animal is also a cat  `)
    }
  }

Search zip code or city name from web form to google map

I have an HTML simple web form to find a specific store in Google Maps by just entering the zip code or the city name. The search form must be targeted to the map like this:

https://www.google.com/maps/search/storename+cityname

Because people know they are going to get results of only Storename, they only write in the input text the zip code or city name so the store name is hidden but parsed after clicking to submit.

I am trying to achieve it like this:

<form action="https://www.google.com/maps/search/storename+city" method="get">
<input type="text" name="city"><input type="submit">
</form>

Any idea how to achieve this ?

Lets say the store name is: Apple
People will only enter the city name for example Miami (in the text field) and the form will in some way redirect the user to https://www.google.com/maps/search/apple+miami