apakah ekstensi Beautify bekerja di semua bahasa pemograman?

does the Beautify vscode extension work for all programming languages,
I’m currently working on a PHP, dart/flutter, html, css, javascript and sass project?
if the Beautify extension does not work in all programming languages, is there another extension that can work in all programming languages such as pretier etc.

How can I make certain words highlighted in incoming text?

I am new to application development and working in React Native. I want the color of certain words in the text to be red and clickable like picture below. You can see the incoming data under the picture. The words in data.highlight should be red and clickable when first seen in the text. Although there are a few “dummy” as seen in the picture, only the first one is red. I tried to do this but couldn’t get it to a loop. Everything is constant when I do it. The incoming data may change and for example there may be more than 3 words in the data.highlight. How can I do this in a practical way?

const data = {
    text: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, dummy when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
    highlight: ["dummy", "standard", "since"]
}

enter image description here

import React from "react"
import { Text, View } from "react-native"


const data = {
    text: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, dummy when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
    highlight: ["dummy", "standard", "since"]
}


const WordBoxText = () => {

    // for first highlight word
    const convertData1 = data.text.split(data.highlight[0])
    let converted = []
    for (i = 1; i < convertData1.length; i++) {
        converted.push(convertData1[i])
    }
    const rest1 = converted.join(data.highlight[0]) // maybe it will useful
    const Highlighter = <Text style={{ color: "red" }}>{data.highlight[0]}</Text>


    // for first highlight word
    const convertData2 = data.text.split(data.highlight[1])
    let converted2 = []
    for (i = 1; i < convertData2.length; i++) {
        converted2.push(convertData2[i])
    }
    const rest2 = converted.join(data.highlight[1]) // maybe it will useful
    const Highlighter2 = <Text style={{ color: "red" }}>{data.highlight[1]}</Text>


    // for first highlight word
    const convertData3 = data.text.split(data.highlight[2])
    let converted3 = []
    for (i = 1; i < convertData3.length; i++) {
        converted3.push(convertData3[i])
    }
    const rest3 = converted.join(data.highlight[2]) //sentences from the last word
    const Highlighter3 = <Text style={{ color: "red" }}>{data.highlight[2]}</Text>


    const Final = () => {
        return (
            <Text>{
                convertData1[0]} {Highlighter}
                {convertData2[0]} {Highlighter2}
                {convertData3[0]} {Highlighter3} {rest3} </Text>
        )
    }

    return (
        <View style={{ marginTop: 100 }}>
            <Final></Final>
        </View>
    )
}

export default WordBoxText

IS THERE A WAY TO PASS A DATA FROM PARENT COMPONENT TO CHILD COMPONENT WITHOUT HAVING THE NEED TO CALL AND DISPLAY THE CHILD TO THE PARENT COMPONENT? [closed]

I’m new to react JS and i am trying to pass a data from a component when i click it to another component..

for example, i have an image(parent) and when i click on it, it would open a new component(child) with the data from the parent.. HOW CAN I DO THAT ON REACT JS?

this is the container

<div className="Videos">
            <h2> Available Lessons </h2>
            <div className="Videos__uploads">

                {
                    vids.map(({ id, data }) => (
                        <Link key={id} to={{ pathname: `/play/${id}`, data: data}}>
                            {console.log(id)}
                            <VideoCard
                                key={id}
                                videoTitle={data.videoTitle}
                                videoDate={data.videoDate}
                                videoCaption={data.videoCaption}
                                videoUrl={data.videoUrl}
                            />
                            {console.log(data.videoUrl)}
                        </Link>
                    ))

                }

            </div>

this is the Parent

function VideoCard({ videoTitle, videoCaption, videoDate, videoUrl}) {

    return (
        <div className="videoCard">
            <img className="videoCard__thumbnail"
                src={Dummy}
                alt="Thumbnail"
                height="200px"
            />
            <div className="video__info">
                {/* <Avatar className="video__avatar"
                    alt={channel}
                    src={chan_img} /> */}
                <div className="video__text">
                    <h4>{videoTitle}</h4>
                    <p>
                        {videoDate}
                    </p>
                    <p>{videoCaption}</p>

                </div>
            </div>

            <VideoPlayer videoUrl={videoUrl}/>
        </div>
    )
}

and this is the child

function VideoPlayer({ key, videoTitle, videoUrl}) {
    
    return (
        <div className="videoPlayer__container">
            <h1>Helloo</h1>
            {console.log(videoUrl)}
            <ReactPlayer
                key={key}
                id="videoPlayer"
                url={videoUrl}
                height="100%"
                width='100%'
                playing={true}
                controls={true}
                volume={1}
                progressInterval={5000}
                pip={true}
            />
    </div>
)

}

Get rotation from camera matrix of format x y z w

I have a 4×4 matrix within JS called world to obj. This matrix I assume from context must be the camera transformations matrix and thus I am trying to extract the rotation from it in radians on x y and z axis.

I have no clue where to start and have tried many things

for context this below image it the camera transformations with no rotation

enter image description here

This second one is with rotation of 1 radian is applied to each axis. it is important to note that this camera is orbiting as well in this example

enter image description here

How to create multiples of of one object?

beginner coder with an assignment due soon and I cannot figure out how to incorporate for() loop in my code so that I will have more than one quad shape that can appear using if (mouseIsPressed) conditional. Here is my code:

//stars in the sky
      if (mouseIsPressed){
  starMorning = color(214,198,214);
  starEvening = color(255,255,225);
  //star colours transition from background colour to pale yellow
  starColours = lerpColor(starMorning,starEvening,mouseX/width);
  noStroke();
  fill(starColours);
  quad(55,40,50,45,55,50,60,45);
  }

This will create one quad shape in the left corner of the screen that slowly appears as you press on your left mouse button and move it horizontally across the screen. Now I want, say, 50 of these quad things all over the screen. How do I do that? Do I need to build classes and then use the for() loop? I’ve tried following so many tutorials but I just can’t seem to apply the logic to my code. Help please!!!

Google analytics track multiple custom variables

I’m tring to use google analytics to monitor activities on my laravel site, as you can see i managed to record the events by $user_name witch is great however how to i associate this user name with another variable for example $project_id so i can see data for each user and on each different project.

enter image description here

enter image description here

any idea how i can achieve this? here is my code:

<script>
$(document).ready(function(){
$(document).mousemove(function(){

  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-9YXX', {
  'custom_map': {'dimension<Index>': 'user_id'}
});

gtag('event', 'user_name', {'user_id': '{!!$user_name!!}'});

});

});

</script>

Javascript boolean logic (comparing double bang with truthy/falsy values)

I’m inspecting some code and I found something I’d like to run by Javascript veterans. I feel pretty comfortable with Javascript but I’ve always manage to run into something that makes me say, “I didn’t know that about Javascript!”

I’m hoping this is one of those situations:

if (this.props.referralId != prevProps.referralId ||
    this.props.referralValidationStatus != prevProps.referralValidationStatus ||
    this.props.customerName != prevProps.customerName &&
    !!prevProps.personId != !this.props.personId) {
   // perform whatever logic is here...
}

My questions:

  1. Does JS know how to automatically identify the mixture of || and &&? Or is this code missing parenthesis’s around the || comparison?
  2. Just as it’s explained here, is it fair and should I expect the obvious behavior when comparing a boolean against a truthy/falsy value?

I’m baffled on what the logic should be here. If I were to rewrite this I would do like so:

if ((this.props.referralId !== prevProps.referralId ||
    this.props.referralValidationStatus !== prevProps.referralValidationStatus ||
    this.props.customerName !== prevProps.customerName)
    && (!!prevProps.personId === !!this.props.personId)) {
   // Perform logic
}

However, I’d like to confirm and make sure I’m not missing something I might have missed about JS.

Thank you in advance for confirming my hunch or educating my on something new when it comes to JS. Looking forward to your comments and/or answers.

What is difference between let , const and var in case of variable shadowing /re declaration in different scope? [duplicate]

Please check below 2 code snippets the difference is redeclaring as const/let and var in foo function.

for var, it executes but for const and let it throughs error.

Please tell me why it behaves differently.

Below code does not through any error as a is declared as var
var a=12; //Global variable
foo(); //hoisting 
function foo() {
    console.log("a="+a);
    var a=13;
    console.log("a="+a);
    if(true) {
        const a=89;
        console.log("in block="+ a);
    }
    var a=90;    //no error
    console.log("a="+a);    
}

Below code throughs variable declaration error “a has already been declared”

var a=12; //Global variable
foo(); //hoisting 
function foo() {
    console.log("a="+a);
    var a=13;
    console.log("a="+a);
    if(true) {
        const a=89;
        console.log("in block="+ a);
    }
    let a=90;    //Or const a :: error
    console.log("a="+a);    
}

Position returned data results in App Lab (code.og)

We simply can’t find an answer this anywhere in the official documentation.

We are getting data on the screen like this…

var theStore = getText("searchlist");

readRecords("games", {store:theStore}, function(records) {
    if (records.length>0) {
        for (var i =0; i < records.length; i++) {
        write("-> " + records[i].title);
        }
    }
});

…which does get data, but the problem is that write() is not really the correct function to use, as it just returns all the data starting at the top of the screen and eventually rendering off screen, which absolutely no way to control it.

So how on earth can I just display the results in a way I can control the position? At the very least, I would be happy if the results were displayed in a textarea element.

Jenkins one_at_a_time hash – trying to Make Python Code reproduce JavaScript code

I borrowed this code from another post recently, and it works great for my needs…
But I’m trying to reproduce the same results from Python code so the two language functions agree, and I’ve been struggling… These two so far do NOT produce the same results like I need… I suspect it’s an issue with the unsigned integers in Python vs JavaScript.

JavaScript Code:

//Credits (modified code): Bob Jenkins (http://www.burtleburtle.net/bob/hash/doobs.html)
//See also: https://en.wikipedia.org/wiki/Jenkins_hash_function
//Takes a string of any size and returns an avalanching hash string of 8 hex characters.
function jenkinsOneAtATimeHash(keyString)
{
  let hash = 0;
  for (charIndex = 0; charIndex < keyString.length; ++charIndex)
  {
    hash += keyString.charCodeAt(charIndex);
    hash += hash << 10;
    hash ^= hash >> 6;
  }
  hash += hash << 3;
  hash ^= hash >> 11;
  //4,294,967,295 is FFFFFFFF, the maximum 32 bit unsigned integer value, used here as a mask.
  return (((hash + (hash << 15)) & 4294967295) >>> 0).toString(16)
};

Python code:

def calcuulateChecksum(keyString: str):
    # Credits(modified code): Bob Jenkins (http://www.burtleburtle.net/bob/hash/doobs.html)
    # See also: https://en.wikipedia.org/wiki/Jenkins_hash_function
    # Takes a string of any size and returns an avalanching hash string of 8 hex characters.
    hash = 0
    # for (charIndex = 0; charIndex < keyString.length; ++charIndex):
    for char in keyString:
        hash += ord(char.encode("utf-8"))
        hash &= 0xFFFFFFFF
        hash += hash << 10
        hash &= 0xFFFFFFFF
        hash ^= hash >> 6
        hash &= 0xFFFFFFFF
    hash += hash << 3
    hash &= 0xFFFFFFFF
    hash ^= hash >> 11
    hash &= 0xFFFFFFFF
    hash += hash << 15
    hash &= 0xFFFFFFFF
    # # 4,294,967,295 is 0xffffffff, the maximum 32 bit unsigned integer value, used here as a mask.
    return hex((hash & 4294967295))

Any help on making the Python code match the JavaScript function would be appreciated…
On the other hand, I believe the Python code matches results shown in the Wiki, so why doesn’t the JavaScript code?

Adding decimal separators to a YouTube view count retrieved via API

I’m trying to retrieve a YouTube view count for a specific video on my WordPress site. I’m not a coder but I’ve managed to get it working using this code:

<div id="viewCount" style="display: inline-block;"></div>
 <script>
       let getviewCount = () => {
        fetch(`https://www.googleapis.com/youtube/v3/videos?part=statistics&id=Cemk32wKN_k&key=XXXXXXXXXXXXXXXXXXXXXXXXXXXXX`)
        .then(response => {
            return response.json()
        })
        .then(data => {
            console.log(data);
            viewCount.innerHTML = data["items"][0].statistics.viewCount;
        })      
    }
    getviewCount(); 
    </script>

The final touch I’d like to add is decimal separators so instead of the number looking like this:

13526897

It looks like this:

13,526,897

Based on some research here I think I need to use a function similar to this:

function numberWithCommas(x) {
    return x.toString().replace(/B(?=(d{3})+(?!d))/g, ",");
}

But I don’t know how to code, so combining these two ideas is beyond my ability right now.

If anyone wouldn’t mind showing me how to do it, I’d be extremely grateful!

Thanks

React Redux and state after refresh

I have a problem with understanding why my app works kinda odd. When I try to reach any site on my page by clicking a link button in navbar, it navigates me there without any problems, like when I click “My account”, the URL changes to “http://localhost:3000/my_account” and everything works just fine. In this place I have to mention that “/my_account” is a protected route – user has to be logged in to reach it, when he is not logged in – he gets send to the homepage. So now the problem is that when user is logged in and tries to reach the protected route like “http://localhost:3000/my_account” by entering this URL and loading page – he is treated like a non-logged user and gets redirected to the homepage. And after he is redirected there and tries to reach this site by clicking the navbar link, he can enter this page – he is logged in. My expected result is that user can enter any URL on the site and react should check PROPRERLY if he is logged in in both cases – either when clicking a link on site or by providing a url. Can anyone tell me where do I make mistake?

UserAccount (/my_account) is a simple component:

import React, { Component } from 'react'

export class UserAccount extends Component {
    render() {
        return (
            <div>
                UserAccount
            </div>
        )
    }
}

export default UserAccount

In router in App.js I declare this route as:

<PrivateRoute path="/my_account" exact component={UserAccount}></PrivateRoute>

And the PrivateRoute is a functional component:

import React from 'react'
import {Route, Redirect} from 'react-router-dom'
import {connect} from 'react-redux'


const PrivateRoute = ({component : Component, auth, ...rest}) => (
    <Route {...rest} render={props => {
        if(auth.isLoading){
            return <h2>LOADING ...</h2>
        }
        else if(!auth.isAuthenticated){
            return <Redirect to="/login"></Redirect>
        }
        else{
        return <Component {...props}/>
        }
    
    }}></Route>
)
    


const mapStateToProps = state =>({
auth: state.auth
})

export default connect(mapStateToProps,null)(PrivateRoute);

My state in auth.js (reducer):

const initialState = {
    access: localStorage.getItem('access'),
    refresh: localStorage.getItem('refresh'),
    isAuthenticated: null,
    isLoading : false,
    user: null,
    requestSent: false,
    payload: null,
    message: null
}

And after successful login, state changes as follows:

    switch(type){
        case AUTHENTICATED_SUCCESS:
            return {
                ...state,
                isAuthenticated: true
            } 
        case LOGIN_SUCCESS:
            localStorage.setItem('access', payload.access);
            return{
                ...state,
                isAuthenticated: true,
                access: payload.access,
                refresh: payload.refresh
            }

And login function from auth.js actions:

export const login = (email, password) => async dispatch =>{
    const config = {
        headers: {
            'Content-Type': 'application/json'
        }
    };
    
    const body = JSON.stringify({email, password});

    try{
        const res = await axios.post(`${process.env.REACT_APP_API_URL}/auth/jwt/create/`, body, config);
        dispatch({
            type: LOGIN_SUCCESS,
            payload: res.data
        })
        dispatch(load_user());
        dispatch(createMessage({logged_in_successfully: "You are now logged in."}))
    } catch (err) {
        dispatch({
            type: LOGIN_FAIL,
            payload: err
        })
        const errors =  {msg: err.response.data, status: err.response.status}
        dispatch({
            type:GET_ERRORS,
            payload: errors
        })
    }
};

Thanks for your time reading that and I am hoping for some help.

Function doesn’t wait react hooks

I’m trying to add items in shopping cart. It works, but after adding items when I want to calculate number of items to show on the shopping cart. Second function (calculate()) doesn’t wait items hooks. Because of that, it shows the correct count after adding second item.

Below code is my functions. As you can see, in the end of first function I’m calling the calculate() function to keep it continue.

const [testArray, setTestArray] = useState([]);
const [total, setTotal] = useState(0);
const [cartCount, setCartCount] = useState(0);

function addToTest(product, quantity = 1) {
    const ProductExist = testArray.find((item) => item.id === product.id);
    if (ProductExist) {
      setTestArray(
        testArray.map((item) => {
          if (item.id === product.id) {
            return { ...ProductExist, quantity: ProductExist.quantity + 1 };
          } else {
            return item;
          }
        })
      );
    } else {
      product.quantity = 1;
      setTestArray([...testArray, product]);
    }

    calculate();
  }
  

  function calculate() {
    let resultCount = 0;
    testArray.map((item) => {
      console.log("map func works!");
      setCartCount(cartCount + item.quantity);
    });
  }

Here is my codesandbox project, I kept it very simple to not bother you.

https://codesandbox.io/s/react-template-forked-u95qt?file=/src/App.js

The possible problem occurs due to synchronise functions. Because of that, when I try to async/await, I’m getting error about parameters, because the first function has parameter.

This is my first try for async/await:

async function calculate(product) {
    await addToTest(product);
    let resultCount = 0;
    testArray.map((item) => {
      console.log("map func works!");
      setCartCount(cartCount + item.quantity);
    });
  }

As other solution I tried to use useEffect by taking the reference setArray hooks. However, in this case, the count number increases exponentially like 1,3,9…

useEffect(()=>{
    let resultCount = 0;
    testArray.map((item) => {
      console.log("map func works!");
      setCartCount(cartCount + item.quantity);
    });
  },[testArray])

I wonder where is the problem? Because when I use the the upper code in Angular/Typescript, it works properly. I think this happens due to react hooks, but I couldn’t understand the problem.

Javascript – How to prevent functions from multiplying themselves [closed]

I’m struggling.
I’m doing some work to make navigation fully accessible by mouse over, keyboard and click, depending on the resolution.

I am looking for that in mobile, only the click works.
And hover, click, keyboard for higher resolutions.

It only works perfectly when I load the page at the correct resolution (low or high).
BUT, if I resize live, my functions multiply by themselves by the number of resizes done.

I tried a lot of thing like e.stopPropagation , bubble, return, split functions, all in one…without success.

  • Here is a example of the problem with a factice code, shorter (maybe it could be suffisant to understand the solution with your help) :
    Need to reduce and maximize screen and click the button for testing.
    https://codepen.io/TanGo21/pen/RwLNWey

  • Here is, a part of my “real” code :
    Go under 770px, then maximize, and look the console when you go over item “THREE” who contains a submenu.
    https://codepen.io/TanGo21/pen/oNGgxBK