How to modify google chart?

Hello i just realised my google chart but i’d like to modify it.

  1. i’d like to change the date display i would like something more readable.
  2. i d like to reverse the chart
  3. i d like to /10 wind speed

Can you help me ?
Thanks.

graphique last 24 h

<script type="text/javascript">
  google.charts.load('current', {'packages':['corechart']});
  google.charts.setOnLoadCallback(graph24h);

  function graph24h() {
    var data = google.visualization.arrayToDataTable([
      ['Date', 'Température', 'Vent Moyen', 'Humidité'],


      <?php 
           $chartQuery = "SELECT * FROM ZiMeteo ORDER BY ID DESC LIMIT 144";
           $chartQueryRecords = mysqli_query($connect, $chartQuery);
                while ($row = mysqli_fetch_assoc($chartQueryRecords)) {
                     echo "['".$row['Date']."',".$row['TmpExt'].",".$row['Vents'].",".$row['HumExt']."],";
                }
       ?>
       ]);

    var options = {
      title: 'Evolution sur 24 h',
      
      legend: { position: 'bottom' }
    };

    var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));

    chart.draw(data, options);
  }

How to get and return each last character of array to be in uppercase using javascript?

I have the following array variable, I want to return the given array where each of element’s last character to be in Uppercase using javascript, I have tried like below, but I am getting undefined unfortunately, Could you please anyone help me to get the desired output like below. Thanks in advance.

Desired Output: [onE, twO, threE, fouR]

var arr = ['one', 'two', 'three', 'four'];

var res = arr.map((item) => {
    item.substr(arr.length) + item.charAt(arr.length -1).toUpperCase();
});
console.log(res);//[undefined, undefined, undefined, undefined]

Understanding of functional reduction

There are a few examples in this functional programing book about equivalency between different functions. For example, if my understanding is correct it means:

func(param => otherFunc(param))
func(otherFunc)                   // simplified

And, if I can articulate it in words to the best of my ability, I would say:

A function that takes a certain number of parameters and then only
returns a second function called with those parameters as arguments
is the same as a function that just takes the second function as a single parameter.

Is this a correct understanding? What would be some examples that would show how this would work? The only ones I can think of myself so far are quite trivial, so I’d like to see if I can see more examples to deepen my understanding of some applications of this.

How to allow custom styles with uppercase in TinyMCE?

This is the only question I’ve found similar to mine even so it is not 100% clear as the solution seems to be static for that key and it’s not explained very well: How to extend the tinymce validation rules for the style tag?

Right now I’m using TinyMCE in my project and the problem is when I have for example an inline style like:

style="height: 12mm; border: solid white 3px; background-color: [Category.FieldNumber01]

The background changes all to lowercase, this happens with any custom style I want to use that has uppercase:

background-color: [category.fieldnumber01]

Is there a way that might be on the configuration o a function to make TinyMCE ignore style uppercases?

Problem with XML HttpRequest and bootstrap modal

I’m filling bootstrap cards with an external json file via XML HttpRequest. This works, all information is shown in the cards.
Now I would like to press “More info” to open a bootstrap modal with more information about the item.

The problem is when I press “More info” the data of the first item1 is always taken.
I know that the solution is that I have to pass the id of the elements to the modal, so that the correct data of the elements can be retrieved.

But I don’t understand how I can pass the id of an item to the modal?

JSON File

[{
    "id": 1,
    "name": "item1",
    "price": "€5",
    "size": "XS",
    "color": "Green"
}, {
    "id": 2,
    "name": "item2",
    "price": "€10",
    "size": "S",
    "color": "Yellow"
}, {
    "id": 3,
    "name": "item3",
    "price": "€15",
    "size": "M",
    "color": "Blue"
}, {
    "id": 4,
    "name": "item4",
    "price": "€20",
    "size": "L",
    "color": "Red"
}, {
    "id": 5,
    "name": "item5",
    "price": "€25",
    "size": "XL",
    "color": "Gray"
}, {
    "id": 6,
    "name": "item6",
    "price": "€30",
    "size": "XXL",
    "color": "Black"
}] 

JS script of my program

<script>
    const divRes = document.querySelector('#divResult');

    myRequest = () => {
        let xhr = new XMLHttpRequest();
        xhr.open('GET', 'files/elements.json', true);
        xhr.send();
        xhr.onload = function() {
            if (xhr.readyState === xhr.DONE) {
                if (xhr.status != 200) {
                    divRes.innerHTML = `Error ${xhr.status}: ${xhr.statusText}`;
                } else {
                    const arrResponse = JSON.parse(xhr.responseText);
                    divRes.innerHTML = createHTMLCard(arrResponse);
                }
            }
        };

        xhr.onerror = function() {
            divRes.innerHTML = "Request failed";
        };
    }

    createHTMLCard = (arrObj) => {
        let res = '';

        for (let i = 0; i < arrObj.length; i++) {
            res +=
                `<div class="col-lg-4 col-md-6 col-sm-12">
                        <div class="card m-2">
                            <div class="card-body">
                                <h5 class="card-title">${arrObj[i].name}</h5>
                                <p><strong>Prijs:</strong> ${arrObj[i].price}</p>
                                <button id="moreInfo" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">More info</button>
                            </div>
                        </div>
                 </div>



                 <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
                        <div class="modal-dialog modal-dialog-scrollable">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title" id="exampleModalLabel">${arrObj[i].name}</h5>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                </div>
                                <div class="modal-body">
                                    <p><strong>Price:</strong> ${arrObj[i].price}</p>
                                    <p><strong>Size:</strong> ${arrObj[i].size}</p>
                                    <p><strong>Color:</strong> ${arrObj[i].color}</p>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                </div>
                            </div>
                        </div>
                 </div>`;
        }
        return res;
    }

    window.addEventListener('load', myRequest);
</script>

Bootstrap cards

Bootstrap modal

property data of type Object is unreadable with ngFor

Angualr does not recognise the property data (dummy data from an API), i get the following error:
Property ‘data’ does not exist on type ‘Object’

I tried removing the data property and just use “let user of users” but it gives me the following error on of : Type ‘Object’ is not assignable to type ‘NgIterable | null | undefined’

my HTML component

<h1>Home</h1>
 
<ul *ngIf="users">
  <li value="user" *ngFor="let user of users.data"> 
    <img [src]="user.avatar">
    <p>{{ user.first_name }} {{ user.last_name }}</p>
  </li>
</ul>

the ts component :

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

  users: Object;

  constructor(private data: DataService) { 
  }

  ngOnInit() {
    this.data.getUsers().subscribe(data => {
      this.users = data
      console.log(this.users)
    })
  }
}

the Dataservice ts component:

import { Injectable } from '@angular/core';
import { HttpClient, HttpClientModule } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class DataService {

  constructor(public http: HttpClient) { }

  getUsers() {
    return this.http.get('https://reqres.in/api/users')
  }
}

Angular – window – EventListener – refresh main tab when other close

I use Angular 7. I deal with documents When I click on “INDEXER” button, a second tab is opened with content of the first document and a form.
When the form is filled, the second document appears on this second tab etc…
When all the documents are ok, this second tab close and and the first main tab must be refreshed.

enter image description here

Code for second tab :

iterate(index) {
this.loadingAction = false;
if (index < this.workflowList.length) {
  this.getDetails(this.workflowList[index]);
} else {
  localStorage.setItem('actualise', 'true');
  window.close();
}
 }

Code for the first tab

 ngOnInit() {
const that = this;

// COMMUNICATION INTER ONGLETS
window.addEventListener('storage', (event) => {
  console.log(event.key)
  // console.log('event storage = LocaleStorage : ' + event.storageArea !== localStorage);
  if (event.storageArea !== localStorage) {
    return;
  }
   if (event.key === 'actualise') {
   // if (event.storageArea.getItem('actualise') === 'true') {
     console.log('appel backend')
     this.refresh();
  } else {
     console.log(localStorage.getItem('actualise'));
   }
});
}

Problem is that backend is called multiple times and when there are a lot of documents, it’s very long.

I updated code in order the backend is called one time, it works but the screen is not refreshed

Original : Backend called multiple time and screen refresh

enter image description here

Update: backend called one time but screen is not refreshed

enter image description here

How can I solve that ?

Remove control characters from UNIX Domain Socket

i have a problem with docker exec command output, when i try to run (with got)

 const output = await client.runCommand([
      "cat -v ./tmp/schema.json"
  ]); 

Where runCommand return a stream with docker socket of exec command

    return new Promise((resolve, reject) => {
      let chunks = [];

      stream.on("data", (chunk) => { 
        let output = chunk.toString();
        chunks.push(output);
      });

      stream.on("error", (err) => reject(err));
      stream.on("end", () => resolve(chunks.join("")));
    });

but when i parse with json parse the result of this promise i receive this control characters

screen

is possible to remove this control characters from the chunks?

threejs gltf loader not defined

i want to use gltf loader. but i get gltf laoder not defined error, want to use orbitcontrols get same error taht they arenot defined.

<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/three.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/examples/js/controls/OrbitControls.min.js"></script>
    <script src="https://cdn.rawgit.com/mrdoob/three.js/master/examples/js/loaders/GLTFLoader.js"></script>

this is me trying to import all of them .

function loadGLTF() {
        let balloonLoader = new THREE.GLTFLoader();

        balloonLoader.load('./model/esa.gltf', (gltf) => {
            Mesh = gltf.scene;
            Mesh.scale.set(0.2,0.2,0.2);
            scene.add(Mesh);
            Mesh.position.x = 0;
            Mesh.position.y = 10.5;
            Mesh.position.z = 17;
        });
    }

this is how i try to use gltf loader. what is wrong with the code could you tell me?

and even better would be if someone could finally explain how to properly import threejs.

How to check if table cell data has a link, avoiding TypeError: Cannot read properties of null (reading ‘href’) using JS?

I’m trying to get the data from an HTML table, but it keeps giving me this error TypeError: Cannot read properties of null (reading 'href') when one of the rows in col 5 doesn’t come with a link.

I’ve tried both c.getAttribute('href') and c.querySelector('a').href but I get the same error.

function updateAllTasks() {
  var table = document.getElementById("dtable");
  var [, ...tr] = table.querySelectorAll("tr");
  var tableData = [...tr].map(r => {
  var td = r.querySelectorAll("td");
  return [...td].map((c, j) => j == 3 ? c.innerHTML.toString() : j == 4 && c.innerHTML != '' ?  c.getAttribute('href') : j == 8 ? c.querySelectorAll('input[name="rowcheckbox"]')[0].checked : c.innerHTML);
  })
  const finalDataset = tableData.map(e => [e[0], e[1], e[8]]);
  google.script.run.updateAllClientsTasks(finalDataset);
}

Thank you!

object freeze does not freeze the object when it is assigned to a new object

I have 2 questions here:-

  1. Why obj2 = 5; is not throwing the error?

  2. If I wish to throw during assignment obj2 = 5; what should I do? Considering obj2 is var or let.

"use strict"

function deepFreeze(object) {
    // Retrieve the property names defined on object
    const propNames = Object.getOwnPropertyNames(object);
  
    // Freeze properties before freezing self
  
    for (const name of propNames) {
      const value = object[name];
  
      if (value && typeof value === "object") {
        deepFreeze(value);
      }
    }
  
    return Object.freeze(object);
  }
  
  let obj2 = {
    internal: {
      a: null
    }
  };
  
  deepFreeze(obj2);
  
//   obj2.internal.a = 'anotherValue'; // fails silently in non-strict mode
//   obj2.internal.a; // null

obj2 = 5; // I want to throw error in this case but it is not throwing error. 

package.json exports and multiple type declaration file

I am trying build a TypeScript library and want to export using exports field in package.json.

From nodejs and webpack’s documentation, I saw that exports is the recommended way to export modules.

https://nodejs.org/api/packages.html#package-entry-points

https://webpack.js.org/guides/package-exports/

The old way is to use “main”, “types” and “module”.

How can I export type declaration using this method?
Should I keep using the “types” field? But what if I have multiple exports?

Here is a sample of exports I have

"exports": {
    ".": {
      "import": "./dist/A.mjs",
      "require": "./dist/A.js"
    },
    "./A": {
      "import": "./dist/A.mjs",
      "require": "./dist/A.js"
    },
    "./B": {
      "import": "./dist/B.mjs",
      "require": "./dist/B.js"
    }
  }

Onclick, Highlight only one list item in an Unordered list. Javascript

Iam following a code to make a quiz.Iam building a function to highlight one list item and add a class to it.

enter code here
function chooseAnswer(){
    answer.querySelectorAll('li').forEach((option)=> { 
    option.addEventListener('click',()=>{
        if(answer.querySelector('.selected')){
            let activeAnswer=answer.querySelector('.selected');
            activeAnswer.classList.remove('selected') 
        }else
        option.classList.add('selected')
})

The code is working but i do not understand the if condition from the source. Can someone help?

hexToHsl typescript function

iam making a javascript library called functionality and iam wondering how to make hexToHsl function with typescript i had serched a lot but all i have got is in js and can not convert to typescript
what i have found in js.

function hexToHsl(hex) {
  // Convert hex to RGB first
  let r, g, b;
  if (hex.length === 4) {
    r = "0x" + hex[1] + hex[1];
    g = "0x" + hex[2] + hex[2];
    b = "0x" + hex[3] + hex[3];
  } else if (hex.length === 7) {
    r = "0x" + hex[1] + hex[2];
    g = "0x" + hex[3] + hex[4];
    b = "0x" + hex[5] + hex[6];
  }
  // Then to HSL
  r /= 255;
  g /= 255;
  b /= 255;
  let cmin = Math.min(r, g, b),
    cmax = Math.max(r, g, b),
    delta = cmax - cmin,
    h = 0,
    s = 0,
    l = 0;

  if (delta === 0) h = 0;
  else if (cmax === r) h = ((g - b) / delta) % 6;
  else if (cmax === g) h = (b - r) / delta + 2;
  else h = (r - g) / delta + 4;

  h = Math.round(h * 60);

  if (h < 0) h += 360;

  l = (cmax + cmin) / 2;
  s = delta === 0 ? 0 : delta / (1 - Math.abs(2 * l - 1));
  s = +(s * 100).toFixed(1);
  l = +(l * 100).toFixed(1);

  console.log(
    "hsl(" + Math.round(h) + "," + Math.round(s) + "," + Math.round(l) + ")"
  );
}