Git – Renaming a Branch Name, Encounter an error

I have given the branch name as below while creating the new branch:

git checkout -b "working_with_controllers(APIs_Logic)"

At them time of creation it didn’t throw an error stating

this is the wrong format

But when trying to switch or rename a branch using command

git branch -m working_with_controllers(APIs_Logic)  new-branch working_with_controllers

Showing the error

bash: syntax error near unexpected token `('

Can any one help me with the solution please

How to hide DIV’s parent in JS with a specific content

I’m trying to hide a DIV’s parent when a certain DIV contains a specific text.

An example. This DIV I want to stay:

<div class="report-per-day">
<div class="report-day">26 May 2022</div>
<div class="status-report-rows">
<p class="report__headline">This is our report</p>
</div>
</div>
</div>

But I want to hide this whole DIV, because there’s a DIV .mt-2, which contains “No new incident.”

<div class="report-per-day">
<div class="report-day">25 May 2022</div>
<div class="mt-2" style="display: none;">
<small class="text-muted">No new incident.</small>
</div>
</div>
</div>

I have this Java Script, but it only hides the .mt-2. I’d also like to hide its 2 parents, .report-per-day and .report-day

Do you guys happen to have any suggestions? Thanks a lot!

const divs = document.getElementsByClassName('mt-2');

for (let x = 0; x < divs.length; x++) {
    const div = divs[x];
    const content = div.textContent.trim();
  
    if (content == 'No incidents reported.') {
        div.style.display = 'none';
    }
}

How to rewrite this template processor without eval?

I currently have a template read from a file into tstr and I replace placeholders in it like so:

const obj = { main: 3 };
const func = () => { const a = 2; };

let tstr = `

<fname func>

<fbare func>

<var obj.main>

`;

tstr = tstr.replace(/<var ([^>]+)>/g, function () { return eval(arguments[1]) });
tstr = tstr.replace(/<fbare ([^>]+)>/g, function () { return eval(arguments[1]).toString() });
tstr = tstr.replace(/<fname ([^>]+)>/g, function () { return arguments[1] + ' = ' + eval(arguments[1]).toString()  });


console.log(tstr);

Is there a simple way to rewrite these replacements without eval?

MUI: The value provided to Autocomplete is invalid. None of the options match with `””`

enter image description here

When a value is entered in the input of the autocomplete component I get this warning that I can’t remove…
This is what my input looks like

 <Autocomplete
            id="cboAdresse"
            sx={{ width: 100 + "%", fontFamily: "Poppins Bold" }}
            getOptionLabel={(option) =>
              typeof option === "string" ? option : option.label
            }
            filterOptions={(x) => {
              return x;
            }}
            options={lstadresse}
            isOptionEqualToValue={(option, value) =>
              value.label === option.label
            }
            autoComplete
            includeInputInList
            filterSelectedOptions
            value={adresse}
            noOptionsText="Aucune adresse trouvée"
            onChange={(event, newValue) => {
              setLstAdresse(
                newValue.name ? [newValue.name, ...lstadresse] : lstadresse
              );
              setAdresse(newValue.name);
              if (newValue.name != "") {
                setVille(newValue.city);
                setCodePostal(newValue.postcode);
              }
            }}
            onInputChange={(event, newInputValue) => {
              setInputRue(newInputValue);
            }}
            renderInput={(params) => (
              <div
                ref={params.InputProps.ref}
                className="login-block__input form_input_white"
              >
                <input
                  type="text"
                  name="adresse"
                  placeholder="Adresse"
                  {...params.inputProps}
                />
              </div>
            )}
      />

We can see that I have integrated the IsOptionEqualToValue parameter without solving the problem. During my research other people have faced this problem and solved it with what I wrote with the IsOptionEqualToValue. If anyone has a solution I’m interested. Thanks in advance.

Why doesn’t the constructor property show up in for/in loop or Object.keys but works with getOwnPropertyNames?

So here’s the code:

function foo() {};

let obj = new foo();

console.log(Object.getOwnPropertyNames(obj)); //  []
console.log(Object.getOwnPropertyNames(Object.getPrototypeOf(obj)));
//  [ 'constructor' ]

We create and instance of foo on line 3. On line 5, we output the own properties of instance obj which outputs and empty array. On line 6, we output the properties on the prototype of instance obj which displays an array containing the constructor property.

However, when I try to check for the constructor property using Object.keys or for/in loop, it doesn’t show up. Why?

function foo() {};

let obj = new foo();

console.log(Object.keys(Object.getPrototypeOf(obj)));   //  []

for (let key in Object.getPrototypeOf(obj)) {
  console.log(key);
}

How to find multple results in Arrays with JavaScript?

How i make this?

const arrays = [
    { servername: "MyServer", owner: "Evelyn" },
    { servername: "Minecraft Server", owner: "Maria" },
    { servername: "You really are reading this? xd", owner: "RaymondG" }
];

const Data = arrays.find(data => data.servername.includes("a"));
// Result: { servername: "Minecraft Server", owner: "Maria" }

// I want get this: [{ servername: "Minecraft Server", owner: "Maria" }, { servername: "You really are reading this? xd", owner: "RaymondG" }];

In summary, I would like to know how to obtain the data of an Array that contains certain requirements, I have tried with for-of, but the problem with this is that with large data, it usually takes a long time…

how to convert html webpage to PDF and download it In Javascript/Vuejs from client-side? That PDF should be editable and not just an image

I am using Vue.js (Vue2) Project and i need to give a functionality of export PDF for the webPage/Html content which is displayed already for the user. there are lots of libraries like jsPDF, html2pdf, etc etc but none of them allows me to select the text or edit the PDF in Online PDF editor.
And 1 more thing that the html content is already rendered in the browser and that html I want to export as a PDF so basically it should be operated totaly from client Side and not from the server Side.
I have heard about pspdfKit but the documentation is not clear.

h1 element not be updated correctly by setInterval

i want to create a simple React app that upadates a h1 element every second with setInterval function. I have an array with strings and every second i want randomly pick a string from that array and uses that string inside h1. But my code doesnt work properly. h1 not be updated every second but every millisecond.

import PersonalInfo from './PersonalInfo.js'
import { useState } from 'react';

function App() {
  const myPersonalInfo = ['books', 'music', 'code']; 
  const [state, changeState] = useState(myPersonalInfo[Math.floor(Math.random() * myPersonalInfo.length)]);

  setInterval(() => {
    changeState(myPersonalInfo[Math.floor(Math.random() * myPersonalInfo.length)]);
  }, 2000);

  return (
    <div className="App">
      <PersonalInfo title={state} />
    </div>
  );
}

export default App;
function PersonalInfo({ title}) {
    return <div>
        <h1>I Love {title} </h1>
    </div>
}

export default PersonalInfo

TypeScript – Distributive conditional types

Talk is cheap,show the code!


type ITypeA = ((args: { A: any }) => any) | ((args: { B: any }) => any);

type Test<T> = T extends (args: infer A) => any ? A : never;

// type Result1 = {
//     A: any;
// } | {
//     B: any;
// }
type Result1 = Test<ITypeA>;

// type Result2 = {
//     A: any;
// } & {
//     B: any;
// }
type Result2 = ITypeA extends (args: infer A) => any ? A : never;

Result1 may use ‘distributive conditional types’ rule in ts, so type Result1 = { A: any;} | { B: any;}. My question is why does Result2 not apply this rule? Is there any difference between them?

How to create dynamic object using javascript?

I have one array variable and object. i need to map the object value with array variable’s key value. i couldn’t map the value when have nested object. kindly refer the data below.

the condition array variable is

let allowedField = [
                'organization_id',
                'organization_name',
                'payload.offer',
                'id',
                'candidate_id'
            ]

full response object is

let data = {
                organization_id: 4002400004,
                organization_name: 'Velocity Global Integration Sandbox',
                action: 'offer_updated',
                payload: {
                    offer: {
                        id: 4524843004,
                        application_id: 31948577004,
                        user_id: 4123647004,
                        version: 1,
                        sent_on: null,
                        resolved_at: '2022-05-19T06:21:25.084Z',
                        start_date: '2022-05-17',
                        notes: null,
                        job_id: 4298940004,
                        offer_status: 'Accepted'
                    }
                }
            }

Below i have mentioned required output,

let ouputObj = {
organization_id: 4002400004,
organization_name: 'Velocity Global Integration Sandbox',
payload: {
offer: {
id: 4524843004,
application_id: 31948577004,
user_id: 4123647004,
version: 1,
sent_on: null,
resolved_at: '2022-05-19T06:21:25.084Z',
start_date: '2022-05-17',
notes: null,
job_id: 4298940004,
offer_status: 'Accepted'
}
}
}

quasar q-select use filter event as a common function not work

I try this @filter event example

https://quasar.dev/vue-components/select#example–basic-filtering

can work

Index.vue

<template>
  <q-select
    :options="options"
    @filter="filter"
    v-model="model"
  ></q-select>
</template>

<script>
import { defineComponent } from "vue";
import { computed, reactive, toRefs, ref } from "vue";
const selectedOptions = ["Google", "Facebook", "Twitter", "Apple", "Oracle"];

export default defineComponent({
  name: "PageIndex",
  setup() {
    let state = reactive({
      model: null,
      options: selectedOptions,
    });

    const filter = (val, update, abort) => {
      update(() => {
        const needle = val.toLowerCase()
        state.options = selectedOptions.filter(v => v.toLowerCase().indexOf(needle) > -1)
      })
    }

    return {
      filter,
      selectedOptions,
      ...toRefs(state),
    };
  },
});
</script>

I want to do common function from utils/filter.js but not work

Index.vue

<template>
  <q-select
    :options="options"
    @filter="
      (val, update, abort) =>
        filter(val, update, abort, selectedOptions, options)
    "
    v-model="model"
  >  </q-select>
</template>

<script>
import { defineComponent } from "vue";
import { computed, reactive, toRefs, ref } from "vue";
import { filter } from "../utils/filter";
const selectedOptions = ["Google", "Facebook", "Twitter", "Apple", "Oracle1"];

export default defineComponent({
  name: "PageIndex",
  setup() {
    let state = reactive({
      model: null,
      options: selectedOptions,
    });

    return {
      filter,
      selectedOptions,
      ...toRefs(state),
    };
  },
});
</script>

utils/filter.js

export function filter(val, update, abort, from, to) {
  update(() => {
    const needle = val.toLowerCase()
    to.value = from.filter((v) => v.toLowerCase().indexOf(needle) > -1)
  })
}

What to do to get filtering to work ?

https://codesandbox.io/s/blissful-brattain-vd085n?file=/src/utils/filter.js

How can I investigate memory issues in NodsJS on kubernetes

I am looking for a way to investigate one of our nodejs services that keeps getting the error

"FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory" 

when testing our performance.

I am looking for a package or program that will give me a warning when there is a memory leak and maybe what exactly is leaking. I know there are the heapdump snapshots, but most of the packages save it to a file that when it is saved on the pod when the pod will crash, will disappear, but also it takes a lot of memory to take the snapshot.

Most of the articles I found are very old and use packages that are already deprecated or just use snapshots and use the chrome dev tools but nobody seems to explain what exactly the columns in the snapshot mean.

Long story short: Do you have any suggestions for how to or which program/package to us for investigating memory issues in a nodejs service that runs on kubernetes and most of its info is received via message queue and not just RestAPI?

How to store video url in usestate and pass it to video popup modal react js

I get a response from API and pass it to the react js.

API response

    Array(80)
    0:
    Camera_Number: "Camera_1"
    Company_Name: "Fraction Analytics Limited"
    Floor Number: "Ground_Floor"
    Group_Name: "Group_1"
    Video_Name: "http://localhost:4000/video/0"
    [[Prototype]]: Object
    
    1:
    Camera_Number: "Camera_2"
    Company_Name: "Fraction Analytics Limited"
    Floor Number: "Ground_Floor"
    Group_Name: "Group_1"
    Video_Name: "http://localhost:4000/video/1"
    [[Prototype]]: Object

After getting a response populated API data to the react-ag grid.

App.js

    import video from "./video_2.mp4";
   ....... 
    export default function App(data, handleFormSubmit) {
      const { id } = data;
      const actionButton = (params) => {
        setOpen(true);
      };
      const [open, setOpen] = React.useState(false);
      const [setFormData] = useState(initialValue);
      const handleClose = () => {
        setOpen(false);
        setFormData(initialValue);
      };
      const columnDefs = [
        { headerName: "Name", field: "Company_Name", filter: "agSetColumnFilter" },
        { headerName: "Floor", field: "Floor Number" },
        { headerName: "Group", field: "Group_Name" },
        { headerName: "Camera", field: "Camera_Number" },
        { headerName: "Videos", field: "Video_Name" },
        {
          headerName: "Actions",
          field: "Video_Name",
          cellRendererFramework: (params) => (
            <div>
              <Button
                variant="contained"
                size="medium"
                color="primary"
                onClick={() => actionButton(params)}
              >
                Play
              </Button>
            </div>
          ),
        },
      ];
      const onGridReady = (params) => {
        console.log("grid is ready");
        fetch("http://localhost:8000/get_all")
          .then((resp) => resp.json())
          .then((resp) => {
            console.log(resp.results);
            params.api.applyTransaction({ add: resp.results });
          });
      };
      return (
        <div className="App">
          <div>
            <Dialog
              open={open}
              onClose={handleClose}
            >

          {/* Issue is Here */}
          <DialogContent>
            <iframe width="420" height="315" title="videos" src={video} />
          </DialogContent>
          {/* Issue is Here */}

        </Dialog>
      </div>
    </div>
  );
}

I used this code to call API and populate external API data to react js. Now the problem is to assign only one video to the source located in the project directory.

      <DialogContent>
       
       <iframe width="420" 
        height="315" 
        title="videos" 
        src={video} />
    
     </DialogContent>

Video_Name:"http://localhost:4000/video/0" , Video_Name:"http://localhost:4000/video/1"

How to assign the above multiple video URLs to the source(src) which I got from API.

Thanks

Why image and username not saved in firebase?

I have a react and firebase app wherein after successful login signup I need to display the username and the profile picture of the user.Its working until I refresh the page.After refreshing the username turns null and the profile picture is reduced to default profile Picture.Here’s the code for the same:

const Homepage = ({user,username,setusername}) => {
    const [photourl,setPhotourl]=useState(profile)
    const [photo,setPhoto]=useState(null);
    const handleImageChange=(e)=>{
       if(e.target.files[0]);
       setPhoto(e.target.files[0]);
    }
     function handleImageClick(e){
        if(photo)
        {
        const photoRef=ref(storage,photourl);
        console.log(photoRef);
         uploadBytes(photoRef,photo).then(()=>{
             getDownloadURL(photoRef).then((url)=>{
                 setPhotourl(url);
             }).catch((err)=>{
                 console.log(err);
             })
         }).catch((err)=>{
            console.log(err);
        });
        alert("Profile Image has been changed successfully. Click OK and Wait for a second to view the changes.");
        }
        else
        alert("Please upload a file")
    }
    // useEffect(()=>{
    //     if(user && user.photoURL)
    //     setphotourl(user.photoURL)
    // })
    return (
        <>
            <header>
                <nav>
                    <div className="logo"><h1 className=""><a href="#">SOLRUF</a></h1></div>
                    <div className="menu">
                            <h3>Welcome {username}</h3>   
                            <img className="avatar" src={photourl}/> 
                            <button >Change Username</button>                    
                    </div>
                </nav>
                <main>
                    <section>
                        <h3>Welcome To India</h3>
                        <h1>Do come and Visit<span className="change_content"> </span></h1>
                        <p>"India once is not enough"</p>
                        
                        <input  type="file" onChange={(e)=>{handleImageChange(e)}}/>
                        <button onClick={(e)=>{handleImageClick(e)}}>Change Profile Pic</button>   
                    </section>
                </main>
            </header>
        </>
    )
}

export default Homepage