Multiselect jquery function won’t work with database data (laravel 5.5)

I’m having a problem with a Jquery plugin called multiselect, or I don’t know if it isn’t fully compatible with laravel, but the system I’m currently doing needs to have a multiselect function on the selects, I’m calling the records from the database with a foreach loop, this jquery function calls through the Id of the HTML tag, inside the id of the select I placed the call for the database records like this:

<select multiple="multiple" class="form-control" id="{{$user->id_user}}" name="user_id">

The id then is going to be called by the jquery function:

$(function () {

  $("#{{$user->user_id}}").multiselect();

});

There’s a button that displays a form with the function of editing the records, inside a table that’s looped to show all the data, inside said form there’s a select with that I desire to have the multiselect function to not only pick one option but rather several options. My problem is that this jquery function is only functioning in one of the forms to edit (the one that corresponds to the last record of the database), and the others it fails, or simply doesn’t work as intended. If you need the complete code here it is:

 <?php foreach ($combos as $user): ?>
            <tr>
              <td scope="row">{{$user->user_id}}</td>
              <td>{{$user->name}}</td>                 
              <td>{{$user->desc}}</td>
              <td><button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapseExample{{$user->user_id}}" aria-expanded="false" aria-controls="collapseExample">edit</button>
              <div class="collapse" id="collapseExample{{$user->user_id}}">
  <div class="card card-body">
                <form action="{{ url('update') }}" method="post">
                  {{method_field('PUT')}}
                  {{csrf_field()}}
              <div class="form-group">
                 <label for="">Name</label>
                 <input required type="text" name="name" class="form-control" aria-describedby="helpId" readonly value="{{$user->name}}">
                 <small id="helpId" class="text-muted">Pepito Peres</small>
               </div>
               <div class="form-group">
                 <label for="">desc</label>
                 <input required type="text" name="desc" class="form-control" aria-describedby="helpId" readonly value="{{$user->desc}}">
                 <small id="helpId" class="text-muted"></small>
              </div>
              <div class="form-group">
                <label for="">code</label>
                <select multiple="multiple" class="form-control" id="{{$user->user_id}}" name="user_id" >
                <option value="">select options</option>
                 <?php foreach ($products as $user) { ?>
                <option value="{{$user->name}}">{{$user->name}}</option>
                 <?php } ?>
                 </select>

Hopefully someone can help me with my issue, sorry if I mispelled some words, english is not my first language. I can also share an image, where it shows the issue more clearly:

The problem in question

how to show variable in script tag into php code [duplicate]

how can i show variable result in script tag into php code ? when i run this code return undefined . can anyone help me to fix this code ? how can i show variable result in script tag into php code ? when i run this code return undefined . can anyone help me to fix this code ?

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>test</title>
</head>
<body>

  <span id="h">00:</span>
  <span id="m">00:</span>
  <span id="s">00</span>
  <button id="submit" onclick="time();">submit</button>



  <script>

    function time(){
      var h = document.getElementById('h').textContent;
      var m = document.getElementById('m').textContent;
      var s = document.getElementById('s').textContent;
      var result = h + m +s;
      alert(result);
      
    }
  
    var b = result;

  </script>


<?php
$variable = "<script>document.write(b)</script>";
echo 'time is : ' . $variable;
?>

</body>
</html>

Receiving returns from asynchronous functions

I’ve searched through multiple questions, but I have failed to find one that matches my case.

The following is the simplified version of my code:

function one() {
    let a;
    // does some fetching; takes about 1s
    a = 1;  // value is obtained from above line
    return a;
}

function two() {
    let b;
    // does some fetching; takes about 2s
    b = 2; // value is obtained from above line
    return b;
}

function three() {
    let c;
    // does some fetching; takes about 0.5s
    c = 3; // value is obtained from above line
    return c;
}

var variables = [];

function final(){
    variables.push(one());
    variables.push(two());
    variables.push(three());
}

console.log(variables);

What above code gives is [], while the desired output is [1, 2, 3](the order doesn’t matter).

I’ve recognized that the solution is deeply related to async/await and promises(return new Promise(...)), but the implementation always fail, either because the await keyword does nothing, or promise comes out <pending>.

Also, through several experiments I’ve found that the return keyword also runs asynchronously, which means that one(), two() and three() almost certainly returns undefined.

Is there a way to get the return values in a synchronous manner?

Add value to input inside iframe?

i have an iframe –

<iframe id="framed" src...>

Inside this iframe there is a pop-up window with a contact form that has an input

<input type="hidden" name="owner" value="" class="hidden" id="owner">

How can I insert value there with or without jquery?
I tried this but it didn’t work…

$(function() {  
var $iframe = $('#iframed');
$iframe.ready(function() {
    $iframe.contents().find("#owner").val('Test');
});

});

Await only valid in async function, waiting for a document to write

I’m trying to write to a file then send that file. I need to wait for the file to write before sending then wait for it to send before looping again. I have the file creation function and file sending function returning promises and the start function is async. However I’m getting await only vaild in async function.

const fs = require('fs');
const csv = require('csv-parser')
const { exec } = require("child_process")
var i = 74243;

async function start() {
  fs.createReadStream('agency_summary_test.csv')
    .pipe(csv())
    .on('data', function (row) {
      var cmd = "curl -XPOST -u 'User:Pass' ";
      var url = "'https://vpc-test-ovlb6af5uhpnaoqb57oqg5xore.us-gov-east-1.es.amazonaws.com/_bulk' --data-binary @agency_temp.json";
      var obj = {}
      Object.entries(row).forEach(([key, value]) => {
        if (!isNaN(value)) {
          value = parseInt(value)
        }
        obj[key] = value
      })

      await writeFile(obj, i);

      var cmdString = cmd + url + " -H 'Content-Type: application/json'";

      await sendFile(cmdString);

      i++;
    })
}

function writeFile(obj, i) {
  return new Promise((resolve) => {
    fs.writeFileSync('agency_temp.json', JSON.stringify({
      index: {
        _index: "agency_summary",
        _id: i
      }
    }) + "n" + JSON.stringify(obj) + "n", (err) => {
      if (err)
        console.log(err);
      else { }
    })
    resolve();
  })
}

function sendFile(cmd) {
  return new Promise((resolve) => {
    exec(cmd, (error, stdout, stderr) => {
      console.log(`stdout: ${stdout}`)
    });
    resolve();
  })
}

start();

Warning: Failed prop type: The prop `open` is marked as required in `ForwardRef(Modal)`, but its value is `undefined`

I get a warning after applying code from Material UI Dialog component. App works fine but i want to solve the warning, do you know how can i solve it ?

here is a link to material ui component:
https://mui.com/material-ui/react-dialog/

Note: before adding the dialog component everything worked fine.

Thanks in advance for everyone answering !

Failed prop type, the prop open is marked as required in 'Forwardref(Popover)'

import * as React from 'react';
import Avatar from '@mui/material/Avatar';
import Button from '@mui/material/Button';
import CssBaseline from '@mui/material/CssBaseline';
import TextField from '@mui/material/TextField';
import FormControlLabel from '@mui/material/FormControlLabel';
import Checkbox from '@mui/material/Checkbox';
import Link from '@mui/material/Link';
import Grid from '@mui/material/Grid';
import Box from '@mui/material/Box';
import LockOutlinedIcon from '@mui/icons-material/LockOutlined';
import Typography from '@mui/material/Typography';
import Container from '@mui/material/Container';
import { createTheme, ThemeProvider } from '@mui/material/styles';
import axios from "axios";
import Switch from '@mui/material/Switch';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogContentText from '@mui/material/DialogContentText';
import DialogTitle from '@mui/material/DialogTitle';
import Slide from '@mui/material/Slide';

import {useNavigate} from "react-router-dom";
import {useState} from "react";

function Copyright(props) {
    return (
        <Typography variant="body2" color="text.secondary" align="center" {...props}>
            {'Copyright © '}
            <Link color="inherit" href="https://mui.com/">
                Your Website
            </Link>{' '}
            {new Date().getFullYear()}
            {'.'}
        </Typography>
    );
}

const theme = createTheme();

const Transition = React.forwardRef(function Transition(props, ref) {
    return <Slide direction="up" ref={ref} {...props} />;
});

export default function SignIn() {

    const history = useNavigate();

    const [dialogueMessage,setDialogueMessage] = useState('')
    const [checked, setChecked] = useState(true);

    const handleChange = (event) => {
        setChecked(event.target.checked);
    };

    const [iopen, setOpen] = useState(false);

    const handleClickOpen = () => {
        setOpen(true);
    };

    const handleClose = () => {
        setOpen(false);
    };
    const handleSubmit = (event) => {
        event.preventDefault();
        const data = new FormData(event.currentTarget);
        const username = data.get('email').split("@")[0];
        if (checked === false ) {
            console.log("post")
            axios.post(process.env.REACT_APP_LOCAL_HOST + "/users/login", {
                email: data.get('email'),
                password: data.get('password')
            }).then((resp) => {
                console.log(resp.data)
                history("/users/" + username,{state:{token:resp.data.token,email:data.get('email'),user_id:resp.data.item.id}})
            })
        }else{
            axios.post(process.env.REACT_APP_LOCAL_HOST + "/admin/login", {
                email: data.get('email'),
                password: data.get('password')
            }).then((resp) => {
                if(resp.data.success === false){
                    handleClickOpen()
                    setDialogueMessage(resp.data.message)
                }else {
                    history("/admin/" + username, {state: {token: resp.data.token, email: data.get('email')}})
                }
            })

        }
    };




    return (
        <ThemeProvider theme={theme}>
            <Container component="main" maxWidth="xs">
                <Dialog
                    open={iopen}
                    TransitionComponent={Transition}
                    keepMounted
                    onClose={handleClose}
                    aria-describedby="alert-dialog-slide-description"
                >
                    <DialogTitle>{"There is a problem with your login !"}</DialogTitle>
                    <DialogContent>
                        <DialogContentText id="alert-dialog-slide-description">
                            {dialogueMessage}
                        </DialogContentText>
                    </DialogContent>
                    <DialogActions>
                        <Button onClick={handleClose}>Disagree</Button>
                        <Button onClick={handleClose}>Agree</Button>
                    </DialogActions>
                </Dialog>
                <CssBaseline />
                <Box
                    sx={{
                        marginTop: 8,
                        display: 'flex',
                        flexDirection: 'column',
                        alignItems: 'center',
                    }}
                >
                    <Avatar sx={{ m: 1, bgcolor: 'secondary.main' }}>
                        <LockOutlinedIcon />
                    </Avatar>
                    <Typography component="h1" variant="h5">
                        Log in
                    </Typography>
                    <Box component="form" onSubmit={handleSubmit} noValidate sx={{ mt: 1 }}>
                        <TextField
                            margin="normal"
                            required
                            fullWidth
                            id="email"
                            label="Email Address"
                            name="email"
                            autoComplete="email"
                            autoFocus
                        />
                        <TextField
                            margin="normal"
                            required
                            fullWidth
                            name="password"
                            label="Password"
                            type="password"
                            id="password"
                            autoComplete="current-password"
                        />
                        <FormControlLabel
                            control={<Checkbox value="remember" color="primary" />}
                            label="Remember me"
                        />
                        <Switch
                            checked={checked}
                            onChange={handleChange}
                            inputProps={{ 'aria-label': 'controlled' }}
                        />
                        Are you an admin ?
                        <Button
                            type="submit"
                            fullWidth
                            variant="contained"
                            sx={{ mt: 3, mb: 2 }}
                        >
                            Log In
                        </Button>
                        <Grid container>
                            <Grid item xs>
                                <div/>
                            </Grid>
                            <Grid item>
                                <Link href="/register" variant="body2">
                                    {"Don't have an account? Register"}
                                </Link>
                            </Grid>
                        </Grid>
                    </Box>
                </Box>
                {/*<Copyright sx={{ mt: 8, mb: 4 }} />*/}
            </Container>
        </ThemeProvider>
    );
}

How to force unit tests coverage for a specific folder in Jest

I’m trying to create a task that runs code coverage for a specific folder in my project (test-coverage-sub-folder). I already have it set for the entire project (test-coverage).

In my package.json I’ve added these two tasks:

{
"test-coverage": "jest unitTests/ --collectCoverage=true --coverage --collectCoverageFrom=./mainFolder/ui/**/*.js --coverageReporters=text-summary",
"test-coverage-sub-folder": "jest unitTests/subFolder/ --collectCoverage=true --coverage --collectCoverageFrom=./mainFolder/ui/**/*.js --coverageReporters=text-summary --config subFolder.jest.config.js",
}

subFolder.jest.config.js

module.exports = {
    verbose: true,
    testRegex: "(/jestTests/.*|(\.|/)(test|spec))\.js?$",
    moduleFileExtensions: [ "js", "jsx", "json", "node", "ts", "tsx", ],
    modulePathIgnorePatterns: [
        "unitTests/helpers/"
    ],
    setupFiles: [
        "<rootDir>/unitTests/helpers/mock.js"
    ],
    testEnvironment: "jsdom",
    coverageDirectory: "./../../../jest-coverage",
    collectCoverage: false,
    forceCoverageMatch: ["unitTests/subFolder/**/*.js"],
    coverageThreshold: {
        global: {
            statements: 80,
            branches: 80,
            functions: 80,
            lines: 80
        }
    }
};

I tried using forceCoverageMatch but it didn’t work unless I’m not using it right?
When I run the task it works, it runs only the tests from the subFolder but it calculates coverage based on all files in the project and I want it to calculate coverage only based on the files from subFolder.

Calculate an alphabetic score for a word

How can I generate a numeric score for a string, which I can later user to order things alphabetically?

(I’d like to add objectIds to a redis sorted set based on a name property. This needs a numeric score. My list-of-things might be too big to sort all at once, hence wanting to score each item individually)

Words earlier in an alphabetic list should have a lower score, with 'a' = 0.

My naive approach so far; (letter alphabetic position from Replace a letter with its alphabet position )

function alphaScoreString(inputString) {
    let score = 0

    inputString
        .trim()
        .toLowerCase()
        .split('')
        .map((letter, index) => {
            const letterNumber = parseInt(letter, 36) - 10
            if (letterNumber >= 0) {
                score += letterNumber / (index + 1) 
            }
        })

    return score * 1000
}

This does not work, as

alphaScoreString('bb')
1500
alphaScoreString('bc')
2000
alphaScoreString('bbz')
9833.333333333334

You can see that ‘bbz’ has a higher score than ‘bc’, whereas it should be lower, as ‘bbz’ would come before ‘bc’ in an alphabetical list.

Filter nested v-for list

<div>
    <q-card              
        v-for="box in boxes"
        :key="box.id">
        <q-item>
            <q-item-section>
                <span> {{ box.name }} </span>
            </q-item-section>
        </q-item>

        <q-list>
            <q-item
                v-for="tool in box.tools"
                :key="tool.id"
                clickable
                <q-item-section>
                    <span> {{ tool.name }} </span>
                </q-item-section>            
            </q-item>
        </q-list>
    </q-card>
</div>

Form input filter value

inputFilterValue = "box A"

Filter boxes

computed: {
    boxes(){
        boxes.filter(box => {
            return box.name.toLowerCase().match(inputFilterValue.toLowerCase())
        });
    }
}

This works

How to filter too nested v-for box-tools list?

Background image in cytoscape loads with delay in Angular App

I have defined all style in a separate ‘nodeselector.ts’ file

Eg:

export const styles = [{
    "selector": "node",
    "style": {
        "text-valign": "bottom",
        "text-halign": "center",
        "text-margin-y": "5px",
        "text-border-width": "5px",
        "font-size": "12px",
        "shape": "rectangle",
        "background-color": "#dedede",
        "border-color": "#000",
        "background-fit": "none",
        "background-repeat": "no-repeat",
        "background-clip": "none",
        "padding-left": 0,
        "padding-top": 0,
        "padding-right": 0,
        "padding-bottom": 0
    }
}, {
    "selector": ".myclass",
     "style": {
        "background-image": ['assets/myimage.png'],
        'background-image-containment': ['inside'],
        'background-width': ['100%'],
        'background-height': ['100%'],
        'background-position-x': ['0px'],
        'background-position-y':['0px'],
        'background-clip': ['node']
    }
    }
    ]

imported this file in another feature component

import * as nodestyle from './nodeselectors'
import * as cytoscape from 'cytoscape';
CreateGraph() {
    this.cy = cytoscape({
      container: document.getElementById('cy'),
      style: nodestyle.styles,
      layout: {
        name: 'preset',
        rows: 1
      }
    });
  }
<div id="cy">

While loading this on browser window, the background image(myimage.png) is taking so much of time to load, meanwhile a white color patch appears in the place of image, all i could see in the network section under chrome dev tools is a png being request with status as ‘pending’. As the number of nodes increases, this may take even more time to load all the nodes. How to resolve this and load all the background images with out any delay ?

Why does my new RegExp delete escape characters? [duplicate]

I have this RegExp expression with variable reference:

let strip_regex = new RegExp('[[(' + escaped_ref + ')|?.*?]]', 'g')
console.log(strip_regex)

However, when outputting this RegExp, the escape character for [ are gone and just [ remains. Same for ] -> ].

The console output says this:
/[[(list() deprecated)|?.*?]]/g

Why?

How to properly configure Suspense position into Canvas?

How to properly set position of a 3d model into Canvas regarding to x,y,z axes?

<div>
   <Canvas shadows dpr={[1, 2]} camera={{position: [5, 50, 5], fov: 10}}>
     <Suspense fallback={null}>
         <Model/>  
     </Suspense>
  </Canvas> 
</div>

My object is centered and extra small, I want to manually configure it’s position regarding to [x,y,z] axes into Canvas

Javascript BlueJ constructor

Im doing a school project where I have to code space invaders in bluej. I want to extend the class SCHIFF (ship) to IMAGEPANEL, but it keeps giving me the following error at SCHIFF constructor. class IMAGEPANEL has been given us by the professor, I didn’t write it. :

constructor IMAGEPANEL in class IMAGEPANEL cannot be applied to given types;
required: java.lang.String
found: no arguments
reason: actual and formal arguments lists differ in length



import java.awt.*;
public class IMAGEPANEL extends Panel
{ 
    private int erfolgreicheMelkungen;
    private Image image;

    
    public IMAGEPANEL(String bildname)
    {
        image = Toolkit.getDefaultToolkit().getImage(bildname);
        setImage(image);

    }
...
}

import java.awt.*;

public class SCHIFF extends IMAGEPANEL
{
    String beschreibung;
    int anzahlKanonen;
    int anzahlBomben;
    
    SCHIFF(String x){
    
    
    
    }

}


return pagination items that always has two siblings before and after the current page

I’m trying to make a function that returns me pagination items, and here is what I tried (based on https://github.com/mui/material-ui/blob/v4.10.2/packages/material-ui-lab/src/Pagination/usePagination.js):

const pagination = (totalPages, siblingCount = 2, pageNumber) => {
  const ELLIPSIS = '…';
  const siblingsStart = Math.max(
      Math.min(
        // Natural start
        pageNumber - siblingCount,
        // Lower boundary when page is high
        totalPages - siblingCount * 2 - 2,
      ),
      // Greater than startPage
      3,
    );

    const siblingsEnd = Math.min(
      Math.max(
        // Natural end
        pageNumber + siblingCount,
        // Upper boundary when page is low
        siblingCount * 2 + 3,
      ),
      // Less than endPages
      totalPages - 2,
    );

    // Basic list of items to render
    return [
      1,

      // Start ellipsis
      // eslint-disable-next-line no-nested-ternary
      ...(siblingsStart > 3
        ? [ELLIPSIS]
        : totalPages - 1 > 2
        ? [2]
        : []),

      // Sibling pages
      ...range(siblingsStart, siblingsEnd),

      // End ellipsis
      // eslint-disable-next-line no-nested-ternary
      ...(siblingsEnd < totalPages - 2
        ? [ELLIPSIS]
        : totalPages - 1 > 1
        ? [totalPages - 1]
        : []),

      totalPages,
    ];
};

This function will return a string like the following when (for example) pageNumber = 6 and totalPages = 20:

1 … 4 5 6 7 8 … 20

This is working fine, since I want to always display two numbers before and after the pageNumber.

So when the pageNumber = 1 I want the following:

1 2 3 … 20

But instead I get this:

1 2 3 4 5 6 7 … 20

The same as when the pageNumber = 20, I want to get this:

1 … 18 19 20

How can I solve this ?

How can I pass map data with props

I just wan’t store and pass current props.url to the videomodal. so I can show the same active video on the video modal. I can’t use usestate in the map. how can I pass it? or is there a any other solution?

Videos.tsx ( props.url must be in the <VideoModal videoURL={here} /> )

 <div className="video__container">
            <div className="video__item">
              {VIDEO_LIST.map((props: any) => (
                <div key={props.id}>
                  {props.id === currentItem && (
                    <>
                      <ReactPlayer
                        url={props.url}
                        playing={true}
                        loop={true}
                        volume={0}
                        muted={true}
                        height="100%"
                        width="100%"
                        controls={true}
                        config={{
                          file: {
                            attributes: {
                              disablepictureinpicture: "true",
                              controlsList:
                                "disablepictureinpicture nodownload noplaybackrate",
                            },
                          },
                        }}
                      />
                    </>
                  )}
                </div>
              ))}
            </div>
          </div>
 <div className="play__video">
         
          {isModalOpen && (
            <VideoModal
              handleCloseModal={closeModal}
              videoURL={HERE I NEED TO PASS THE URL}
            />
          )}
        </div>

VideoModal.tsx


  <div className="body">
                    <div className="player-wrapper">
                        <ReactPlayer
                            className="react-player fixed-bottom"
                            url={videoURL}
                            width="100%"
                            height="100%"
                            playing={true}
                            controls={true}
                        />
                    </div>
                </div>