Anychart wordWrap

I a using AnyChart in a React project. I would like to use wordWrap on my legend.
Here is the JSON configuration for my legend:

  legend: {
    enabled: true,
    fontSize:10,
    itemsLayout: 'vertical-expandable',
    position:'right', 
    "width":60,
    "wordWrap": "break-word",
    "wordBreak":"break-all",
  },

Each item in the legend has the text “lah blah blah” but as you can see in the picture, the text just gets cut off.
Does anyone know why the text is not going to the next line. Any help is greatly appreciated.
enter image description here

How to change Javascript hitboxes for images that dont take up the full width of the object

I am pretty new to HTML canvas, and I am trying to make a flappy bird clone.
I have the bird and the pipes on screen, but the images do not take up the full width of the area I have assigned for the objects on the screen because there are invisible pixels. This is due to me having to remove a background and make it transparent. Does anyone know how to make the hitbox of the pipes take up the same amount of space as the image of the pipes even with the invisible pixels? Thank you.

const canvas = document.getElementById("canvas");
const c = canvas.getContext("2d");
const backgroundImage = document.getElementById("image")
const flappyBirdImage = document.getElementById("flappy-bird-image");
const topPipeImage = document.getElementById("top-pipe-image");
const bottomPipeImage = document.getElementById("bottom-pipe-image")
let controlsKeyDown = {up: false, right: false, down: false, left: false};
let dx = 2;
let dy = 2;

canvas.width = innerWidth;
canvas.height = innerHeight;




class Bird {
    constructor(x, y, width, height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }
    
    draw() {
        c.beginPath();
        c.fillStyle = 'blue';
        c.strokeStyle = 'lightBlue';
        c.drawImage(flappyBirdImage, this.x, this.y, this.width, this.height)
        c.fill()
        c.stroke();
        c.closePath();
    }
    
}



class Pipe {
    constructor(x, y, height, width, color, image) {
        this.x = x;
        this.y = y;
        this.height = height;
        this.width = width;
        this.color = color;
        this.image = image;
    }
    
    draw() {
        c.beginPath();
        c.drawImage(bottomPipeImage, this.x, this.y, this.width, this.height)
        c.fill();
        
    }

    drawtop() {
        c.beginPath();
        c.drawImage(topPipeImage, this.x, this.y, this.width, this.height);
        c.closePath()
    }
}

const topPipe = new Pipe(400, 200, 100, 200, 'black')

const bottomPipe = new Pipe(500, 200, 100, 200, 'black')

const myBird = new Bird(200, 200, 40, 40)

function birdControlsKeyDown(Event) {
    if(Event.key === 'ArrowUp') {
        controlsKeyDown.up = true;
    }
    if(Event.key === 'ArrowRight') {
        controlsKeyDown.right = true;
    }
    
    if(Event.key === 'ArrowLeft') {
        controlsKeyDown.left = true;
    }
    
    if(Event.key === "ArrowDown") {
        controlsKeyDown.down = true;
    }
}
function birdControlsKeyUp(Event) {
    if(Event.key === 'ArrowUp') {
        controlsKeyDown.up = false;
    }
    
    if(Event.key === 'ArrowRight') {
        controlsKeyDown.right = false;
    }
    
    if(Event.key === 'ArrowLeft') {
        controlsKeyDown.left = false;
    }
    
    if(Event.key === 'ArrowDown') {
        controlsKeyDown.down = false;
    }
}

//Bird  With Edge Collision Detection

function birdCollisionDetection() {
    // Bird Hits Bottom Of Screen
    if(myBird.y + myBird.height >= canvas.height){
        myBird.y -= dy;
    }
    
    // Bird Hits Top Of Screen
    if(myBird.y <= 0) {
        myBird.y += dy;
    } 
    
    // Bird Hits Left Of Screen
    if(myBird.x<= 0) {
        myBird.x += dx;
    }
    
    // Bird Hits Right Of Screen
    if(myBird.x + myBird.height >= canvas.width) {
        myBird.x -= dx;
    }
    
    // Bird With Pipe Collision Detection
    
}
function birdWithPipeCollisionDetection(a,b) {
    
    if(a.x + a.width >= b.x && a.x <= b.x + b.width && a.y  <= b.y + b.height && a.y + a.height >= b.y){
        console.log('test');
        a.x -= dx;
        
    }
}
function draw() {
    c.drawImage(backgroundImage, 0,0,canvas.width,canvas.height)
    myBird.draw() 
    topPipe.drawtop()
    bottomPipe.draw()
  
   
    
    // Bird Controls
    
    addEventListener('keydown', birdControlsKeyDown)
    
    addEventListener('keyup', birdControlsKeyUp)
    
    
    if(controlsKeyDown.up) {
        myBird.y -= dy;
    }
    if(controlsKeyDown.right) {
        myBird.x += dx;
    } 
    
    if(controlsKeyDown.left) {
        myBird.x -= dx;
    }

    if(controlsKeyDown.down) {
        myBird.y += dy;
    }

    birdCollisionDetection();


    birdWithPipeCollisionDetection(myBird, topPipe);

    birdWithPipeCollisionDetection(myBird, bottomPipe);



    requestAnimationFrame(draw)
}
console.log(myBird)


draw()
html {
    margin: 0;
    padding: 0;
}

body {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
}

canvas {
    overflow: hidden;
}

image {
    background: transparent;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="icon" type="image/png" href="./Flappy Bird Pictures and Animations/Flappy Bird Icon.png" type="icon">
    <script src="Flappy Bird.js" defer></script>
    <link rel="stylesheet" href="Flappy Bird.css">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flappy Bird</title>
</head>
<body>
    <canvas id="canvas"></canvas>
    <img src="./Flappy Bird Pictures and Animations/background image.png" id="image">
    <img src="./Flappy Bird Pictures and Animations/The Flappy Bird.png" id="flappy-bird-image">
    <img src="./Flappy Bird Pictures and Animations/Bottom Pipe.png" id="bottom-pipe-image">
    <img src="./Flappy Bird Pictures and Animations/Top Pipe.png" id="top-pipe-image">
</body>
</html>

Select the table according to the category, topic and microtopic using just one model Node.Js

I have several tables that have the same structure, they all have a title, description, topic and microtopic but they have different content. I want to display the table information according to the page I am using a single Model.

On this site I will have a page with several categories such as: Movies, music and series. Each category will have a topic, for example, Movies will have: Action, horror, adventure. And each topic will have a microtopic, for example the Film category that has the Action topic will have the following microtopics: Old, current, future releases. And within each microtopic you will have a list containing movies with their title, description, topic and microtopic corresponding to that search.

I would like to know how I could carry out this process. I have here an example of a model that I created and what I imagined would be to change the tableName according to the url but I didn’t find a way to do that.

I leave here the example of the model I created:

import {Model, DataTypes} from 'sequelize';
import {sequelize} from '../instances/mysql';

export interface ContentInstance extends Model{
    id: number,
    title: string,
    description: string,
    topic: string,
    microtopic: string,
};

export const Content= sequelize.define<ContentInstance>("Content", {
    id:{
        primaryKey: true,
        autoIncrement: true,
        type: DataTypes.INTEGER
    },
    title:{
        type: DataTypes.STRING,
    }, 
    description:{
        type: DataTypes.STRING,
    },
    topic:{
        type: DataTypes.STRING
    },
    microtopic:{
        type: DataTypes.STRING
    }   

}, {
    tableName: 'actionold', //I imagined something like concatenating topic + microtopic but dinamically
    timestamps: false
});

I’m new to backend and Node.Js (and I’m using mySQL)

Candy Crush 1D – How to Delete Consecutive Identical Sequences greater than 3 in the entire array?

Prompt: Write a function to crush candy in one dimensional board. In candy crushing games, groups of like items are removed from the board. In this problem, any sequence of 3 or more like items should be removed and any items adjacent to that sequence should now be considered adjacent to each other.

Input: “aaaabbbc”

Output: “c”

Explanation:

Remove 3 ‘a’: “aaaabbbbc” => “bbbbc”
Remove 4 ‘b’: “bbbbc” => “c”

here is my solution so far, im trying to use 2 pointer method, not sure where my logic is wrong, please help.

function candyCrush(s){

    var n = s.length;
    var j = 0;
    var k = 1;
    for(var i = 0; j < n; i++, j++)
    {
        s[i] = s[j];
        if(i > 0 && s[i-1] == s[i])
        {
            k++;
        }
        else{
        
            if(k >= 3)
            {
                i = i - (k+1);
                j -= 1
                k = 1;
            }
            else{
                k = 1;
            }

        }
    }
    return s.substring(0,i+1);
}  

Fill a div with repeated images without cutting the last image

I have been trying to repeat images without cutting the last images, i have tried the ordinary background-image style to repeat the image but u can’t always get the perfect results.
I have set the background image in a position absolute span inside li the span has 86% of the li so i can see a little of the last letter.

background-image: url(https://source.unsplash.com/jTSf1xnsoCs);
background-size: auto 51px;

In the first example the images fit the 86% of the li cause there is enough space, but in the second one the image is cutted. as i said i have used the background-image style.

enter image description here

Is there a way to fit the 86% or even 100% of li with completed images using javascript

Here is an example https://jsfiddle.net/4cfjd10a/

Angular can’t use await in TypeScript function

I am using Angular and in a function to generate two DIVs to 2 pages PDF I am using await but it’s not working and giving me this error 'await' expressions are only allowed within async functions and at the top levels of modules.

const pdf = new jsPDF('p', 'mm', 'a4');
const imgWidth = 208;
const position = 0;

let data = document.getElementById('pdf-one')!;
let dataTwo = document.getElementById('pdf-two')!;
const [imgPage1, imgPage2] = await Promise.all([html2canvas(data), html2canvas(dataTwo)]);
// Process first image
let imgHeight = imgPage1.height * imgWidth / imgPage1.width;
let contentDataURL = imgPage1.toDataURL('image/jpeg');
pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight);
pdf.addPage();
// Process second image
imgHeight = imgPage2.height * imgWidth / imgPage2.width;
contentDataURL = imgPage2.toDataURL('image/jpeg');
pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight);

pdf.save('Result.pdf');

NestJS + GraphQL Standalone application, NO Server Socket

I’m trying to make an already incredible lambda micro service I created, that utilizes awsLambdaFastify and GraphQL. So I did a demo on my project last week, and was instantly criticized for even having a fastify server running at all, and made me question the same thing now. So I’ve been trying to find examples of standalone NestJS applications and came across this ServerLess NestJS no HTTP. Ive gotten that working, and Immediately noticed a performance boost (before using fastify and all, my cold starts were around 360 ms, and this standalone app, we are looking at around 20-30 ms).

So with that context, does anyone have experience setting up a standalone NestJS app with no Server Socket running(no fastify, no express, no network) and how would you go about translating the lambda event and context into something I can then feed the standalone app, and how would I do that?

This snippet just shows the index.ts file (copied from the website, tested and working prototype).

I already have resolvers and services set up (GraphQL). I could probably create a custom router to parse the event and then go from there (match it to the correct service etc.) but is there a way that’s maybe built in that can do this for me? Thanks in advanced.

import {
  Context,
  APIGatewayProxyEvent,
  APIGatewayProxyResult,
} from 'aws-lambda';
import { ContextIdFactory } from '@nestjs/core';
import { INestApplicationContext } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';

import { AppModule } from './app.module';
import { AppService } from './app.service';
import { Logger } from '@nestjs/common';

let app: INestApplicationContext;

/**
 * Re-use the application context across function invocations
 */
async function bootstrap(): Promise<INestApplicationContext> {
  if (!app) {
    app = await NestFactory.createApplicationContext(AppModule, {
      // if a custom logger is supposed to be used, disable the default logger here
      logger: !process.env.AWS_EXECUTION_ENV ? new Logger() : console,
    });
    // And in this case attach a custom logger
  }

  return app;
}

export const handler = async (
  event: APIGatewayProxyEvent,
  context: Context
): Promise<APIGatewayProxyResult> => {
  /**
   * Setup the application context
   */
  const instance = await bootstrap();
  /**
   * Instantiate a request-scoped DI sub-tree and obtain the request-scoped top-level injectable
   */
  const contextId = ContextIdFactory.create();
  console.log(contextId, '<--context id');
  instance.registerRequestByContextId({ context }, contextId);
  const service = await instance.resolve<AppService>(AppService, contextId);

  /**
   * Finally, do something with the event we received, this is where I need to route 
   * to the correct service and pass in the paremeters
   */
  const result = service.getHello(event.body);

  // Return the computed result
  return { statusCode: 200, body: result };
};

NodeJS Issue with errors & trying to send custom error message

I am facing an issue with handling errors in my app. This is what my back-end is set up to send.

exports.getTVEvent = async (req, res) => {
    try {
        let response = await axios.get(``)
        if (response.data.tvevent === null) throw new Error("No Channel found")
        return res.status(200).send(response.data.tvevent)
    } catch (err) {
        return res.status(404).send(err.message)
    }
}

When I look back at the front-end of the app all I get is 404 Not Found and not the actual error message of No Channel Found

enter image description here

When I look at the body of the response this is what I get. My code below is a fetch hook I use throughout the app.

const getData = async () => {
    setIsPending(true);
    try {
        const res = await fetch(`http://localhost:3000/${url}`, {signal: controller.signal})
        console.log(res)
        if (!res.ok) throw new Error(res.statusText)
        const json = await res.json();
        setIsPending(false)
        setError(null);
        setData(json);
    } catch (err: unknown) {
        if (err instanceof Error) {
            if (err.name === "AbortError") {
                console.log("Fetch was aborted.")
            } else {
                console.log(err)
                setIsPending(false)
                setError('Error received from server: ' + err.message)
                console.log(err.message)
            }
        }
    }
}

getData();

I am not sure as to what I am doing wrong and why the front-end is not able to receive the back-end message. I have also tried to send the message within an object too return res.status(404).send({error: err.message}) if anyone has any ideas?

Response.json() – How can I return specific values? [duplicate]

I am using this API: “https://rickandmortyapi.com/api/character/?page=2&name=rick”

With javascript I have to get the values of the characters of Rick & Morty with fetch:

The response.json() when I look for the character ”Rick” returns this:

Characters

But in the return, I want only to get the first character in the array (In the image the yellow square)

const fetch = require ('node-fetch');

  function searchCharacter(){
   
    fetch(`https://rickandmortyapi.com/api/character/?name=rick`)
    .then( (response) => {
        let array =  response.json();
        return array;
    })
    .then ( (body) => {
        console.log(body);
    })
}

searchCharacter();

How to pass multiple objects into a component

I’m working through the Fullstack Open MOOC course from the University of Helsinki and I’m currently stuck on exercise 1.3

I have a collection of objects that contain a course name and the number of exercises for that associated course. I need to pass down these objects into the Content component so that each course name and exercises render on the page. I’ve coded it up like so:

const Part = (props) => {
  console.log("propsPart: ", props)
  return(
    <>
    <p>{props.name} {props.exercises}</p>
    </>
  )
}


const Content = (props) => {
  console.log("propsContent: ", props)
  return(
    <>
    <Part {...props}/>
    <Part {...props}/>
    <Part {...props}/>
    </>
  )

}


const App = () => {
  const course = 'Half Stack application development'
  const part1 = {
    name: 'Fundamentals of React',
    exercises: 10
  }
  const part2 = {
    name: 'Using props to pass data',
    exercises: 7
  }
  const part3 = {
    name: 'State of a component',
    exercises: 14
  }


  return (
    <div>
      <Header course={course}/> 
      <Content {...part1} />
    </div>
  )
}

I don’t understand how to pass in multiple objects into the Content component. Can someone tell me what’s missing from the Content component and how to structure it so it accepts multiple props?

How to add image link to firebase?

I am trying to add an image to firebase and while the image is uploading to my storage it is not uploading to my database. How can I fix this. This is the code I have for that section

for (let i = 0; i < filess.length; i++) {
            storage.ref(refUUID + '/' + filess[i].name).put(filess[i]).then(() => {
                storage.ref(refUUID + '/' + filess[i].name).getDownloadURL().then(function (url) {
                    database.ref(listingType + '/' + refUUID + '/Description/Images/Image' + (i + 1)).set({
                        Link: url,
                        name: 'Image' + (i + 1)
                    })
                });
            });
        }

How do we schedule a series of oscillator nodes that play for a fixed duration with a smooth transition from one node’s ending to the other?

We are trying to map an array of numbers to sound and are following the approach mentioned in this ‘A Tale of 2 Clocks’ article to schedule oscillator nodes to play in the future. Each oscillator node exponentially ramps to a frequency value corresponding to the data in a fixed duration (this.pointSonificationLength). However, there’s a clicking noise as each node stops, as referenced in this article by Chris Wilson. The example here talks about smoothly stopping a single oscillator. However, we are unable to directly use this approach to smoothen the transition between one oscillator node to the other.

To clarify some of the values, pointTime refers to the node’s number in the order starting from 0, i.e. as the nodes were scheduled, they’d have pointTime = 0, 1, 2, and so forth. this.pointSonificationLength is the constant used to indicate how long the node should play for.

The first general approach was to decrease the gain at the end of the node so the change is almost imperceptible, as was documented in the article above. We tried implementing both methods, including setTargetAtTime and a combination of exponentialRampToValueAtTime and setValueAtTime, but neither worked to remove the click.

We were able to remove the click by changing some of our reasoning, and we scheduled for the gain to start transitioning to 0 at 100ms before the node ends.

However, when we scheduled more than one node, there was now a pause between each node. If we changed the function to start transitioning at 10ms, the gap was removed, but there was still a quiet click.

Our next approach was to have each node fade in as well as fade out. We added in this.delay as a constant to be the amount of time each transition in and out takes.

Below is where we’re currently at in the method to schedule an oscillator node for a given time with a given data point. The actual node scheduling is contained in another method inside the class.

private scheduleOscillatorNode(dataPoint: number, pointTime: number) {
    let osc = this.audioCtx.createOscillator()
    let amp = this.audioCtx.createGain()

    osc.frequency.value = this.previousFrequencyOfset
    osc.frequency.exponentialRampToValueAtTime(dataPoint, pointTime + this.pointSonificationLength)
    osc.onended = () => this.handleOnEnded()
    osc.connect(amp).connect(this.audioCtx.destination)

    let nodeStart = pointTime + this.delay * this.numNode;
    amp.gain.setValueAtTime(0.00001, nodeStart);
    amp.gain.exponentialRampToValueAtTime(1, nodeStart + this.delay);
    amp.gain.setValueAtTime(1, nodeStart + this.delay + this.pointSonificationLength);
    amp.gain.exponentialRampToValueAtTime(0.00001, nodeStart + this.delay * 2 + this.pointSonificationLength);

    osc.start(nodeStart)
    osc.stop(nodeStart + this.delay * 2 + this.pointSonificationLength)
    this.numNode++;

    this.audioQueue.enqueue(osc)
    // code to keep track of playback
}

We notice that there is a slight difference between the values we calculate manually and the values we see when we log the time values using the console.log statements, but the difference was too small to potentially be perceivable. As a result, we believe that this may not be causing the clicking noise, since the difference shouldn’t be perceivable if it’s so small. For example, instead of ending at 6.7 seconds, the node would end at 6.699999999999999 seconds, or if the node was meant to end at 5.6 seconds, it would actually end at 5.6000000000000005 seconds.

Is there a way to account for these delays and schedule nodes such that the transition occurs smoothly? Alternatively, is there a different approach that we need to use to make these transitions smooth? Any suggestions and pointers to code samples or other helpful resources would be of great help!