Making a counter using JavaScript/JQuery clone method in an HTML table

I need to make a counter using JavaScript/JQuery with clone method in the second column like for example the first row 1 and when I click on add button it automatically display number 2. I am using clone method in JavaScript/JQuery and I don’t know how to add this. This is my full code:

var cloned = $('#myTable tr:last').clone();
$(".add-row").click(function(e) {
  e.preventDefault();
  cloned.clone().appendTo('#myTable');
});

$('#myTable').on('click', ".delete-row", function(e) {
  e.preventDefault();
  $(this).closest('tr').remove();
});
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered table-hover table-striped table-sm" id="myTable">
  <thead>
    <th></th>
    <th>#</th>
    <th>test1</th>
    <th>test2</th>
    <th>test3</th>
    <th>test4</th>
    <th>test5</th>
  </thead>
  <tbody>
    <tr>
      <td>
        <a href="#" class="btn btn-sm btn-danger delete-row">delete</a>
      </td>
      <td>
      <!-- Counter here -->
      </td>
    </tr>
  </tbody>
</table>
<a href="#" class="btn btn-sm btn-primary add-row">add</a>

Python’s zlib decompresses data, but Pako (JavaScript zlib) fails

I’m trying to inflate some zlib compressed data (Ren’Py Archive 3 archive file structure for those wondering) with JavaScript, but I can’t seem to reproduce the Python behavior in Node.js.

This Python script works:

import zlib

# Data written to a file from a different Python script, for demo purposes
# This would be a value in memory in JS
data = open("py", "rb")

# Works
print(
    zlib.decompress(data.read(), 0)
)

While this Node.js script:

const fs = require('fs');
const pako = require('pako');

const data = fs.readFileSync('py', 'binary');

// Doesn't work
console.log(
    pako.inflateRaw(data)
);

Throws this error:

C:UsersgunneDocumentsProgrammingnode.jsrpa-extractornode_modulespakolibinflate.js:384
  if (inflator.err) throw inflator.msg || msg[inflator.err];
                    ^
invalid stored block lengths
(Use `node --trace-uncaught ...` to show where the exception was thrown)

As per the Python zlib.decompress documentation, a wbits parameter (the second parameter) of 0 “automatically [determines] the window size from the zlib header,” something that the Pako implementation seemingly doesn’t do.

Am I doing something incorrectly? How would I achieve the same output as in Python using Node.js?

Possible optimizations for my alpha-beta pruning algorithm?

I’m a new programmer currently coding a javascript alpha-beta pruning minimax algorithm for my chess engine. I’ve implemented a basic algorithm with move ordering, and instead of evaluating each leaf node I’m “tracking” each move made along the way as to speed up the board evaluation. Currently, it’s evaluating around 14000 nodes for 8 seconds, which is way too slow. Is there something wrong with my algorithm or are there optimizations that I can implement? I was also thinking about making each branch search asynchronously, i.e. each of the x possible moves will run at the same time and compare the results when all branches have finished evaluating. Thank you.

function minimax(game, depth, distanceFromRoot, alpha, beta, gameEval) {//returns gameEval
    if (depth === 0) {
      nodeNum++;
      if(game.turn() === 'b'){
        return (-gameEval / 8);
      }else{
        return (gameEval / 8);
      }
    }

    // run eval 
    var prevEval = gameEval;

    var moves = game.moves();
    moveOrdering(moves);
    var bestMove = null;
    var bestEval = null;
    for (let i = 0; i < moves.length; i++) {
      var gameCopy = new Chess()//dummy board to pass down
      gameCopy.load(game.fen())
      const moveInfo = gameCopy.move(moves[i])

      var curGameCopy = new Chess()//static board to eval, before the move so we know which piece was taken if a capture occurs
      curGameCopy.load(game.fen())
      var curEval = trackingEval(curGameCopy, prevEval, moveInfo, moves[i]); //returns the OBJECTIVE eval for the current move for current move sequence
      var evaluated = -minimax(gameCopy, depth - 1, distanceFromRoot + 1, -beta, -alpha, curEval);//pass down the current eval for that move
      if (evaluated >= beta) {
        return beta;
      }

      if (evaluated > alpha){
        alpha = evaluated
        bestMove = moves[i]
        bestEval = evaluated;
        if (distanceFromRoot === 0) {
          bestEval = evaluated;
        }
      }
    }
    
    if(distanceFromRoot === 0){
      setEval(-bestEval)
      return bestMove;
    }
    return alpha;
  }

How does one pass an array with no fixed size into the vertex shader?

I have an array with no fixed size (let noise = [];) in my .js file where it stores the noise values for a point (noise[i] -> a single point).

I was wondering if I’m able to pass all the values inside the array into my vertex.shader by doing:

//.js
for(let i = 0; i < noise.length; i++) {
    const uNoise = gl.getUniformLocation(program, "uNoise[" + i + "]");
    gl.uniform3fv(uNoise, MV.flatten(noise[i]));
}

//vertex.shader
let uNoise[];

If not, how would it possible to do it?

isAuth is not defined

i defined isAuth in Line 14 but i got error “srcApp.js
Line 25:13: ‘isAuth’ is not defined no-undef”
idk, maybe i defined it wrong, looking up for your help, thanks

import React, { Component } from 'react';
import './css/main.css';
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
import Home from './pages/Home';
import CreatePost from './pages/CreatePost';
import Login from './pages/Login';


class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      isAuth: false,
      setIsAuth: false
    };
  }

  render() {
    return (
      <Router>
        <nav>
          <Link to="/">Home</Link>
          <Link to="/createpost"> Create New Post</Link>
          {!isAuth && <Link to="/login">Login</Link>}
        </nav>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/login" element={<Login setIsAuth={this.state.setIsAuth} />} />
          <Route path="/createpost" element={<CreatePost />} />
        </Routes>
      </Router>
    );
  }
}

export default App;

How to find whether time ranges overlap?

I have the following time ranges 1pm to 3pm and 9am to 5pm. I know a doctor is available between 9am and 5pm. The patient is looking for doctors that are available from 1pm to 3pm. When he inputs that time range, he should be able to see the doctor in the list. For example, if the doctor is available from 9am to 12pm, and the patient input 3pm to 5pm, the doctor won’t show up. I’m trying to match doctors with appointments with patients where patients give a time range when they are available and so do doctors. How can I do this using javascript? Here’s my inefficient solution.

            // startDate and endDate is the time range for the doctor.
            const startDateTime = startDate.format('HH:mm');
            const endDateTime = endDate.format('HH:mm');

            const stimeParts = startDateTime.split(":");
            const stime1 = parseInt(stimeParts[0], 10);
            const stime2 = parseInt(stimeParts[1], 10);

            const etimeParts = endDateTime.split(":");
            const etime1 = parseInt(etimeParts[0], 10);
            const etime2 = parseInt(etimeParts[1], 10);

            const startminutes = (stime1 * 60) + stime2;
            const endminutes = (etime1 * 60) + etime2;

            // so patients can select times in a 3 hour range
            // for example from 0:00 to 3:00 or 12:00 to 15:00
            // key is the first number in the time range that the user selected
            // so if they select the time range 15:00 to 18:00, then key = 15
            const timeSelected = key;
            const fromMinutesSelected = timeSelected * 60;
            const toMinutesSelected = (timeSelected * 60) + (3 * 60);

            let timeStart = startminutes;

            while ( found === false && (timeStart < endminutes && ((timeStart + 30) <= endminutes))) {
                if (timeStart >= fromMinutesSelected && (timeStart + 30 < toMinutesSelected)) {
                    found = true;
                } else {
                    timeStart += 30;
                }
            }

if found == true then the two time ranges overlap. selectedTime

Math for combining two array’s values as notation for a large number

I am currently trying to write a part of my code that takes a large number, say, 1e31, and converts it to 1no where no is a units measure. I currently have my code set up as such:

function getNotation(num) {
  let firstArray = ["", "un", "du", "tr", "qa", "qi", "sx", "sp", "oc", "no"];
  let secondArray = ["", "Du", "Tr", "Qa", "Qi", "Sx", "Sp", "Oc", "No"];
  let output = "";
  console.log((Math.floor(Math.log10(num) / 3)) + " " + (Math.floor(Math.log10(num) / 3) % 11 - 1) + " " + (Math.floor(Math.floor(Math.log10(num) / 3) / 11)));
  output += firstArray[Math.floor(Math.log10(num) / 3) % 11 - 1];
  output += secondArray[Math.floor(Math.floor(Math.log10(num) / 3) / 11)];
  return output;
}

The issue that I am running into is that the index I use for firstArray works fine until it hits 9, then it jumps to -1. If anyone could give me some help that would be greatly appreciated. Let me know if you need any more of the code.

Pinterest Tag Health Make sure you are including Product IDs in your Add to Cart events. SHOPIFY

Make sure you are including Product IDs in your Add to Cart events. A Product ID can be any format that you choose as long as it matches the format used by your Catalog.

I am getting this error on Pinterest tag health and I don’t know how to fix it. I am using Shopify. I have tried to add this code to submit button:

onclick="pintrk('track', 'addtocart');"

But it is not working. Is this some kind of bug?

How do you click on this deeply nested class in javascript?

How can I access the class I marked blue on the screenshot below and click on it?
The “main class” and “section class” always got the same name. I have tried by starting at a class which I believe is the parent and find about its children step by step by using

var x = document.getElementsByClassName("_9eogI E3X2T")[0];
window.alert(x);

but that keeps giving me “undefined” and I don’t know how to get into the class I marked on the screenshot because the blue marked area in code always got a different name too :/

enter image description here

How debug Laravel 8 api call done in browser?

I have a project in Laravel 8 where I’ve created a controller with a update method.

    public function update(Product $product, Request $request)
    {
        $data = $request->all();

        $validator = Validator::make($data, [
            'name' => 'string',
            'quantity' => 'integer',
            //'image_path' => 'required|mimes:jpeg,bmp,png',
        ]);

        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors(), 'error']);
        }

        $product->fill($data);
        $product->save();


        return new ProductResource($product);
       }

I’ve followed this answer to set up Phpstorm to debug Laravel and when I call that end-point with Postman the debug effectively starts.

Now, I am trying to use this endpoint, doing a js function that send the data of a html form.

From this answer, I wrote the following code

const productEditFormSubmit = async (e) => {
  let formData = new FormData();
  formData.append('fileData', e.target.elements.image.files[0]);
  formData.append('code', e.target.elements.name.value);
  formData.append('quantity', e.target.elements.code.value);
  formData.append('name', e.target.elements.quantity.value);

  try {
    const apiUrl = `http://localhost:8000/api/product/${e.target.elements.code.value}`;
    const options = {
      method: 'PATCH',
      body: formData
    };

    
    const response = await fetch(apiUrl, options);
    const body =  await response.json();

    return body;
  }
  catch (error) {
    console.log('(App) Error: ', error);
  }
  e.preventDefault();
}

However, the debug doesn’t start at all.
I’m sure the end-point is called and doesn’t crash midway, because if I alter it to send a “fake” response instead of return new ProductResource($product);, I find it in the browser network table:

call response

However, The update doesn’t do its logic – I mean, the product isn’t correctly updated as it happens with postman call.

Now, I am in the blind, as I can’t see what is actually happening inside that function.
Any idea why the debugger doesn’t start in this case? I’ve also installed and tried to enable the Xdebug helper extension but that doesn’t change anything.

By the way, any other ways to check what happens in that function when called in the browser? Log, dump function, whatever?

CSS/React My button moves out of place when minimizing window

Trying to make a generic search bar in React, having trouble preventing the search button from moving when minimizing the window. The arrow will always move out of position when I minimize the window even if just a bit, wondering what I am missing in my code. I want the search arrow button to maintain its place even when minimizing the window but it keeps moving.

Searchbar.js

import React from "react";
import './SearchBar.css';
import arrow from './arrow.png';

const SearchBar = ({placeholder,data}) => {
    return (
        <div className="search">
                <div className="searchInputs">
                    <input type="text" placeholder={placeholder}/>
                    <button className='button' style={{position: 'relative',
                                                right: 420, top: 15}}>
                    <img className='arrow' src={arrow} alt="logo" 
                        style={{position: 'relative', right: 15, bottom: 11}}
                    ></img>                            
                                                </button>
                    <div className="searchIcon"></div>
                </div>
                <div className="dataResult"></div>
        </div>
    );
}

export default SearchBar;

Searchbar.css

.searchInputs {
  margin-top: 55px;
  display: flex;
  position: relative;
}

.search input {
  background-color: white;
  border: 0;
  border-radius: 40px;
  font-size: 16px;
  height: 72px;
  width: 676px;
  margin: auto;
  font-family: Proxima Nova,Arial,sans-serif;
  font-weight: 700;
  line-height: 1.33;
  
  color: #414141;
}


input:focus {
  outline: none;
}

.searchIcon svg {
  font-size: 16px;
}

.button {
  display: flex;
  flex-direction: row;
  align-items: left;
  height: 10px;
  width: 10px;
  border-radius: 50%;
  border: none;
  padding: 20px;
  background-color: #428a13;
  transition: background-color .2s;
  
}

.arrow {
  height: 24px;
  width: 31px;
}

.button:hover {
  color: rgba(255, 255, 255, 1);
  box-shadow: 0 0px 22px orange;
}

How to get javascript value of html data with Jsoup in Java

I’ve been using Jsoup for a long time. I need to get values of a wheather conditions.

That’s the link i’m work on : https://www.mgm.gov.tr/tahmin/il-ve-ilceler.aspx?il=ANKARA&ilce=

The problem here: I can’t directly access the values I want.

As you can see at below i need to access values which is showing in picture.enter image description here

The question is how can i access the data generated by javascript in html ?

How to write array elements to a rangelist using Google Apps Script?

I have this rangelist as the destination and a row of values that should be written to the destination.
I was thinking of iterating through the row of data and also through th rangelist and set value along the way, but I can’t find a way to iterate through the elements in the row of data.
Here’s the piece of code I’m working on:

let data = [];
  for (let i = 0; i < values.length; i++) {
    if (values[i][0] == ref && values[i][4] == variac) {
      data.push(values[i])
    }
  }
  const destRng = [
    "B5", "D5", "G5", "I5", "M5",
    "B7", "H7",
    "B9",
    "C12", "C14", "C16", "C18", "C20", "C22", "C24",
    "B27", "E27", "H27", "L27",
    "B29",
    "B32", "E32", "H32", "L32",
    "B34", "E34", "H34", "L34",
    "B36", "E36",
    "B40", "F40", "J40",
    "B42",
    "B44", "F44", "J44",
    "B46", "F46", "J46",
    "B48", "F48", "J48",
    "B50",
    "D53",
    "D55",
    "B58", "D58", "G58", "I58", "L58",
    "B61", "E61", "G61", "J61",
    "B65", "G65"
  ]

  Logger.log('Data: ' + data)

  const rngList = sheetCadProd.getRangeList(destRng).getRanges();
  for (let n = 0; n < data.length; n++) {
    for (let i = 0; i < rngList.length; i++) {
      let dado = data[n] 
      rngList[i].setValue(dado)//It sets the first value throughout the rngList
    }
  }
}

Now, this is getting the first element of data and writing it to all destination cells. How can I go through these data elements?

Thank you!

Why is a function I expect to be shaken from a tree still there on a create-react-app build?

Similar to Tree shaking create-react-app? but more of how to validate and fix.

So I have a created a library of react hooks. In there I added an example to help me understand how tree-shaking would work.

import { useClock, useDeepState } from '@trajano/react-hooks';
export function App(): JSX.Element {
  useClock();
  useDeepState("foo");
  return <div>Hello world</div>
}

However, there’s a function called useAsyncSetEffect that I added in my library code base, but tracing through the code for useClock and useDeepState I don’t hit that function at all, but when I look at the generated files I see a reference to useAsyncSetEffect.

Not really sure what’s causing it, the library isn’t large so the size is just a K gzipped, but I am curious as to why it is being included.

POST http://localhost:7500/api/users/posts 400 (Bad Request)

So I am trying to save some data into a mongodb data base using axios
I created a form to fill then when i click on save the data must be saved.

this is my try:

import auction1 from '../../Images/auction1.png'
import {useState} from 'react';
import './HomeScreen.css'
import {Button, Modal } from 'react-bootstrap';
import axios from 'axios';

const HomeScreen = ()=>{

    const [show, setShow] = useState(false);
    const handleClose = () => setShow(false);
    const handleShow = () => setShow(true);

    
    const [name, setName] = useState("");
    const [price, setPrice] = useState(null);
    const [deadline, setDeadLine] = useState("");
    const [description, setDescription] = useState("");

    const [img, setImg] = useState("");

    const [imgMessage, setImgMessage] = useState(null);
    const [error, setError] = useState(false);


    const handleSubmit = async(e)=>{

        e.preventDefault();

        try{
            const config = {
                headers: {
                    "Content-Type": "application/json",
                }
            }

            const {data} = await axios.post("http://localhost:7500/api/users/posts",
            {name, img, deadline, price, description}, 
            config
            );

            console.log(data);

        }catch(error){
            console.log(error.response.data.message);
        }
    };


    const postDetails = (pic)=>{

        if(!pic){
            return setImgMessage('Please select a picture');
        }

        setImgMessage(null);

        if(pic.type === 'images/jpeg' || pic.type==='image/png'){
            const data = new FormData();
            data.append('file', pic);
            data.append('upload_preset', 'battta');
            data.append('cloud_name', 'ChkounZed');
            fetch("https://api.cloudinary.com/v1_1/ChkounZed/upload", {
                method: 'post',
                body: data
            })
            .then((res)=> res.json())
            .then((data)=> {
                console.log(data);
                setImg(data.url.toString())
            })
            .catch((error)=>{
                console.log(error);
            });
        }else{
            return setImgMessage('Please select a picture');
        }
    };


    
    return(
        <div className="container bg">
            <img src ={auction1} className='landing-image' />
            <div style={{marginLeft:460}}> 
                <Button variant="primary" onClick={handleShow}>
                    Create Post
                </Button>
            </div> 
            <Modal show={show} onHide={handleClose}>
                <form onSubmit={handleSubmit}>
                    <Modal.Header closeButton>
                        <Modal.Title>Create Post</Modal.Title>
                    </Modal.Header>
                    <Modal.Body>
                        <form >
                            <div className="form-group">
                                <label>Post Name:</label>
                                <input type="text" className="form-control" placeholder="Enter Name"
                                value={name} onChange={(e)=> setName(e.target.value)}/>
                            </div>

                            <div className="form-group">
                                <label>Post Images:</label>
                                <input type="file" className="form-control" multiple onChange="readURL(this)" accept="Image/*" 
                                onChange={(e)=> postDetails(e.target.files[0])}/>
                            </div>

                            <div>
                                <label>Price:</label>
                                <input type="number" className="form-control" placeholder="TND"
                                value={price} onChange={(e)=> setPrice(e.target.value)}/>
                            </div>
                            <div>
                                <label>DeadLine:</label>
                                <input type="datetime-local" className="form-control"
                                value={deadline} onChange={(e)=> setDeadLine(e.target.value)}/>
                            </div>
                            <div>
                                <label>Description:</label>
                                <textarea className="form-control" rows="3"
                                value={description} onChange={(e)=> setDescription(e.target.value)}/>
                            </div>
                        </form>
                    </Modal.Body>
                    <Modal.Footer>
                        <button type="submit" className="btn btn-primary" data-bs-dismiss="modal" onClick={handleClose} >
                            Save Post
                        </button>
                        <button type="submit" className="btn btn-secondary" data-bs-dismiss="modal" onClick={handleClose}>
                            Close
                        </button>
                    </Modal.Footer>
                </form>
            </Modal>
        </div>
    )

};

export default HomeScreen;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

that was my react component and the problem is that i keep getting a message that says the post already exists.

this is my postController from the backend side:

const Post = require("../Models/postModel");
const asyncHandler = require("express-async-handler");


const savePost = asyncHandler(async(req,res)=>{

    const {name, deadline, price, description, image} = req.body;
 

    const postExists = await Post.findOne({image});
    
    if(postExists){
        res.status(400);
        throw new Error('Post Already Exists');
    }

    const post = await Post.create({
        name,
        deadline,
        price,
        description,
        image
    });

    if(post){
        res.status(201).json({
            _id: post._id,
            name: post.name, 
            price: post.price, 
            image: post.image,
            deadline: post.deadline,
            description: post.description
        });
    }else{
        res.status(400);
        throw new Error('Error');
    }
});

module.exports = {savePost};

I would be so grateful if you can give me hand of this and by the way i wanna make my post unique using the images and still did not know how