How can we convert this atom to jotai?

I am trying to convert a recoil atom to jotai, looks like its not perfectly converting, maybe the effects here, I have tried following way, can we convert this another better way?

import { atom, useRecoilState } from 'recoil';
const initialState = [Scenes.Default];
const sceneStackAtom = atom<ReadonlyArray<Scenes>>({
    key: 'sceneStackAtom',
    default: initialState,
    effects: [
        ({ onSet }) => {
            onSet(newScene => {
                logger.debug('Current Scene Graph:', newScene);
            });
        },
    ],
});
const [openSceneStack, setOpenSceneStack] = useRecoilState(sceneStackAtom);

Here is approach to convert this,

import { atom, SetStateAction, useAtom} from 'jotai';
const initialState = [Scenes.Default];
export const sceneStackAtom = atom<ReadonlyArray<Scenes>>(initialState);

const sceneStackWithLoggerAtom = atom(
    (get) => get(sceneStackAtom),
    (_get, set, update: SetStateAction<ReadonlyArray<Scenes>>) => {
      set(sceneStackAtom, (currentState) => {
        const newState = typeof update === 'function'
          ? update(currentState)
          : update;
        logger.debug('Current Scene Graph:', newState);
        return newState;
      });
    }
  );
const [openSceneStack, setOpenSceneStack] = useAtom(sceneStackWithLoggerAtom);

Why is column 14 switching to column 15 in this GAS iteration

Please take a look at the following code- its a simple function that increments the value in column 14 each time it is run until it sees “Yes” in column 15. However notice the last line in the code i am setting the value of column 15? Why has it changed? Thanks for your help.

function checkDisMail() {
  var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1QdKrB555555555555Ed2j-k0P6DQKrAawDZ0kxOk/edit?gid=0#gid=0")
  var sheet = ss.getSheetByName("Orders");
  var data = sheet.getRange(3, 1, sheet.getLastRow()-2, 25).getValues();

  for (i = 0; i < data.length; i++) {
    var emailSent = data[i][14]
    Logger.log(data[i][14] + " - " +data[i][15])
    
    if(data[i][15] != "Yes"){
      emailSent++
        Logger.log("Sending initial email")
        //send email here
        sheet.getRange(i+3, 15).setValue(emailSent)
    }
  }
}

How to return `html` response from Astro component as code inside head or body tag

In an Astro component MyScript.astro with a fetch call i am requesting the html from the response. It’s returning e.g. <script async src="https://my-api"></script>.

    // MyScript.astro
    ---
    const { prop1, prop2 } = Astro.props;
    
    const response = await fetch(import.meta.env.API_URL, {
      method: 'POST',
      headers: new Headers({
        'Content-Type': 'application/json',
      }),
      body: JSON.stringify({
        prop1,
        prop2
    
      }),
    });

const { html } = await response.json();
---

How do I return / output html in the body of the page as code?

How to declare a variable with the type of global object (of other JavaScript Context)?

How to declare a variable to have the type of global object (of other JavaScript context)?
That is, it contains all JavaScript built-in objects, but it is not typeof globalThis (which is automatically resolved for user global variables by vscode).

globalThis.abc = 123;

// How to declare this type?
// {typeof globalThis} will have property 'abc', which is unwanted.
/** @type {???} */ var otherContextGlobal = <...>;

ViteJS how do use custom env file? Instead of default .env file

For some reason I can’t use a file named .env, instead i have to use a file named dev.env. I can’t even use .env.dev, only dev.env file.

This is what i tried but its not working 🙁

function parseEnvFile(filePath) {
  const envContents = readFileSync(filePath, 'utf-8');
  const envVars = {};
  envContents.split('n').forEach((line) => {
    const [key, value] = line.split('=');
    if (key && value) {
      envVars[key.trim()] = value.trim();
    }
  });
  return envVars;
}
// Load custom environment file
const customEnv = parseEnvFile(path.resolve(__dirname, 'dev.env'));

export default defineConfig({
  plugins: [
    react(),
    legacy()
  ],
  define: {
    'import.meta.env': JSON.stringify(customEnv),
  },
  test: {
    globals: true,
    environment: 'jsdom',
    setupFiles: './src/setupTests.ts',
  }
})

RSA Decryption in Flutter using existing public/private key

I am converting a Capacitor/Javascript app to Flutter and need to decode strings via RSA, the existing app uses the following with similar looking keys:

import RSAUtils from 'js-rsa-dave';
this.key = RSAUtils.getKeyPair("10001", "20170qadbd85e2d7182720c3a0ee19c1", "30cb31542ace0f7d37a629ef5eba28cb");
decodeddata = RSAUtils.decryptedString(this.key, encryptedtext);

I can’t anything equvalent in Flutter, I’ve tried multiple plugins and using encrypt and pointycastle RSA utilities does not seem to like the format of the keys.

What I have so far is

  final parser = RSAKeyParser();
  var rsakeypublic = parser.parse("20170qadbd85e2d7182720c3a0ee19c1") as RSAPublicKey;
  var rsakeyprivate = parser.parse("30cb31542ace0f7d37a629ef5eba28cb") as RSAPrivateKey;
  final decrypter = Encrypter(RSA(privateKey:rsakeyprivate, encoding:RSAEncoding.OAEP));

  // Decrypt the base64-encoded data
  final encryptedtext = Encrypted.fromBase64(encryptedtext);
  final decryptedData = decrypter.decrypt(encryptedtext);

This fails on the parser, and I can’t find anything directly equivalent to the original code. Any ideas for a workaround on this?

Save Cookie value to hidden input field without name or id?

I am pulling a cookie value into a hidden form field. If there is a name I know how to do it but when there is not I cannot seem to figure it out. I cannot change the form by adding anything to the input field but need to save a cookie value to that field.

Example:

<p class="form-field organic_source pd-hidden hidden">
<input type="hidden" value="">
</p>

<script>
function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(';');
  for(var i = 0; i <ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}
  
 document.querySelector("input[name='fieldname']").value = getCookie("organic_source");
</script>

If the form had a name this works great but without one it does nothing. Maybe somehow basing it off of the child of organic_source paragraph but I an still relatively green at js and not sure how that would work.

Positioning an object relative to different screens [closed]

In general, the bottom line is this: on one screen, we collect images into an array, recognize the coordinates (touch move) relative to the screen (in percentages), and then in type=2 we find out the pixel values relative to these percentages. However, percentages are displayed in console.log, everything is fine, but for some reason everything is created in the upper-left corner, as if percentages are being used instead of pixels.

I’ve already spammed several CHATGPT’s, they can’t help me in any way =(

function addImage(touch, type, selectedImage) {
   
    let width = 125; 
    let scale = "scale(0.5)";
    let offset = width / 2;
    let clientX = touch.clientX;
    let clientY = touch.clientY;

    let touchBlock = document.getElementById('touchBlock');
    let blockRect = touchBlock.getBoundingClientRect(); // Получаем размеры и позицию touchBlock
    let blockWidth = blockRect.width;
    let blockHeight = blockRect.height;
    let targetScreenWidth = window.innerWidth;
    let targetScreenHeight = window.innerHeight;
    let calculatedX = clientX - blockRect.left; // Пересчет координат относительно touchBlock
    let calculatedY = clientY - blockRect.top;  // Пересчет координат относительно touchBlock

    let xPercent = blockWidth > 0 ? (calculatedX / blockWidth) * 100 : 0;
    let yPercent = blockHeight > 0 ? (calculatedY / blockHeight) * 100 : 0;
   
    let xPercentz;
    let yPercentz;
    if (type == 2) {
        scale = "scale(0.7)";
        offset = width / 2;
        // Пересчет координат в проценты
        xPercentz = xPercent;
        yPercentz = yPercent;
        // Пересчет процентов в пиксели относительно целевого устройства
        calculatedX = (xPercentz / 100) * targetScreenWidth;
        calculatedY = (yPercentz / 100) * targetScreenHeight;
        console.log("targetScreenWidth: " + targetScreenWidth + " | x: " + xPercentz + " | y: " + yPercentz);
    }
    else {
        // Для type == 1 просто сохраняем координаты в процентах
        xPercentz = xPercent;
        yPercentz = yPercent;
    }

    // Позиционируем изображение с учетом смещения
    img.css({
        'width': width + 'px', 
        'position': 'absolute',
        'left': calculatedX - offset + 'px', 
        'top': calculatedY - offset + 'px', 
        'transition': 'all 1.5s',
        'transform': scale
    });
}   
<div class="container container-main" style="margin-left: 0; padding-top: 10px; width: 100%; margin-right: 0;">
  <div class="container-fluid d-flex flex-column" style="height: 75vh; width: 100%; background: #808080;">
    <div class="row" style="height: 100%; width: 100%; touch-action: none; overflow: hidden;" id="touchBlock">
        <div id="imageContainer" style="position: relative;"></div>
    </div>
  </div>

  <div class="row" style="height: 5vh">
    <div class="scrollable-photos">
    </div>
  </div>
  <br><br>
</div>

Bruno is not able to identify fs module from nodejs

  1. I have installed Bruno and imported the collection.

  2. I have set the $PATH to where node.js is installed.

    export PATH=”/opt/homebrew/bin:/usr/local/bin:/opt/homebrew/bin/node:$PATH”

  3. When I run a request in bruno, I get this error

Error invoking remote method ‘send-http-request’: Error: Error: Cannot find module fs

I have tried everything. Could someone help me ?

Using function shift in a map function

I expect the snippet below to print the element without the first letter, but this doesn’t seem to work. Someone knows why?

let str = 'Pig latin is cool';
str = str.split(' ');
str.map(el => {
  const fl = el.split('').shift();
  el += fl + 'ay';
  console.log(el.join(''));
});

How can I give the already available color in my Echart Geomap

series: [
                {
                    name: map_name,
                    type: "map",
                    map: map_name,
                    emphasis: {
                        label: {
                            show: true,
                        },
                        itemStyle: {
                            areaColor: null
                        },
                    },
                    roam: true,
                    aspectScale: 0.9,
                    scaleLimit: { min: 1, max: 1.3 },
                    data: this.geo_map_data,
                    select: { 
                        itemStyle : {
                            areaColor: null
                        }
                    }
                },
            ],

Here in this code the select : { itemStyle : { areaColor : null }} I tries entering null, inherit, transparent but none of them seems to give the actual color.
I already have colors based on some configurations how can I get the actual color there

I tried entering null, inherit, transparent.
Is there any other keyword that I can use to get the actual color.
When I don’t put anything in there it will be default as yellow

Javascript request stuck pending – page crashes – need help debugging

On my shopify site I have a wholesale app installed that runs a javascript request every time a product loads on a collection page in order to display the correct price. This is because the wholesale app allows you to set custom prices for certain products, so when the product loads it has to check if that product has a custom price or not. This was working perfectly fine until I updated the theme I’m using to the latest version. Now when a collection page loads I will intermittently (although more often than not), end up with one of these javascript requests getting stuck in a “pending” state, leading to the page crashing. It doesn’t happen on the initial page load, rather when it loads more products after scrolling down the page.
I cannot figure out what it is about the theme update that is causing it to crash. The stuck pending request in the network tab on dev tools isn’t providing me with any information (at least I don’t think so). I’m a bit of a loss on how to debug this issue. It will almost certainly end up with a pending request if I throttle the traffic on the dev tools to “slow 4G”. Any pointers would be appreciated!

You can replicate the issue by visiting: https://1o8j69mfu4lnvx1c-73098035497.shopifypreview.com/collections/wholesale

In the network tab throttle the traffic to “Slow 4G”, and filter the results to “search” to see the requests that get sent and eventually get stuck pending after loading more products.

enter image description here

I’m trying to create a password generator

I’m trying to make a password generator with checkboxes in the UI to include Numbers, Symbols, Upper Case letters and Lower Case letters, but it doesn’t work.

The label to display the Generated Password is merely showing the “Your Password is ” then blank space.

See code for the basic HTML:

const numbersTing = document.getElementById("numbersTing");
const LCase = document.getElementById("LCase");
const UCase = document.getElementById("UCase");
const symbols = document.getElementById("symbols");
const passwordText = document.getElementById("passwordText");
const passW = document.getElementById("passW");

const passwordLength = 12;
const includeLowerCase = true;
const includeUpperCase = true;
const includeSymbols = true;
const includeNumbers = true;

passW.onclick = function generatePassword(length, includeLowerCase, includeUpperCase, includeNumbers, includeSymbols) {

  const lowerCaseChars = 'abcdefghijklmnopqrstuvwxyz';
  const upperCaseChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  const numbersChars = '0123456789';
  const symbolsChars = '!@#$%^&*()_+';

  let allowedChars = '';
  let password = '';

  if (LCase.checked) {
    allowedChars += lowerCaseChars;
  } else {
    allowedChars += "";
  }

  if (UCase.checked) {
    allowedChars += upperCaseChars;
  } else {
    allowedChars += "";
  }

  if (numbersTing.checked) {
    allowedChars += numbersChars;
  } else {
    allowedChars += "";
  }

  if (symbols.checked) {
    allowedChars += symbolsChars;
  } else {
    allowedChars += "";
  }


  for (let i = 0; i < length; i++) {
    const remixUpdate = Math.floor(Math.random() * allowedChars.length);
    password += allowedChars[remixUpdate];
  }

  passwordText.textContent = `Your password is ${password}`;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>My Website</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <input type ="checkbox" id="numbersTing"/>
  <label for="numbersTing">Tick to include number</label>
  <input type ="checkbox" id="LCase"/>
  <label for="LCase">Tick to include Lower Case letters</label>
  <input type ="checkbox" id="UCase"/>
  <label for="UCase">Tick to include Upper Case Letters</label>
  <input type ="checkbox" id="symbols"/>
  <label for="symbols">Tick to include Symbols</label>
  <br><br>
  <button type="submit" id="passW" class="passW">Generate Password</button>
  <br>
  <label id="passwordText"></label>
  <script src="index.js"></script>
</body>

</html>

I know I’m missing something, but can’t figure out what. Please help.

How to ensure the nodes are connected in this tree diagram

I have the following data structure:

const data = {
    label: "root",
    children: [
      {
        label: "child_1_A",
      },
      {
        label: "child_1_B",
      },
      {
        label: "child_1_C",
      },
      {
        label: "child_1_D",
      },
      {
        label: "child_1_E",
      },
      {
        label: "child_1_F",
        children: [
          {
            label: "child_2_A",
            children: [
              { label: "child_3_A" },
              { label: "child_3_B" },
              { label: "child_3_C" },
              {
                label: "child_3_D",
                children: [
                  {
                    label: "child_4_A",
                    children: [
                      {
                        label: "child_5_A",
                        children: [
                          {
                            label: "child_6_A",
                          },
                        ],
                      },
                      {
                        label: "child_5_B",
                        children: [
                          {
                            label: "child_6_B",
                          },
                        ],
                      },
                      {
                        label: "child_5_C",
                      },
                      {
                        label: "child_5_D",
                        children: [
                          {
                            label: "child_6_C",
                            children: [
                              {
                                label: "child_7_A",
                                children: [
                                  {
                                    label: "child_8_A",
                                  },
                                  {
                                    label: "child_8_B",
                                    children: [
                                      {
                                        label: "child_9_A",
                                        children: [
                                          {
                                            label: "child_10_A",
                                            children: [
                                              {
                                                label: "child_11_A",
                                              },
                                              {
                                                label: "child_11_B",
                                                children: [
                                                  {
                                                    label: "child_12_A",
                                                  },
                                                ],
                                              },
                                            ],
                                          },
                                        ],
                                      },
                                    ],
                                  },
                                ],
                              },
                            ],
                          },
                          {
                            label: "child_6_D",
                          },
                        ],
                      },
                      {
                        label: "child_5_E",
                        children: [
                          {
                            label: "child_6_E",
                            children: [
                              {
                                label: "child_7_B",
                              },
                              {
                                label: "child_7_C",
                                children: [
                                  {
                                    label: "child_8_C",
                                  },
                                ],
                              },
                            ],
                          },
                        ],
                      },
                    ],
                  },
                ],
              },
            ],
          },
        ],
      },
    ],
  };

I need to render a nested tree diagram with lines which connect all levels:

enter image description here

This works fine for most levels but when I get to a node which has inner nested children the outer line that connects the nodes doesn’t join up:

enter image description here

so in the grab you can see that child_4_A has a number of children and the line that should connect all of those children doesn’t extend far enough down to child_5_E. I’ve tried lots of different things. The code I have to calculate how tall to draw that line is:

  const calculateTotalHeight = (nodes, depth = 0) => {
    if (!nodes || nodes.length === 0) return 0;

    const nodeHeight = 38;
    let totalHeight = 0;

    // Process all siblings
    for (let i = 0; i < nodes.length - 1; i++) {
      // Add height for this sibling
      totalHeight += nodeHeight;

      // Process children for all nodes, not just non-last siblings
      if (nodes[i].children && nodes[i].children.length > 0) {
        totalHeight += calculateTotalHeight(nodes[i].children, depth + 1);
      }
    }

    return totalHeight;
  };

The entire code is here:

const TreeNode = ({ label, children, index, siblingCount }) => {
  // Add helper function to calculate total height
  const calculateTotalHeight = (nodes, depth = 0) => {
    if (!nodes || nodes.length === 0) return 0;

    const nodeHeight = 38;
    let totalHeight = 0;

    // Process all siblings
    for (let i = 0; i < nodes.length - 1; i++) {
      // Add height for this sibling
      totalHeight += nodeHeight;

      // Process children for all nodes, not just non-last siblings
      if (nodes[i].children && nodes[i].children.length > 0) {
        totalHeight += calculateTotalHeight(nodes[i].children, depth + 1);
      }
    }

    return totalHeight;
  };

  // Helper to generate curved connecting path
  const getConnectorPath = () => {
    return `
      M 0 16
      L 10 16
    `;
  };

  const getCurvedConnectorPath = () => {
    return `
      M 0 -2 L 0 14.08 C 0 18.4541 4.38531 22 8.7594 22V22
    `;
  };

  const isSibling = index !== undefined && siblingCount > 1;
  const isLastSibling = index === siblingCount - 1;

  return (
    <div className="tree-node">
      {/* Main node */}
      <div className="node-content">
        <span className="label">{label}</span>
      </div>

      {isSibling && !isLastSibling && (
        <>
          <svg
            className="connector-path"
            style={{
              position: "absolute",

              left: 0,
              top: 0,
              width: "24px",
              height: "100%",
              transform: "translateX(-9px)",
              overflow: "visible",
            }}
          >
            <path
              d={getConnectorPath()}
              fill="none"
              stroke="#ccc"
              strokeWidth="1"
            />
          </svg>
        </>
      )}

      {isSibling && isLastSibling && (
        <svg
          className="connector-curved"
          style={{
            position: "absolute",
            left: 0,
            top: 0,
            width: "24px",
            height: "100%",
            transform: "translateX(-9px) translateY(-4px)",
            overflow: "visible",
          }}
        >
          <path
            d={getCurvedConnectorPath()}
            fill="none"
            stroke="#ccc"
            strokeWidth="1"
          />
        </svg>
      )}

      {/* Single child connector */}
      {children?.length === 1 && (
        <svg
          className="connector-in"
          style={{
            position: "absolute",
            left: 0,
            top: 0,
            width: "24px",
            height: "100%",
            transform: "translateX(7px) translateY(33px)",
            overflow: "visible",
          }}
        >
          <path
            d={getCurvedConnectorPath()}
            fill="none"
            stroke="#ccc"
            strokeWidth="1"
          />
        </svg>
      )}

      {children?.length > 1 && (
        <svg
          className="vertical-line"
          style={{
            position: "absolute",
            left: 0,
            top: "33px",
            width: "24px",
            transform: "translateX(7px) translateY(-1px)",
            overflow: "visible",
            zIndex: 1,
          }}
        >
          <path
            d={`M0 0 V ${calculateTotalHeight(children)}`}
            stroke="#ccc"
            strokeWidth="1"
            fill="none"
          />
        </svg>
      )}

      {children?.length > 0 && (
        <>
          <div className="children-container">
            <div className="children">
              {children.map((child, idx) => (
                <TreeNode
                  key={idx}
                  {...child}
                  parent={label}
                  index={idx}
                  siblingCount={children.length}
                />
              ))}
            </div>
          </div>
        </>
      )}

      <style>{`
        .tree-node {
          position: relative;
        }

        .node-content {
          display: flex;
          z-index: 2;
          position: relative;
          align-items: center;
          gap: 6px;
          border: 1px solid #ccc;
          border-radius: 6px;
          padding: 6px 12px;
          width: 95%;
        }

        .label {
          font-size: 12px;
        }

        .children-container {
          position: relative;
          margin-left: 16px;
          padding-top: 6px;
        }

        .children {
          display: flex;
          flex-direction: column;
          gap: 6px;
        }
      `}</style>
    </div>
  );
};

const Diagram = () => {
  const data = {
    label: "root",
    children: [
      {
        label: "child_1_A",
      },
      {
        label: "child_1_B",
      },
      {
        label: "child_1_C",
      },
      {
        label: "child_1_D",
      },
      {
        label: "child_1_E",
      },
      {
        label: "child_1_F",
        children: [
          {
            label: "child_2_A",
            children: [
              { label: "child_3_A" },
              { label: "child_3_B" },
              { label: "child_3_C" },
              {
                label: "child_3_D",
                children: [
                  {
                    label: "child_4_A",
                    children: [
                      {
                        label: "child_5_A",
                        children: [
                          {
                            label: "child_6_A",
                          },
                        ],
                      },
                      {
                        label: "child_5_B",
                        children: [
                          {
                            label: "child_6_B",
                          },
                        ],
                      },
                      {
                        label: "child_5_C",
                      },
                      {
                        label: "child_5_D",
                        children: [
                          {
                            label: "child_6_C",
                            children: [
                              {
                                label: "child_7_A",
                                children: [
                                  {
                                    label: "child_8_A",
                                  },
                                  {
                                    label: "child_8_B",
                                    children: [
                                      {
                                        label: "child_9_A",
                                        children: [
                                          {
                                            label: "child_10_A",
                                            children: [
                                              {
                                                label: "child_11_A",
                                              },
                                              {
                                                label: "child_11_B",
                                                children: [
                                                  {
                                                    label: "child_12_A",
                                                  },
                                                ],
                                              },
                                            ],
                                          },
                                        ],
                                      },
                                    ],
                                  },
                                ],
                              },
                            ],
                          },
                          {
                            label: "child_6_D",
                          },
                        ],
                      },
                      {
                        label: "child_5_E",
                        children: [
                          {
                            label: "child_6_E",
                            children: [
                              {
                                label: "child_7_B",
                              },
                              {
                                label: "child_7_C",
                                children: [
                                  {
                                    label: "child_8_C",
                                  },
                                ],
                              },
                            ],
                          },
                        ],
                      },
                    ],
                  },
                ],
              },
            ],
          },
        ],
      },
    ],
  };

  return (
    <div style={{ padding: "24px", minHeight: "100vh" }}>
      <TreeNode {...data} />
    </div>
  );
};

export default Diagram;

If I remove the -1 from the for loop then every node with a child ends up with a line being drawn to the bottom of the diagram. The code somehow needs to take all nested children in to account but stop drawing the vertical line at the last child.

How to wrap a variable so that it doesn’t break the code? [closed]

I have a data.txt file that has both plain text and special characters. These special characters may be different each time, what they will be is not known in advance.

I make:

const data2 = fs.readFileSync(`data.txt`, 'utf8');

How do I wrap the data2 variable so that I don’t break the code when I use it?

ADD:

  const completion = api.chat.completions.create({
    model: "mistralai/Mistral-7B-Instruct-v0.2",
    messages: [
      {
        role: "system",
        content: systemPrompt,
      },
      {
        role: "user",
        content: data2,
      },
    ],
    temperature: 0.7,
    max_tokens: 256,
  });