How to custom format Chart.js ticks based on dynamic data?

I’m trying to make a chart that displays cryptocurrency prices using the CoinGeckoAPI and Chart.js. The data will be updated about every minute or so. I want my chart x-axis to look similar to this: enter image description here

My x-axis data is an array of unix time values that I need to convert to Date before setting them as labels in the chart. I’m using SignalR and a background task in an ASP.NET Core MVC application to periodically send CoinGeckoAPI data to the client.

How can I set specific dynamic values as the x-axis ticks? Ideally the ticks would be set to something like every third hour within my dataset.

HTML:

<canvas id="myChart" width="400" height="400"></canvas>

JavaScript:

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script type="text/javascript">

        //Establish SignalR connection
        var connection = new signalR.HubConnectionBuilder().withUrl("/hub").build();

        //Set up chart and initial empty configuration
        const config = {
            type: 'line',
            data: {},
            options: {}
        };
        const myChart = new Chart(document.getElementById('myChart'),
            config);

        //Pass data from SignalR Hub to client
        connection.on("CryptoPriceUpdated", function (unixTimeArray, priceArray) {

            //Convert unix time array to Date array with desired date formatting
            var formattedDateArray = new Array();
            for (var i = 0; i < unixTimeArray.length - 1; i++) {
                var dateTemp = new Date(unixTimeArray[i]);
                formattedDateArray[i] = dateTemp.getHours() + ':' + dateTemp.getMinutes();
            }

            //Configure chart with new data
            var labels = formattedDateArray;
            var data = {
                labels: labels,
                datasets: [{
                    label: 'Price',
                    backgroundColor: 'rgb(255, 99, 132)',
                    borderColor: 'rgb(255, 99, 132)',
                    radius: 1,
                    data: priceArray
                }]
            };
            var options = {
                responsive: true,
            }

            //Update chart
            myChart.data = data;
            myChart.options = options;
            myChart.update();
        });

        connection.start();
    </script>

How to have multiple draggable containers in same droppable div in react-beatiful-dnd?

I am trying to implement React Beautiful DND in an existing project. Everything is working fine.

What needs to be done?

  1. I want to know how we can map through the array directly to make draggable and droppable divs instead of array objects
  2. I want to know how we can add static draggable text without mapping over the array. Thanks in advance

Here is what I have tried so far: https://codesandbox.io/s/hardcore-colden-un7el?file=/src/App.js:89-108

RSA Key to generate an other public key in javascript

I have the encryption_key but the below code generates another public key as below.
I need help in writing the same code in Javascript. Please let me know how can I do it.

Note: I am creating an AES key(random 32 bytes) and iv(initialization vector) of 16 bytes, then use these to encrypt my payload. This AES Key & IV will be then encrypted by public key(below generated). But, I have exhausted all options to rewrite the below code in Javascript.

public static PublicKey getOtherPublicKey(String encryption_key) {
    try {
        byte[] publicBytes = Base64.getDecoder().decode(encryption_key);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(keySpec);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (InvalidKeySpecException e) {
        System.out.println("Invalid key specification.");
        throw new IllegalArgumentException(e);
    }
}

How to check CSS Box model of an element in Cypress?

I plan to create visual testing for my library jQuery Terminal. But I need to know, if it’s possible to check the CSS box model (margin, padding, width, and height) of the elements.

I need to check if the CSS is working as it should, sice I unintentionally introduced bugs, like spacing before an image caused by ::before pseudo element or invalid width of the span that contained wider characters (like Chinese or Japanese). Can you test stuff like this with Cypress?

I was searching but was not able to find any information. There is DOM API but I don’t see size.

how can i launch an app on mobile phone with php code?

I have a lot of followers on Instagram
But sometimes I upload my videos on YouTube and share the video link on Instagram Story.
The problem is that:
Instagram’s internal browser does not allow you to open links in the youtube app.
I want to make this possible using php code.
I already saw a code in JavaScript that does this, but I want to use php.

Can anyone help me?

How to remove all instances of line breaks and tabs using Javascript

I am scraping a website and need to remove all the /n and /t from my strings.

I have tried the following code:

item.post_category = [];
 Array.from($doc.find('h6.link')).forEach(function(link){ 
            console.log(link.textContent.replace(/t+n+/gm, ""));        
            item.post_category.push(link.textContent);
          })
//this removes the linebreaks but not the tabs

Here are multiple sample array I have to iterate over:

["ntttttJune 15, 2021 • nttttttntttttnttttttttttntttttttttttttttnttttttFamily,ntttttntttttttttttttttntttttttttttttttnttttttGender Equality,ntttttntttttttttttnttttttnttttttnttttttntttttntttttntttttttttttntttttIn the Newsntttt"]

["ntttttJune 13, 2020 • nttttttntttttnttttttnttttttnttttttnttttttntttttntttttntttttttttttntttttIn the Newsntttt"]

["ntttttJuly 5, 2021 • nttttttntttttnttttttnttttttnttttttnttttttntttttntttttntttttttttttntttttNewsntttt"]

IDEALLY, I would want my arrays to look like this. Remove the date AND the n and t.

["Family,Gender Equality,In the News"]
["In the News"]
["News"]

How I can use BrowserRouter in React correctly?

I’m creating a React project and I want to implement the BrowserRouter but the problem is that when I used it, it always throw the React Error of:

***Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app
    See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.***

I don’t know what is this about, because as far as I know, I’m not using hooks and I read the documentation and other tutorials to solve this problem (like deleting double react or npm link and that’s stuff) but this still a problem.

Here are my files.

App.js

import { BrowserRouter, Route, Routes, Link } from "react-router-dom";

import Navbar from "./components/navbar"
import Login from "./components/login";
// import CreateExercise from "./components/create-exercise.component";
// import CreateUser from "./components/create-user.component";

function App() {
  return (
    // <h1>HOASNKFNLSA</h1>
    // <div>
    //   <Home/>
    
    // </div>
    <BrowserRouter>
      <Routes>
      <Route path="/" render={() => {
      <h1>HOKAKSFNAKSO</h1>
    }}>

    </Route>
    </Routes>
    </BrowserRouter>
    
    
    
  );
}

function Home() {
  return (
    <div className="container text-center"> 
      <h1>KEVIN STYLE PELUQUERIA</h1>
      
    </div>
  );
}

function About() {
  return (
    <div>
      <h2>About</h2>
    </div>
  );
}

function Dashboard() {
  return (
    <div>
      <h2>Dashboard</h2>
    </div>
  );
}

export default App;

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import reportWebVitals from './reportWebVitals';

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


reportWebVitals();

package.json

{
  "name": "kevin-style-peluqueria",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.1",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "4.0.3",
    "web-vitals": "^1.1.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

I don’t know if you need anything else, but if you do, ask me in comments. If you need to know more extra info, I’m not using webpack. I’m using the classic React structure application when you do the command npx create-react-app. I’m also using express and MongoDB like my backend (basically I’m creating an application with the MERN Stack).

Vue.js prob is always undefined

Hello i am new to Vue and trying to use probs, but in my component i cant use the prob-data, because the probs are always undefined and appears as $attrs in the Vue-Debugger.

My Plan:
I want to Use the TabWrapper Component to fill the Modal-Component-Slot. The has an unnamed slot for multiple . Now i want to pass data via probs to the to define the “title” and the selected status, which has a default of false! Here, however, my probs are apparently not recognized because they appear as “attr” in the Vue debugger.

Vue-Debugger-Screenshot

parent.vue

.<template>
  <div class="options">
    <div class="textbox">
      <!-- todo -->
      <p class="login" @click="$refs.modalName.openModal()">Login / Registrieren</p>
      <p class="settings">Einstellungen</p>
      <p class="darkmode">Dunkles Design
        <input @click="toggleTheme" type="checkbox" name="switch" id="switch">
        <label for="switch"></label>
      </p>
    </div>
  </div>

  <!-- User-Settings-Modal -->
  <BasicModal ref="modalName">

    <template v-slot:header>
        <h1>Modal title</h1>
    </template>

    <template v-slot:body>

      <TabWrapper>
        <Tab title="Title-A" :selected="true">
           Demo Content: A
        </Tab>
        <Tab title="Title-B" >
           Demo Content: B
        </Tab>
        <Tab title="Title-C">
           Demo Content: C
        </Tab>
        <Tab title="Title-D">
           Demo Content: D
        </Tab>
      </TabWrapper>

    </template>
    
  </BasicModal>

</template>

<script>
import BasicModal from '@/components/Ui/BasicModal.vue'
import TabWrapper from '@/components/Ui/TabWrapper.vue'
import Tab from '@/components/Ui/Tab.vue'

export default {
  components: {
    BasicModal,
    TabWrapper,
    Tab
  },
  data() {
    return {
      theme: ''
    }
  },
  methods: {
    toggleTheme() {
      this.theme = this.theme == 'darkMode' ? 'root' : 'darkMode'
      document.documentElement.setAttribute('data-theme', this.theme);
    }
  }
}
</script>

tabwrapper.vue

<template>
<div class="tabs-wrapper">
  <div class="tabs-navigation">
    <ul>
      <li v-for="(tab, index) in tabs" :key="index">
        <div class="tabs-navigation-item"
            :class="{ 'is-active': tab.isActive }"
            @click="selectedTab(tab)">

            {{ tab.name }}

        </div>
      </li>
    </ul>
  </div>
    <div class="tabs-content">
        <slot></slot>
    </div>
</div>

</template>

<script>
export default {
  data() {
    return {
      tabs: []
    }
  },
  methods: {
    selectedTab(selectedTab) {
      this.tabs.forEach(tab => {
        tab.isActive = (tab.name === selectedTab.name);
      });
    }
  }
}
</script>

tab.vue

<template>
    <div v-show="isActive">
        <slot></slot>
    </div>
</template>

<script>
    export default {
        probs: {
            title: { required: true},
            selected: {
                type: Boolean,
                default: false
            }
         }
        ,
        data() {
            return {
                 isActive: this.selected,
                 name: this.title
            }
        },
        created() {
            console.log(this.title)
            this.$parent.tabs.push(this);
        }
    }
</script>

NestJS timeout for prevent duplicates

I have an application in NestJS, when a request is made to create an object, it validates that an object with the same name and some other parameters does not exist, in those validations the process takes approximately 30 seconds, before actually being saved.
But when from the angular front several requests are made by pressing the “create” button many times, and the process of the first one has not been completed, all the requests pass because the name does not yet exist for the system since the object is not yet saved with this name. In the end the objects end up being saved duplicates.

I know it can be avoided by disabling the “create” button from front until a response is obtained.

But my task from the back is to also prevent this error, I can think of a set.timeout in receiving the request, but I am not sure, more than anything, only allow a request every “x” time only for each user.

Any idea, I have something like this extract on my code:

async createRole(role: RoleDto, permissions) {
    const { Name, Account } = role;

    if (!Name)
        throw new UnprocessableEntityException(
            'The Name must be provided.',
        );

    if (!Account)
        throw new UnprocessableEntityException(
            'The Account must be provided.',
        );
    const roleExist = await this.rolesRepository.findOne({
        where: { Name, Account },
    });
    if (roleExist)
        throw new ConflictException(
            'Name has been already used on this corporation.',
        );
    var roleToSave = new Role();
    roleToSave.Name = Name;
    roleToSave.Account = Account;
    roleToSave = await this.rolesRepository.save(roleToSave);

Ajax send function in data property [duplicate]

I need some reactivity in vanila js. I solved the problem but ran into a problem. Simple example:

Why does it work correctly:

       let data = {
           'test': ()=>"some value"
       }

        $.ajax({
            url: "/api/test",
            dataType: "json",
            type: 'post',
            data: data,
            success: function(data){
            }});

and it doesn’t work:

        let data = {}
        Object.defineProperty(data,'test', {
            get: () => "some test value"
        }
        $.ajax({
            url: "/api/test",
            dataType: "json",
            type: 'post',
            data: data,
            success: function(data){
            }});
    }

Node JS Redis client doesnt call lPop callback on pushing items to queue

I have created two lists on Redis database I intend to read data from them using lPop and insert using rPush. I am using Node-Redis driver to connect to Redis and do operations below is my code

const redis = require('redis');
const https = require('https')

const client = redis.createClient({
    host: 'host',
    port: 6379,
    password: 'pwd'
});


const main = async() => {

    console.log('starting app..');
    
    client.on('error', err => {
        console.log('Error ' + err);
        return;
    });
    
    await client.connect();
   
    client.lPop('Response',(err,msg) => {
        console.log('Received on Response :' + msg); // 'message'
       
    });
    
    // this is for testing purpose 
    const testMsg = {
        "id": "77777",
        "operation": "create_acc",
        "success": "true",
        "explorerUrl": "url"
    };

    await client.rPush('Response',JSON.stringify(testMsg));
   
}

I setup the callback on lPop and then pushing data using rPop at the bottom . I am able to receive this data using redid-cli commands but not using the code above. That is when at the bottom part rPush pushes the data which is received on CLI using LPOP command but in above code the lPop callbacks aren’t working
Please suggest whats missing.

How can I manually implement anti-aliasing with canvas?

I wrote a renderer of sorts that can create Signed Distance Fields in Javascript / Canvas

https://jsfiddle.net/MisterSirCode/zrbx8493/273/

It works well, but the SDFs it renders, while accurate, are rough and pixelated

(Im calculating each pixel manually and applying the color data based on the X Y position / distance and then editing the image data of the canvas)

enter image description here

This is less than what I want to achieve. I want the rendered SDFs to have an anti-aliased appearance, but I’ve never made an algorithm to achieve it, and I’ve found little online that could help me.

What I want to know is, how can I correctly alias the corners and edges of my SDFs to give them a smoother appearance from far away.

This is the main function I draw my SDFs onto the image data with: (The full source code is in the above link)

draw() {
    let image = this.ctx.createImageData(this.image);
        let ivec = new Vector(image.width, image.height);
        for (var y = 0; y < image.height; ++y) {
            for (var x = 0; x < image.width; ++x) {
                let sphereOne = SDF.sphere(new Vector(ivec.x / 2, ivec.y / 2), 25)(new Vector(x, y, 1));
                let sphereTwo = SDF.sphere(new Vector(ivec.x / 4, ivec.y / 4), 15)(new Vector(x, y, 1));
                let dist = SDF.smoothAdd(sphereOne, sphereTwo, 35);
        let pos = (y * image.width + x) * 4;
                if (dist < 0) {
                    image.data[pos++] = x / image.width * 255;
                    image.data[pos++] = y / image.height * 255;
                    image.data[pos++] = (image.width - x) / image.width * 255;
                    image.data[pos] = 255;
                } else {
                    let bc = this.scene.backColor;
                    image.data[pos++] = bc[0] * 255;
                    image.data[pos++] = bc[1] * 255;
                    image.data[pos++] = bc[2] * 255;
                    image.data[pos] = bc[3] * 255;
                }
            }
        }
    this.ctx.putImageData(image, 0, 0);
}

Put the objects together given key with same value [duplicate]

I’m dealing with some chart data issues

I want to generate from this

 [
    {date: '17:18:21', throughput_series: '149.28'},
    {date: '17:18:31', throughput_series: '168.25'},
    {date: '17:18:21', avg_response_time_series: '111.04'},
    {date: '17:18:31', avg_response_time_series: '155.39'},
    {date: '17:18:21', max_active_user_series: '297.42'}
    {date: '17:18:31', max_active_user_series: '174.41'}    
]

to this:

  [
        {date: '17:18:21', throughput_series: '149.28', avg_response_time_series: '111.04', max_active_user_series: '297.42'},
        {date: '17:18:31', throughput_series: '168.25', avg_response_time_series: '155.39', max_active_user_series: '174.41'},
  ]

How can I extract into the same object with a given date?

Thanks for any help.

Pointers/examples of Chrome Extension/Javascript Code to fetch HTML/Content of tabs

New to Javascript/Chrome extensions.

I’m looking to create a test extension that would capture the HTML/Content of the tabs for the Browser. It would be cool if the test could filter off the “URL” as well.

I’ve been looking over different test apps, and I’ve managed to get the Cookies, but can’t see how to get the content.

I’ve looked over the Chrome/Mozilla stores with no luck.

Pointers are appreciated.

thanks