How do I scrape links from a website using cheerio?

I’m trying to do some web scrapping, I’m trying to get the link of some articles, but I can’t seem to hit the links. This is my code:

app.get('/test', (req, res) => {

    var articles = []

    axios.get("https://www.transfermarkt.com/rumour/rubrik/aktuell/18")
        .then(response => {
            const $ = cheerio.load(response.data)

            $("div.newsticker__box").each( (i, element) => {
                const link = $(element)
                    .find("a.newsticker__link")
                    .attr("href");

                    articles.push({
                        link
                    })
                console.log(link)
            })
        })
    res.json(articles)
})

When I try to just return response.data I get just lots of symbols like this:

"u001f�bu0000u0000u0000u0000u0000u0000u0003�y�H�(��̧��{��u0014v��"!��U]H�u0002�#��c��Њu0016$���_Jl��ն���}�7�vu0019edfDFƖ�����G�7�߭&dW׾��u001c�Ihcc^I�F��?

What am I doing wrong here?

VueJs get json from file and wait for response

I am new to VueJS with limited knowledge of Javascript, trying to do something I thought would be incredibly simple and commonplace.
Here is a simplified version of the code that demonstrates the problem:

export default {

    template: `
        
        <br><br>
        
        testData:
        
        <br>
        
        {{ testData }}
        
        <br><br>
        
        <button @click="getData()">Get Data</button>
        
    `,

    data() {
        return {
            testData: []
        }
    },

    methods: {

        getData() {

            fetch('json.txt', {method: 'GET'})
                .then(response => response.json())
                .then((data) => {
                    this.testData = data;
                });

            this.doSomethingWithData()

        },

        doSomethingWithData() {
            alert(this.testData[1]);
        }

    }

}

The json.txt file contains :

["one","two","three"]

The problem here is that when you click the button, calling the getData() method, it doesn’t do things in the order in the code, instead it gets the json data after doing everything else, causing this.testData[1] in the next method to return ‘undefined’ instead of ‘two’.

This must be something to do with Javascript await, promise asynchronious somethingorother, which I have yet to learn about, but how do you get the code to wait for the data from the text file before proceeding to the next bit of code. (I have spent hours on StackOverflow and elsewhere trying many variations of the code above without success.)

The equivalent in PHP is just this simple line of code:

$testData = json_decode(file_get_contents('json.txt'), true);

Many thanks in advance !

https://dog.ceo/api Trouble accessing API other than on endpoints. Need to extract data and convert to CSV

Hi I am working on a project where I need to take the api https://dog.ceo/api. Extract data for Breeds, sub breeds and images and output them to a 3 column CSV file. I have tried hitting the API as a whole and continue to get CORS errors but I am able to freely hit the endpoints which seem to be able to give me sufficient data. I really am not sure how to proceed. This is what I have so far and I feel like im on the right path but also unable to figure out what I need to do next.

fetch('https://dog.ceo/api/breeds/list/all')
  .then(res => res.json())
  .then(data => handle(data))
  .catch(error => console.log('Error'));

function handle(inputData) {
  const headers = ['Breed', 'Sub_Breed', 'Image'];
  console.log(inputData);

  const main = inputData.map(item => {
    return item.toString();
  });
  console.log(main);
}

I am able to console log all of the breeds / sub breeds from inputData but it comes from the object “message:”. I am usually good at figuring things out but I cannot for the life of me figure out what I need to do here. This is a simple web application I built and view in the browser. It is a personal project so I am not necessarily working from any server, just html, CSS, JS files. Any tips or push in the right direction are much appreciated.

I have tried to hit the API as a whole because instructions for that are much clearer, but at the moment I am only able to hit specific endpoints for data. Unsure what I need to do to get this to work the way I need to. the API site is https://dog.ceo/dog-api/

Upload and save image ReactJs

Can i upload image and save it in my project directory?

input for upload images

<div class="tab">
          <input type="radio" name="css-tabs" id="tab-3" class="tab-switch" />
              <div class="tab-content"> 
               <label><span>Images <span class="required">*</span></span><br></br>  
               <input id="file" type="file" multiple onChange={fileSelectedHandler} name="images" value={files} /></label>
              <input type="submit" onClick={handleClick} value="Add message"  class="submitButton"/>
          </div>
     </div>

`
I can upload images, but how can i save it in directory folder?
Thanks!

How should I pass data to the component after routing?

How can I pass the data from the BookList to the Book component after routing and then print it?
I’m trying to use the state but I’m not sure if that’s the right approach, please suggest to me how it should be done correctly.

BookList.js

import React from "react";
import { Link } from "react-router-dom";

const BookList = () => {
  return (
    <>
      <Link
        to={{
          pathname: "/books/1",
          state: {
            id: 1,
            title: "The Hobbit",
            description: "A hobbit goes on an adventure",
          },
        }}
      >
        Book 1
      </Link>
    </>
  );
};

export default BookList;

Book.js

import React from "react";

const Book = () => {
  return (
    <div>
      <h1>Book</h1>
    </div>
  );
};

export default Book;

Angular reactive form display input error validation based on dropdown selected

i am learning reactive forms in angular and i am building heat index calculator that takes temperature input and humidity input and it calculates feels like temperature. From dropdown user can choose either celsius or fahrenheit. It cant be calculated for temperatures lower than 26 celsius or 80fahrenheit. Right now the validation only works if user has selected celsius and input number lower than 26 the error shows but not when fahrenheit selected. Any help appreciated

this is html

<form [formGroup]="heatIndexForm" class="wrapper" (ngSubmit)="onSubmit()">
    <label class="temperature-row">
      <p class="temperature-input">Air Temperature</p>
      <div class="field col-12 md:col-4">
        <p-inputNumber
        [style]="{'height': '51px'}"
        formControlName="temperature"
        mode="decimal"
        class="form-control">
      </p-inputNumber>
      <div *ngIf="heatIndexForm.get('selectedTemp').value.code === 'C' && !heatIndexForm.get('temperature').valid" >Temperature must be above 26&deg;C</div>
    </div>
      <p-dropdown
      class="form-control"
      [style]="{'height':'51px', 'paddingTop': '5px', 'marginLeft': '5px'}"
      formControlName="selectedTemp"
      (onChange)="reset();" [options]="temps"
      optionLabel="units"></p-dropdown>
    </label>
    <div class="humidity-row">
      <p class="humidity-input">Relative Humidity</p>
      <p-inputNumber mode="decimal"formControlName="humidity" class="form-control"></p-inputNumber>
      <p class="percent">%</p>
    </div>
    <div class="buttons">
      <button
      class="form-control"
      [disabled]="(!heatIndexForm.get('temperature').valid || !heatIndexForm.get('humidity').valid)"
       pButton
       label="Calculate"></button>
      <p-button label="Reset" (onClick)="reset()"></p-button>
    </div>
  </form>

this is ts

export class HeatIndexComponent implements OnInit {
  haveResult: boolean = false;
  temps: Temperature[];
  selectedTemp: Temperature;
  heatIndexForm: FormGroup;

  constructor(private heatIndexService: HeatIndexService) {
    this.temps = [
      {
        units: 'Celsius',
        code: 'C',
      },
      {
        units: 'Fahrenheit',
        code: 'F',
      },
    ];
  }

  ngOnInit(): void {
    this.heatIndexForm = new FormGroup({
      temperature: new FormControl(null, Validators.min(26)),
      humidity: new FormControl(null, Validators.max(100)),
      selectedTemp: new FormControl({ code: 'C' }),
      result: new FormControl(''),
      resultComment: new FormControl(''),
    });
  }

  calculateHeatIndex() {
    const temperature = this.heatIndexForm.get('temperature').value;
    const humidity = this.heatIndexForm.get('humidity').value;
    this.haveResult = true;
    if (this.heatIndexForm.get('selectedTemp').value.code === 'C') {
      this.heatIndexForm
        .get('result')
        .setValue(
          this.heatIndexService.calculateHeatIndexInCelsius(
            temperature,
            humidity
          )
        );
      this.heatIndexForm
        .get('resultComment')
        .setValue(
          this.heatIndexService.determineCommentWhenInCelsius(
            this.heatIndexForm.get('result').value
          )
        );
    } else {
      this.heatIndexForm
        .get('result')
        .setValue(
          this.heatIndexService.calculateHeatIndexInFahrenheit(
            temperature,
            humidity
          )
        );
      this.heatIndexForm
        .get('resultComment')
        .setValue(
          this.heatIndexService.determineCommentWhenInFahrenheit(
            this.heatIndexForm.get('result').value
          )
        );
    }
  }

  reset() {
    this.haveResult = false;
    this.heatIndexForm.get('temperature').reset();
    this.heatIndexForm.get('humidity').reset();
  }

  onSubmit() {
    this.calculateHeatIndex();
  }
}

i tried adding this to html but didnt work

      <div *ngIf="heatIndexForm.get('selectedTemp').value.code === 'F' && !heatIndexForm.get('temperature').valid" >Temperature must be above 80&deg;F</div>

Tab duplication in Chrome shares the same process for both tabs

In the latest Google Chrome Version 108.0.5359.95 (Official Build) (64-bit) with default settings, I observe that making new tab

New tab

always starts new process (even if I open same site as in another tab).

But if an existing tab is duplicated:

Duplicate tab

then both new and old tabs share the same process. It can be observed both in operating system and Chrome Task Manager (opened by Shift+Esc):

one process for two tabs

The latter scenario – two tabs in one process – produces some weird errors for my site, which uses WASM multi-threading and 3D rendering. For example after duplication, the original tab finishes with an error in an WebGL shader, which never happens if the tab owns uniquely a process.

Is there a way to make Chrome duplicate a tab with my site by always creating a new process?

Splitting nested arrays [duplicate]

I would like to split nested arrays into groups of 3 (in javascript):

e.g.

let array = [[123],[456],[789],[321],[654],[987]];

I would like split this into a new nested array, i.e.

new_array = [
              [
                [123],[456],[789]
              ]
              [
                [321],[654],[987]
              ]
            ]
let array = [[123],[456],[789],[321],[654],[987]];

let new_arr = [];
for (i=0; i<array.length; i+2){
    new_arr.push(array[i]);
    i++;
    new_arr.push(array[i]);
    i++;
}

When I log this out to the console, there is no grouping, it just added all the nested array to a new array.

How do I create a function that reverses an array in JavaScript?

I tried with the following code but when I run it the function is not shown reversed although the number I chose is even:

const myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const number = 32;

const myReversedArray = number => {
  if (number % 2 === 0) {
    return myArray.reverse();
  } else {
    return myArray;
  }
}

console.log(myReversedArray());

I expected the function to be shown in reverse since the number I chose is even, but instead it is shown in the normal order (1, 2, 3, 4, 5, 6, 7, 8, 9, 10).

Lodash : how to do a Non-ASCII characters sorting on a collection using orderBy?

I need to sort an multidimentional array with Non-ASCII characters and multiple objects.

tried this but doesn’t worked

const users = [
  { name: 'A', age: 48 },
  { name: 'B', age: 34 },
  { name: 'á', age: 40 },
  { name: 'b', age: 36 }
]

const nameLocale = users.sort((a, b) => (a.name.localeCompare(b.name)));

const sortedUsers = _.orderBy(users, [nameLocale, 'age'], ['asc', 'asc'])

the sorted array i need would be like this:

   { name: 'á', age: 40 }
   { name: 'A', age: 48 },
   { name: 'B', age: 34 },
   { name: 'b', age: 36 }

but the responde i got is this:

[
  { name: 'B', age: 34 },
  { name: 'b', age: 36 },
  { name: 'á', age: 40 },
  { name: 'A', age: 48 }
]

Javascript function [duplicate]

I’m trying to learn javascript here and I have an assignment, I have to: ”Write the makeStickers function that accepts the detailsCount integer and the robotPart string. The function returns an array of strings in the following format: {{robotPart}} detail #{{n}} (for example, Hand detail #1).

For example:

makeStickers(3, ‘Body’); // [‘Body detail #1’, ‘Body detail #2’, ‘Body detail #3’]
makeStickers(4, ‘Head’); // [‘Head detail #1’, ‘Head detail #2’, ‘Head detail #3’, ‘Head detail #4’]
makeStickers(0, ‘Foot’); // []”

function makeStickers(detailsCount, robotPart) {
  // write code here
}

I wrote the following function, but for some reason it always gives me just robot part #2, without any other iteration. Please help.

function makeStickers(detailsCount, robotPart) {

  let arr = [];

  for(let i = 1; i <= detailsCount; i++){
    arr = [`${robotPart} detail #${arr.push(i)}`]
  };
  return arr
};  

Массив в JS работает не корректно [closed]

It is necessary to display unaccounted arrays of elements with a margin of 0, the rest remain as they are

`

a = [3,-5,8,14,6,-3,12,-5];
newArray = []
c = a.forEach((element,index) => {
    newArray = (index % 2 == 0);
    newArray.push(element - element)
    return newArray
});
console.log(newArray); //NOT WORK!!!

`

I don’t understand why this program doesn’t work

Having Problem Displaying Data In Jquery Datatables using PHP

This is HTML code:

<div class="container">
  <h5 style="text-align: center">Registered Records</h5>
  <table id="spam_site_contributions">
   <thead>
    <tr>
      <th>Id</th>
      <th>Contribution</th>
      <th>Contribution Date</th>
      <th>Review Status</th>
    </tr>
   </thead>
  </table>
</div>

This is my Js code:

 $('#spam_site_contributions').DataTable({
    processing: true,
    serverSide: true,
    ajax: '../SPR/backend/get_User_Contrib_Spam_Sites.php',
});

This is my Php code:

 $data['index'] = array($nresults_arr);
 $data['c'] = array($contrib_arr);
 $data['cd'] = array($contrib_date_arr);
 $data['review'] = array($review_arr);
     
 echo json_encode($data); // Array of arrays

There is no error in Php part because it sends the correct response.
The problem is with the datatable not showing up the data.
I’m quite new to jQuery datatables. Tried many solutions but none of them worked.Any help will be of great pleasure. Thanks in advance.

Lifetime of JavaScript objects created inside functions

Ok, I’m totally new to JS and I’m not sure if it’s a right question to ask.

Assume that I have a HTML list <ul> and I add <li> items dynamically with JS. So the list becomes like this:

<ul id="parent">
  <li> //container
  Some text <button>Delete</button>
  </li>
</ul>

Here the <button> is used to delete the <li> using JS. I created a class with a delete() method to delete the <li> when the button is clicked:

class MyObj{
    constructor(parent, container) {
        this.parent = parent ;
        this.container= container;
    }

    delete() {
        this.parent.removeChild(this.container);
    }
}

And this is the function that is used to create <li> elements:

function create() {

    let container = document.createElement('li');
    let deleteContainerBtn = document.createElement('button');

    container.innerHTML = "Sometext";
    container.appendChild(deleteContainerBtn);
    parent.appendChild(container);
    
    const obj= new MyObj(parent, container, deleteContainerBtn);
    deleteContainerBtn.onclick = function() {obj.delete()};
};

This works fine (I add <li> containers with function create() as many as I want and they can be deleted when I click their Delete buttons). How?
When function create() is done executing, isn’t obj supposed to be deleted? How does it perform the delete() method if it is deleted?