Google analytics reporting api for Node JS filter not returning category events

I’m building a small Node JS cli and am using Google Analytics reporting, I have a bunch of events set up, my category is called “Fudge: Core”, but when I attempt to use the filters I don’t get any data back in rows, but removing the filters entirely I do see the data.

What am I missing?

#!/usr/bin/env node
require('dotenv').config();
const fs = require('fs');
const path = require('path');
const dotenv = require('dotenv');
const env = dotenv.parse(fs.readFileSync(path.resolve(__dirname + '/../', `.env`)));
const Table = require('cli-table3');
const colors = require('colors');
const { google } = require('googleapis');
const dayjs = require('dayjs');

const startDate = dayjs().format('YYYY-MM-DD')
const endDate = dayjs().format('YYYY-MM-DD')

// Google scopes and credentials
const scopes = 'https://www.googleapis.com/auth/analytics.readonly'
const credentials = JSON.parse(env.GOOGLE_APPLICATION_CREDENTIALS)

// Google jwt
const jwt = new google.auth.JWT(credentials.client_email, null, credentials.private_key, scopes)

// Analytics view
const view_id = '257544393'

async function getData() {
  const response = await jwt.authorize()
  const result = await google.analytics('v3').data.ga.get({
    'auth': jwt,
    'ids': 'ga:' + view_id,
    'start-date': '2022-01-01',
    'end-date': endDate,
    'metrics': 'ga:uniqueEvents',
    'filters': 'ga:eventCategory=="Fudge: Core"', // <-- something wrong here?
    'dimensions': 'ga:eventCategory,ga:eventAction,ga:eventLabel'
  })

  console.dir(result.data.rows)
}

getData()

How to spam numbers in javascript

I want from script to do
1
2
3
4
5…
But it give me 499.
What I need to add to the script is not to add numbers but just to print them

function numbers() {
  for (let i = 0; i < 500; i++) {
    var spam = i + "<br>";
  }
  document.getElementById('demo20').innerHTML = spam;
}

How to change brush tip from circle to other shape to draw on canvas with javascript

I am drawing freehand on canvas with javascript and currently the line consists out of multiple circles drawn over each other to create the illusion of a line.

How can I set the default circle to irregulat shapes similar to photoshop brushes?
also related, this would be needed to create a calligraphy like stroke for a pen or marker.

any help, links or keywords for further research are aprechiated.

Deep nested Array of Objects, find and remove Object with specific ID

I am trying to find an Object by ID and remove it. (Of course if this object has subTasks all Objects hanging on this tree are removed too).
I have a structure like this (For example), which can grow very big and deep:

[
  {
    "id": 0,
    "lane": 0,
    "name": "Task A",
    "start": 0,
    "end": 10000,
    "subTasks": [
      {
        "id": "0.1",
        "lane": 0,
        "name": "Subtask",
        "start": 0,
        "end": 10000,
        "class": "danger",
        "sublane": 0,
        "subTasks": [
          {
            "id": "0.1.1",
            "name": "Subtask",
            "start": 0,
            "end": 10000,
            "subTasks": [
              {
                "id": "0.1.1.1",
                "name": "Subtask",
                "start": 0,
                "end": 10000,
                "subTasks": [
                  {
                    "id": "0.1.1.1.1",
                    "name": "Subtask",
                    "start": 0,
                    "end": 10000
                  },
                  {
                    "id": "0.1.1.1.2",
                    "name": "Subtask",
                    "start": 0,
                    "end": 10000
                  }
                ]
              },
              {
                "id": "0.1.1.2",
                "name": "Subtask",
                "start": 0,
                "end": 10000
              }
            ]
          },
          {
            "id": "0.1.2",
            "name": "Subtask",
            "start": 0,
            "end": 10000
          },
          {
            "id": "0.1.3",
            "name": "Subtask",
            "start": 0,
            "end": 10000
          }
        ]
      },
      {
        "id": "0.2",
        "name": "Subtask",
        "start": 0,
        "end": 10000
      }
    ],
    "class": "danger",
    "sublane": 0
  },
  {
    "id": 1,
    "lane": 2,
    "name": "Task B",
    "start": 15000,
    "end": 25000,
    ],
    "class": "success",
    "sublane": 0
  }
]

Now I want to remove the ID = 0.1.1.1.1 for example, but it should work with every other Object the same way, no matter how deep it is nested.

For finding and editing Im using this dfs algorithm:

   edit: function (name, start, end) {
        for (let obj of gantt.items()) {
            result = dfs(obj, id);
            if (result) {
                result.name = name;
                result.start = start;
                result.end = end;
            }
        }
    
      dfs: function (obj, targetId) {
            if (obj.id === targetId) {
                return obj;
            }
            if (obj.subTasks) {
                for (let item of obj.subTasks) {
                    let check = dfs(item, targetId);
                    if (check) {
                        return check;
                    }
                }
            }
            return null;
        },

But how can I remove/delete the specific Object?

Emscripten: How to catch JS exception?

Emscripten ‘val.h’ API allows calling methods of JS objects, however, C++ try-catch won’t catch JS exception. Consider this example:

#include <emscripten.h>
#include <emscripten/val.h>

void test(){
    string t = "some invalid json";
    val    v = val::object();

    // This C++ try-catch doesn't catch JS exception
    try {
        v = val::global("JSON").call<val>("parse", t);
        cout <<"ok" <<endl;
    }
    catch(...){
        cout <<"failed" <<endl;
    }

    cout <<"ret" <<endl;
}

The JS exception makes the ‘test’ function stop and no ok, no failed, no ret printed out. How to catch that JS exception thrown by JSON.parse?

There’s 1 issue here but it’s still open: https://github.com/emscripten-core/emscripten/issues/11496

React JS onChange function of Material UI ‘number’ TextField uses previous value

I have an onChange function on this element:

<TextField id="rowinput" type="number" 
           defaultValue={this.defaultRows} // defaultrRows = 1
           inputProps={{ min: "1", max:"5"}}
           onChange={this.handleRows}>
</TextField>

This is the function:

handleRows = ev => {
        let newrows = ev.target.value;
        let newcount = newrows * this.state.cols;
        this.setState( {rows: newrows, panelcount: newcount} )
        console.log("Row Count: " + this.state.rows);
        console.log("Total Count: " + this.state.panelcount);
}

What this should do is take the value of the input field when the up and down arrows are clicked, and update the state. However, I’ve found that when the console statement in the handler prints its result, the number used is one step behind.

As you can see, on page load it starts with a default value of 1 (as does the cols value it is referencing), and so when the up arrow is clicked, the value changes to 2 and it should print out:

Row Count: 2

Total Count: 2

When I print the temporary variables it prints 2 and 2, but when I use the state call here, it prints 1 and 1.
Here for example, I increased the value up to 5, and you can see the console never logged higher than 4:

enter image description here

enter image description here

Is the state update called asynchronously? How can the temporary variables be correct but calling this.state.rows is one iteration behind?

Any help would be greatly appreciated

D3 X-Axis Stretches While Zooming

The X-Axis Scale of my Bar Chart Stretches and Contracts when I zoom in and out. Also, the scale overflows out of the set clip-path (No such issues with the Bars). I’ve tried to get the X-Axis Scale to Re-Scale, but I was unable to do it. Also this is a Dynamic Bar Chart, where its updating at constant intervals, I’ve resolved many issues it had, I’m just left with this one. Can anyone help me with this?

My Code: https://plnkr.co/edit/qU5DfrAPnkFfB3sT?open=lib%2Fscript.js&preview

Zoom Function:

const zoom = d3.zoom()
zoom.scaleExtent([0.5, Infinity])
    .on("zoom", ({ transform }) => {

        const scaleFactor = transform.k;
        const xOffset = transform.x;
        
        zoomGroup.attr('transform', `translate(${xOffset} 0) scale(${scaleFactor} 1)`);
        xAxisGroup.attr('transform', `translate(${xOffset} 260) scale(${scaleFactor} 1)`);

   
    });
svg.call(zoom);

How to correctly use @mdx-js/loader with create-react-app?

Just following the instructions from: https://mdxjs.com/docs/getting-started/#create-react-app-cra

I did the following:

$ npx create-react-app react-app
$ cd react-app
$ npm install @mdx-js/loader

Then as per the getting started guide, created the src/content.mdx file like so:

# Hello, world!

This is **markdown** with <span style={{color: "red"}}>JSX</span>: MDX!

Then modified src/App.js like so:

/* eslint-disable import/no-webpack-loader-syntax */
import Content from '!@mdx-js/loader!./content.mdx'

export default function App() {
  return <Content />
}

When I run the app, then I see the following errors on the console:

react-dom.development.js:20085 
        
       The above error occurred in the </static/media/content.152fde8da01171ae4224.mdx> component:

    at /static/media/content.152fde8da01171ae4224.mdx
    at App

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
logCapturedError @ react-dom.development.js:20085
update.callback @ react-dom.development.js:20118
callCallback @ react-dom.development.js:12318
commitUpdateQueue @ react-dom.development.js:12339
commitLifeCycles @ react-dom.development.js:20736
commitLayoutEffects @ react-dom.development.js:23426
callCallback @ react-dom.development.js:3945
invokeGuardedCallbackDev @ react-dom.development.js:3994
invokeGuardedCallback @ react-dom.development.js:4056
commitRootImpl @ react-dom.development.js:23151
unstable_runWithPriority @ scheduler.development.js:468
runWithPriority$1 @ react-dom.development.js:11276
commitRoot @ react-dom.development.js:22990
performSyncWorkOnRoot @ react-dom.development.js:22329
scheduleUpdateOnFiber @ react-dom.development.js:21881
updateContainer @ react-dom.development.js:25482
(anonymous) @ react-dom.development.js:26021
unbatchedUpdates @ react-dom.development.js:22431
legacyRenderSubtreeIntoContainer @ react-dom.development.js:26020
render @ react-dom.development.js:26103
./src/index.js @ index.js:7
options.factory @ react refresh:6
__webpack_require__ @ bootstrap:24
(anonymous) @ startup:7
(anonymous) @ startup:7
bootstrap:27 
        
       Uncaught DOMException: Failed to execute 'createElement' on 'Document': The tag name provided ('/static/media/content.152fde8da01171ae4224.mdx') is not a valid name.
    at createElement (http://localhost:3000/static/js/bundle.js:16384:38)
    at createInstance (http://localhost:3000/static/js/bundle.js:17571:24)
    at completeWork (http://localhost:3000/static/js/bundle.js:26697:32)
    at completeUnitOfWork (http://localhost:3000/static/js/bundle.js:30002:20)
    at performUnitOfWork (http://localhost:3000/static/js/bundle.js:29974:9)
    at workLoopSync (http://localhost:3000/static/js/bundle.js:29900:9)
    at renderRootSync (http://localhost:3000/static/js/bundle.js:29866:11)
    at performSyncWorkOnRoot (http://localhost:3000/static/js/bundle.js:29483:22)
    at scheduleUpdateOnFiber (http://localhost:3000/static/js/bundle.js:29071:11)
    at updateContainer (http://localhost:3000/static/js/bundle.js:32608:7)

What am I missing?

Looks like the webpack loader or babel isn’t kicking in properly… not sure.

How do I use React state in combination with a dynamic filter component?

I have a filter component that filters a set of data. I want to output the filtered data to the DOM by using the filtered object in the local state. I cannot figure out how to use state without reseting the filter input and I can also not figure out how to output the filtered data to the DOM without using state.

This is the dataset:

const data = [
{ Name: John,
Tags: [walking, senior, Amsterdam]
},
{Name: Chris,
Tags: [biking, junior, The Hague]
},
{Name: Marc,
Tags: [walking, junior, Amsterdam]
}

I want to filter this dataset based on the tags the client selects:

<select data-categorie={hobby} onChange={filterTagHandler}>
<option value='all'>All><option>
<option value='walking'>Walking><option>
<option value='biking'>Biking><option>
<select>

<select data-categorie={age} onChange={filterTagHandler}>
<option value='all'>All><option>
<option value='junior'>Junior><option>
<option value='senior'>Senior><option>
<select>

<select data-categorie={city} onChange={filterTagHandler}>
<option value='all'>All><option>
<option value='amsterdam'>Amsterdam><option>
<option value='the hague'>The Hague><option>
<select>

The filter select components are dynamically generated from client input. Therefor there is just the filterTagHandler instead of a nameHandler, hobbyHandler, cityHandler.

First thing is to handle the selected tags and create an array from the selected tags:

const selectedTagsArray = []

    const filterTagHandler = (e) => {
        const option = e.target.options

        const tagSelected = option[option.selectedIndex].value
        const categorie = e.target.dataset.categorie

        selectedTagsArray.push(tagSelected)

        // Handle new option in categorie
        handleNewOptionInCategorie(categorie, tagSelected)

        // Handle all option
        handleAllOption(tagSelected)

        // Filter items
        filterItems(selectedTagsArray)
    }

So the first thing that happens in this onChange function is the selected tag is push to the selectedTagsArray. If I would set the selectedTagsArray to state:

const [tagsArray, setTagsArray] = useState([])

setTagsArray(selectedTagsArray)

the selectedTagsArray would be emptied every time the client selects a new filter option, because the state get’s updated. So that’s no good.

So first I use some logic to update the selectTagsArray if the client selects a new option within a categorie (select component):

const handleNewOptionInCategorie = (categorie, tagSelected) => {
        filterTags && filterTags[categorie].forEach((tag) => {
            if(selectedTagsArray.includes(tag.Tag) && tag.Tag !== tagSelected){
                const index = selectedTagsArray.indexOf(tag.Tag)
                selectedTagsArray.splice(index, 1)
            }
        })
    }

Then I handle the ‘All’ option:

const handleAllOption = (tagSelected) => {
        if(tagSelected === 'All'){
            const index = selectedTagsArray.indexOf(tagSelected)
            selectedTagsArray.splice(index, 1)
        }
    }

This all works fine (as long as there is no state change along the way).

Next I filter the data based on the selected tags:

const filterItems = (array) => {

    const newArray = []

    data.forEach(item => {

        if(array.every(tag => item.Tags.includes(tag))){
            newArray.push(item)
        }
    })
}

So this gives me the filtered data in the newArray object. The next logical step now would be to:

const [filteredItems, setFilteredItems] = useState(data)

setFilteredItems(newArray)

This has to be done inside the filteredItems object.

But I cannot use state here as well, since the filterItems function is called inside the filterTaghandler onChange and so every time the client selects a new option the state updates and the selectedTagsArray is emptied.

So, how can I use the newArray object to update the DOM or how can I use state without emptying the selectedTagsArray?

How I can test a subscribe in Angular 11

I need helps about test in Angular. I have a method which in I use a subscribe, after lot of researchs I don’t found a solution thats corresponding to my situation,

my component

In this component I want to test ngOnInit

port { Component, OnInit } from '@angular/core';
import { ProjectEditionService } from '../../../project-view/services/project-edition.service';

@Component({
  selector: 'ngx-brush-width-popover',
  templateUrl: './brush-width-popover.component.html',
  styleUrls: ['./brush-width-popover.component.scss'],
})
export class BrushWidthPopoverComponent implements OnInit {
  private canvas: fabric.Canvas;
  public brushWidth: number = 1;

  public readonly MIN_WIDTH: number = 1;
  public readonly MAX_WIDTH: number = 100;
  public readonly STEP: number = 0.1;

  constructor(private projectEditionService: ProjectEditionService) {}

  ngOnInit(): void {
    this.projectEditionService.currentCanvas$.subscribe((canvas) => {
      this.canvas = canvas;
      this.brushWidth = this.canvas.freeDrawingBrush.width;
    });
  }

My spec file

import { ComponentFixture, fakeAsync, TestBed, waitForAsync } from '@angular/core/testing';
import { ProjectEditionService } from 'app/feature/project-view/services/project-edition.service';
import { fabric } from 'fabric';
import { of } from 'rxjs';
import { compileFunction } from 'vm';

import { BrushWidthPopoverComponent } from './brush-width-popover.component';
let canvas = new fabric.Canvas("canvas", {
  width: 1280,

});
fdescribe('BrushWidthPopoverComponent', () => {
  let component: BrushWidthPopoverComponent;
  let fixture: ComponentFixture<BrushWidthPopoverComponent>;
  let projectEditionService: ProjectEditionService;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [BrushWidthPopoverComponent],
      providers: [
        ProjectEditionService,
        ],
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(BrushWidthPopoverComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    projectEditionService = TestBed.inject(ProjectEditionService);
    component['canvas'] = { freeDrawingBrush: {} } as fabric.Canvas;
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  describe('ngOnInit', () => {
    it('onInit', () => {
        component.ngOnInit();
        expect(canvas).toBeDefined();
        expect(component.brushWidth).toEqual(1);
        expect(canvas.freeDrawingBrush.width).toEqual(1);
        expect(component.brushWidth).toEqual(canvas.freeDrawingBrush.width);
        });
      });

My test pass but am not sure if it’s test correctly my method ngOnInit because I don’t use projectEditionservice in my test.
thnks if you can help me to find a good solution

How to check if an Array with Object contains a Property

i’m coding a decentralized app and i’m stuck.
Here is my problem : i’m calling with async function and return an array with object :

const result = [
{ trait_type: "Neck Gear", value: "1" },
{ trait_type: "Alpha Score", value: "6" },
{ trait_type: "Generation", value: "Gen 0" },];

I need to access the line “Alpha score”. I have to check if alpha score exist in this object.
So i did this :

async function checkAlpha() {
    try {
        const checkAlphaTxn = await traitsContract.compileAttributes([4]) 
                    .then((result) => {
                        // console.log(result.hasOwnProperty("Alpha Score")) //return false
                        console.log(result) //return array above
                    })
    } catch (error) {
        console.log(error)
    }
}

I wanted to use the .hasOwnProperty() method but it returns to me FALSE. But alpha score value exist.

Thank you in advance for those who can unblock me ! 🙂

Render values from array of objects which contains an object (React, Typescript)

I’m trying to print, for example, the Names on some in my TSX.
Data has this form :

const targets: {
    [key: string]: {
        [key: string]: string[]
    }
}[] = [
    {
        '0665496f-7a4e-46b6-a922-2d42ce205c03': {
            names: ['Hello', 'World'],
            dob: ['1971-09-01'],
        },
    },
    {
        '2679d2b8-9c25-44e3-bfad-3e2ef6b93b94': {
            names: ['Jordan'],
        },
    },
    {
        '8a8b7630-5bc8-443e-a88d-c1601659b39e': {
            names: ['John Doe'],
        },
    },
]

How can I do it the more efficient way ? The code I tried is very complicated, I’m pretty sure I’m doing it wrong…

Here’s what I need for output, for example for the first object :

<div>
    <input data-profile-id="0665496f-7a4e-46b6-a922-2d42ce205c03" data-key="names" type="checkbox" />
    <label>Hello</label>
</div>
<div>
    <input data-profile-id="0665496f-7a4e-46b6-a922-2d42ce205c03" data-key="names" type="checkbox" />
    <label>World</label>
</div>

I need this infos in dataset to handle click on those inputs.

Thanks a lot.

window.ScrollTo(x, y) not working when searching for an element

I’ve got a document that contains certain elements with unique ids. This page contains what could be hundreds of different divs, each with their unique id. For example, consider the following:

<div id='root'>
    <div id='my-1-id'>1</div>
    <div id='my-2-id'>2</div>
    <div id='my-3-id'>3</div>
    <div id='my-4-id'>4</div>
    <div id='my-5-id'>5</div>

    // Even more divs

    <div id='my-1000-id'>1000</div>
</div>

Within my React component, I’ve implemented a LazyRendering feature so that the document gets loaded as the user scrolls down the page (which is pretty custom behavior).

However, right now, I’m looking to implement a feature that looks through certain parts of the page using document.getElementById. But finding everything on the page isn’t working because the full document isn’t being rendered in one go. So if the user is on the top of the page and uses this functionality to look for something on the bottom of the page (i.e. the part that hasn’t been ‘lazy rendered’), then document.getElementById will return null.

As a result of all this, I’m looking to implement a function that will simply loop over the document to search for this element. As an example:

const lookForElement = (id) => {
    let element = document.getElementById(id)
    while (!element) {
        window.ScrollTo(0, 200) //NOT scrolling
        element = document.getElementById(id)
    }
    return element
}

As you can see, if the element is not found, continue scrolling by 200 pixels in height until you find the element. However window.ScrollTo(0, 200) isn’t working and the page is always fixated at the original height of the page. What am I doing wrong?