How can i get not boxnote type in boxnote API?

I’m using Airtable for getting my box files. I can get the boxnote type but the not boxnote type, i can’t get it. Here’s my code:

`const query = async( type, item, query = {} ) => {
const key = type === ‘list’ ? ‘folder’ : type

console.log("test log :>> ", {connection: connectionId, [key]: item, query})
try {
    const res = await fetch( `${urlRoot}/${type}`, {
        method: 'POST',
        headers: {
            'Authorization': `Bearer ${apiKey}`,
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({connection: connectionId, [key]: item, query})
    })
    return await res.json()
} catch( err ) {
    console.log('Query Error', type, item, query, err)
}

}

let noteFiles = await query(‘search’, ‘boxnote’, {
ancestor_folder_ids: folderIds.join(“,”),
file_extensions: ‘boxnote’,
updated_at_range:lastModified,
all:true,
fields: “id,name,type,created_at,parent,path_collection,owned_by,created_by,content_modified_at,comment_count,extension,item_status,modified_at,modified_by,size”
})
console.log(‘Note Files’, noteFiles)

let clientFiles = await query(‘search’, ‘NOT boxnote’, {
ancestor_folder_ids: folderIds.join(“,”),
updated_at_range:lastModified,
all:true,
fields: “id,name,type,created_at,parent,path_collection,owned_by,created_by,content_modified_at,comment_count,extension,item_status,modified_at,modified_by,size”
});
console.log(‘Client Files’, clientFiles)`

This is the log of note and client files:

“Note Files”
{total_count: 9, entries: Array(9), limit: 200, offset: 0, type: “search_results_items”}

“Client Files”
{error: “Unexpected API Response [400 Bad Request | lvw3gihmiaed5fyu.075e4969f821267f53ac46597acf7dc3c] bad_request – Bad Request”}

I tried to search for getting not boxnote type but I can’t see any resources to make reference.

Regarding passing file path for JSON from one .jsx into another .jsx to populate a table

This is my first question so I would appreciate any patience with my request.

I am currently building my first React application. This application has three dependent dropdown’s, each dependent on the prior dropdown. Upon clicking on some choice in the third dropdown, I would like to load a .json into a table. I have built both of these functions independently but I am having difficulty connecting the two. I have two .jsx’s, one for the dependent dropdown and the second for the table itself.

I’ve tried adding a property to my “neighborhoods” called “src” which had a string pointing to the location my .json. I then imported this component into my table and attempted to pass it in as a prop but it unfortunately did not work.

My dependent dropdown code:

import React, { Component } from "react";

import { Container } from "../../components/container";
import { Section } from "../../components/section";
import Select from "../../components/select";

// styled components
//

class Main extends Component {
  state = {
    source: {
      country: [
        {
          id: 1,
          name: "Main Story",
        },
      ],
      state: [
        {
          id: 1,
          name: "São Paulo",
          country: 1,
        },
        {
          id: 2,
          name: "Rio de Janeiro",
          country: 1,
        },
        {
          id: 3,
          name: "Andaluzia",
          country: 2,
        },
        {
          id: 4,
          name: "Aragão",
          country: 2,
        },
        {
          id: 5,
          name: "Flórida",
          country: 3,
        },
        {
          id: 6,
          name: "Geórgia",
          country: 3,
        },
      ],
      city: [
        {
          id: 1,
          name: "São Paulo",
          state: 1,
        },
      ],
      neighborhoods: [
        {
          id: 1,
          name: "Vila Formosa",
          city: 1,
        },
      ],
    },

    country: [],
    state: [],
    city: [],
    neighborhoods: [],

    sourceMap: {
      country: 0,
      state: 1,
      city: 2,
      neighborhoods: 3,
    },
  };

  componentDidMount = () => {
    const { country } = this.state.source;
    this.setState({
      country,
    });
  };

  handleChange = (params) => (ev) => {
    const target = ev.currentTarget;
    const { value } = target;
    const { current, next } = params;
    this.setNewValues({ value, current, next });
  };

  setNewValues = ({ value, current, next }) => {
    const { source } = this.state;
    const data = source[next];

    if (data) {
      this.setState({
        [next]: data.filter((el) => el[current] === Number(value)),
      });
    }

    this.clearValues(next);
  };

  clearValues = (next) => {
    const { sourceMap } = this.state;
    const nextkey = sourceMap[next];

    Object.entries(sourceMap)
      .filter(([_, value]) => value > nextkey)
      .forEach(([key]) => {
        this.setState({
          [key]: [],
        });
      });
  };

  render() {
    const { country, state, city, neighborhoods } = this.state;
    return (
      <Container>
        <h1>Dependent dropdown</h1>
        <Section>
          <Select
            data={country}
            action={this.handleChange}
            current="country"
            next="state"
          />
          <Select
            data={state}
            action={this.handleChange}
            current="state"
            next="city"
          />
          <Select
            data={city}
            action={this.handleChange}
            current="city"
            next="neighborhoods"
          />
          <Select data={neighborhoods} />
        </Section>
      </Container>
    );
  }
}

export default Main;

My table code:

import React from 'react'

 function JsonDataDisplay(prop){
    const DisplayData=loadJson.map(
        (info)=>{
            return(
                <tr>
                    <td>{info.id}</td>
                    <td>{info.speaker}</td>
                    <td><img src={info.img} className="imgsize"></img></td>
                    <td>{info.text}</td>
                </tr>
            )
        }
    )
 
    return(
        <div>

            {/* <div>
                <Navbar />
            </div>
            <div className="center d-flex justify-content-around">
                <ButtonDarkStoryType />
                <ButtonDarkStoryCh />
            </div> */}
            
            <table className="table table-striped center m-top">
                <thead>
                    <tr>
                    <th>Line</th>
                    <th>Name</th>
                    <th></th>
                    <th>Text</th>
                    </tr>
                </thead>
                <tbody>
                    {DisplayData}
                </tbody>
            </table>
        </div>
    )
 }
 
 export default JsonDataDisplay;

Can’t figure out how to migrate to manifest v3

I have an extension called sync.js that backs up and restores localstorage data from websites. It does this by using chrome.tabs.executeScript() in it’s action popup window.

I’ve followed all of Google’s stupid guides to convert it, but nothing worked. It’s popup opens, but the buttons do nothing.

Here is my JavaScript:

function topAction() {
  window.open("https://sync-js.pages.dev/backup?fromURL=" + btoa(location.href) + "&data=" + btoa(JSON.stringify(localStorage)).replaceAll("+","%2B"),"","width=500,height=900")
}

function bottomAction() {
  var sjswin123 = window.open("https://sync-js.pages.dev/get?url=" + btoa(location.href),"","width=500,height=900"); 
  var sjstimer = setInterval(function() { 
    if(sjswin123.closed) { 
      clearInterval(sjstimer); 
      var sjsSYSjson = JSON.parse(prompt("Paste Data:"));
      Object.keys(sjsSYSjson).forEach(function (k) {
        localStorage.setItem(k,sjsSYSjson[k])
      }) 
    } 
  }, 1000)
}

document.getElementById('topB').addEventListener('click', async function() {
  // Your JavaScript code to execute on the current tab
  const [tab] = await browser.tabs.query({ active: true, currentWindow: true });
  await browser.scripting.executeScript({
    target: { tabId: tab.id },
    function: topAction,
  });
});
document.getElementById('bottomB').addEventListener('click', async function() {
  // Your JavaScript code to execute on the current tab
  const [tab] = await browser.tabs.query({ active: true, currentWindow: true });
  await browser.scripting.executeScript({
    target: { tabId: tab.id },
    function: bottomAction,
  });
});

Updating total value of cart dynamically in php using woocommerce products

I’m quite new to coding, and I’m in way over my head at this point.I’m trying to create a multipage chechout flow plugin for my wordpress site.

On page 1: Select number of bags full of recycleable cans and give credit for each bag selected. I then store the credit using an AJAX Handler, and displaying that value on page 2.

On page 2: Successfully showing credit from page 1, and listing woocommerce products.

My issue: I need to subtract the value of the woocommerce products from the credit value displayed on page 2 dynamically. I had it working once, but moved on to styling the product page, and now i cant get it working again. I’ve tried rewriting it, and doing it in different ways, but i just cant get it to update the credit. It’s just static.

This is my js for updating the credit:

jQuery(document).ready(function($) {
    var initialCredit = parseFloat(rtsc_ajax.initial_credit);
    updateCreditDisplay(initialCredit);

    // Add event listener for checkbox changes and quantity input changes
    $('input[type=checkbox][name="selected_products[]"], input[type=number][name^="product_quantity"]').on('change input', updateCredit);

    function updateCredit() {
        var totalSelected = 0;
        
        $('input[type=checkbox][name="selected_products[]"]').each(function() {
            var productId = $(this).val();
            var quantity = parseInt($('input[name="product_quantity[' + productId + ']"]').val());
            
            // Retrieve the product price from WC (I've defined it in my php)
            var productPrice = parseFloat($('input[name="product_price[' + productId + ']"]').val());
    
            console.log("Product ID: " + productId);
            console.log("Quantity: " + quantity);
            console.log("Product Price: " + productPrice);
    
            if (quantity > 0) {
                totalSelected += (productPrice * quantity);
            }
        });
        
        var remainingCredit = initialCredit - totalSelected;
        updateCreditDisplay(remainingCredit);
    }
    
    function updateCreditDisplay(credit) {
        $('#rtsc_credit_amount').text(credit.toFixed(2));
    }

This is how i show the credit on page 2:

    $credit_amount = isset($_SESSION['rtsc_credit_amount']) ? $_SESSION['rtsc_credit_amount'] : 0;
    $credit_amount = floatval($credit_amount); 

    echo '<div id="rtsc_credit_info">Your Credit: <span id="rtsc_credit_amount">' . esc_html($credit_amount) . '</span> kr</div>';

I think it stopped working after i changed how you select the product, insted of the standard checkbox i use the quantity input, and I’m showing it when clicking the product container:

jQuery(document).ready(function($) {
    $(document).on('click', '.product-image', function() {
        var container = $(this).closest('.rtsc-product-container');
        var quantityContainer = container.find('.quantity-container');
        var quantityInput = quantityContainer.find('.quantity-input');
        var priceElement = container.find('.product-price');

        // Toggle the visibility of quantity container
        if (quantityContainer.is(":visible")) {
            quantityContainer.hide();
            quantityInput.val(0);
            priceElement.css('padding-bottom', '46px');
        } else {
            quantityContainer.show();
            quantityInput.val(1);
            priceElement.css('padding-bottom', '0');
        }

        // Toggle the checkbox's state
        var checkbox = container.find('.product-checkbox');
        checkbox.prop('checked', !checkbox.prop('checked'));
    });
});


Note: The value is not used for anything else than displaying it

Auto pan and update map position when data inside Popup changes

I have some dynamic data inside <Popup> that will change the Popup box size after opening. When you first click on the <Marker> it will update the content, position and adjust the pan of your map to fit direct at the top of Popup box.

Auto Pan Popup Box

However if the data (in this case an img) inside the Popup box changes it, your view wont move and will be cut off:
Image has been cut off

This is what I want to happen when updating data inside the Popup box. It adjusts your view to the very top of the popup box:
Image perfectly in frame

I’ve tried a few things like setting autopan autoPan={true} or manually updating view on click:

const onClickHandler = () => {
    const currentCenter = map.getCenter();
    const mapZoom = map.getZoom();
    const newCenter = [currentCenter.lat + (5 / mapZoom), currentCenter.lng];
    map.flyTo(newCenter, mapZoom);
}

but it doesn’t really work as well as clicking open <Marker>. Are there any hooks that I’m missing that is able to update the Popup when the size changes?

import React, { useEffect, useState, useRef } from 'react'
import { MapContainer, TileLayer, Popup, LayersControl, Marker,  useMap, useMapEvents  } from 'react-leaflet';


const MyMap = () => {
    const [showImage, setShowImage] = useState(false);

    const handleButtonClick = () => setShowImage(!showImage);
    const position = [51.805, -0.11];
    const popupRef = useRef(null);

    return (
        <MapContainer center={position} zoom={3} minZoom={2} scrollWheelZoom={true} style={{ height: "100vh", width: "100%" }}>
            <TileLayer
            attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
            url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            />
            <Marker position={position}>
                <Popup minWidth={200}>
                    {showImage && 
                    <img style={{maxWidth: "500px"}} src="https://upload.wikimedia.org/wikipedia/commons/9/9b/Photo_of_a_kitten.jpg" alt="cat" />
                    }
                    <button onClick={handleButtonClick} style={{width: "100px", height: "150px"}}>
                        Click me!
                    </button>
                </Popup>
            </Marker>
        </MapContainer>
    )
}

export default MyMap;

browser.declarativeNetRequest property is undefined despite processing static DNR redirects [duplicate]

I am attempting to add dynamic DNR redirects to a MV3 web extension running in Firefox 123. When the script in charge of adding dynamic redirects runs, it throws the error TypeError: can't access property "updateDynamicRules", browser.declarativeNetRequest is undefined. However, if I add a static redirect via the declarative_net_request property in the extension’s manifest.json, it redirects the network requests exactly as expected.

The extension has the necessary permissions and host permissions needed to use the declaritiveNetRequest API, and attempts to add dynamic rules via the declarativeNetRequest.updateDynamicRules() method in a content script.

manifest.json

"permissions": [ "storage", "declarativeNetRequestWithHostAccess" ],
"host_permissions": ["*://*.example.com/"],

content script

await browser.declarativeNetRequest.updateDynamicRules({
  removeRuleIds: oldIds,
  addRules: newRules,
});

How to configure VSCode / “auto-add import to function” feature in a TypeScript package to always append `.js` to the import?

I don’t remember exactly which feature it causing VSCode to automatically add import statements when I type some function that hasn’t been imported, it is one of:

  • .vscode/settings.json file in the package.
  • .eslintrc.json
  • tsconfig.json

Maybe it’s an ESLint thing, here is my .eslintrc.json:

{
  "env": {
    "browser": true,
    "es2021": true
  },
  "parserOptions": {
    "ecmaVersion": "latest",
    "sourceType": "module",
    "project": ["./tsconfig.json"]
  },
  "overrides": [
    {
      "files": ["*.yaml", "*.yml"],
      "parser": "yaml-eslint-parser"
    }
  ],
  "parser": "@typescript-eslint/parser",
  "plugins": [
    "@typescript-eslint",
    "import",
    "simple-import-sort",
    "sort-exports",
    "typescript-sort-keys",
    "sort-keys",
    "prettier"
  ],
  "settings": {
    "import/resolver": {
      "alias": {
        "extensions": [".js", ".ts"],
        "map": [["~", "."]]
      }
    }
  },
  "extends": ["prettier", "next"],
  "rules": {
    "curly": 2,
    "@typescript-eslint/quotes": [
      "error",
      "single",
      {
        "avoidEscape": true,
        "allowTemplateLiterals": true
      }
    ],
    "@typescript-eslint/no-unnecessary-condition": 0,
    "@typescript-eslint/array-type": [
      2,
      {
        "default": "generic"
      }
    ],
    "@typescript-eslint/await-thenable": "error",
    "@typescript-eslint/consistent-type-definitions": 0,
    "@typescript-eslint/consistent-type-exports": "error",
    "@typescript-eslint/method-signature-style": "error",
    "@typescript-eslint/naming-convention": 0,
    "@typescript-eslint/no-explicit-any": "off",
    "@typescript-eslint/no-for-in-array": "error",
    "@typescript-eslint/no-namespace": 0,
    "@typescript-eslint/no-non-null-assertion": "off",
    "@typescript-eslint/no-require-imports": "error",
    "@typescript-eslint/no-this-alias": "error",
    "@typescript-eslint/no-unsafe-argument": "off",
    "@typescript-eslint/no-unsafe-assignment": "off",
    "@typescript-eslint/no-unsafe-member-access": "off",
    "@typescript-eslint/no-unsafe-return": "off",
    "@typescript-eslint/no-useless-empty-export": "error",
    "@typescript-eslint/prefer-function-type": "off",
    "no-array-constructor": "off",
    "@typescript-eslint/no-array-constructor": "error",
    "no-throw-literal": "off",
    "@typescript-eslint/no-throw-literal": "error",
    "lines-between-class-members": "off",
    "@typescript-eslint/lines-between-class-members": "error",
    "object-curly-spacing": "off",
    "@typescript-eslint/object-curly-spacing": [2, "always"],
    "padding-line-between-statements": "off",
    "@typescript-eslint/padding-line-between-statements": [
      "error",
      {
        "blankLine": "always",
        "prev": "*",
        "next": ["type"]
      }
    ],
    "space-before-blocks": "off",
    "@typescript-eslint/space-before-blocks": ["error", "always"],
    "@typescript-eslint/type-annotation-spacing": [
      "error",
      { "after": true }
    ],
    "import/first": "error",
    "import/newline-after-import": "error",
    "import/no-duplicates": "error",
    "sort-exports/sort-exports": "off",
    "typescript-sort-keys/interface": "off",
    "typescript-sort-keys/string-enum": "off",
    "sort-keys": "off",
    "sort-keys/sort-keys-fix": "off",
    "prettier/prettier": 2,
    "@typescript-eslint/no-unused-vars": "off",
    "default-case": "off",
    "default-case-last": "off"
  }
}

Anyhow, how can I specify to always append .js to the import? So instead of adding this:

import { ChildProcessError, exec } from '~/code/tool/process'

It adds this (assuming ~/code/tool/process.js is a file:

import { ChildProcessError, exec } from '~/code/tool/process.js'

Or if it’s an index.js file, it would add:

import { ChildProcessError, exec } from '~/code/tool/process/index.js'

I forget why I need to add .js to get things working in the first place, but without it, when I import this package into a Next.js app, it complains and errors with import { ChildProcessError, exec } from '~/code/tool/process' internal to that package.

Any way to configure this to always happen?

If it’s helpful, my tsconfig.json is:

{
  "compilerOptions": {
    "module": "ESNext",
    "target": "ES2020",
    "lib": ["es2020", "dom"],
    "outDir": "host",
    "rootDir": ".",
    "sourceMap": true,
    "declaration": true,
    "moduleResolution": "node",
    "strictNullChecks": true,
    "strict": true,
    "esModuleInterop": true,
    "noUncheckedIndexedAccess": true,
    "baseUrl": ".",
    "allowJs": false,
    "noErrorTruncation": false,
    "resolveJsonModule": true,
    "types": ["node"],
    "typeRoots": ["node_modules/@types"],
    "noImplicitAny": false,
    "paths": {
      "~/*": ["./*"]
    }
  },
  "include": ["*.ts", "./**/*.ts", "*.d.ts"],
  "exclude": ["node_modules", "host", "tmp", "test"]
}

Script has started showing broken image icon

I have a script which selects an image from a directory based on the date. It has worked for a few years, finding the correct image and showing it. However, now it shows the broken image icon. The logic still works and finds the correct src reference (if I cut and paste the URL from debug, a page shows with the image). Can anyone see what I am doing wrong such that the image no longer shows from the script.

<!DOCTYPE html>
<html>
<body>
<link rel="stylesheet"
          href="https://fonts.googleapis.com/css?family=Lato">
          
<style>
  .titleFormat
    {
      font-family:    Lato;
      font-size:      17px;
      font-weight:    bold;
      color:          rgba(34,110,147,1)
    }
  .bodyFormat
    {
      font-family:    Lato;
      font-size:      15px;
      font-weight:    normal;
      color:          black;
    }
    .imgFormat {
      max-width: 100%;
      max-height: 100%;
    }

</style>

    <h2 id="title" class="titleFormat">Wreck of the day:</h2>

    <p id="wreckText" class="bodyFormat"></p>

    <img id="wreckImage" class="imgFormat" src='https://drive.google.com/uc?export=view&id=1dUQ3PQvtqBm-RvVFPk-yTOGtkkLwhTkp'> 
  

<script>
//table of all wrecks including link details and thumbnail picture sources

var wreckList = [


["Aberdeenshire",21,10,1910,"1dUQ3PQvtqBm-RvVFPk-yTOGtkkLwhTkp","https://www.buchandivers.com/wrecks/aberdeenshire","This Aberdeen registered fishing trawler ran aground in heavy weather one mile south of Boddam, all 9 crew were rescued by breeches buoy.  She now lies, badly broken up, in about 14m of water."],
["Adventure",6,1,1922,"1kjZ7_i1DgTpn0Cane-PPCvh3Zclg-iWG","https://www.buchandivers.com/wrecks/adventure","This Peterhead registered trawler struck a leftover WW1 mine which exploded midships and sank the vessel.  All her crew got off safely into another trawler.  She now lies at a depth of 71m."],
["Anvers",13,11,1940,"1X01MLV3UOR3MeeG53Ef4dRSQjuS26J_Z","https://www.buchandivers.com/wrecks/anvers","A Belgian registered cargo ship carying scrap steel and bound for Methil, Fife.  She was bombed by German aircraft with the loss of 20 of her crew.  She now lies in 52m of water."],
["Astronomer",2,6,1940,"1244389oL_idnAUnK1euA2LuuAMnwhFyP","https://www.buchandivers.com/wrecks/astronomer","A Liverpool registered cargo ship, she was carying boom equipment for use at the naval base in Scapa Flow, Orkney.  She was sunk by torpedoes from the U 58 with the loss of 5 of her crew, she now lies in 67m."],
["Atland",25,3,1943,"1DVNrzH_-76wbK8lQzNsUkFjBbcvmkMDT","https://www.buchandivers.com/wrecks/atland","A Swedish registered cargo vessel of a unique "Turret" design.  She was carying iron ore, bound for Methil in Fife, when she collided with another ship in her convoy and sank with the loss of 19 of her crew.  She now lies in 64m."],
["Bel Lily",14,5,1917,"1mpfy0h8EWRyPA4hOoIufhkpYJK8i66Nk","https://www.buchandivers.com/wrecks/bel-lily","A Grimsby registered trawler which hit a mine laid by UC 49 while fishing off Peterhead.  All 10 of her crew were lost in the sinking.  She now lies in 50m."],
["Bretagne",17,4,1917,"1tASywryz3ftU_bwUvgIQtzhBT6iDzTif","https://www.buchandivers.com/wrecks/bretagne","Registered in Copenhagen, she was carying a cargo of coal from North Sheilds to Copenhagen when she was attacked by the U 45 and sunk by gunfire and torpedo.  All of the crew were rescued. She now lies in 61m."],
["Cairnavon",1,11,1925,"1xy0Q0gIVMk7H9VeedWe-onxFbLlRnu2N","https://www.buchandivers.com/wrecks/cairnavon","She ran aground in dense fog while en route from Leith to Montreal with a general cargo, including coal, coke, rags and manganese.  All passengers and crew were rescued.  She now lies in 18m."],
["Cairnmona",30,10,1939,"1GQ5-RZnCyZksK0A6ImTr9FOqOrBgqrRF","https://www.buchandivers.com/wrecks/cairnmona","Registered in Newcastle-upon-Tyne and a member of the Cairn line, she held a cargo of wool, gain, copper and zinc bound from Montreal to Leith when she was sunk by a torpedo from the U-13.  Three of the crew were lost.  She now lies in 51m."],
["Cape York",27,8,1940,"187e-rJxKrSfv7AhhB7u6d2QNjt9v4m2e","https://www.buchandivers.com/wrecks/cape-york","Registered in Glasgow, she was loaded with grain, wood and lead ingots and bount for Methil, Fife, she was bombed JU88 bombers from Aalsburg.  She no lies in 93m."],
["Charles Goodanew",17,4,1917,"1pHvVDvD4avHgp5koBXU1-IgJ7MaWGRVg","https://www.buchandivers.com/wrecks/charles-goodanew","Registered in Plymouth as an admiralty stores carrier, she was en route to the military base in Scapa Flow with a cargo of government stores when she was sunk by a mine laid by UC 45.  Only two of her crew of 15 survived.  She now lies in 52m."],
["Chicago",10,10,1894,"1E3uifEFlLHPQmDkCHUiyfBSCfGSmvJXC","https://www.buchandivers.com/wrecks/chicago","A Sunderland registered cargo vessel, she was heading for Baltimore with a cargo of cement, pickled herrings and wine hen she ran aground on the rocks below New Slains Castle.  All of her crew were saved.  She now lies in 13m."],
["City of Osaka",23,9,1930,"192JpeG36zfcrmDZi07J6L7ezXC-BRaDx","https://www.buchandivers.com/wrecks/city-of-osaka","A Liverpool registered cargo ship, she was carying a load of timber and bound for New York when she ran aground in thick fog.  All her rew were saved.  She now lies, broken up, in 12m.."],
["Constant Star",27,8,1987,"1VOYdSJwNFFQHTenLSrWm0HkB5hzAww-V","https://www.buchandivers.com/wrecks/constant-star","A Peterhead registered fishing vessel, she was heading home to avoid bad weather when she ran aground on Skerry Rock just outside Peterhead harbour.  All her crew were saved by the lifeboat.  She now lies, broken up, in 15m."],
["Crisabelle Stephen",16,1,1939,"1_tjk5BSoDYRis1H7UVhssmQrKYmBQWiX","https://www.buchandivers.com/wrecks/crisabelle-stephen","An Aberdeen registered trawler, she was rescued after running aground near Cruden Scaurs however she capsized while on tow back to Aberdeen with the loss of all 9 of her crew."],
["Dungonnell",24,2,1903,"1OQR8nYLPrkjjTlMxSfXgJrSkSmbaPR0y","https://www.buchandivers.com/wrecks/dungonnell","A Glasgow registered cargo vessel, she was carying a load of telegraph poles from Shields, bound for Belfast in February, 1903.  She and her crew were never seen again."],
["Einar",16,8,1893,"1mlLbauYSN2v0LMxoAvegv3wXN0vtvOO4","https://www.buchandivers.com/wrecks/einar","A Norwegian cargo vessel, she ran aground in fog while en route from Middlesbrough to Iceland with a cargo of salt.  She now lies in 8m."],
["Ethel Gwendoline",21,3,1890,"1ZKK759fiyP72VX6_nMn-vEVNGBqGuaEM","https://www.buchandivers.com/wrecks/ethel-gwendoline","Registered in Cardiff, she had loaded coal and general cargo at Sunderland and was making for Inverness when she foundered off Cairnbulg during a south-easterly gale.  Six of her nine crew were lost.  She now lies in 56m. "],
["Flotta",6,11,1941,"1ZMRBJMxtGKxtgF072WZn_woemI694S50","https://www.buchandivers.com/wrecks/flotta","A Royal Navy Isles Class minesweeper, she ran aground and was refloated a week later, however she soon foundered with the loss of 5 of her fourteen crew.  She now lies in 62m."],
["Fort Royal",9,2,1940,"16FjqsyVf6KNwNz-bRhVhPri1J7605YYj","https://www.buchandivers.com/wrecks/fort-royal","Originally built as a trawler, she was requisitioned by the Royal Navy in 1939 and converted into an Aberdeen based minesweeper to patrol the north east of Scotland.  She was lost in an enemy aircraft raid and now lies in 63m."],
["Fram",1,2,1940,"1hetFvjjloV-RvXIdfE1x5-vpyhvW4cgq","https://www.buchandivers.com/wrecks/fram","A Swedish registered cargo ship in ballast and sheltering from weather in Aberdour Bay, she was torpedoed by the U-13 and sank in two halves, with the loss of 10 of her 25 crew.  The bow lies in 37m, the stern in 46m."],
["Friedrich Bolte",16,2,1941,"1gY_SL_ejMXDvbFVs3qVOcMARuFakMBwc","https://www.buchandivers.com/wrecks/friedrich-bolte","A German registered trawler which foundered six miles east of the Cruden Scares, the fate of her crew is unknown.  She now lies in 66m."],
["Gelsina",25,6,1917,"1wJVCSrOjPxZYxHp3H-CnYi6AvRfxicie","https://www.buchandivers.com/wrecks/gelsina","A Grimsby registered trawler, requisitioned as a minesweeper but hit a mine laid by the UC 40. Five of her crew were lost.  She now lies in 62m."],
["Hit or Miss",3,12,1900,"1z_GMHCsGXmn21FRh1ynqj81Vn-iZG64t","https://www.buchandivers.com/wrecks/hit-or-miss","A small Aberdeen registered trawler making its way to home when her boiler failed, drifting her onto Skerry Rock where she was holed and later foundered.  She now lies in 44m and close to two other small wrecks."],
["Kathleen",26,1,1914,"1tAD9BgzqY667MfX55scOwjAcrM5FCHFa","https://www.buchandivers.com/wrecks/kathleen","Built in Belfast but registered in Aberdeen, she was lost with all hands in a gale whilst en route from Burghead to Middlesborough with a cargo of wood.  She now lies in 72m."],
["Kildale",3,11,1940,"1ntXKf7JLKHnDYoPkRFBUGI6Wzoyc3AWX","https://www.buchandivers.com/wrecks/kildale","Registered in Whitby, she had loaded with sugar in the Dominican Republic and sailed accross the Atlantic in convoy.  She was en route to Methil, Fife when she was sunk by bombfire from German aircraft.  Two of her 37 crew were lost.  She now lies in 63m."],
["Lord Nelson",22,11,1940,"1HrhxFbQla2lHXjAQLifK7CwWiRGWr09D","https://www.buchandivers.com/wrecks/lord-nelson","An Icelandic trawler, she was off Peterhead when she collided with another trawler, the Northman.  She soon foundered and sank.  All of her crew were taken aboard the Northman.  She now lies in 57m."],
["Maria W",22,2,1966,"120vueYAO8pIDAq0CVUW4_XIAB6CRStax","https://www.buchandivers.com/wrecks/maria-w","A Dutch registered cargo vessel.  She was en route from Ghent to Scrabster carrying fertiliser when she became lost in thick fog.  She was blown stern first into Sandy Haven having struck the Skares and lost her propeller,  she became a total loss and now lies broken up and dispersed in 6m."],
["Mercator",1,12,1940,"1AVmn3dXcwOAhLvyCN7bZmSQs4ifswXDy","https://www.buchandivers.com/wrecks/mercator","A Finnish registered cargo ship, she sailed from Buenos Aires to Leith with a cargo of coffee, maize, linseed, casein and groundnut meal.  From Leith she departed for Helsinki and was torpedoed off Peterhead by the U-21.  All but one of her crew were saved.  She now lies in 82m."],
["Muriel",17,12,1918,"14cF1CqsG-O4qOKGx2tWclLE_CAEk2Mtw","https://www.buchandivers.com/wrecks/muriel","Registered in Newport, UK she was en route from the Tyne to Scapa Flow with a cargo of coal. Whilst passing Peterhead at 11:20 am she was struck by a torpedo fired by UC 58.  All of her crew were rescued.  She now lies in 48m."],
["Ormonde",16,2,1941,"1GL50qETlxY5EOk1Gy2gq4_Lt5sCwSYz_","https://www.buchandivers.com/wrecks/ormonde","A Grimsby registered trawler, she was requisitioned by the Admiralty as an armed mine-sweeper.  She was patrolling off Cruden Bay when she was attacked and sunk by German aircraft.  All of her crew perished.  She now lies in 60m."],
["Prestonian",25,5,1915,"1hNVx9dnlS-86CaEWevOMAAvVka3avO0u","https://www.buchandivers.com/wrecks/prestonian","Registered in Preston, she was on a voyage from Archangel to Dundee with a cargo of flax and timber when she ran aground at Aberdour Bay.  She now lies in 15m."],
["Remuera",16,8,1940,"13HfvbDsw3iSwr1TUFpTET2QrZEYO0RlB","https://www.buchandivers.com/wrecks/remuera","One of our favourites, she was registered in Plymouth but built for the New Zealand Shipping Co. Ltd.  A large cargo liner, she was en route from Wellington and almost at her destination when she was attacked by aircraft and sunk by aerial torpedo.  All of the crew were rescued.  She now lies in 57m."],
["Robert Bowen",9,2,1940,"1IGH6Wpf5eXWkZ_L1QzAsbVPXIyElGL6t","https://www.buchandivers.com/wrecks/robert-bowen","An armed trawler working out of Aberdeen on minesweeping duties patrolling the North East coast.  She was operating just north of Aberdeen when she was discovered by enemy aircraft and sunk by a direct bomb hit, killing all onboard."],
["Simonburn",20,10,1940,"1XJaajaPodSdLI19q3nqUHzeWFBvI1hQP","https://www.buchandivers.com/wrecks/simonburn","A Newcastle registered cargo ship, she loaded with cargo in Montreal and was heading down the Buchan coast to Methil when she ran aground in a gale.  She was refloated but later foundered.  All of her crew were taken off by the Peterhead lifeboat.  She now lies on 54m."],
["Sofie Bakke",4,8,1940,"1ZSEP9PGfEEidW1IH2S4pMCLgKCO5Oc3v","https://www.buchandivers.com/wrecks/sofie-bakke","A Swedish registered ship, she was bound for London with a general cargo loaded in South America when she collided with another ship in her convoy and sank.  All of her crew were rescued.  She now lies in 68m."],
["St Clement",5,4,1941,"1jK7XkvDJi77S8qebJKk0gEzT4Czr7Ygy","https://www.buchandivers.com/wrecks/st-clement","An Aberdeen registered passenger and cargo carrier operating the Aberdeen to Caithness route, she was bombed and sunk by German aircraft with the loss of one of her crew.  She now lies in 55m."],
["St Fergus",31,12,1940,"1V32c-Zx0xzmOonbyAqPM9Y73PApZ3VVA","https://www.buchandivers.com/wrecks/st-fergus","An Aberdeen registered passenger and cargo carrier operating the Aberdeen to Stromness route, she collided with a much larger ship, the SS Lima, and sank with the loss of at least one of her crew.  She now lies in 77m."],
["St Glen",6,9,1940,"1ZhjI6NtJbMPT3A8llvOr20RxkYSUEgbR","https://www.buchandivers.com/wrecks/st-glen","A Newport registered cargo ship, she was en route from Freetown to Methil with a cargo of wheat and tinned corned beef when she was attacked and sunk by German aircraft.  Three of her crew were lost.  She now lies in 67m."],
["St Magnus",12,2,1918,"1po60xIz_c20-FkbGMZIVMHM8H4momBGV","https://www.buchandivers.com/wrecks/st-magnus","The Aberdeen registered passenger and cargo carrier had sailed from Lerwick for Aberdeen and was just passing Peterhead when she was torpedoed by UC 58. Four of her passengers and one of her crew were lost.  She now lies in 49m."],
["Subworker",26,3,1913,"1j7M7kf2obN1oSReK2y1g7YBkW9VGiBvj","https://www.buchandivers.com/wrecks/subworker","The London registered bucket dredger barge was under tow from the Clyde to Aberdeen when the tow parted and she foundered in heavy seas 16 miles off Rattray Head.  She now lies in 83m."],
["Taylor",30,9,1937,"1TS_Z5L1I7pkiU89C62TcE3OehCCNdw7P","https://www.buchandivers.com/wrecks/taylor","The Sunderland registered steam lighter was on a voyage from Buckie to Sunderland with a cargo of sleepers, when she capsized and foundered off Peterhead. Her captain survived and was picked up by the Grimsby steam trawler Ocean Princess, however the remaining five crew were lost.  She now lies in 58m."],
["Trevorian",29,11,1943,"12i5WdIoo-j2Z9U5TvLlIUvs4J5dads91","https://www.buchandivers.com/wrecks/trevorian","The St Ives registered cargo ship was on a voyage from Hull to the Mediterranean when she collided with and Icelandic trawler and sank.  The fate of her crew is unknown.  She now lies in 76m."],
["Trsat",7,9,1941,"1hS25UdOvh8jBGrwKL-kKZPpNOYKP38Zu","https://www.buchandivers.com/wrecks/trsat","Registered in Cardiff, she was a steam coaster on passage from Reykjavik to Hull with a cargo of 845 tons of fish when she was bombed by a single Luftwaffe aircraft off Kinnaird Head.   Three men were lost in the sinking.  She now lies in 68m."],
["Tynemouth Castle",9,12,1939,"1MvcCuyzoPJFTY7A_4PMp9wQ-718x5lqV","https://www.buchandivers.com/wrecks/tynemouth-castle","A Grimsby registered trawler, she struck the Cruden Scares and founderd 3 miles south east of Cruden Bay.  The fate of her crew is unknown, she now lies in 58m."],
["U-1206",14,4,1945,"1kXvJJV01z9NVM2KCiHpXpyvVzBscEh6J","https://www.buchandivers.com/wrecks/u-1206","A type VII-C U-boat, she was on patrol off the Buchan coast when she was abandoned and scuttled.  All of the crew escaped in the liferafts and either made it ashore or were picked up by local boats.  Three of the crew lost their life attepting to scale the cliffs south of Boddam."],
["U 77",7,7,1916,"1a9zzZKQjjuULnLa4waT8Ka7_qCvispv0","https://www.buchandivers.com/wrecks/u-77","A type UE 1 mine laying U-boat from WW1.  Lost, presumed in an accident, while on a mine laying mission off Kinnaird Head, Fraserburgh.  All of the crew were lost."],
["Windward Ho",9,5,1917,"1J3AwYcyTn1YoK57Espdt2ovjr5aeSbKx","https://www.buchandivers.com/wrecks/windward-ho","A Hull registered trawler en route from Hull to the fishing grounds she detonated a German contact mine which had been laid by UC 49.  All eight crew were lost when she sank three miles SSE of Buchan Ness.  She now lies in 50m."],
["Wrangler",6,10,1941,"13PfwElHM-e3BSvz-8U9H_wlT9bpJavz-","https://www.buchandivers.com/wrecks/wrangler","A Southampton registered hopper-barge she was engaged in close-inshore salvage work to the north of Peterhead when she ran aground on the Girdle Wears and foundered.  She now lies 48m."],
["Zitella",7,2,1940,"17-JD6a6okDe7OlZulVPHLp2VgfoxZtvf","https://www.buchandivers.com/wrecks/zitella","A London registered steam ship, she was outward bound from Narvik in Norway to Middlesborough with a cargo of iron ore in her hold and with 33 crew members on board when she ran aground in poor weather and fog at Longhaven, just south of Buchan Ness.  All of her crew were rescued and she now lies broken up in 10m."],
    ]

//use todays date to find which wreck to display
let wreckDetails = findWreck();
let wreckIndex = wreckDetails[0]; //pointer to the wreck in table to display
let ageText = wreckDetails[1]; //number of years since sank
let title = wreckDetails[2]; //formatted title page either wreck of day or anniversary
let srcPath = "https://drive.google.com/uc?export=view&id=" + wreckList[wreckIndex][4]  //

var paraText = "The " + "<a href="" + wreckList[wreckIndex][5] +"">" + wreckList[wreckIndex][0] + "</a>" + " sank " + ageText + wreckList[wreckIndex][6];

document.getElementById("title").innerHTML = title;
document.getElementById("wreckText").innerHTML = paraText;
document.getElementById("wreckImage").src = srcPath

function findWreck() {// returns index of wreck to display plus sinking anniversary text and title in 3 element array

    var today = new Date();
    var dayCount = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];  //cumulative days in year at start of month
    var mn = today.getMonth();
    var dn = today.getDate();
  var yn = today.getYear() + 1900; //getYear returns year since 1900 so add 1900
    var dayOfYear = dayCount[mn] + dn;
    
    //loop through table until wreck found with with day/month same as today
    
    var index = 999;
    
    var i;
    for (i = 0; i < wreckList.length; i++) {
        if (wreckList[i][1] == dn && wreckList[i][2] == mn + 1) {
            index = i;
        }
    }
    
    if (index < 999) { //wreck sank this day was found
        return [index, yn - wreckList[index][3] + " years ago today. ", "Wrecked on this day: " + wreckList[index][0]];
    } else { //no wreck anniversary so choose any wreck based on day number mod num. wrecks
        index = (dayOfYear) % wreckList.length;
      var dateSinceSinking = yn - wreckList[index][3];
        return [index, dateSinceSinking + " years ago. ", "Wreck of the day: " + wreckList[index][0]];
    }
    
}

</script>


</body>
</html>

Problem reading JSON values from file into array in javascript

I am writing a web application showing departures from a preselected station. An id of the selected station is saved as a coockie. A JSON file containing id’s and full names is read into an array with the id’s as keys and full names as values, like this Stations[Id] = FullName. This works just fine when writing to console but not to the html page when it is opened or reloaded, the checkCoockie()function. It says undefined instead of the station. After a new station has been chosen the stations full name is shown properly, the setCoockie()function.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script>

var Stations = [];

function onLoad() {
    checkCookie();
    return;
}

async function loadStations() {
    fetch("tinystations.json")
        .then(response => response.json())
        .then(stations => stations.forEach(item => 
            Stations[item.Id] = item.FullName));
        return;
}

async function checkCookie() {
    await loadStations();
    console.log(Stations);
    var station1 = getCookie("station1");
    document.getElementById("chosen1").innerHTML = station1 + " : " + Stations[station1];
    return;
}

function setCookie() {
    const d = new Date();
    d.setTime(d.getTime() + 100000000000); // Sufficiant amount of time. 3 years.
    let expires = "expires=" + d.toUTCString();
    let station1 = document.getElementById("TIstation1").value;
    document.cookie = "station1=" + station1 + ";" + expires;
    document.getElementById("chosen1").innerHTML = station1 + " : " + Stations[station1];
    return;
}

function getCookie(name) {
  const value = `; ${document.cookie}`;
  const parts = value.split(`; ${name}=`);
  if (parts.length === 2) return parts.pop().split(';').shift();
}
</script>
</head>
<body onload="onLoad()">
    <div id="coockie">
        <p>Select new stations</p>
        <input id="TIstation1" type="text" placeholder="Choose station" />
        <button onclick="setCookie()">Save</button>
    </div>
    <div id="chosen">
        Preselected:
        <p id="chosen1"> </p>
    </div>
</body>
</html>```

This is my JSON file:

[
{
“FullName”: “Arlanda C”,
“Id”: “Arnc”
},
{
“FullName”: “Huddinge”,
“Id”: “Hu”
},
{
“FullName”: “Jakobsberg”,
“Id”: “Jkb”
},
{
“FullName”: “Stuvsta”,
“Id”: “Stu”
},
{
“FullName”: “Rotebro”,
“Id”: “R”
},
{
“FullName”: “Stockholm City”,
“Id”: “Sci”
}
]“`

When opening or reloading page it look like this:
When opening or reloading page

And after a new station been chosen and new coockie set:
enter image description here

I thought the Stationsarray might not be ready when checkCoockie() was executed so I made checkCoockie() async and made it wait for loadStations() to finish. That didn’t help. I have tried many async/await solutions the last month but none have helped.
Any suggestions how I can get this to work on page load?

server database isn’t displaying on client main.js page

my client main.js file, the code below, is supposed to display the previous entries to the form on the web page, however when the form is submitted no entries are displayed on the html page, my port is 7777 and the root route works on postman, and so doesnthe post request on the server.js file, this adds an enrtry into the guestbook database. I have created a database through a seed.js file in the server folder, which can be displayed in my vs code, but won’t load in chrome. I will put in my html, my client main.js and my server.js file. Any help would be greatly appreciated. As a user you are supposed to be able to submit a name, date and comment into the guestbook and view the other entries into the guestbook. The front end is done with vite.

HTML


    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <link rel="icon" type="image/svg+xml" href="/vite.svg" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <script type="module" src="/main.js" defer></script>
        <title>Cold and rainy cottage guest book</title>
      </head>
      <body>
        <div class="nav-bar">
          <h4>Cold and rainy Cottege guest book!</h4>
          <form id="form">
            <label for="name">Name</label>
            <input id="name" type="text" name="name" />
            <label for="date">Date</label>
            <input type="text" name="date" id="date" />
            <label for="comment">Comment</label>
            <input type="text" id="comment" name="comment" />
            <button type="submit">submit</button>
          </form>
        </div>
        <div id="guest-container"></div>
        <div id="new-container"></div>
      </body>
    </html>
    

Client main.js

const form = document.getElementById(`form`);
const guestContainer = document.getElementById(`guest-container`);
const newContainer = document.getElementById("new-container");
//set  base url
const baseURL = `http://localhost:7777`;

//submit  form
form.addEventListener(`submit`, async (e) => {
  e.preventDefault();
  // create weird formdata type
  const formData = new FormData(form);
  const entryData = Object.fromEntries(formData);
  // fetch response
  const response = await fetch(`${baseURL}/guestbook`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(entryData),
  });
  // response  conditionals
  if (response.ok) {
    displayGuests();
  } else {
    console.error("Failed to add guest entry", response.status);
  }
});

//fetches all entries
async function fetchGuests() {
  const guests = await fetch(`${baseURL}/guestbook`);
  //parse into array
  let result = await guests.json();
  return result;
}
// display guests
async function displayGuests() {
  console.log("function workin");
  let guests = await fetchGuests();
  guestContainer.innerHTML = "";
  guests.forEach((guest) => {
    // create guestbook in html
    let h3Tag = document.createElement("h3");
    let pTag = document.createElement("p");
    let commentTag = document.createElement("p");
    let delButton = document.createElement("p");
    let infoDiv = document.createElement("div");
    let guestCard = document.createElement("div");
    h3Tag.textContent = guest.name;
    h3Tag.setAttribute(`class`, `guestName`);
    pTag.textContent = guest.date;
    commentTag.textContent = guest.comment;
    delButton.textContent = `X`;
    // delete button
    infoDiv.appendChild(h3Tag);
    infoDiv.appendChild(pTag);
    guestCard.appendChild(infoDiv);
    guestCard.appendChild(commentTag);
    guestCard.appendChild(delButton);
    guestContainer.appendChild(guestCard);
    newContainer.appendChild(guestContainer);
    //check if html  was created
    console.log("function ran :(");
    //delete button
    delButton.addEventListener(`click`, (e) => {
      e.preventDefault();
      // delete function
      handleDelete(guest.id);
    });
  });
}

//delete function
async function handleDelete(id) {
  const result = await fetch(`${baseURL}/guestbook/${id}`, {
    method: "DELETE",
  });
  console.log(result);
  if (result.ok) {
    displayGuests();
  }
}
// call display guests
displayGuests();

server.js

    import express from "express";
    import cors from "cors";
    import Database from "better-sqlite3";
    
    //  variables
    const app = express();
    const PORT = `7777`;
    const db = new Database("database.db");
    //middleware
    app.use(express.json());
    app.use(cors());
    //listen request
    app.listen(`${PORT}`, () => {
      console.log(`port started on PORT:${PORT}`);
    });
    
    //get request, root route
    app.get("/", (req, res) => {
      res.send(`root ROUTE ⊂(◉‿◉)つ`);
    });
    //get request at database
    app.get("/guestbook", (req, res) => {
      //try catch
      try {
        //find guest by id
        if (req.query.id) {
          let guestBook = db
            .prepare(`SELECT * FROM guestbook WHERE id = ?`)
            .all(`req.query.id`);
          res.status(200).json(guestBook);
          return;
        }
      } catch (err) {
        res.status(500).json(err);
      }
      if (req.query.one) {
        res.send("Query one");
      }
    });
    //post route to add visitors to guest-book
    app.post("/guestbook", (req, res) => {
      //try catch
      try {
        //set varibles
        const name = req.body.name;
        const date = req.body.date;
        const comment = req.body.comment;
        const newEntry = db
          .prepare(`INSERT INTO guestbook (name , date , comment) VALUES(?,?, ?)`)
          .run(name, date, comment);
        res.status(200).json(newEntry);
      } catch (err) {
        res.status(500).json({ error: err });
      }
    });
    
    // delete
    app.delete("/guestbook/:id", (req, res) => {
      try {
        const id = req.params.id;
        const deletedEntry = db
          .prepare(`DELETE FROM guestbook WHERE id = ? `)
          .run(id);
        //http response codes
        res.status(200).json({ recordDeleted: deletedEntry });
      } catch (err) {
        res.status(500).json({ error: err });
      }
    });

Seed.js

import Database from "better-sqlite3";
//hook up our database.db to get methods
const db = new Database("database.db")
//.exec executes some sql query 
//have to use backticks 
db.exec(`CREATE TABLE  IF NOT EXISTS movies (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    movie TEXT,
    year INTEGER ,
    imgURL TEXT)`)

    db.exec(`
    INSERT into movies (movie, year, imgURL)
    VALUES
    ('Black Narcissus' , 1947, 'https://posters.movieposterdb.com/07_11/1947/39192/l_39192_20b67beb.jpg'),
    ('Ran' , 1985 , 'https://posters.movieposterdb.com/23_04/1985/89881/l_ran-movie-poster_0c1ca44d.jpg'),
    ('Day of Wrath' , 1943, 'https://posters.movieposterdb.com/21_09/1943/36506/l_36506_d9d2b6c8.jpg' )
     `)

How to merge or split overlapping dates?

I am currently stuck on a problem and trying to find a viable solution for it. For context, I am working with EXTJS, and in our system, we have a tab panel and inside the each tab is a grid with data. We can drop things and we dynamically create tabs and populate grid. The things we dropped have duration, a list of dates and we modify the tabs to reflect those dates. Example is I dropped something that has date (1/9), a tab is created with title 1/9 and data is loaded into grid for that date. Whenever an item is dropped, the server will correctly returns a list of dates, and base on this I create the tab and modify title with the dates. The dates can either be single or a list of its own as well. Here are the 2 types of data return. Type 1: [1/8,1/9] and type 2 [ [1/8 ], [1/9] ] or a combination of both. [1/5, [1/6, 1/7], 1/8].

What I am doing is looping the list and if the current item is an array, I am concatenating the dates (1/6 – 1/7) a tab was created for each item in list (3 in above case). The dates can be disjointed or consecutive.

The issue is before dropping something, there could be existing tabs with their own dates, maybe same dates we get back from server. What I want is either merge or separate overlapping dates base on a condition. I want to ignore dates I get back from server that is not overlapping. for example, if there are is a tab with dates (1/5, 1/6) and I get back (1/7) from server, we simply ignore, no tabs are created.

Example:

Given a tab with dates:

[1/5, 1/6, 1/7, 1/8, 1/9]

After dropping item, I get get back [ [1/8], [1/9] ] from server

I want to modify the first tab and change it 1/5 – 1/8 and then create a second tab and give 1/9 as date.

Reason is because if I were to drop item and get back [ [1/8], [1/9] ] from server without any prior tabs, we will have 2 tabs since it is a list within a list.

Given a tab with dates:

[1/5, 1/6, 1/7, 1/8, 1/9]

After dropping item, I get get back [1/8, 1/9] from server

I want to have 1 tab with dates 1/5 – 1/9

Reason: because the dates are single and not list within a list and they both overlap tab dates, we don’t add or modify the tab

Dates don’t overlap example

Given a tab with date:

[1/9]

After dropping item, I get get back [1/8, 1/9] or [ [1/8], [1/9] ] from server (depends on item drop)

I want to have 1 tab with date 1/9 because the tab doesn’t have 1/8 so that date is ignored.

There could be multiple tabs with single/ multiple dates that overlap or don’t overlap dates return by server.

My approach:

  1. I was iterating existing tabs and getting dates of each tab.

  2. I am comparing against server dates to see if any overlap occur

  3. I ignore the tab if it doesn’t have any dates or the tab dates doesn’t overlap the server dates

I don’t have actual code because I was stuck on the logic part but here is a pseudocode of something I tried (javascript language)

Exp: 1 tab exists with dates [1/5, 1/6, 1/7, 1/8, 1/9] and I dropped item and server returns [ [1/8, 1/9] ]

const itemDates = content; (from server)

tabs.forEach(function(tab, index){

let tabDates = tab.getDates();

// skip if tab has no dates
if(tabDates.length > 0) {

// use tab index to retrieve date from itemDates
const currentItemDate = itemDates[index];

// it could be null since index can be out of bounds
if(currentItemDate){

 
//we will ignore if currentItemDate is a list because it either has to be already present in the tab 
//or it will be dates that are not overlapping
 
// if single date, we want to create new tab as neccessary
if(!Array.isArray(currentItemDate){

// there is at least one date overlap
if(tabDates.some(date => currentItemDate.includes(date)) {

}

// 

}
 
 }

 }


});

Upload inputted file to sftp server

i am trying to send a file i’ve uploaded from a javacsript input form to my sftp server. i’ve decoupled the react app and the nodejs server, so read the file as a URL and send it to the server that then calls the put function of the ssh2-sftp-client. The problem is that when it tries to put it doesn’t work and returns status code 500 as should. i’ve tried sending directly the inputFile to the server side but it won’t pass it as if i console log the passed file in the server it returns an empty array: {}. how can i solve this issue? thanks for the help.

this is the client side:

async function handleDockerInput(e) {
    const inputFile = e.target.files[0];

    try {
      const loginResponse = await authService.logIn(user);
      console.log('Login Response: ', loginResponse);

      if (inputFile) {
        const reader = new FileReader();

        reader.readAsDataURL(inputFile);

        reader.onload = async (event) => {
          const dataUrl = event.target.result;

          const body = JSON.stringify({
            connect: SFTPConfig,
            filepath: dataUrl,
            remoteFilePath: '/'
          });

          const response = await dockerService.putObject(body);

          console.log(response);
        };
      } else {
        alert('Please upload a file');
      }
    } catch (error) {
      console.error('Failed to login: ', error);
    }
  }

here is the dokerService.putObect function:

async putObject(body) {
    const response = await axios.post('/docker/upload', body);
    return response;
  }

here is the server side function that is called:

public async upload(req: Request, res: Response): Promise<void> {
    const dataUrl = req.body.filepath;

    const remoteFilePath: string = req.body.remoteFilePath; 
    const sftp = new Client();
    const { host, port, username, password } = req.body.connect;

    const sftpConfig: SftpConfig = {
      host: host,
      port: port,
      username: username,
      password: password,
    };

    try {
      await sftp.connect(sftpConfig);
      const pathExists = await sftp.stat(remoteFilePath);

      if(pathExists) {
        try {
          await sftp.put(dataUrl, remoteFilePath);
          console.log('File uploaded successfully');
          res.status(200).send('File uploaded successfully'); // Example error handling
        } catch (error) {
          res.status(500).send('Error uploading file to SFTP here'); // Example error handling
        }
      } else {
        console.log('Inserted path doesn't exist');
        res.status(500).send('Inserted path doesn't exist'); // Example error handling
      }
    } catch (error) {
      console.log(error, 'catch error');
      res.status(500).send('Error uploading file to SFTP'); // Example error handling
    } finally {
      sftp.end(); // Ensure the connection is closed after operation
    }
  }

How javascript substitute values in object? [closed]

I am new to javascript and trying to learn about objects.

let species = "name"
var animal = {
    name : "frog",
    colour : "green"
}

console.log(animal[species]);

For the above code,I was trying to create objects literals.But stumbled upon the code above.

I declared the variable species with value “name” .And the animal object has a variable name with the value frog but when I try to print animal[species] why does it give me the “frog” value instead of an error?

how to make new dir and place file in local javascript?

  1. What would be the methods for making new folder?
  2. And how to place file in folder?

Needed for files managing. Just local, not web.

Maybe this too much of a starter question, but any right direction is helpfull.
I want to learn.

Tried:
Found info but many related to web usage. Not what I needd. I am lost a this. I did search w3school.com for javascript but did not find the makedir method explanation.

Join Multiple Strings in an Array Filter [closed]

First, here’s my contacts array:

[
    {firstname: "John", lastname: "Wick"},
    {firstname: "John", lastname: "Cena"},
    {firstname: "Cody", lastname: "Rhodes"},
]

I want to create a search function where it will display the results typed by the user. The keyword given by the user can either be found on firstname, lastname or both.

Here’s my code:

const result = contacts.filter((x) => {
  const name = `${x.firstname} ${x.lastname}`;
  name.toLowerCase().includes(search.toLowerCase());
});

However this gives out an empty array.
If I just use something like:

x.firstname.toLowerCase().includes(search.toLowerCase());

… it will work. The multiple strings won’t. Any ideas?