Get line of file content that contain a string

I wanted to get line content in a file that contains a string in discord js node.

Something like this:

If (file contains("string")){
console.log(line content)
}

like, if one of the lines in the file contains the string. It’s gonna send the line that contains the string to the console.

threejs how to load gltf model textures

hey guys i am new to threejs and i am trying to load my gltf models and their respectives textures using gltf models. i heard that gltf loaders automatically load the textures along with the models respectively, but that seems to be not the case here as it missed out the textures hence the errors any ideas how to solve this? thanks in advance

canglong_normal.png:1 GET http://127.0.0.1:5500/textures/canglong_normal.png 404 (Not Found)

canglong_metallicRoughness.png:1 GET http://127.0.0.1:5500/textures/canglong_metallicRoughness.png 404 (Not Found)

canglong_baseColor.png:1 GET http://127.0.0.1:5500/textures/canglong_baseColor.png 404 (Not Found)

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>3d model</title>
    <style>
      body {
        margin: 0;
      }
      canvas {
        position: fixed; top: 0; left: 0;

      }
      div#test2 {
  height: 5000px;
}
    </style>
  </head>
  

  <body>
    <script type="module">
        import * as THREE from 'https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js';
        
        import { OrbitControls } from 'https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/controls/OrbitControls.js';
        import { GLTFLoader } from 'https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/loaders/GLTFLoader.js';
        import { RGBELoader } from 'https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/loaders/RGBELoader.js';
        
        var container, controls;
        var camera, scene, renderer, mixer, clock;
        var obj , material , texture
        
        init();
        animate();
        
        function init() {
        
          container = document.getElementById( 'test' );
          document.body.appendChild( container );
          
          

          camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.01, 1000 );
        //   camera.position.set(0, 5, 30);
          camera.position.x = 0
          camera.position.y = 5
          camera.position.z = 10 


        
          scene = new THREE.Scene();
          scene.background = new THREE.Color(0xffffff);
          var light = new THREE.HemisphereLight(0xffffff,0x000000,10);
          scene.add(light);
    
         var texture = new THREE.MeshMatcapMaterial()

        //  var matcapTexture = new THREE.TextureLoader().load('purple.jpg')

        //  var texture = new THREE.MeshMatcapMaterial( {map: matcapTexture})

        //  console.log(texture)

        

          clock = new THREE.Clock();
        
              // model
          
              var loader = new GLTFLoader();
              loader.load( 'scene.gltf', function ( gltf ) {
                


                obj = scene.add( gltf.scene );
        
                mixer = new THREE.AnimationMixer( gltf.scene );
                
                gltf.animations.forEach( ( clip ) => {
                  
                    mixer.clipAction( clip ).play();
                  
                } );
        
              } );


        
        
          renderer = new THREE.WebGLRenderer( { antialias: true } );
          renderer.setPixelRatio( window.devicePixelRatio );
          renderer.setSize( window.innerWidth, window.innerHeight );
          renderer.toneMapping = THREE.ACESFilmicToneMapping;
          renderer.toneMappingExposure = 0.8;
          renderer.outputEncoding = THREE.sRGBEncoding;
          container.appendChild( renderer.domElement );
        

          function rotateFunction() {
        obj.rotation.y += 0.02;        
        console.log(obj.rotation.y)
        
      }

      document.addEventListener('scroll', function(e) { rotateFunction() });


        
        }
        function onWindowResize() {
          camera.aspect = window.innerWidth / window.innerHeight;
          camera.updateProjectionMatrix();
        
          renderer.setSize( window.innerWidth, window.innerHeight );
        }
        
        //
        
        function animate() {
          requestAnimationFrame( animate );
          var delta = clock.getDelta();
          if ( mixer ) mixer.update( delta );
          renderer.render( scene, camera );
        
        }

        function adjustCamera() {              
    var t = scrollY / (5000 - innerHeight);
    console.log(t)
    // t is 0 to 1

        camera.position.z = 10 + 5 * t;


        }

        document.addEventListener('scroll', function(e) { adjustCamera() });



        </script>
  </body>
  <div id="test">

  </div>

  <div id="test2">

    testing121

  </div>

</html>

Javascript hexadecimal to ASCII with latin extended symbols

I am getting a hexadecimal value of my string that looks like this:

String has letters with diacritics: č,š,ř, ...

Hexadecimal value of this string is:

0053007400720069006E006700200068006100730020006C0065007400740065007200730020007700690074006800200064006900610063007200690074006900630073003A0020010D002C00200161002C00200159002C0020002E002E002E

The problem is that when i try to convert this value back to ascii it poorly converts the č,š,ř,.. and returns symbol of little box with question mark in it instead of these symbols.

My code for converting hex to ascii:

function convertHexadecimal(hexx){

  let index = hexx.indexOf("~");
  let strInfo = hexx.substring(0, index+1);
  let strMessage = hexx.substring(index+1); 
  var hex  = strMessage.toString();
  var str = '';     
  for (var i = 0; i < hex.length; i += 2){     
      str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));     
  }
  console.log("Zpráva: " + str);
  var strFinal = strInfo + str;
  return strFinal; 
}

Can somebody help me with this?

How to check one of my object value is empty or not

I need to check my java object value is empty or not. And I need to check this one by one.
I crate my code to do this task…But I can’t check values one by one. If all of my object value is empty, my code is working…But it can’t check values one by one.

const coverDesc = action.data.coverDescriptionLocalization;

enter image description here

Methord 01- :-

 if (Object.values(coverDesc ).every((x) => x === null || x === '')) {
        console.log('Empty');
    } else {
        console.log('Not empty');
    }

Methord 02- :-

for (const key in coverDesc) {
    if (coverDesc.hasOwnProperty(key)) {
        if (Object.values(coverDesc[key]).every((x) => x === null || x === '')) {
           console.log('Empty');
        } else {
            console.log('Not empty');
        }
    }
}

Stripe Elements won’t load my custom font

I’m using this code to load a custom font for my Stripe card number element:

const elements = stripe.elements({
                    fonts: [
                        {
                            family: 'Avenir-Regular-Bold',
                
                            src: 'url('styles/AvenirNextLTPro-Bold.otf')'
                        }
                    ]
                });

And I’m getting this error about loading said font:

Access to font at ‘https://example.com/app/styles/AvenirNextLTPro-Bold.otf’ from origin ‘https://js.stripe.com’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

I have no idea what this means or why Stripe is saying this. Any way I can get my custom font to load?

HERE Maps JavaScript API: how to get info from click on cluster marker

Following these 2 docs:

https://developer.here.com/documentation/examples/maps-js/clustering/custom-cluster-theme

https://developer.here.com/documentation/maps/3.1.30.3/dev_guide/topics/clustering.html

I have a cluster of markers. But the target data from clicking on the cluster marker is different from that from clicking on the noise marker.

  1. How do I distinguish when I click on the cluster and when on the individual marker so that I can display correct info in a bubble?
  2. How do I stop the ridiculous zoom-in and zoom-out effect when clicking on a cluster marker? Because if the map is set to zoom 2 and the noise markers are on zoom 16, when you click on the cluster marker it starts zooming all the way from 2 to 16 and then straight back to 2 without even a chance of loading the maps. This is awful. How can I stop it?

Thank you.

is it possible to show the variable in closure when using google chrome to debugger

Today I found a google chrome an optimized strategy that make it could to show the closure variable when debugging. More details below:

But it is not convenient when using google chrome to debugging, is it possible to make it show the closure variable?

Why am I getting a JSON error and how do I fix it

I am trying got take the value that is inserted into the first and last name fields and then take that and insert it into a MySQL database backend that I have running using restAPI. I got some help to fix the form but I am trying to find the error when I try to take the input form the form and enter it in the database

The table code is this

  <div class="superhero">
    <h1>Lets add our first name </h1>
    <form action="/add_user" method="post">
        <input type = "text" firstname = "firstname">
    <h1>Lets add our last name </h1>
    <form action="/add_user" method="post">
        <input type = "text" lastname = "lastname">
        <input type="submit" class="btn btn-primary">
    </form>

Then this is taken into the nodeJS server with this command

app.post('/add_people', function(req, res){
    axios.get('http://127.0.0.1:5000/api/adduser')
    .then((response)=>{
        var restlist = response.data.results;
        console.log(restlist);
// Now we will execute the results in the page named thanks
    });
});

Then at the end it is going to be taken to the RestAPI with that is using this route

@app.route('/api/adduser', methods = ['POST']) # This is a post method because the user needs to be able to add info
def adding_stuff():
    request_data = request.get_json() # Gets the info from the table and converts to JSON format
    new_fname = request_data['firstname']
    new_lname = request_data['lastname']
    conn = create_connection("", "", "", "")
    sql = "INSERT INTO restaurantusers (firstname, lastname) VALUES ('%s', '%s');" % (new_fname, new_lname) # This sql statement will then be uploaded to the databse to add a new record
    execute_query(conn, sql) # This will execute the query
    return 'Post worked'

Sorry if what I am asking sounds really complicated. Professor goes too fast in class and I’ve been trying to find out how to do this for sometime with no luck.

UDATE: I later changed the two items as suggested. The route is

app.post('/add_people', function(req, res){
    axios.post('http://127.0.0.1:5000/api/adduser')
    .then((response)=>{
        var restlist = response.data.results;
        console.log(restlist);
// Now we will execute the results in the page named thanks
    });
});

and the form is now

        <form action="/add_people" method="post">
            <input type = "text" firstname = "firstname">
        <h1>Lets add our last name </h1>
            <input type = "text" lastname = "lastname">
            <input type="submit" class="btn btn-primary">
        </form>

I get the error that

  },
  isAxiosError: true,
  toJSON: [Function: toJSON]
}

and also this error on the restAPI window

TypeError: 'NoneType' object is not subscriptable

Trying to show exact mount of days when select specific month

I was trying to create a form to select month and day. I want dynamically add the exact amount of days when a specific month is selected. But only the January, February, and April of months are selectable after running the switch statement. Can anyone pls help me?

html:

<select id="months" name="months">
            <option value='31'> January </option>
            <option value='28'> February </option>
            <option value='31'> March </option>
            <option value='30'> April </option>
            <option value='31'> May </option>
            <option value='30'> June </option>
            <option value='31'> July </option>
            <option value='31'> August </option>
            <option value='30'> September </option>
            <option value='31'> October </option>
            <option value='30'> November </option>
            <option value='31'> December </option>
        </select>

        <select id="days" name="days"></select>

js:

const $months = document.getElementById('months')

function dayOfMonthOne() {
    for (let i = 1; i < 32; i++) {
        const days = `
        <option>${i}</option>
        `
        const $days = document.getElementById('days')
        $days.innerHTML = $days.innerHTML + days
    }
}

function dayOfMonthZero() {
    for (let i = 1; i < 31; i++) {
        const days = `
        <option>${i}</option>
        `
        const $days = document.getElementById('days')
        $days.innerHTML = $days.innerHTML + days
    }
}

function dayOfMonthTwo() {
    for (let i = 1; i < 29; i++) {
        const days = `
        <option>${i}</option>
        `
        const $days = document.getElementById('days')
        $days.innerHTML = $days.innerHTML + days
    }
}

$months.addEventListener('change', function(){
    switch ($months.value) {
        case '31':
            $months.value = '31'
            dayOfMonthOne()
            break
        case '30':
            $months.value = '30'
            dayOfMonthZero()
            break
        case '28':
            $months.value = '28'
            dayOfMonthTwo()
            break
    }
})

Advantage of mapping with a async binding vs a concrete object in Angular?

Is there any advantage or benefit to using a async binding vs just mapping to a concrete object when my service call returns with data for my HTML page?

Here is an example of the two options.

  1. Map to a concrete object
// component
event: any;

// ngOnInit()
this.eventService.getEvent(this.id).pipe(take(1)).subscribe(response => {
  this.event = response;
}, error => {
  console.log(error);
});

// service
getEvent(id: number): Observable<any> {
  return this.http.get<any>(this.baseUrl + 'events/' + id);
}
<div>{{event.title}}</div>
<div>{{event.date}}</div>
  1. map to a async binding
// component
event$: Observable<any> = of (undefined);

// ngOnInit
this.event$ = this.eventService.getEvent(this.id).pipe(take(1),
  catchError(error => {
    console.log(error);
    return throwError(error);
  }));

// service
getEvent(id: number): Observable<any> {
  return this.http.get<any>(this.baseUrl + 'events/' + id);
}
<div>{{(event$ | async).title}}</div>
<div>{{(event$ | async).date}}</div>

Write after end error when launch server in nodejs

I am beginner at NodeJS and Im doing a “NodeJS and Express.js full course” at freecodecamp yt and I copied author code wich for him works perfectly but I got an error.

Code:


  const server = http.createServer((req, res)=> {
if(req.url === '/') {
  res.end('Home Page')
}
if(req.url === '/about') {
 res.end('About us')
}
res.end('Error')
})

server.listen(3000, ()=>{
  console.log('Server listening...');
})

Idk why He got home, about and error page when user go to wrong page it should throw “Error” text on page, but instead my program is throwing an error in nodeJS program:


events.js:377
    throw er; // Unhandled 'error' event
     ^

Error [ERR_STREAM_WRITE_AFTER_END]: write after end
    at new NodeError (internal/errors.js:322:7)
    at writeAfterEnd (_http_outgoing.js:694:15)
    at ServerResponse.end (_http_outgoing.js:815:7)
    at Server.<anonymous> (C:UsersjonatDesktopnodejsapp.js:10:5)
    at Server.emit (events.js:400:28)
    at parserOnIncoming (_http_server.js:900:12)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:127:17)
Emitted 'error' event on ServerResponse instance at:
    at writeAfterEndNT (_http_outgoing.js:753:7) 
  at processTicksAndRejections (internal/process/task_queues.js:83:21) {
  code: 'ERR_STREAM_WRITE_AFTER_END'
}

Can someone explain this to me? I would be appreciate. Thank you in advance.

How to do update in AWS Dynamo DB using NodeJS

I have written this function to do update in dynamo table

const updateTask = async (req, res) => {
  try {
    const { existingTaskText,updatedTaskText } = req.body;
    console.log(existingTaskText,updatedTaskText );
    UPDATE({
      TableName: "todos",
      Key:{ task: existingTaskText},
      UpdateExpression:"set task = :task",
      ExpressionAttributeValues: {":task": updatedTaskText},
    });
    res.status(200).json({ data: "this is controller" });
  } catch (error) {
    res.status(400).json({ message: error.message });
  }
};

this is calling UPDATE

const UPDATE = async (payload) => {
  try {
    console.log(payload);
    const updateDoc = await dbClient
      .update({
        TableName: payload.TableName,
        Key: payload.Key,
        UpdateExpression: payload.UpdateExpression,
        ExpressionAttributeNames:payload.ExpressionAttributeNames,
        ReturnValues: "UPDATED_NEW",
      })
      .promise();
    console.log(updateDoc);
  } catch (error) {
    console.log(error);
  }
};

When I am testing this in postman, I am getting this error

ValidationException: Invalid UpdateExpression: An expression attribute value used in expression is not defined; attribute value: :task

this is payload log getting passed

{
  TableName: 'todos',
  Key: { task: 'see its  done' },
  UpdateExpression: 'set task = :task',
  ExpressionAttributeValues: { ':task': 'edited' }
}

Clickable date in full calendar

I am a beginner I downloaded full calendar 5.10.1 from fullcalendar.io. Here’s what I want to do. If I click on any date, it will go to my registration.html.

Here is calendar script:

document.addEventListener(‘DOMContentLoaded’, function() {
var calendarEl = document.getElementById(‘calendar’);
var calendar = new FullCalendar.Calendar(calendarEl, {
initialView: ‘dayGridMonth’
});
calendar.render();
});

Here is registration form:

    <fieldset>
      <legend>For person</legend>
      <label>
        Name
        <input type="text" name="name" required>
      </label>
      <div class="two-cols">
        <label>
          Email address
          <input type="email" name="email" required>
        </label>
        <label>
          Phone number
          <input type="tel" name="phone">
        </label>
      </div>
    </fieldset>

    <fieldset>
      <legend>Appointment request</legend>
      <div class="two-cols">
        <label>
          Datum
          <input type="date" name="Appointment request" required>
        </label>
        <div class="inline">
          <label>
            <input type="hidden" name="Morning desired" value="no">
            <input type="checkbox" name="Morning desired" value="yes">
            Morning
          </label>
          <label>
            <input type="hidden" name="Afternoon desired" value="no">
            <input type="checkbox" name="Afternoon desired" value="yes">
            Afternoon
          </label>
        </div>
      </div>
      <p>Confirmation requested by</p>
      <div class="inline">
        <label>
          <input type="radio" name="Confirmation requested by" value="email" checked>
          Email
        </label>
        <label>
          <input type="radio" name="Confirmation requested by" value="phone">
          Phone call
        </label>
      </div>
    </fieldset>
    
    <div class="btns">
      <input type="text" name="_gotcha" value="" style="display:none;">
      <input type="submit" value="Submit request">
    </div>

  </form>