PKCE code_verifer and code_challenge using JavaScript

Referencing post – Creating a code verifier and challenge for PKCE auth on Spotify API in ReactJS

// GENERATING CODE VERIFIER
function dec2hex(dec) {
  return ("0" + dec.toString(16)).substr(-2);
}
function generateCodeVerifier() {
  var array = new Uint32Array(58 / 2);
  window.crypto.getRandomValues(array);
  return Array.from(array, dec2hex).join(""); 
}

function sha256(plain) {
  // returns promise ArrayBuffer
  const encoder = new TextEncoder();
  const data = encoder.encode(plain);
  return window.crypto.subtle.digest("SHA-256", data);
}
function base64urlencode(a) {
  var str = "";
  var bytes = new Uint8Array(a);
  var len = bytes.byteLength;
  for (var i = 0; i < len; i++) {
    str += String.fromCharCode(bytes[i]);
  }
  return btoa(str)
    .replace(/+/g, "-")
    .replace(///g, "_")
    .replace(/=+$/, "");
}
async function generateCodeChallengeFromVerifier(v) {
  var hashed = await sha256(v);
  var base64encoded = base64urlencode(hashed);
  return base64encoded;
}

console.log("code_verifier = " + generateCodeVerifier());
var v = generateCodeVerifier();
console.log("challenge = " + generateCodeChallengeFromVerifier(v));


// Eg:
// {
//  "code_verifier":"M25iVXpKU3puUjFaYWg3T1NDTDQtcW1ROUY5YXlwalNoc0hhakxifmZHag",
//  "code_challenge":"qjrzSW9gMiUgpUvqgEPE4_-8swvyCtfOVvg55o5S_es"
// }

I am geting the generatedCodeVerifier(), but how do you get the challengeFromVerifier(v) === returning as object[promise]. console.log(“code_verifier = + generateCodeVerifier()); var v = gernerateCodeVerifier(); console.log(“challenge = ” + generateCodeChallengeFromVerifier(v)); // object[promise]

Thanks @Moojjoo

I have the next problems with this code in python (backend) to emmit data on a web server

I have the next problems with my code: my backend code doesn’t initiate when i try to compile it and make it send coordinates to my html page of a web server that i created in javascript on Visual Studio code.
First, i created a code with python to open the camera of my laptop and calculate the area of each square (or rectangles) that the camera could recognize. Then I created a web server with express and Socket.io. For this I created a directory on my computer to make this, and in a folder named public and another named nodejs_web_server.
Now, i will share the codes here. THE FIRST CODE IS:

import cv2 
import numpy as np 
import requests from socketIO_client import SocketIO, BaseNamespace 
import json

IP_SERVER = 'localhost'  # servers ip SERVER_URL = 'http://localhost:3000'  # URL of Express server

print("Starting...") socketIO = SocketIO(IP_SERVER, 3000) try: socketIO = SocketIO(IP_SERVER, 3000) print("Connected to server") except Exception as e: print(f"Error by trying to connect to server: {e}")

cap = cv2.VideoCapture(0)

frame = cv2.imread('your_image.jpg')  # Replace 'your_imagen.jpg' with the path of your image

while True: ret, frame = cap.read()

print(f"Readed frame: {ret}") 

if not ret:
    break

# Convert the image to a gray scale
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

# Apply a gaussian filter to reduce the noise
gray = cv2.GaussianBlur(gray, (5, 5), 0)

# detect the borders of the image
edges = cv2.Canny(gray, 50, 150)

# detect the contours of the image
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# minimum area to recognize squares
minimum_area = 1000  

for contour in contours:
    perimeter = cv2.arcLength(contour, True)
    approx = cv2.approxPolyDP(contour, 0.04 * perimeter, True)

    
    if len(approx) == 4 and cv2.contourArea(contour) > minimum_area:
        # Find the centre of the square
        M = cv2.moments(contour)
        if M["m00"] != 0:
            cx = int(M["m10"] / M["m00"])
            cy = int(M["m01"] / M["m00"])
            coordenadas = {'x': cx, 'y': cy}
            response = requests.post(f'{SERVER_URL}/coordenadas', json=coordenadas)
            print(response.status_code, response.text)
        # Send the values to server with the id "coordenadas"
        coordenadas_json = json.dumps({'x': cx, 'y': cy})
        socketIO.emit('coordenadas', coordenadas_json)
   
 # invert the image horizontally
frame = cv2.flip(frame, 1)

# show the image in real time
cv2.imshow('Detection of squares', frame)

# stop the loop when 'q' is pressed
if cv2.waitKey(1) & 0xFF == ord('q'):
    break

# wait 500ms
if cv2.waitKey(500) & 0xFF == ord('q'):
    break
#close the camara and the window

cap.release() cv2.destroyAllWindows()`

Then i have this one named “app.js”:

var express = require('express');
var app = express();
var server = require('http').Server(app);
const io = require('socket.io')(server);

app.use(express.static('public'));

ArduinoSocketID = null;
io.on('connection', function(socket){

    socket.on('coordenadas',(mensaje)=>{
        console.log('mensaje del cliente', mensaje);
        io.sockets.emit('coordenadas',mensaje);
        //console.log(ArduinoSocketID);
    });
});

server.listen(3000, function(){
    console.log("Servidor corriendo en el puerto 3000")
});

Then this one “main.js”:

var socket = io.connect('http://localhost:3000', {'forceNew': true});

socket.on('coordenadas', (mensaje) => { console.log('coordenadas recibidas', mensaje);
var data = JSON.parse(mensaje);
console.log('COOR X:', data.x);
console.log('COOR Y:', data.y);
document.getElementById("19212438").innerHTML = "X=" + data.x + ", Y=" + data.y;
});`

Now, the number “19212438” its my ID in the list of my classmates that appears on my html page, in which one i want to trasmit the values of x and y in real time. (Each class members appears on my html code and each of them has its own ID. “19212438” its mine and i have to transmitt the x and y values generated on my backend code of python in the html page on real time).

Thanks for your support.

I have asked ChatGPT to solve it but it only generates even more and more errors during the compilation. I dont have experince in coding. Its my final project of my class in school. Hope someone could help me.

If you want to send me questions about my project, this is my email direction: [email protected]

Override JS function Odoo 15

how can I override this Odoo class, I want to change the content of get date function, but I restart the service, the POS, even tried in private windows to avoid cache problems but Odoo is not seeing my custom js class :

odoo.define('pos_sale.SaleOrderRow', function (require) {
'use strict';

const PosComponent = require('point_of_sale.PosComponent');
const Registries = require('point_of_sale.Registries');
const utils = require('web.utils');
/**
 * @props {models.Order} order
 * @props columns
 * @emits click-order
 */
class SaleOrderRow extends PosComponent {
    get order() {
        return this.props.order;
    }
    get highlighted() {
        const highlightedOrder = this.props.highlightedOrder;
        return !highlightedOrder ? false : highlightedOrder.backendId === this.props.order.backendId;
    }

    // Column getters //

    get name() {
        return this.order.name;
    }
    get date() {
        return moment(this.order.date_order).format('YYYY-MM-DD hh:mm A');
    }
    get customer() {
        const customer = this.order.partner_id;
        return customer ? customer[1] : null;
    }
    get total() {
        return this.env.pos.format_currency(this.order.amount_total);
    }
    /**
     * Returns true if the order has unpaid amount, but the unpaid amount
     * should not be the same as the total amount.
     * @returns {boolean}
     */
    get showAmountUnpaid() {
        const isFullAmountUnpaid = utils.float_is_zero(Math.abs(this.order.amount_total - this.order.amount_unpaid), this.env.pos.currency.decimal_places);
        return !isFullAmountUnpaid && !utils.float_is_zero(this.order.amount_unpaid, this.env.pos.currency.decimal_places);
    }
    get amountUnpaidRepr() {
        return this.env.pos.format_currency(this.order.amount_unpaid);
    }
    get state() {
        let state_mapping = {
          'draft': this.env._t('Quotation'),
          'sent': this.env._t('Quotation Sent'),
          'sale': this.env._t('Sales Order'),
          'done': this.env._t('Locked'),
          'cancel': this.env._t('Cancelled'),
        };

        return state_mapping[this.order.state];
    }
    get salesman() {
        const salesman = this.order.user_id;
        return salesman ? salesman[1] : null;
    }
}
SaleOrderRow.template = 'SaleOrderRow';

Registries.Component.add(SaleOrderRow);

return SaleOrderRow;

});

I want to change the content of this function

get date() {
        return moment(this.order.date_order).format('YYYY-MM-DD hh:mm A');
    }

I tried :

odoo.define('slnee_appointment_sale.CustomSaleOrderRow', function (require) {
'use strict';

console.log('innnnnnnnnn XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
var SaleOrderRow = require('pos_sale.SaleOrderRow');
const Registries = require('point_of_sale.Registries');
const moment = require('moment'); // Import the moment library if it's not already imported

const CustomSaleOrderRow = SaleOrderRow => class extends SaleOrderRow {
    // Override the date getter to return a custom date format
    get date() {
        // Get the order's date in UTC
        const utcDate = moment.utc(this.order.date_order);

        // Convert the UTC date to the browser's timezone
        const browserTimezoneDate = utcDate.clone().local();

        return browserTimezoneDate.format('YYYY-MM-DD hh:mm A');
    }
};

Registries.Component.extend(SaleOrderRow, CustomSaleOrderRow);

return SaleOrderRow;

});

but it’s showing nothing in the web browser console, like it’s not even seeing my js file even it’s added in the manifest

'assets': {
    'point_of_sale.assets': [

        "slnee_appointment_sale/static/src/js/CustomSaleOrderRow.js",

    ],

},

Server Error TypeError: Cannot read properties of undefined (reading ‘attributes’)

i am using nextjs and i cant display the data in the html page..

in the console the data displaying properly..but in the html i have error(Server Error TypeError: Cannot read properties of undefined (reading ‘attributes’)…

code from pages/index.js




import HeroBanner from "@/components/HeroBanner"

import ProductCard from "@/components/ProductCard"
import Wrapper from "@/components/Wrapper"
import Category from "./category/[slug]"

import { fetchDataFromApi } from "@/utils/api"


export default function Home({ products }) {

  return (
    <>
      <main>
        <HeroBanner />

        <Wrapper>
          {/* heading and paragraph start */}
          <section className="text-center max-w-[800px] mx-auto my-[50px] md:my[80px]" >

            <div className="text-[28px] md:text-[34px] mb-5 font-semibold leading-tight capitalize" >
              αντικραδασμική προστασια
            </div>
            <div className="text-md md:text-xl">
              Απογείωσε το παιχνίδι και τα άλματά σου. Με αντικραδασμική προστασία Max Air στη φτέρνα, αυτό το ανάλαφρο και σταθερό παπούτσι σε βοηθά να απογειώνεσαι με σιγουριά και να προσγειώνεσαι με άνεση. Επίσης, το καουτσούκ αγκαλιάζει τα πλαϊνά για μεγαλύτερη ανθεκτικότητα και σταθερότητα.
            </div>

          </section>
          {/* heading and paragraph end */}
          <article className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5 my-14 px-5 md:px-0">
            {/* products grid start */}
            {products?.data?.map((product) => (
              <ProductCard key={product?.id} data={product} />
            ))}
            {/* <ProductCard />
          <ProductCard />
          <ProductCard />
          <ProductCard />
          <ProductCard />
          <ProductCard />
          <ProductCard />
          <ProductCard />
          <ProductCard /> */}
            {/* products grid end */}

          </article>
          <Category />
        </Wrapper>
      </main>
    </>
  )

}


export async function getStaticProps() {
  const products = await fetchDataFromApi("/api/products?populate=*")
  return {
    props: {
      products
    }
  }
}

code from components/productCard.jsx

import Link from "next/link";
import React from "react";
import { BiEuro } from "react-icons/bi";

const ProductCard = ({ data: { attributes: p, id } }) => {
  return (
    <Link
      href={`/product/${p.slug}`}
      className="transform overflow-hidden bg-white duration-200 hover:scale-105 cursor-pointer"
    >
      <Image
        width={500}
        height={500}
        src={p.thumbnail.data.attributes.url}
        alt={p.name}
      />

      <div className="p-4 text-black/[0.9]">
        <h2 className="text-lg font-medium">Product name</h2>
        <div className="flex items-center text-orange-700">
          <p className="mr-2 text-lg font-semibold flex items-center justify-center">
            <BiEuro className="text-black" />
            20.00
          </p>

          <p className="text-base font-medium line-through flex items-center justify-center text">
            <BiEuro />
            25.00
          </p>
          <p className="ml-auto text-base font-medium text-green-500">
            20% off
          </p>
        </div>
      </div>
    </Link>
  );
};

export default ProductCard;

I appreciate any help..

Truffle smart contract error -32000 for working contract

I have a javascript backend that I use to provide an API, which can be used to save and get strings from the blockchain.

I used truffle to deploy my contract on the Goerli test net.

And the contract is written in solidity as below:

contract StringStorage {
mapping(uint256 => string) public stringList;
uint256 public stringCount = 0 ;

function storeString(string memory _value) public {
    stringCount++;
    stringList[stringCount] = _value;
}

function getString(uint256 _index) public view returns (string memory) {
    require(_index > 0 && _index <= stringCount, "Invalid index");
    return stringList[_index];
}

function getCount() public view returns (uint256) {
        return stringCount;
    }
}

I created a script, that i used to test the deployed contract and I am able to save aswell as read strings from the blockchain. This is the script:

const Web3 = require('web3');
const contract = require('./BackendITProjektNODEJS/blockchain_setup/build/contracts/StringStorage.json');

const HDWalletProvider = require('./BackendITProjektNODEJS/blockchain_setup/node_modules/@truffle/hdwallet-provider');

const web3 = new Web3(new HDWalletProvider('myKey', 'https://rpc.ankr.com/eth_goerli')); // Replace with your Ethereum node URL

const contractAddress = 'myAdress'; // Use the address deployed by truffle migrate
const instance = new web3.eth.Contract(contract.abi, contractAddress);

async function storeString(stringToStore) {
    const accounts = await web3.eth.getAccounts();
    console.log(accounts)
    await instance.methods.storeString(stringToStore).send({ from: accounts[0] }).then((receipt) => {
        console.log('Transaction receipt:', receipt);
    })
    .catch((error) => {
        console.error('Error:', error);
    });
    console.log(`String "${stringToStore}" stored on the blockchain.`);
}

async function getString(index) {
    const storedString = await instance.methods.getString(index).call();
    console.log(`Retrieved string at index ${index} from the blockchain: ${storedString}`);
}

// Example usage:
storeString("test123");
//storeString("String 2");

//console.log(getString(3)); // Retrieve the first string
//getString(2); // Retrieve the second string

This works perfectly fine.

Now I have similiar code in my backend and I am able to call the read function and read the strings I wrote with the above script.
But the StoreString function never gets executed successfully.
This is the code:

import StringStorage from '../blockchain_setup/build/contracts/StringStorage.json' assert { type: "json" };
import HDWalletProvider from '../blockchain_setup/node_modules/@truffle/hdwallet-provider/dist/index.js'

import {Web3} from "web3"
class BspChain {

    constructor(){

        
        this.contract = StringStorage
      
        
        
        this.web3 = new Web3(new HDWalletProvider('myKey', 'https://rpc.ankr.com/eth_goerli'));

        
       
        this.contractAddress = 'myAdress';
       
        this.instance = new this.web3.eth.Contract(this.contract.abi, this.contractAddress);
    }

    async storeString(stringToStore) {
        console.log(stringToStore)
        
        const accounts = await this.web3.eth.getAccounts();
      
        //await instance.methods.storeString(stringToStore).send({ from: accounts[0] });
        await this.instance.methods.storeString(stringToStore).send({ from: accounts[0] })
        .then((receipt) => {
            console.log('Transaction receipt:', receipt);
        })
        .catch((error) => {
            console.error('Error:', error);
        });
    
       
    }
    
    async getString(index) {
        //const storedString = await instance.methods.getString(index).call();
        const storedString = await this.instance.methods.getString(index).call();
        console.log(`Retrieved string at index ${index} from the blockchain: ${storedString}`);
        return storedString
    }

}

export { BspChain as default };

I am catching the following error:

Error: {
  jsonrpc: '2.0',
  id: 'e056ced5-bea4-4dc2-8663-2a57e5f0a967', //this naturally changes each try 
  error: { code: -32000, message: 'execution reverted' }
}

I am somewhat clueless.

Please notice I changed personal information.

I appreciate every hint and help I get.

Many Thanks in advance.

Webpage crashes on mobile after interacting with Iframe

I have a modal that contains an Iframe that utilises Three.js to load a 3d Door.

The Iframe works fine on desktop top however, when we interact with it on mobile, it crashes or reloads the page when we close the modal. On safari the page reloads but on the second reload it crashes the page

Page Loading the Iframe

<iframe loading="lazy" id="door-viewer" src="<?= "{$site_url}/3d-spinner.php?sku={$unique_skus[0]}"; ?>" sandbox></iframe>

File which generates iframe

<?php 
   $product_sku = isset($_GET['sku']) ? strtoupper($_GET['sku']) : null;

    $proto = $_SERVER['HTTP_X_FORWARDED_PROTO'];
    $name = $_SERVER['SERVER_NAME'];

    $site_url = "{$proto}://{$name}";
?>
<?php
    header("Content-Security-Policy: frame-ancestors 'self' ".file_get_contents(getcwd()."/3d-spinner-assets/allowed-domains.txt").";");
?>
<html>
    <head>
        <!-- Three JS CDN Scripts -->
        <script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
        <script type="importmap">
        {
            "imports": {
            "three": "https://unpkg.com/[email protected]/build/three.module.js",
            "three/addons/": "https://unpkg.com/[email protected]/examples/jsm/"
            }
        }
        </script>
        <!-- IFRAME STYLES -->
        <style>
            body {
                margin: 0;
                box-sizing: border-box;
            }
            canvas {
                object-fit: cover;
                width: 100% !important;
                height: 100% !important;
                aspect-ratio: 1;
                background-image: radial-gradient(at 50% 50%, rgb(245, 245, 245) 20%, rgb(206, 206, 206) 90%);
            }

            .lpd-360-image-icon {
                position: absolute;
                top: 2rem;
                left: 2rem;
            }

            #door-viewer {
                position: relative;
            }

            noscript {
                display: flex;
                align-items: center;
                justify-self: center;
                font-size: 2rem;
                height: 100vw;
                width: 100vw;
            }
        </style>
    </head>
    <body>
        <noscript>
            Please enable JavaScript and reload your browser
        </noscript>
        <?php if($product_sku) : ?>
            <div id="door-viewer">
                <!-- Canvas is injected via Three.js -->
            </div>
        <?php else : ?>
            <div>
                <p>Product not found, check your sku</p>
            </div>
        <?php endif; ?>
        <script type="module">
            const sku = "<?= preg_replace('/[^-a-zA-Z0-9_]/', '', $product_sku ); ?>"
            const site_url = "<?= $site_url; ?>"

            import initSpinner from "./3d-spinner-assets/assets/scripts/main.js"

            initSpinner(sku, site_url);
        </script>
    </body>
</html>

Main.js File

import * as THREE from "three";
import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";

function initSpinner(sku, site_url) {
  document.addEventListener(
    "DOMContentLoaded",
    () => {
      const doorAssetPath = `${site_url}/3d-spinner-assets/door/${sku}/model.gltf"`;
      const doorViewerCanvas = document.getElementById("door-viewer");

      // Scene
      const scene = new THREE.Scene();

      // Camera
      const camera = new THREE.PerspectiveCamera(75, 500 / 500, 0.1, 800);
      camera.position.z = 10;
      camera.position.y = 0;
      camera.position.x = 0;

      // Renderer
      const renderer = new THREE.WebGLRenderer({
        antialias: true,
        devicePixelRatio: 1,
        alpha: true,
      });
      renderer.setSize(1200, 1200); // Set Scene Size
      renderer.shadowMap.enabled = true;
      renderer.setClearColor(0xffffff, 0); // Make scene transparent
      renderer.setPixelRatio(window.devicePixelRatio); // Set Pixel Ratio in line with device

      // Scene Lighting
      const ambientLight = new THREE.AmbientLight(0x404040, 90);
      scene.add(ambientLight);

      // Controls
      const controls = new OrbitControls(camera, renderer.domElement);
      controls.enableDamping = true; // Add damping for smoother motion
      controls.dampingFactor = 0.05; // Adjust the damping factor
      controls.rotateSpeed = 0.5; // Adjust rotation speed
      controls.zoomSpeed = 1.2; // Adjust zoom speed

      // Load Door
      const loader = new GLTFLoader();
      loader.load(doorAssetPath, (gltfScene) => {
        const loadedDoor = gltfScene.scene;

        // Traverse the loadedDoor to set transparency for the windows
        const windowMaterials = []; // Add the window materials to this array

        // Inside the load callback function
        loadedDoor.traverse((child) => {
          if (
            (child.isMesh && child.name === "glass") ||
            child.name === "Glass"
          ) {
            const windowMaterial = child.material;
            windowMaterial.transparent = true;
            windowMaterial.opacity = 0; // Adjust opacity value
            windowMaterials.push(windowMaterial);
          }
        });

        const scaleFactor = 0.003; // Adjust this value as needed
        loadedDoor.scale.set(scaleFactor, scaleFactor, scaleFactor); // Adjust door's scale 
        loadedDoor.position.setY(-3); // Offset door's position
        scene.add(loadedDoor); // Add the door to the scene
      });

      doorViewerCanvas.appendChild(renderer.domElement); // Mount canvas to the DOM

      function animate() {
        requestAnimationFrame(animate);
        controls.update(); // Update the controls
        renderer.render(scene, camera);
      }

      animate();
    },
    { once: true }
  );
}

export default initSpinner;

I have had a look for a memory leak but unable to find anything

How to convey variable numbers in corpus?

The documentation examples are simple and clear so kudos for that but I have a simple question.

I would like to know how to structure data that is a bit more complicated than the greeting examples and I do not know how to move forward.

So for example, the app I am trying to create centers around 3 words:

  • switch port site

sites contain switches, switches have ports and ports connect to each other across switches.

Switches each have a name(or number) and ports each have a number.

The user says thing like “On site 3 connect switch 5’s port 3 to switch 7 port 4”

The result is a data structure such as:

{
  site:3
  switches:[{number:5, port:3},{number:7, port:4}],
  action:function(){
        switches[0].connect(switches[1])
   } 

}

The data structure could be anything as long as it is consistent.

Question

I would like to know how to structure data that is a bit more complicated than the greeting examples and I do not know how to move forward.

The example below is an example of the kind of data I want to work with. I feel like all the numbers should be “variables” instead of hard coded and I don’t know how to convey that in NLP.js

manager.addDocument('en', 'switch 3 port 1', 'switch.create');
manager.addDocument('en', 'switch', 'switch.connect');

manager.addAnswer('en', 'switch.create', '{ switches:[{name:undefined,port:undefined}]}');
manager.addAnswer('en', 'switch.create', `{ switches:[{name:3,port:1}]}`);
manager.addAnswer('en', 'switch.connect', `{ switches:[{name:3,port:1}]}`);

Can’t use the PDF loader in Langchain javascript

I’m trying out the PDF loader for a langchain tutorial:

npm install langchain
npm install pdf-parse
import { PDFLoader } from "langchain/document_loaders/fs/pdf";
const loader = new PDFLoader("src/document_loaders/example_data/example.pdf");
const docs = await loader.load();

Regardless of what url I use for the PDF, I always get this error:

Uncaught TypeError: readFile is not a function

Could this mean that pdf-parse only works in node.js and not in the browser?
How can I load PDF files in the browser with langchain?

How to remove point labels in react-chartjs-2 Line component?

I am working with the Line component from react-chartjs-2 and having trouble with removing labels on the points of the line.

Line Graph Result

Line Options:

const chartOptions: DeepPartial<
  CoreChartOptions<"line"> &
    ElementChartOptions<"line"> &
    PluginChartOptions<"line"> &
    DatasetChartOptions<"line"> &
    ScaleChartOptions<"line"> &
    LineControllerChartOptions
> = {
  responsive: true,
  plugins: {
    legend: {
      position: "top" as const,
    },
    title: {
      display: false,
    },
  },
  elements: {
    point: {
      radius: 2,
    },
  },
};

Line Data:

const chartData: ChartData<"line", number[], string> = {
    labels: Object.keys(sampleData),
    datasets: [
      {
        label: "Score",
        data: Object.values(sampleData).map(
          (val) => Math.round(val * 100) / 100
        ),
        backgroundColor: "#FF6384",
        borderColor: "#FF6384",
        pointRadius: 1,
        borderWidth: 2,
        tension: 0.1,
      } as ChartDataset<"line", number[]>,
    ],
  };

Sample data:

const sampleData = {
    "2016-08-28": 0.5786274509803921,
    "2016-10-09": -0.5872549019607842,
    "2016-10-10": 0.02058823529411765,
    "2016-11-07": 0.05679738562091504,
}

How can i divide a div to equal div parts without distorting the image?

myDiv

I have div and I want to slice it equal parts like in image.
Then I want to animate this sliced divs one by one.
My goal is adapt animation in this js fiddle:

https://jsfiddle.net/F5SbD/1/

<a href="#" class="toggle">Toggle</a>
<div class="grid">
    
    <div class="tile posone">
        <div class="front"><img src="http://placehold.it/250x175/00baff/ffffff" height="175" height="250" /></div>
        <div class="back"><img src="http://placehold.it/250x175/ffa800/ffffff" height="175" height="250" /></div>
    </div>

    <div class="tile posone">
        <div class="front"><img src="http://placehold.it/250x175/00baff/ffffff" height="175" height="250" /></div>
        <div class="back"><img src="http://placehold.it/250x175/ffa800/ffffff" height="175" height="250" /></div>
    </div>

    <div class="tile posone">
        <div class="front"><img src="http://placehold.it/250x175/00baff/ffffff" height="175" height="250" /></div>
        <div class="back"><img src="http://placehold.it/250x175/ffa800/ffffff" height="175" height="250" /></div>
    </div>
    
    <div class="tile posone">
        <div class="front"><img src="http://placehold.it/250x175/00baff/ffffff" height="175" height="250" /></div>
        <div class="back"><img src="http://placehold.it/250x175/ffa800/ffffff" height="175" height="250" /></div>
    </div>
    
</div>
* { font-family:Arial, Helvetica, sans-serif; }
.toggle { display:inline-block; padding:20px; background:#666; margin:0 0 10px 0; color:#fff; font-size:15px; text-decoration:none; }
.grid { overflow:hidden; }
.tile { width:250px; height:175px; position:relative; float:left; margin:0 1px 1px 0; cursor:pointer; -webkit-perspective:600px; }
.tile > div { position:absolute; top:0; left:0; right:0; bottom:0; -webkit-backface-visibility:hidden; -webkit-transition:-webkit-transform 0.2s ease-in-out; }

.tile .front { -webkit-transform:rotateX(0deg); }
.tile .back { -webkit-transform:rotateX(-180deg); }

.tile.postwo .front { -webkit-transform:rotateX(180deg); }
.tile.postwo .back { -webkit-transform:rotateX(0deg); }

jQuery 1.8.3 code:

    flip = { 
        init: function(){
            $('.toggle').on('click', flip.toggle);
            $('.tile').on('hover', flip.hover);
        },
        
        toggle: function(e){
            e.preventDefault();
            $('.tile').each(function(i, elm) {
                    setTimeout(function(){
                flip.autoFlip($(elm));
            }, i*40);
            });
        },
        
        hover: function(e){
            if (e.type === 'mouseenter'){
                var dir = flip.getDir($(this), { x:e.pageX, y:e.pageY });
            }
            flip.flipOver($(this), e.type, dir);
        },
        
        flipOver: function($elm, type, dir){
                
                switch (dir) {
                    case 0 :
                        $elm.addClass('top');   
                    break;
                    case 1 :
                        $elm.addClass('right'); 
                    break;
                    case 2 :
                        $elm.addClass('bottom');    
                    break;
                    case 3 :
                        $elm.addClass('left');  
                    break;
                    default :
                        $elm.removeClass('top right bottom left');
                }
                
                $elm.toggleClass('posone postwo');
            
        },
        
        autoFlip: function($elm){
            $elm.toggleClass('posone postwo');
        },
        
        getDir: function($elm, coord){
            var w = $elm.width(),
                h = $elm.height(),
                x = ( coord.x - $elm.offset().left - ( w/2 )) * ( w > h ? ( h/w ) : 1 ),
                y = ( coord.y - $elm.offset().top  - ( h/2 )) * ( h > w ? ( w/h ) : 1 ),
                direction = Math.round( ( ( ( Math.atan2(y, x) * (180 / Math.PI) ) + 180 ) / 90 ) + 3 )  % 4;
            return direction;
        }
        
    }
    
    $(document).ready(function() {
        flip.init();
    });
    

If I can slice this div into equal parts with pure js or a js library I think I can somehow get somewhere.

I did some research, but I couldn’t find this kind of div slice on the internet.

Is there anyone who knows about this thing and can help?

Vue Advanced Chat – scroll to footer

I use vue-advanced-chat component with vue 3

"vue-advanced-chat": "^2.0.7", 
"vue": "^3.0.0",

I keep the entire object of the selected room roomSelected, which contains the canWriteMessage parameter, which defines for me whether the user can write and send a message or not.

<vue-advanced-chat
...
:show-footer="roomSelected.canWriteMessage"
...
/>

I have the entire vue advanced chat component located at the bottom of my website. The page is relatively long, contains article details, gallery, etc. and the chat is located below these data

PROBLEM:

when the client comes to the site, the page immediately tries to scroll through the entire content and come to the chat

respectively, the chat component tries to scroll the footer. when I set :show-footer="false", the client stayed up after being added to the page, which I consider correct

Expectation:

it shouldn’t be like that, the client should stay up and look at the detail of the article and gradually scroll down

I tried, but it didn’t help:

autoScroll: {
  send: { new: false, newAfterScrollUp: false },
  receive: { new: false, newAfterScrollUp: false }
},

NodeJS/JS – write colored text into file

I was wondering if it is possible to append text to a file (e.g. with writeStream) that is colored.
There was a lot of information about how to color console.log text, but I wasn’t able to find anything about colored text written into a file.

I’ve tried to use modules like colors or chalk and also adding nodejs color references (e.g. FgBlack = “x1b[30m”), but always with the fs.createWriteStream() and no result.

SVG foreignObject is different when used as an image with src attribute

I have an SVG with some text in a foreignObject that I want to convert to an HTML image element <img src="data:image/svg+xml;utf8,%3Csvg%20xmlns..."> but resulting image looks a little bit different from the SVG. It looks like there is more line height in the resulting image. I’ve tried with text with different font families but the image and SVG still do not match.

Link to the code – https://jsfiddle.net/2x91gzjo/

JS:

const svgString = `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="160"
  height="143">
  <foreignObject width="100%" height="100%"
    style="line-height: normal; letter-spacing:0.25px; font-style:normal; font-weight:normal; color:#000000; font-size:11pt; text-decoration:none; text-align:left;font-kerning:auto;overflow-wrap:break-word;padding:10px;width:160px;height:143px;">
    <style>
      p {
        margin-top: 0px;
        margin-bottom: 0px;
      }
    </style>
    <div xmlns="http://www.w3.org/1999/xhtml" style="">
      <p><span style="font-family: Arial Narrow;">Hello World</span></p>
      <p><span style="font-family: Arial Narrow;">Hello World</span></p>
      <p><span style="font-family: Arial Narrow;">Hello World</span></p>
      <p><span style="font-family: Arial Narrow;">Hello World</span></p>
      <p><span style="font-family: Arial Narrow;">Hello World</span></p>
      <p><span style="font-family: Arial Narrow;">Hello World</span></p>
    </div>
  </foreignObject>
</svg>`
document.getElementById('svg').innerHTML = svgString;

const data = 'data:image/svg+xml;utf8,' + encodeURIComponent(svgString);

const img = document.createElement('img');
img.src = data;

document.getElementById('svg').appendChild(img);

CSS:

svg p {
  color: red;
}

svg, img {
  position: absolute;
  left: 10px
}

HTML:

<div id="svg"></div>

On the image below you can see that SVG (colored in red for convenience) has smaller line height than the generated image (colored in black).

Image on top of SVG

It looks like this problem exists only in Chrome MacOS. If you open the jsfiddle link in Firefox the image and the SVG are aligned.

Related questions:
SVG with foreignObject has a different height when used as an image src attribute
https://bugs.chromium.org/p/chromium/issues/detail?id=1442475

Any workaround is appreciated!