PUT request crashes the server

I’m getting this error when trying to update an entry (in this case, checking a todo and setting it to true/false)
It seems like i’m getting the proper object (seen in the data console log) which makes me wonder why i’m getting [object Object].

Would appreciate any kind of help!

enter image description here

Here’s the action :

export function onSaveTodo(todo) {
  return async (dispatch) => {
    try {
      const savedTodo = await todosService.saveTodo(todo);

      const action = {
        type: 'UPDATE_TODO',
        todo: savedTodo,
      };

      dispatch(action);
    } catch (err) {
      console.log('cant save todo');
    }
  };
}

the service :

const BASE_URL = 'todo';

async function saveTodo(todo) {
  try {
    if (todo._id) {
      return httpService.put(BASE_URL, todo);
    } else {
      return httpService.post(BASE_URL, todo);
    }
  } catch (err) {
    console.log(`could not save todo `, err);
    throw err;
  }
}

Http service :

export const httpService = {
  get(endpoint, data) {
    return ajax(endpoint, 'GET', data);
  },
  post(endpoint, data) {
    return ajax(endpoint, 'POST', data);
  },
  put(endpoint, data) {
    console.log('endpoint:', endpoint);
    console.log('data:', data);

    return ajax(endpoint, 'PUT', data);
  },
  delete(endpoint, data) {
    return ajax(endpoint, 'DELETE', data);
  },
};

The backend controller :

async function updateTodo(req, res) {
  try {
    const { todo } = req.body;
    // console.log('todo:', todo);

    const savedTodo = await todoService.update(todo);

    res.json(savedTodo);
  } catch (err) {
    logger.error('Failed to update todo', err);
    res.status(500).send({ err: 'Failed to update todo' });
  }
}

and the backend service :


async function update(todo) {
  try {
    const newTodo = {
      ...todo,
      _id: ObjectId(todo._id),
    };

    console.log('newTodo:', newTodo);

    const collection = await dbService.getCollection('todo');
    await collection.updateOne({ _id: newTodo._id }, { $set: newTodo });
    return todo;
  } catch (err) {
    logger.error(`Can not update toy ${todo._id}`, err);
    throw err;
  }
}

Can’t delete a row from MUI DataGrid in MERN CRUD app using Redux/RTK?

For the life of me, I can’t figure out why I can’t get the delete button to work on this Material UI (MUI V5) Data Grid table. I’m a little new to coding, especially with MERN and Redux, so my brain is fried at the moment, and I’ve tried a million things all weekend, including Google, Stack Overflow, and taking a long break. The code below is how I think it should work, but when the button is clicked, nothing happens on the front end. A delete request is successfully sent to the server (or fulfilled), but I get this response message back in the console using redux dev tools:

“Cast to ObjectId failed for value “undefined” (type string) at path “_id” for model “Purchase””

Creating or adding items works fine on the front end in a separate form on a separate route. Delete worked fine when I tested it in Postman before building out the front end. The answer is probably very simple, I just can’t figure it out due to inexperience. Is it a simple JS issue with a object variable that I’m not seeing (seems like it from the error message) or maybe a state management/redux issue? Could it have something to do with MongoDB’s default “_id” property interacting with MUI? Or something else entirely? Here is the data grid component:

import React, { useState, useEffect } from 'react'
import { DataGrid, GridToolbar } from '@mui/x-data-grid'
import {getPurchases} from '../features/purchases/purchaseSlice'
import {useSelector, useDispatch} from 'react-redux'
import { Button } from '@mui/material'
import {deletePurchase} from '../features/purchases/purchaseSlice'

const TableForm = () => {

  const [pageSize, setPageSize] = useState(10);
  
  const dispatch = useDispatch()
  const {purchase, purchases, isError, message} = useSelector((state) => state.purchases)

  useEffect(() => {

    if (isError) {
      console.log(message);
    }

    dispatch(getPurchases());

  }, [isError, dispatch, message]);

  const renderDetailsButton = () => {
    return (
        <strong>
            <Button
                className="delete"
                variant="contained"
                color="primary"
                size="small"
                style={{ margin: 0}}
                onClick={() => {dispatch(deletePurchase(purchases.id))}}
            >
                 X           
            </Button>
        </strong>
    )
}

    
  const columns = [
    {field: '_id', headerName: 'ID', sortable: 'false', filterable: 'false', disableColumnMenu: 'true', visibility: 'false'},
    {field: 'title', headerName: 'Title', editable: true},
    {field: 'producer', headerName: 'Producer'},
    {field: 'director', headerName: 'Director'},
    {field: 'platform', headerName: 'Platform'},
    {field: 'year', headerName: 'Year of Release', maxwidth: 75},
    {field: 'price', headerName: 'Price', maxwidth: 75},
    {field: 'length', maxwidth: 75},
    {field: 'requesterName', headerName: 'Requester Name'},
    {field: 'requesterEmail', headerName: 'Requester Email'},
    {field: 'requesterDepartment', headerName: 'Requester Department'},
    {field: 'notes', headerName: 'Notes/Comments'},
    {field: 'createdAt', headerName: 'Created On', type: 'date' },
    {
        field: 'col5',
        headerName: 'Edit',
        width: 150,
        renderCell: renderDetailsButton,
        disableClickEventBubbling: true,
    },
    /*{
        field: 'col6',
        headerName: 'Delete',
        width: 150,
        renderCell: renderDetailsButton,
        disableClickEventBubbling: true,
    },*/
  ];


  return (
    <div style={{ height: 700, width: '100%' }}>
      <DataGrid experimentalFeatures={{ newEditingApi: true }} getRowId={row => row._id}
        sx={{
          boxShadow: 1,
          border: 1,
          borderColor: 'lightgrey',
          '& .MuiDataGrid-cell:hover': {
            color: 'primary.main',
          },
        }}
        initialState={{
          columns:{
            columnVisibilityModel: {_id: false}
          },
        pagination: {
          pageSize: 10,
          },
        }}
        rows={purchases}
        columns= {columns}
        components={{Toolbar: GridToolbar}}
        pageSize={pageSize}
        onPageSizeChange={(newPageSize) => setPageSize(newPageSize)}
        rowsPerPageOptions={[10, 25, 50, 100]}
      />
    </div>
  )
}

export default TableForm

The Slice:

import {createSlice, createAsyncThunk} from '@reduxjs/toolkit'
import purchaseService from './purchaseService'



const initialState = {
    purchases: [],
    isError: false,
    isSuccess: false,
    isLoading: false,
    message: ''
}

//Create new Purchase
export const createPurchase = createAsyncThunk(
    'purchases/create', 
    async (purchaseData, thunkAPI) => {
    try {
        const token = thunkAPI.getState().auth.user.token
        return await purchaseService.createPurchase(purchaseData, token)
    } catch (error) {
        const message =
            (error.response && 
            error.response.data &&
            error.response.data.message) ||
            error.message ||
            error.toString()
        return thunkAPI.rejectWithValue(message)
    }
})

//Get purchases
export const getPurchases = createAsyncThunk('purchases/getAll', async(_, thunkAPI) => {
    try {
        const token = thunkAPI.getState().auth.user.token
        return await purchaseService.getPurchases(token)
    } catch (error) {
        const message =
            (error.response && 
            error.response.data &&
            error.response.data.message) ||
            error.message ||
            error.toString()
        return thunkAPI.rejectWithValue(message)
    }
})

//Delete Purchase
export const deletePurchase = createAsyncThunk(
    'purchases/delete', 
    async (id, thunkAPI) => {
    try {
        const token = thunkAPI.getState().auth.user.token
        return await purchaseService.deletePurchase(id, token)
    } catch (error) {
        const message =
            (error.response && 
            error.response.data &&
            error.response.data.message) ||
            error.message ||
            error.toString()
        return thunkAPI.rejectWithValue(message)
    }
})

export const purchaseSlice = createSlice({
    name: 'purchase',
    initialState,
    reducers: {
        reset: (state) => initialState,
    },
    extraReducers: (builder) => {
        builder
            .addCase(createPurchase.pending, (state) => {
                state.isLoading = true
            })
            .addCase(createPurchase.fulfilled, (state, action) => {
                state.isLoading = false 
                state.isSuccess = true
                state.purchases.push(action.payload)
            })
            .addCase(createPurchase.rejected, (state, action) => {
                state.isLoading = false 
                state.isError = true
                state.message = action.payload
            })
            .addCase(getPurchases.pending, (state) => {
                state.isLoading = true
            })
            .addCase(getPurchases.fulfilled, (state, action) => {
                state.isLoading = false 
                state.isSuccess = true
                state.purchases = action.payload
            })
            .addCase(getPurchases.rejected, (state, action) => {
                state.isLoading = false 
                state.isError = true
                state.message = action.payload
            })
            .addCase(deletePurchase.pending, (state) => {
                state.isLoading = true
            })
            .addCase(deletePurchase.fulfilled, (state, action) => {
                state.isLoading = false 
                state.isSuccess = true
                state.purchases = state.purchases.filter((purchases) => purchases._id !== action.payload.id)})
            .addCase(deletePurchase.rejected, (state, action) => {
                state.isLoading = false 
                state.isError = true
                state.message = action.payload
            })
    }
})

export const {reset} = purchaseSlice.actions
export default purchaseSlice.reducer

Slice Service:


const API_URL = '/api/purchases/';

//Create new Purchase
const createPurchase = async (purchaseData, token) => {
    const config = {
        headers: {
            Authorization: `Bearer ${token}`
        }
    }

    const response = await axios.post(API_URL, purchaseData, config)

    return response.data
}


//Get purchases
const getPurchases = async (token) => {
    const config = {
        headers: {
            Authorization: `Bearer ${token}`
        }
    }

    const response = await axios.get(API_URL, config)

    return response.data
}

//Delete Purchase
const deletePurchase = async (purchaseId, token) => {
    const config = {
        headers: {
            Authorization: `Bearer ${token}`
        }
    }

    const response = await axios.delete(API_URL + purchaseId, config)

    return response.data
}

const purchaseService = {
    createPurchase,
    getPurchases,
    deletePurchase,
}

export default purchaseService

And the page/route the data grid component is on, just in case

import {useEffect} from 'react'
import {useNavigate} from 'react-router-dom'
import {useSelector} from 'react-redux'
import TableForm from '../components/tableForm'
import '../index.css'
import Spinner from '../components/Spinner'


function Table() {
  const {user} = useSelector((state) => state.auth)
  let navigate = useNavigate();
  const {isLoading, isError, message} = useSelector((state) => state.purchases)

  useEffect(() => {

    if (isError) {
      console.log(message);
    }

    if (!user) {
      navigate('/login')
    }
  
  }, [user, navigate, isError, message] )

  return (
    <>
      <div className='heading'>
        <h1>License Table</h1>
      </div>
    
      <TableForm/>
    </>
  )
}

export default Table

How to use DRACO Loader with GLTF Loader?

Hello guys!

Been doing some experiments with three.js, managed to get a 70mb model down to 10 MB using draco, however I am not really familiar with Draco and I haven’t been able to find a good example on how to use Draco loader together with GLTF Loader, can anyone show me a good example or check my code to see which things I have to change to use it and load the compressed model? TYSM!

    import * as THREE from '../build/three.module.js';
        import Stats from './jsm/libs/stats.module.js';
        import { OrbitControls } from './jsm/controls/OrbitControls.js';
        import { GLTFLoader } from './jsm/loaders/GLTFLoader.js';

        let camera, scene, renderer, stats;
        var raycaster, mouse = { x : 0, y : 0 };
        var objects = []; 
        var selectedObject;


        init();
        animate();

        function init() {

            const container = document.createElement( 'div' );
            document.body.appendChild( container );

            camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 0.25, 20 );
            camera.position.set( - 1.8, 0.6, 2.7 );

            scene = new THREE.Scene();
            scene.background = new THREE.Color( 0xa0a0a0 );
            raycaster = new THREE.Raycaster();


            const hemiLight = new THREE.HemisphereLight( 0xa0a0a0,  0xa0a0a0, 2);
            scene.add(hemiLight);


                // model
                
                        const loader = new GLTFLoader().setPath( 'models/fbx/lowlight3_out/' );
                        loader.load( 'lowlight3.gltf', function ( gltf ) {

                            gltf.scene.traverse( function ( child ) {

                        if ( child.isMesh ) {

                            child.castShadow = true;
                            child.receiveShadow = true;


                        }

                    } );

                    scene.add( gltf.scene );

                } );

Filter range.getValues() array matching the values from the first element (apps script_

I have a sheet that lists all cities in my countries with their respective states.
This sheet will be used in a form, but of course I don’t want the user to look in a list with all the existent cities. Thus I want to filter based on state.

Logging output too large. Truncating output. [[AC, Acrelândia], [AC, Assis Brasil], 
[AC, Brasiléia], [AC, Bujari], [AC, Capixaba], [AC, Cruzeiro do Sul], [AC, Epitaciolândia], 
[AC, Feijó], [AC, Jordão], [AC, Mâncio Lima], [AC, Manoel Urbano], [AC, Marechal Thaumaturgo], 
[AC, Plácido de Castro], [AC, Porto Walter], [AC, Rio Branco], [AC, Rodrigues Alves], [AC, Santa Rosa do Purus], 
[AC, Senador Guiomard], [AC, Sena Madureira], [AC, Tarauacá], [AC, Xapuri], [AC, Porto Acre], 
[AL, Água Branca], [AL, Anadia], [AL, Arapiraca], [AL, Atalaia], [AL, Barra de Santo Antônio], 
[AL, Barra de São Miguel], [AL, Batalha], [AL, Belém] (...)

The first element is the state, I want to filter this array in a way I would only get values with the same state. So if the selected state is AC it would result in:

[[AC, Acrelândia], [AC, Assis Brasil], [AC, Brasiléia], [AC, Bujari], [AC, Capixaba], 
[AC, Cruzeiro do Sul], [AC, Epitaciolândia], [AC, Feijó], [AC, Jordão], [AC, Mâncio Lima], [AC, Manoel Urbano], [AC, Marechal Thaumaturgo],[AC, Plácido de Castro], [AC, Porto Walter], 
[AC, Rio Branco], [AC, Rodrigues Alves], [AC, Santa Rosa do Purus], [AC, Senador Guiomard], [AC, Sena Madureira], [AC, Tarauacá], [AC, Xapuri], [AC, Porto Acre], [AL, Água Branca], 
[AL, Anadia], [AL, Arapiraca], [AL, Atalaia], [AL, Barra de Santo Antônio], 
[AL, Barra de São Miguel], [AL, Batalha]

I’m new to HTML, Javascript, and CSS. I’m trying to create a login form and i can’t seem to login succesfully, how to fix it? [closed]

I’m trying to create login form, but I can’t seem to login successfully, it always says login failed. how do I fix this? is there something that miss in my code? I followed a youtuber’s code and adjust with my own.

function validate() {
  var username = document.getElementById("username").Value;
  var password = document.getElementById("password").Value;
  if (username == "test" && password == "pass") {
    alert("login succesfully");
    return false;
  } else {
    alert("Login Failed");
  }
}
<div class="center">
  <h1>Login</h1>
  <form method="post">
    <div class="txt_field">
      <input type="text" id="username" required>
      <span></span>
      <label>Username</label>
    </div>
    <div class="txt_field">
      <input type="password" id="password" required>
      <span></span>
      <label>password</label>
    </div>
    <input type="submit" value="Login" onclick="validate()">
  </form>
</div>

How to combine 3 multidimentional arrays using GAS?

I got prepared 3 arrays, which I’d like to combine into one:

let array1 = 
[
 ["Col1", "Col2", "Col3"],
 ["Data1","Data2","Data3"]
]

let array2 = 
[
 ["Col5", "Col10", "Col21"],
 ["Data5","Data10","Data21"]
]

let array3 = 
[
 ["Col8", "Col11"],
 ["Data8","Data11"]
]

How can I make it like this?

resultingArray = 
[
 ["Col5", "Col10", "Col21","Col5", "Col10", "Col21","Col8", "Col11"],
 ["Data1","Data2","Data3","Data5","Data10","Data21","Data8","Data11"]
]

where order of the columns doesn’t matter.

I’ve tried using push(), ... the spread operator and concat(), but I haven’t been able to apply it properly.

thank you!

issue populating chart.js from entity framework in .Net Core 5

I am trying to populate a chart with test data before using production data but I cannot get the data into the chart. I do not have any errors that I can find and the controller is returning 2 complete datasets on the return Json(_chart);. The chart displays but there is no data in the chart. What am I doing wrong here?

index.cshtml

    <head>
       <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.js"></script>
       <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
       <script type="text/javascript">
           jQuery.extend({
               getValues: function (url) {
                   var result = null;
                   $.ajax({
                       url: url,
                       type: 'get',
                       contentType: "application/json; charset=utf-8",
                       dataType: 'json',
                       async: false,
                       sucess: function (data) {
                           result = data;
                       }
                   });
                   return result;
               }
           });
       </script>  
    </head>
    
    <body>
       <canvas id="myLineChart" width="400" height="200"></canvas>

       <script type="text/javascript">
           var ctx = document.getElementById("myLineChart").getContext('2d');
           var tData = $.getValues("/Home/MultiLineChartDataEF");
           var myLineChart = new Chart(ctx, {
               type: 'line',
               data: tData
           });
       </script>
    </body>

HomeController.cs

        public JsonResult MultiLineChartDataEF()
        {
            var chartData = _context.ChartTests.ToList();
            var uniqueProducts = from d in chartData orderby d.ProductName group d by d.ProductName into m select m.Key;
            var uniqueMonths = from a in chartData orderby a.MonthNumber group a by a.Month into g select g.Key;
            string[] cols = new string[] { "#FF0000", "#000000" };
            int i = 0;
            Chart _chart = new();
            _chart.labels = uniqueMonths.ToArray();
            _chart.datasets = new List<Datasets>();
            List<Datasets> _dataSet = new();
            foreach(var d in uniqueProducts)
            {
                var colors = new string[uniqueProducts.Count()];
                for (int j = 0; j < colors.Length; j++) colors[j] = cols[i];
                _dataSet.Add(new Datasets()
                {
                    label = d,
                    data = (from a in chartData where a.ProductName == d select a.Amount).ToArray(),
                    backgroundColor = new string[] { cols[i] },
                    borderColor = new string[] { cols[i] },
                    borderWidth = "1"
                });
                i++;
            }
            _chart.datasets = _dataSet;
            return Json(_chart);
        }

Chart.cs

using System.Collections.Generic;

namespace ChartTest.Models
{
    public class Chart
    {
        public string[] labels { get; set; }
        public List<Datasets> datasets { get; set; }
    }
    public class Datasets
    {
        public string label { get; set; }
        public string[] backgroundColor { get; set; }
        public string[] borderColor { get; set; }
        public string borderWidth { get; set; }
        public string[] data { get; set; }
    }
}

ChartTest.cs

namespace ChartTest.Models
{
    public partial class ChartTest
    {
        public string ProductName { get; set; }
        public string Month { get; set; }
        public string Amount { get; set; }
        public int? MonthNumber { get; set; }
    }
}

screenshot of the empty chart

Function show div in with localstorage

I’m trying to learn about “localstorage”, and so far I’ve managed to apply it to a select. But I’m having trouble getting it to show the “div” with Content One or Contet Two after page load. Localstorage saves the selected option, but the “showDivOne” and “showDivTwo” functions do not work, only after clicking the same option again. Is there any way to make these two div’s appear without having to click again on some option?

var init = function (){
  //an ugly warning to users without localStorage support
  if(!window.localStorage){
    $('body').prepend('Sorry, you browser does not support local storage');
    return false;
  }
  var sel = $('select'),
      but = $('button');
  
  var clearSelected = function(){
      sel.find(':selected').prop('selected', false);
  }
  
  if(localStorage.getItem('pref')){
    var pref = localStorage.getItem('pref');
    clearSelected();
    //set the selected state to true on the option localStorage remembers
    sel.find('#' + pref).prop('selected', true);
  }

  var setPreference = function(){
    //remember the ID of the option the user selected
    localStorage.setItem('pref', sel.find(':selected').attr('id'));
  };
  
  var reset = function(){
    clearSelected();
    localStorage.setItem('pref', undefined);
  }
  
  sel.on('change', setPreference);
  but.on('click', reset);
};
$(document).ready(init);


        
function showDivOne(divId, element){
    document.getElementById(divId).style.display = element.value == 0 ? 'block' : 'none';
}

function showDivTwo(divId, element){
  document.getElementById(divId).style.display = element.value == 1 ? 'block' : 'none';
}
select, button {
  margin-top: .5em;
}


#one_div{
    display: none;
}



#two_div {
    display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>


<select onchange="showDivOne('one_div', this); showDivTwo('two_div', this);">
  <option selected>Select an option</option>
  <option id="opt1" value="0">1</option>
  <option id="opt2" value="1">2</option>
</select>


<button>Reset preference</button>

<div id="one_div">Content One</div>
<div id="two_div">Content Two</div>

Passing function expression to object returns undefined

I have reviewed similar questions and most seem to concern this, mine doesn’t. I am trying to create a new property that is a function expression on objects in an array but the property returns undefined. I need it to return function

Here is a fiddle version.

let athleteArray = [
  rupert = {
    name: 'Mike',
    age: '33',
    sport: 'sitting',
    quote: 'Hello Super nintendo chalmers'
  },

  alice = {
    name: 'Bill',
    age: '35',
    sport: 'cooking',
    quote: 'stop that'
  }
];


const win = function(name, sport) {
  console.log(`${name} won the ${sport} event!`)
}

//loop to add new 'win' property

for (let i = 0; i < athleteArray.length; i++) {
  athleteArray[i].win = win(athleteArray[i].name,
    athleteArray[i].sport)
  console.log(athleteArray[i])
  console.log(typeof(athleteArray[i].win))
}

Play a set of (looped through) videos on hover over buttons

I am having the hardest time figuring this ‘seemingly’ simple thing out.

I have a set of video. Each video is accompanied by a button that I want to hover over to play/pause the video.

This below implementation just plays the first video on button hover, but not the others.

I don’t know what I’m doing wrong and I need your help as a noob.

div class="video_wrapper">

<video class="video" style="object-fit: contain; overflow:hidden" preload="preload" loop="loop" muted="muted" playsinline="playsinline"> 
    <source src="/url" type="video/mp4">
</video>      

JS:

const items = document.querySelectorAll('.testbutton');
const videos = document.querySelectorAll(" .video_wrapper .video");

for (const video of videos) {
items.forEach(item => {
    const video = document.querySelector('.hover_video_wrapper .video');

    item.addEventListener('mouseover', function () {
        video.play();
    });

    item.addEventListener('mouseout', function () {
        video.pause();
    });
});

}

How can I get the count of filtered odata?

I am attempting to get the count of filtered odata results in a SAP Fiori Ui5 application. I am able to get the correct count using both $count and $inlinecount in Postman using the following:
entitySet/$count?$filter=Id eq '9'
and
entitySet?$filter=Id eq '9'&$inlinecount=allpages&$format=json.

However, when I try to use these query parameters in my Ui5 code, I do not get the result I want.

odataModel.read("/entitySet/$count?$filter=Id eq '9'", { ...

gives me the count of the unfiltered results, while

odataModel.read("/entitySet?$filter=Id eq '9'&$inlinecount=allpages", { ...

gives me all the records, and I am unable to access the inline count.

Any suggestions?
Thanks

How to add another object to an object using typescript?

i want to add an object into another object using typescript.

below is data1

data1 {firstDetails: {...}}

when i expand the data1 above it is like below,

   firstDetails: 
       id: '1',
       name: 'first'
       description: 'description'
       //other fields,
     

and there is data2 like below

 data2 {secondDetails: {...}}

expanding data2 is like below

secondDetails:
    id: '1',
    items: [],
    values: [],

now i want to remove property id from secondDetails and then take items and values from data2 and add it to data1.

so the expected output is like below

firstDetails:
    id: '1',
    name: 'first',
    description: 'description',
    items: [],
    values: [],

i have tried like below,

const formattedData2 = formattedData2.secondDetails;
const without_id = omit(formattedData2, 'id')
data1.firstDetails = Object.assign(data1.firstDetails, without_id);

but this gives error in dat1.firstDetails in the last line. it says variable data has implicitly any type.

could someone help me fix this. how can i put one object into another using typescript. thanks.

how can I use a RegEx on a string of comma separated items?

I’m trying to partially hide email addresses from a string of comma-separated emails. I’m using this expression to go through the first item in the string, but i wondering how to do it on each email ( ie. each item following a comma). the list contains a variable number of email addresses, and i dont know how to go through each one and display them accordingly.

redactedemail = email.replace(/(w{3})[w.-]+@([w.]+w)/, "$1***$2");

so that a string like :

"[email protected],[email protected],[email protected]"

will show like :

par***@youremail.com,lon***@youremail.com,oth***@youremail.com"

right now, only the first item in the list is processed by the RegEx.

How to run a cmd command in the current Terminal

I have a simple issue involding child_proccess. If you call child_process from a script its going to run that command in that script. If you export a function that runs the command, for what i’ve tested, it tries to run the command in the library terminal and not the current terminal.
Example:
Lets say you have your script a.js that you export to b.js and in a.js you have this function called hello that prints “Hello World” with the echo command:

//a.js
export function hello(){
  child_process.execSync("echo Hello World");
}
import {hello} from "a.js"
hello();

When you run it it will not send you anything. If you print “Hello World” with console.log() it will return it in the current terminal. Is there a way to execute a cmd command in the current terminal?

Changing color in ticks google charts

__Hello, guys. I’m practicing in google charts. And I met a problem, which I can’t to solve.
google chart

I’m using ticks labels:

‘vAxis’: {
ticks: [{ v: 720, f: ’12:00′ }

And want to customize colors for two values in tick label:

data.addRow(
        ['{{list[i][0]}}',
        { v: {{list[i][1][0]}}, f: '{{list[i][1][1]}} {**color: #335408**}Yest: + {{list[i][2]}}' }]

How can I do this?