SQL Database Design Trains and Containers

I am trying to figure out the best database schema for the following. I will be using Postgres along with Nodejs unless there is something better suited to this task.

I apologize if the answer is obvious. I am new to all of this.

I have a list of train-id’s and a list of intermodal containers. I need to be able to query by intermodal container to check which train-id it is on, and also to query by train-id to get a list of all intermodal containers on this train. I would also like to be able to query historical information.

The issue I have is the train-id’s repeat once per month so I can’t use them as a primary key, or query just based on train-id as it would return containers on the train-id from previous months as well.

The best that I have come up with so far is to create a composite key consisting of the date of departure and the train-id and query based on this to get the list of containers. The day of departure is already included in the train-id, however the month of departure is not. I’m not sure how to make this user friendly though as preferably the user would not have to specify the month of departure.

For querying by container-id I believe I could just limit the result to 1 to only get the most recent train it is on, or is there a better way of doing this?

There will be other details stored in this database as well such as ETA’s, car numbers, etc. However the above is what I’m having difficulty with currently.

Permutation using Recursion in Javascript

Through youtube, I’ve learned to obtain a multi-dimensional output of permutations using recursion, i.e anagrams with passing in an array of letters as an argument (i.e [‘a’, ‘b’, ‘c’]) but is there a way to modify the code to pass in a string instead ‘abc’ to obtain the output below??

Into
[ 'abc', 'bac', bca', 'acb', 'cab', 'cba' ]

This is my code. Is there a way to modify to obtain the desired result, using a string as the argument(i.e ‘abc’)?
Thank you, much appreciated

function anagrams(inputString){
  if(inputString.length ===0) return [[]];
  const stringArr = inputString;
  const firstEl = stringArr[0];
  const restArr = stringArr.slice(1);
  const anagramWithoutFirst = anagrams(restArr);
  const masterArr = [];

  anagramWithoutFirst.forEach(anagram => {
    for (let i=0; i<=anagram.length; i++){
      const anagramWithFirst = [...anagram.slice(0, i), firstEl, ...anagram.slice(i)]
      masterArr.push(anagramWithFirst)
    }
  })
  return masterArr
}

console.log(anagrams(['a', 'b', 'c']))

UseContext doesn’t re-execute component

I am experienced javascript developer. However I have to move on react so right now I know few concepts. I’ve been debugging this code for 4 hours and couldn’t find any mistake. I mean, it is probably up to because this hook is a bit confusing.

What app should do? Basically it should display food component based on dummy coded data. It works good. On that newly displayed component should be a form which has input field. When we submit form, that number from the form should be taken and written in a food object. Object should look like this: {Sushi: 0}. Whenever I submit, it should update. Besides that, there isn’t just one property in object. There could be more, for example: {Sushi: 0, Pizza: 0, Cherry: 0}. That depends on dummy data. At the begging of the app it automatically creates this object and push into state. Then, I send state updating function to the child component and when we submit form it updated the state. That works fine. Now on the current component, I have useEffect. That use effect trigers whenever state changes. What it does, it updates context. Now when I update context, in “third” component all the values should be taken and sum of the values should bee displayed. The problem is that, whatever I tried, It doesn’t re-executes that “third” component…

Code:
App.js

function App() {
return (
<FoodStateContext.Provider
  value={{
    foodState: {},
    setContext: function (val) {
      this.foodState = val;
    },
  }}
>
  <Header />
  <BodyContainer>
    <Card className={styles["food-message"]}>
      <h2>Delicious Food, Delivered To You</h2>
      <p>
        Choose your favourite meal from our broad selection of avaible meets
        and enjoy a delicious lunch or dinner at home.
      </p>
      <p>
        All our meals are cooked with high-quality ingredients, just-in-time
        and of course by experienced chefs!
      </p>
    </Card>
    <FoodContainer foodList={food} />
  </BodyContainer>
</FoodStateContext.Provider>
);
}

export default App;


Food container

import react, { useState, useEffect, useReducer, useContext } from "react";

import styles from "./FoodContainer.module.css";
import Card from "../UI/Card/Card";
import FoodComponent from "./FoodComponent";
import FoodStateContext from "../store/food-state-context";

const FoodContainer = (props) => {
const foodList = props.foodList;

const [foodState, setFoodState] = useState({});
const ctx = useContext(FoodStateContext);

useEffect(() => {
let obj = {};
for (let i = 0; i < foodList.length; i++) {
  obj[foodList[i].name] = 0;
}
setFoodState(obj);
}, []);

console.log(foodState);

useEffect(() => {
console.log("muda");
ctx.foodState = foodState;
ctx.setContext(foodState);
console.log(ctx.foodState);
}, [foodState]);

return (
<Card className={styles["food-container"]}>
  {foodList.map((food) => {
    return (
      <FoodComponent
        key={food.name}
        food={food}
        updateFoodState={setFoodState}
      ></FoodComponent>
    );
  })}
</Card>

);
};

export default FoodContainer;


Food component

import React, { useReducer, useEffect, useContext } from "react";
import styles from "./FoodComponent.module.css";
import Input from "../UI/Input/Input";
import Button from "../UI/Button/Button";

const FoodComponent = (props) => {
const food = props.food;

const formSubmitHandler = (e) => {
e.preventDefault();
props.updateFoodState((prevState) => {
  return {
    ...prevState,
    [food.name]: prevState[food.name] + +e.target[0].value,
  };
});
};

return (
<div className={styles["food-component"]}>
  <div className={styles["food-component__description"]}>
    <p>{food.name}</p>
    <p>{food.description}</p>
    <p>{food.price}</p>
  </div>

  <form onSubmit={formSubmitHandler}>
    <div>
      <div>
        <span>Amount:</span>
        <Input />
      </div>
      <Button type="submit">+Add</Button>
    </div>
  </form>
</div>
);
};

export default FoodComponent;

Food context

import react from "react";

const FoodStateContext = react.createContext({
foodState: "",
setContext: (val) => {
console.log(val);
this.foodState = val;
},
});

export default FoodStateContext;

That third component

import React, { useState, useContext, useEffect } from "react";
import styles from "./Cart.module.css";
import FoodStateContext from "../store/food-state-context";

const Cart = (props) => {
const [totalProductsNumber, setTotalProductsNumber] = useState(0);

const ctx = useContext(FoodStateContext);
console.log(ctx.foodState);
useEffect(() => console.log("govna"), [ctx]);

return (
<div className={styles.cart}>
  <div>Ic</div>
  <p>Your Cart</p>
  <div>
    <span>{totalProductsNumber}</span>
  </div>
</div>
);
};

export default Cart;

Three JS and Parcel – Having problems loading HDR file

At the moment I am working on my first Three.js project, everything was working fine until the moment I tried to load an HDR File. I suppose it is something related to importing static files using parcel. But a am really not sure. And if it is the case I have no idea how to fix it.

Here is the error I am having:

@parcel/core: No transformers found for _src/assets/sunset_in_the_chalk_quarry_4k.hdr_.

Reflective-3D/node_modules/@parcel/config-default/index.json:3:3

2 |  "bundler": "@parcel/bundler-default",
3 |   "transformers": { 
4 |     "types:*.{ts,tsx}": ["@parcel/transformer-typescript-types"],
5 |     "bundle-text:*": ["...", "@parcel/transformer-inline-string"],
6 |     "data-url:*": ["...", "@parcel/transformer-inline-string"],  
7 |     "worklet:*.{js,mjs,jsm,jsx,es6,cjs,ts,tsx}": [
8 |       "@parcel/transformer-worklet",  
9 |       "..." 
10 |     ],
11 |     "*.{js,mjs,jsm,jsx,es6,cjs,ts,tsx}": [ 
12 |       "@parcel/transformer-babel",
13 |       "@parcel/transformer-js",

And my JS code


    import * as THREE from "three";
    import {OrbitControls} from "../node_modules/three/examples/jsm/controls/OrbitControls.js";
    import {FlakesTexture} from "../node_modules/three/examples/jsm/textures/FlakesTexture.js";
    import {RGBELoader} from "../node_modules/three/examples/jsm/loaders/RGBELoader.js";
    
// HERE I IMPORT MY FILE
import HdrImage from "./assets/sunset_in_the_chalk_quarry_4k.hdr";

    let scene, camera, renderer, controls, pointlight;

    function init() {
      scene = new THREE.Scene();

      renderer = new THREE.WebGLRenderer({alpha: true, antialias: true});
      renderer.setSize(window.innerWidth, window.innerHeight);
      document.body.appendChild(renderer.domElement);

      renderer.outputEncoding = THREE.sRGBEncoding;
      renderer.toneMapping = THREE.ACESFilmicToneMapping;
      renderer.toneMappingExposure = 1.25;

      camera = new THREE.PerspectiveCamera(
        50,
        window.innerWidth / window.innerHeight,
        1,
        1000
      );
      camera.position.set(0, 0, 500);
      controls = new OrbitControls(camera, renderer.domElement);

      controls.autoRotate = true;
      controls.autoRotateSpeed = 0.5;
      controls.enableDamping = true;

      pointlight = new THREE.PointLight(0xffffff, 1);
      pointlight.position.set(200, 200, 200);
      scene.add(pointlight);

      let envmaploader = new THREE.PMREMGenerator(renderer);

      new RGBELoader().load(HdrImage, function (hdrmap) {
        let envmap = envmaploader.fromCubemap(hdrmap);
        let texture = new THREE.CanvasTexture(new FlakesTexture());
        texture.wrapS = THREE.RepeatWrapping;
        texture.wrapT = THREE.RepeatWrapping;
        texture.repeat.x = 10;
        texture.repeat.y = 6;

        const ballMaterial = {
          clearcoat: 1.0,
          cleacoatRoughness: 0.1,
          metalness: 0.9,
          roughness: 0.5,
          color: 0x8418ca,
          normalMap: texture,
          normalScale: new THREE.Vector2(0.15, 0.15),
          envMap: envmap.texture,
        };

        let ballGeo = new THREE.SphereGeometry(100, 64, 64);
        let ballMat = new THREE.MeshPhysicalMaterial(ballMaterial);
        let ballMesh = new THREE.Mesh(ballGeo, ballMat);
        scene.add(ballMesh);

        animate();
      });
    }
    function animate() {
      controls.update();
      renderer.render(scene, camera);
      requestAnimationFrame(animate);
    }
    init();

And my folder structure

[folder structure][1]
[1]: https://i.stack.imgur.com/H3JnT.png

Has someone faced this trouble before?

Thanks a lot for your ideas on it (:

Unique ID and array usage

The user is supposed to paste a hex code into an input which then gets used with a unique ID. I do not want that id to change and I am adding it to some HTML code that I am making with JS. What doesn’t work is to use the hex code from the array on color-block and hex classes

let color = {
let colorp1 = [];
let colorhexmaker = $("#color-hex-maker");
let preset1colordiv = $("#preset1-color-div")
        let color = {
            id: Date.now(),
            hex: colorhexmaker.val()
        }
        colorp1.push(color)
        colorp1.forEach((item, i) => {
            item.id = i + 1;
        });

        preset1colordiv.prepend(" <div class="color-div">n" +
            "            <label>n" +
            "                <input maxlength="10" placeholder="Name" class="color-side-input">n" +
            "            </label>n" +
            "            <br>n" +
            "            <div class="color-block"></div>n" +
            "            <p class="hex">hex</p>n" +
            "        </div>")
        $(".hex").attr("id", colorp1.filter(({id}) => id))
        localStorage.setItem("ColorPreset1", JSON.stringify(colorp1))

I am having problems getting the unique ID to be used, as well as not overwriting the other IDs when assigning the unique ID.

$(".hex").attr("id", colorp1.filter(({id}) => id))

Can I force a shinyTree to be loaded when the app is started?

Summary: When I put a shinyTree (from the R package of the same name) in a dropdownButton (from the shinyWidgets package), it seems that the tree in question is not accessible from the input variable until the user has interacted with the tree in some way. Is there a way I can force the tree to load when the app is loaded at the start?

Here is a minimal (almost) example:

library(shiny)
library(shinyWidgets)
library(shinyTree)
library(magrittr)

render.as.text <- function(t) {
  if (is.null(t)) {
    'argument is NULL'
  } else {
    q <- get_selected(t)
    if (length(q) == 0) {
      'none selected'
    } else {
      paste(q, sep=', ', collapse=', ') 
    }
  }
}

ui <- fluidPage(
  dropdownButton(shinyTree('tree', checkbox=TRUE), circle=FALSE, inputId='dd')
)

server <- function(input, output, session) {
  output$tree <- renderTree({ list(OptionA = structure(list(OptionAA='', OptionAB=''), stopened=TRUE), OptionB='') })
  updateActionButton(session, 'dd', label='initial label')
  
  observe({
    updateActionButton(session, 'dd', label=render.as.text(input$tree))
  }) %>% bindEvent(input$dd_state)  
}

shinyApp(ui = ui, server = server)

When I run this app, the button begins with the text ‘initial label’ (as expected), then when I click on it the first time the text changes to ‘argument is NULL’ (showing that the variable input$tree has a NULL value), but the tree displays correctly in the dropdown. If I then click the button again to close the dropdown, the text ‘argument is NULL’ remains – it remains until I actually select one or more of the tree’s checkboxes after which (and after clicking the button again) it will display either a comma-separated list of selected options or ‘none selected’ as expected.

I would very much like to be able to refer to input$tree beginning with the first time the user takes any action in the app – ideally I am looking for some command to insert in either the server or ui code (or both) which will mean that the first time the user clicks the button its text will change directly to ‘none selected’ because input$tree is no longer NULL. Is this possible?

issue running scripts on npm ( npm scripts error )

I recently encountered strange problems when using NPM in the system to execute projects, one of which is when executing gulp during the LAUNCH of projects. What could be the reason for this error and how can it be solved?

Apparently this error is related to PowerShell execution policies , how can this problem be solved?

enter image description here

Vue cli serve, how to get a httprequest with success (404 file not found)

I have a vue app. I have a ‘vue cli serve’ command that compiles the app and serves the application
(Using a webpack node server as far as I know)

I want to get a file using XMLHttpRequest

Ok, I want to retrieve a file using:

var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
       debugger
        this.responseText;
      }
    };
    xhttp.open("GET", file, true);
    xhttp.send();

ok i have played with a lot of combinations for:

http://192.168.0.2:8080//
http://localhost:8080//

and different folders and existing files without success.
I have allways the error: ( or similar)

 GET http://192.168.0.2:8080/public/web_icon.txt 404 (Not Found)

Any idea of to fix this ?
Thanks in advance

Form mail sending issue

Please someone should help me I tried posting it as a code but I couldn’t vet through it I was getting an error message someone should tell me why I’m not receiving form responses in my mailrrap after clicking the button html form

I tried what was there and was expecting a form where I receive form fills to maitltrpa but to no avail

Use Tailwind in Content Script of Browser Extension

I’m trying to write a browser extension which injects some buttons and custom components into a website, therefore I wanted to use Tailwind (and DaisyUI) to style them.

I found this discussion and configured my project according to the solution and I got Tailwind and DaisyUI working for the popup of my extension. My App.css looks like

@tailwind base;
@tailwind components;
@tailwind utilities;

This gets imported in my Popup.tsx with import "../App.css";. No problems there.

But when I try to do the same import in my content-script, I don’t get any errors, but the script somehow fails/doesn’t get executed at all anymore. If I put in a console.log without importing App.css, it gets printed. If I import App.css, it’s not shown anymore.

Could this be an error with my webpack/postcss-config or is there something else preventing me from using custom CSS in the content script? I’m confused because it’s working in the popup without any problems.

GET http://localhost:5000/auth/me 404 (Not Found)

I am following a MERN tutorial and made a React site where it receive data like name and email of the logged in user and then theses data are shown.

Here my back code:

routes/user.js:

const express = require('express')

const userController = require('../controllers/user')
const route = express.Router()
const checkAuth = require('../middleware/auth')


route.post('/', userController.register)
route.post('/login', userController.login)
route.get('/isauth', checkAuth, userController.isAuthenticated)
route.post('/logout', checkAuth, userController.logout)
route.post('/me', checkAuth, userController.getMe)


module.exports = route

controllers/user.js:

module.exports = {
getMe: (req, res) => {
        const {sub} = req.user

        User.findOne({_id : sub}, (err, user) => {
            if (err) {
                res.status(500).json({
                    message : 'User not found',
                    data : null
                })
            } else {
                res.status(200).json({
                    message : 'User found',
                    data : user
                })
            }
        })
    },
}

Here my front code:

authenticationAPI.js:

export const AuthenticationService = {
 getMe: () => {
    return axiosInstance
      .get(requests.getme, { credentials: "include" })
      .then((res) => {
        return res;
      })
      .catch((err) => {
        return err;
      });
  },
}

config/requests.js:

export const requests = {
    register : '/auth',
    login : '/auth/login',
    logout : '/auth/logout',
    getme : '/auth/me',
}

authenticationSlice.js:

import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { AuthenticationService } from "./authenticationAPI";

const initialState = {
  registerstatus: "",
  errormessage: "",
  userDetails: null,
};

//getme redux action
export const getMe = createAsyncThunk(
  "users/me",
  async () => {
    const response = AuthenticationService.getMe();
    return response;
  }
);

//creation du slice
const authenticationSlice = createSlice({
  name: "authentication",
  initialState,

extraReducers: {

//getMe http request 3 cases
    [getMe.pending]: (state, action) => {

    },
    [getMe.fulfilled]: (state, action) => {
        console.log(action.payload);
        state.userDetails = action.payload.data.data
    },
    [getMe.rejected]: (state, action) => {

    },

export const { } = authenticationSlice.actions;
export const selectUserDetails = (state) => state.authentication.userDetails
export default authenticationSlice.reducer;

views/posts/post.jsx:

import React, { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { getMe, selectUserDetails } from '../../features/authentication/authenticationSlice'
export default () => {

    const dispatch = useDispatch()

    useEffect(() => {
      dispatch(getMe())
    }, [])

    const userDetails = useSelector(selectUserDetails)
    

    return (
        <h5>{userDetails && userDetails.name}</h5>
        <hr />
        <h6>{userDetails && userDetails.email}</h6>
    )
}

The email and the name still do not render.

I tried runnig this code on browser, but i got theses two errors in devtools Console when i’m logged in (i can see the access_token in Application):

Error: Request failed with status code 404
GET http://localhost:5000/auth/me 404 (Not Found)

I really appreciate your help. Thank you all.

Sending message from Main to Renderer

Could someone help me out here. I’m completely confused on how to solve this. I’ve now spent about a week trying to find a solution for this but have come up short and there appears to be a lack of a solid solution online. I’ve made a github repository trying to demonstrate the issue.

In short I’ve implemented a status bar in my application which i want to populate with various string messages. These messages would be sent from functions that are contained inside a js file that imports electron, which mean’s it doesn’t have direct access to the Renderer. So how would I send these messages to the Renderer. I’m assuming this needs to be done using the ContextBridge, but i have no clue how to successfully do this, so if your response is just linking me to the context bridge docs, don’t bother, lol I’ve exhausted myself looking at that. The other alternative i was considering is using a custom event but but i’m not sure that would solve the problem either.

Here is a sample of what im trying to do along with repo on github. If you do a pull-request to fix the repo, ill gladly merge and keep the repo public for others to benefit from and share with the community. https://github.com/JokerMartini/statusbar

As a minor problem, im not sure why i can no longer call getPath from ‘app’ from within a js file that’s not loaded into the render thread.

I trigger a method from Renderer

index.vue

const doWork = () => {
    window.messenger.doWork();
}

electron-preload.js

import { contextBridge } from "electron";

const messenger = require("../src/helpers/messenger");
contextBridge.exposeInMainWorld("messenger", messenger);

messenger.js

const { app } = require("electron");
const path = require("path");

// using electron module to demonstrate this file can't be imported into renderer
export function showMessage(msg) {
  const dir = path.join(app.getPath("documents"), "presets");
  console.log(dir);
  // TODO: send message to renderer...
}

export function doWork() {
  console.log("Doing working...");

  // step 1: long process
  showMessage("Processing step 1...");

  // step 2: long process
  showMessage("Processing step 2...");

  // step 3: long process
  showMessage("Processing step 3...");
}

I’d like to display the messages sent from the main to renderer to be displayed in the status bar of

main.vue

<q-footer>
     <q-bar>
        <span class="text-caption">Show message here...</span>
    </q-bar>
</q-footer>

DOM of new page inaccessible after window.location.href value changes

I’ve a rating submission form. In form.onSubmit(), I capture the rating data, redirect to a “thank you page” with window.location.replace(url).

I’m trying to append the rating data in the new page. However, once the page is replaced, I can access the formData variable, but, DOM of the new page seems inaccessible.

Code:

function handleSubmit(e) {
  e.preventDefault();

  const formData = new FormData(form);

  window.location.replace('thankyou.html');

  console.log(formData.get('rating'));
  
  // dom not accessible after replace
  console.log(document.body);
}

Any leads?