Print and save button in laravel

How can I add two function which is the print and move the data to another table in a one button?

Please refer to this image.

Here when I click the borrow button the print preview will display only the row data and move the row data to borroweditem table. While the quantity of that item which is in another table will be deducted by 1.

Here’s my view.blade.php

<div class="card shadow mb-4">
<div class="card-header py-3">
<h6 class="m-0 font-weight-bold text-primary">Accepted Reservations</h6>
</div>
<div class="card-body">

<div class="table-responsive">
 <table class="table table-bordered tbl_acceptres display" id="dataTable" width="100%" cellspacing="0">
 <thead>
                                                        <tr>
                                                            <th hidden>Id</th>
                                                            <th>Name</th>
                                                            <th>Equipment</th>
                                                            <th>Reservation Date</th>
                                                            <th>Rooms</th>
                                                            <th>Action</th>
                                                         </tr>
                                                    </thead>

<tbody>
                                                         @foreach ($acc as $accdata)

                                                        <tr>
                                                            <td hidden> </td>
                                                            <td>{{ $accdata->name }} </td>
                                                            <td>{{ $accdata->Name_item }}</td>
                                                            <td>{{ $accdata->dt_item }}</td>
                                                            <td>{{ $accdata->room_item }}  </td>
                                                            <td>

                                                               <button type="submit" class="btn btn-primary btn-sm" onClick="window.print()">Borrow <i class="fas fa-chevron-right"></i></button>
                                                            </td>
                                                        </tr>

                                                     @endforeach
                                                    </tbody>
 </table>
 </div>
</div>

How to destruct array of numbers in an object and combine to one in javascript?

i have this object:

const memorized = [
 {
  verses: [1, 2, 3, 4, 5],
  when: '2022 Jan 14'
 },
 {
  verses: [6, 7, 8, 9]
  when: '2022 Jan 15'
 },
 {
  verses: [10, 11, 12, 13, 14, 15]
  when: '2022 Jan 16'
 },
...
]

and how can i get the total verses like this:

const total_verses = [1, 2, 3, 4, 5, ..., 15]

My possible solution would be:

let total_verses = []
memorized.map(ar => total_verses.push(...ar.verses))

But i would like to do it by just filtering or mapping.

Thanks in advance!

In react authentication app in console showing Error (auth/invalid-api-key)

More Specific Error:-

at createErrorInternal
at assert
at new Auth
at Component.instance.INTERNAL.registerComponent.firebase_component__WEBPACK_IMPORTED_MODULE_2
.Component.setServiceProps.ActionCodeInfo.Operation.EMAIL_SIGNIN [as instanceFactory]
at Provider.getOrInitializeService
at Provider.getImmediate
at FirebaseAppImpl._getService
at FirebaseAppImpl.firebaseAppImpl. [as auth]
at Module../src/firebase.js (firebase.js:27:1)
at Module.options.factory (react refresh:6:1)

Note: For version 9 it’s required to compat/app otherwise showing error also

firebase.js file

import "firebase/compat/auth";

const app = firebase.initializeApp({
apiKey:process.env.REACT_APP_FIREBASE_API_KEY,

authDomain:process.env.REACT_APP_FIREBASE_AUTH_DOMAIN ,

databaseURL:process.env.REACT_APP_FIREBASE_DATABASE_URL ,

projectId:process.env.REACT_APP_FIREBASE_PROJECT_ID ,

storageBucket:process.env.REACT_APP_FIREBASE_STORAGE_BUCKET ,

messagingSenderId:process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID ,

appId:process.env.REACT_APP_FIREBASE_APP_ID ,

measurementId:process.env.REACT_APP_FIREBASE_MEASUREMENT_ID
})

export const auth = app.auth();
export default app;

.env.local file:


REACT_APP_FIREBASE_AUTH_DOMAIN=*************
REACT_APP_FIREBASE_DATABASE_URL =*************

REACT_APP_FIREBASE_PROJECT_ID =***************
REACT_APP_FIREBASE_STORAGE_BUCKET =*****************
REACT_APP_FIREBASE_MESSAGING_SENDER_ID =*****************
REACT_APP_FIREBASE_APP_ID =*******************
REACT_APP_FIREBASE_MEASUREMENT_ID =*******************```

Sum for array with While loop JS

I have tried to make a while loop where I add all the numbers of the array to one sum. I keep on getting an endless loop. I’ve also tried to do (array.length) (array.length –) (array.length>numbers)
But nothing I tried worked… any suggestions? šŸ™‚

function sumNumbersWhileLoop(array, sum) {
  array = [1, 5, 4, 6, 7];
  sum = 0;
  for (let numbers of array) {
    while (array.length>0) {
      sum += numbers;

      console.log(sum);
    }
  }
}

vscode snippets: How to link a position in the snippet to a tabstop?

I want to create a snippet that prints the value of a variable for debugging purposes. this is what I came up with:

{
  "Debug": {
    "prefix": ["db"],
    "body": ["console.log("$1 :", $1)"]
  }
}

When I use this snippet cursor goes between the quotes ( | is the cursor position):

console.log("| :",)

And after I typed the name of a variable it copies the name to the second parameter:

console.log("name :", name)

But I can’t use autocompletion in strings. sometimes the variable is an object and auto-completion helps me pick a specific key of the object. I want the cursor to stop in the second parameter so I can use autocompletion:

console.log(" :", |)

How can I do that?

How do I find a point at a given distance along a route? epoly.js is giving me extremely inaccurate and unusable results

I’m trying to find the point along a Google Maps API Directions route given a distance from the starting point. I have my code working and it gives me very accurate results most of the time. However when I make very long directions requests (for example, 1,000+ kilometers), the results are less accurate, and the longer the directions route the more inaccurate the results are. Once I reach approximately 3,000 kilometers the results are off by about 4,000 meters, which is entirely unacceptable for my application.

The function I’m using to compute the point is from epoly.js, and the code is as follows:

google.maps.Polyline.prototype.GetPointAtDistance = function(metres) {
    if (metres == 0) return this.getPath().getAt(0);
    if (metres < 0) return null;
    if (this.getPath().getLength() < 2) return null;
    var dist=0;
    var olddist=0;
    for (var i=1; (i < this.getPath().getLength() && dist < metres); i++) {
        olddist = dist;
        dist += this.getPath().getAt(i).distanceFrom(this.getPath().getAt(i-1));
    }
    if (dist < metres) {
        return null;
    }
    var p1= this.getPath().getAt(i-2);
    var p2= this.getPath().getAt(i-1);
    var m = (metres-olddist)/(dist-olddist);
    return new google.maps.LatLng( p1.lat() + (p2.lat()-p1.lat())*m, p1.lng() + (p2.lng()-p1.lng())*m);
}

What is causing the result to be so inaccurate over large distances and what can I do to make it more accurate? (I need accuracy down to approximately 1-3 meters) Does the Google Maps API have any way to do this or is epoly.js my best bet? If so, then what can I change about the above code to make it give more accurate results?

I’ve been searching for an answer to this for a while, but everything I can find either recommends epoly.js or shows code snippets that perform exactly the same computations as epoly.js. It seems as though Google doesn’t have any built-in way to do this, however I’ve seen something similar done in some applications like https://routeview.org, where you can clearly see the orange man tracing along the route perfectly even when navigating thousands of kilometers at a time, so I have to believe a higher level of accuracy is possible.

Here are two screenshots illustrating a short distance request and a long distance request. Note that it’s very accurate over short distances but becomes wildly inaccurate over longer distances. Also note that the marker in the second image is being viewed from far away. It may look close to the path, but it’s actually about 5,000 meters away on the other side of a large hill. (The marker in the first image is viewed from very close up, and even when viewed so closely it doesn’t deviate from the path any noticeable amount)

This image is for a 20km route:

Short distance marker placed perfectly on path

This image is for a 3326km route:

Long distance marker placed thousands of meters off of path

What the logic behind b1 ? b1 : b2 in my coding in if-conditions?

1.Here is the assignment.

Declare a functionĀ orĀ that works likeĀ ||, but without using theĀ ||Ā operator.
/**

  1. @param {any} ??? – the first operand
  2. @param {any} ??? – the second operand
  3. @returns {any} the same result as applying the || operator to the given operands, in order

2.Here is what tried(actually people gave me advice on return b1 ? b1 : b2.But i couldn’t understand it ,and haven’t found a proper explanation about it online.

function or(b1, b2) {
  if (b1 == false && b2 == false) return false;
  else return b1 ? b1 : b2;
}

3.Here are the coding tests, and the code above passed all of them. But would anyone tell me the logic of b1 ? b1 : b2. I am a beginner, please help me !

//TEST 1

actual = or("bananas", false);

expected = "bananas";

if (actual === expected) {
  console.log("Yay! Test PASSED.");
} else {
  console.error("Test FAILED. Keep trying!");
  console.log("    actual: ", actual);
  console.log("  expected: ", expected);
}

//TEST 2

actual = or("", "bananas");

expected = "bananas";

if (actual === expected) {
  console.log("Yay! Test PASSED.");
} else {
  console.error("Test FAILED. Keep trying!");
  console.log("    actual: ", actual);
  console.log("  expected: ", expected);
}

//TEST 3

actual = or(true, true);

expected = true;

if (actual === expected) {
  console.log("Yay! Test PASSED.");
} else {
  console.error("Test FAILED. Keep trying!");
  console.log("    actual: ", actual);
  console.log("  expected: ", expected);
}

//TEST 4

actual = or(true, false);

expected = true;

if (actual === expected) {
  console.log("Yay! Test PASSED.");
} else {
  console.error("Test FAILED. Keep trying!");
  console.log("    actual: ", actual);
  console.log("  expected: ", expected);
}

(TypeScript) Type Alias / Interface defined by object literal

I am making some schema of JSON message to transfer between server & client, for serialization I created an object literal as a template such as below

type uint8 = number;

const schema1 = {
    type: 'object',
    fields: {
        type: { type: 'uint8' },
        title: { type: 'string', optional: true }
    }
};

// can below automatically defined by schema1?
type schema1Type = {
    type: number,
    title?: string
};

const data1: schema1Type = {
    type: 1,
    title: 'Hello World'
};

It is alright to validate the message format by object literal schema (type alias seems cannot do this job in runtime), but for more comprehensive usage, I wish to define a type alias according to the object literal template, to guard message format in compile time, is it possible to do so? please sharing some hints for me, thank you.

Why does using async…await on non-asynchronous code seemingly mess up the order?

I have been running different code I wrote to observe the behavior of async ... await key words.

I have two examples, which behave drastically differently:

Example 1:

const func1 = async () => {
  await setTimeout(() => console.log('first'), 0);
  console.log('second')
  console.log('third')
}

console.log('hi1');
func1();
console.log('hi2');

// logs hi1, hi2, second, third, first

Example2:

const func2 = async () => {
  await console.log('first');
  console.log('second');
  console.log('third');
}

console.log('hi1');
func2();
console.log('hi2');

// logs hi1, second, third, hi2, first

I do understand everything in Example 1, but not Example 2.
Specifically, I expect Example 2 to log

'hi1', 'first', 'second', 'third', 'hi2'

This is because there is nothing to wait for when logging 'first', so it should immediately log 'first', as Javascript is synchronous language.

So in summary I am curious of these two things:

  1. Why does Example 2 log as is instead of logging 'hi1', 'first', 'second', 'third', 'hi2'.

  2. Can I use async …await on non-asynchrnous code like console.log('first')? Then shouldn’t it return error? It does not, therefore I assume it is usable.

Any explanation would be appreciated!

Socket IO Broadcast Emit sending to sender

I have an app where I need the users to be able to send a message. Right now, users can send a message and socket IO broadcasts the message, but the sender also receives. I need messages sent to go to everyone but sender

Server code:

io.on("connection", (socket) => {
    socket.on("upGuess", (guess, room) => {
        if (room) {
            socket.to(room).emit("broadcastMessage", guess);
        } else {
            socket.broadcast.emit("broadcastMessage", guess);
        }
    });
});

Client side Code:

socket.on("broadcastMessage", (guess) => {
    console.log(guess);
});

const handleButton = () => {
    socket.emit("upGuess", "TestGuess");
};

Current behavior: User A calls handleButton function, User A and User B receive broadcastMessage and console log guess

Wanted behavior: User A calls handleButton function. Only user B receives broadcastMessage and logs guess

react-three-fiber object looks in grey color

I’ve been using React.js with @react-three/fiber library.

And following some tutorials, I faced this issue.

All object color rendered in grey color as follows:

grey color rendered image

Here’s my code:

// App.js

import React, { Suspense } from "react"
import styled from "styled-components"
import { Canvas } from "@react-three/fiber"
import { OrbitControls, Stars } from "@react-three/drei"

const AppContainer = styled.div`
  width: 100%;
  height: 100%;
`

function App() {
  return (
    <AppContainer>
      <Canvas>
        <Suspense fallback={<div>Loading...</div>}>
          <ambientLight intensity={0.5} />
          <mesh>
            <Stars />
            <OrbitControls />
            <sphereGeometry args={[2, 16, 16]} attach="geometry">
              <meshPhongMaterial color="red" attach="material" />
            </sphereGeometry>
          </mesh>
        </Suspense>
      </Canvas>
    </AppContainer>
  )
}

export default App
// index.js

import React from "react"
import ReactDOM from "react-dom"
import "./index.css"
import App from "./App"
import reportWebVitals from "./reportWebVitals"


ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById("root"),
)

reportWebVitals()

And if I change some index.css attributes,

/* index.css */

#root {
  width: 100vw;
  height: 100vh;
  margin: 0;
  padding: 0;
}

as above,

background color changed

background’s color has been changed.

But I wonder why this happens… why is it in grey color?

I can’t get the “length” of a search with match – Javascript

I’m new to Javascript but I’m starting to like it and I had an idea for a little system.
This system will be used to correct some words entered in an input, but if the word I want to correct appears more than once, I need to warn that it will not work correctly.

So I created a variable to search for the word and another to count its appearance but in the test I do, I keep getting the undefined error. What am I doing wrong?

function(){
    var text = document.getElementById('texto').value; //the input
    var duplo = text.match(/pq/ig);
    var testeduplo = (duplo.lenght);
    if (1 == 1){
    document.getElementById("demo").innerHTML = testeduplo ;}}

Thank you very much!

React Router v6 navigate to the homepage when logged in

I’m using Firebase v9 and react-router v6. I haven’t used v6 and now I’m confused as to how I can redirect the user to the homepage when logged in. Also, how can I make it where the guest user can only access the login page. Only users who were logged in can access the homepage and other pages.

import { auth } from "./Firebase/utils";

function App() {
  let navigate = useNavigate();
  const user = auth.currentUser;

  console.log(user);

  if (user) {
    // User is signed in, see docs for a list of available properties
    // https://firebase.google.com/docs/reference/js/firebase.User
    // ...
    navigate("/Homepage");
    console.log("logged");
  } else {
    // No user is signed in.
    console.log("2");
  }

  return (
    <div>
      <div>
        <Routes>
          <Route
            path="/"
            element={
              <Layout>
                <LogInPage />
              </Layout>
            }
          />

          <Route path="/Homepage" element={<Homepage />} />
          <Route path="/Profile" element={<Profile />} />
        </Routes>
      </div>
    </div>
  );
}

export default App;

This is what the console.log(user) shows:

enter image description here

Package.json file:

enter image description here