Use an object attribute to create an array with it

Hi guys i want to do something “simple” but not for me, I have this array

[
  { x: 'bmw', vehicule_type: car, y: 1 },
  { x: 'mercedes', vehicule_type: car, y: 2 },
  { x: 'airbus', vehicule_type: plane, y: 1 }
]

And i want to transform it to this thing

[
  car : [{ x: 'bmw',  y: 1 },  { x: 'mercedes', y: 1 }]
  plane: [{ x: 'airbus',  y: 1 }]
] 

I cant find a way to do it, i saw that i could use “reducer()” but for the rest i’m lost

Google Places Autocomplete Returns Undefined

I have this autocomplete snippet code that when the user clicks on the autocomplete suggestion (which is the first input field) the other fields will have its value added based on the place variable. I do not know why it returns as undefined though. Any guidance would be helpful. Thank you.

let autocomplete;
let placeSearch;
let componentForm = {
  street_number: 'short_name',
  route: 'long_name',
  locality: 'long_name',
  administrative_area_level_2: 'long_name',
  country: 'long_name',
  postal_code: 'short_name'
};

function initAutocomplete(){
  if ( jQuery( '#autocomplete-streetNumber' ).length ) {
    autocomplete = new google.maps.places.Autocomplete(
      document.getElementById( 'autocomplete-streetNumber' ),
      {
        types: ['address'],
        componentRestrictions: {'country':['AU']},
        fields: ["address_components"] }
    );
    autocomplete.addListener( 'place_changed', fillInAddress );
  }
};

function fillInAddress() {

  // Get the place details from the autocomplete object.
  let place = autocomplete.getPlace();

  // Get each component of the address from the place details
  // and fill the corresponding field on the form.
  document.getElementById('autocomplete-streetNumber').value = place.address_components.street_number;
  document.getElementById('streetName').value = place.address_components.route;
  document.getElementById('suburb').value = place.address_components.locality;
  document.getElementById('postCode').value = place.address_components.postal_Code;
}

Why should I care if my react project has incorrect/unmet peer dependencies?

Does having incorrect/unmet peer dependencies have any significant impact on my react project. I have read the yarn official documentation and it says:

Peer dependencies are a special type of dependency that would only ever
come up if you were publishing your own package.

I am not publishing any package here, just a simple react project with installed dependencies. I don’t know why it is the case with my react application but I am getting this warning each time I hit yarn install

[3/4] Linking dependencies...
warning "@react-pdf/renderer > [email protected]" has incorrect peer dependency "react@^16.0.0".
warning " > @testing-library/[email protected]" has unmet peer dependency "@testing-library/dom@>=7.21.4".
warning "aws-amplify > @aws-amplify/analytics > @aws-sdk/client-firehose > @aws-sdk/middleware-retry > [email protected]" has unmet peer dependency "react-native@>=0.56".
warning " > [email protected]" has incorrect peer dependency "mobx@^2.2.0 || ^3.0.0 || ^4.0.0 || ^5.0.0".

Should I take it seriously and add the peer dependencies properly, and If I choose not to do so, does this negatively impact my project? Can they be automatically added? and why do the packages I install not automatically add them?

devenv: Using yarn v1.22.18 as my package manager with node:16-buster image.

I have installed webpacker and but rails won’t recognise javascript code

I am new to rails and I am making an Instagram clone for practice. For flash messages, I am using toastr-rails gem and javascript code where required But my app is not recognizing javascript script tags and the code is not executing. here is my application.html.erb file code
app/views/layouts/application.html.erb

<!DOCTYPE html>
<html>
  <head>
    <title>Instagram</title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
    <script src="https://kit.fontawesome.com/5238639648.js" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <!-- jQuery library -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

    <!-- Latest compiled JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    </head>

  <body>

    <%= render 'shared/navbar' if current_user %>
    <div class="container">
      <%= yield %>
    </div>
    <% if flash.any? %>
      <script type="text/javascript">
        <% flash.each do |key, value| %>
          <% type = key.to_s.gsub('alert', 'error').gsub('notice', 'success') %>
          toastr.<%= type %>('<%= value %>')
        <% end %>
      </script>
    <% end %>

  </body>
</html>

On installing webpacker and adding gem webpacker in my app, nothing happened to my javascript folder as well, like no folder named packs was generated and I did that manually but still, my app won’t recognize javascript and files with extension js.erb

Comparing 2 arrays, then push if the condition is met

I am trying to filter out emails that are already existing in userData, but my code keeps pushing same data over and over as long as the email is not the same.

Here’s my code:

var userData = this.userData
var parsedData = this.parseData
complete: function(results) {
            const parseData = results.data
            for(var j = 0; j < parseData.length; j++){
              userData.map((data)=>{
                  if(data.email.toLowerCase() != parseData[j].email.toLowerCase()){
                    parsedData.push(parseData[j])
                    
                  }else{
                     alert("This "+parseData[j].email+" already exist.")
                   }
              })
            }
          }

Next Run code until Button is clicked again

learning next and stuff and had a question I did not have any success on finding online.

So I have a button

<button onClick={toggle} className="common-btn">{buttonText}</button>

I am wanting this button to control how long a section of code is ran. So within the toggle method I update the state and that works just fine. I also run a while loop hoping that if the state ever changed it would break out of the while loop running the code like so

...
setRunning(!running)
if(running){
    while(running) 
    {
      console.log("Running")
    }
}

... 

The issue comes in since it never breaks out of the while loop so even if the state is false it will continue to run the original while loop. Does anyone have any better insight on how to go about this?

AppCheck tokens are not recognised only when using mobile

I’m developing a webapp authentication system using Firebase. When I login and use the webapp from my computer everything works fine but when I use it on mobile appcheck does not work anymore and it gives me the following error in the console:

https://content-firebaseappcheck.googleapis.com/v1/projects/nameoftheproject/apps/1:784721317237:web:5db5892bc06253ab6b173c:exchangeRecaptchaEnterpriseToken?key=myKey
Failed to load resource: the server responded with a status of 403 ()

This is the code I’m using to create initialise appCheck in my webapp:

const appCheck = initializeAppCheck(app, {
    provider: new ReCaptchaEnterpriseProvider(config[process.env.REACT_APP_ENV]['recaptcha-key']),
    isTokenAutoRefreshEnabled: true
  });

export const getAppCheckToken = async () => {
    let appCheckTokenResponse;
    try {
        appCheckTokenResponse = await getToken(appCheck, false);
    } catch(err) {

        console.log(err);
    }
    return appCheckTokenResponse.token;
}

So a typical use case for that function is this:

//This is the code from one of my functions, it's just an example to show you how I use appcheck tokens
if (querySnapshot.docs.length === 0) {
                headerAPI.headers['X-Firebase-AppCheck'] = await getAppCheckToken();

                await axios.post(signupAPI, {
                    email: email,
                    username: displayName
                }, headerAPI);

                await sendEmailVerification(auth.currentUser, {
                    url: config[process.env.REACT_APP_ENV]['url-used-to-send-mail-auth-signup'],
                    handleCodeInApp: true
                })

                props.cookieAlert('Info', 'Cookies', 'Informations here...');
            } else {
                window.location.href = '/dashboard/home';
            }

Now, I can’t understand why it doesn’t work on mobile…I hope my code is clear enough to let you understand my troubles, thank you in advance.

React Native how to prevent elements to jump to top when opening keyboard?

I have vert simple activity in React Native.
My activity has one text field TextInput.
And Button an the bottom submit.
But my problem is that when i try to enter something into TextInput.
Keybord which is opening pushes button from the buttom to the top, and makes button cover textInput.

enter image description here

Here’s my code, maybe anyone knows how can i fix it?
I tried to use zindez and absolute but it didn’t work

    <View 
     style={{
       marginTop: 10, 
       marginBottom: 10, 
       backgroundColor: '#E6ECF0',
       borderRadius: 10,   
     }}
    >
      <TextInput
        style={{
          margin: 20,
          backgroundColor: '#e6ecf0',
          height: 200,
          minWidth: 250,
        }} 
      />        
  </View>    
  <View 
    style={{ 
      backgroundColor: 'white', 
      justifyContent: 'flex-end', 
      flexDirection:'row', 
      flex: 2 
    }}
  >
    <View 
      style={{ 
        justifyContent: 'flex-end', 
        alignItems: 'center', 
        paddingBottom: 70 
      }}
    >
      <Button text={'submit'} />
    </View>
  </View>

Is there a way to rotate a element and treat the input as its rotated value?

I have a canvas with ID foobar. I’ve already drawn to it.

let canvas = document.getElementById("foobar");

I need to rotate this canvas 90°. Rotating #foobar with CSS doesn’t work:

#foobar {
  /* When I click somewhere on the canvas, it registers the position of the click
     as what the position would be pre-rotation rather than post-rotation. */
  transform: rotate(90deg);
}

In addition, rotating the context only works when an element has yet to be drawn, so this won’t work either:

let context = canvas.getContext("2d");
context.rotate(90 * (Math.PI / 180));

I am saving an IPFS file and using res.send() to push it to the front end, why is this not working?

The error tells me i “Cannot set headers after they are sent to the client”

async function saveFile(file) {
    await ipfs.add(file, (err, result) => {
        if (err){
            console.log(err);
        }
        console.log(result);
    });
}
app.post('/upload', async (req, res) => {
    const file = req.files.file;
    const fileName = req.body.fileName;
    const filePath = 'files/' + fileName;
    console.log(file);
    const fileHash = saveFile(JSON.stringify(file));
    res.send(fileHash);
    res.render('pages/upload.ejs', { fileName, fileHash });
    
});

VS Code auto-import is appending index to the path

When I try to auto-import variables from an index.js file. They get imported from path/to/file/index instead of just path/to/file. How can I stop the auto-import from appending “index” to the import path.

This is what my jsconfig.json looks like

{
    "compilerOptions": {
      "module": "commonjs",
      "paths": {
        "src/*": ["./src/*"],
        "test/*": ["./test/*"]
      },
      "baseUrl": "./"
    }
  }

How can I use either req.query, or req.params, or req.* outside its scope without saving in database

I’ve been trying to build a helper function that will allow me to apply DRY pattern in order to stop repeating myself. My backend and the whole application is complete, however, I’d like to optimize my code, and my actual problem is that pretty much every express http method is similarly formatted the same way. The only time I’ve happened to come close to the solution is when I’ve omitted the req.params as arguments. The problem is that each method has its own req.params format. Here’s how I was trying to solve:

  • I tried to use node-persist package to store req.params, and it only works after I change and resave the file, which makes sense. This happened as I first passed the params as the argument and tried to pass the persisted params value when I call the function. If there’s a way to have the req.params stored somewhere locally first, I wouldn’t be worried.

  • Second Option, I tried to use recursion and called the so-called function twice. I expected the first call to return an undefined params, and the second function call to return stored req.params, but unfortunately it wasn’t the case.

  • I then decided to try using req.redirect where I’ve to access the database with req.params that came from req.query. Although this works, it still brings me back to the same problem as I’ll keep redirecting everything

  • My problem, I want to have a helper function like the following:

  export const storage = require('node-persist'); //package to persist data
 

Few of types used:

type AllHTTPMethods = "post" | "delete" | "all" | "get" | "put" | "patch" | "options" | "head";

type HTTPMethod = core.IRouterMatcher<core.Express, AllHTTPMethods>;
export async function onFetch(httpMethod: HTTPMethod | any, sql: string, path:string, params?: string){
    
    httpMethod(path, async(req, res) => {
        
        await storage.init({});
      
       
        /**
            Check if there is something already stored
         */
        if (Object.keys(req.params).length === 0) {
            await storage.setItem('params', req.params)
            await storage.updateItem('params', req.params)
        }
      
          conn.query(sql, [params],
            (err:any, data:any) => {
            if (err) {
                return new Error("Something went wrongn"+err)
            }
            console.log("Successfully fetched");
            console.log(data)
            return res.json(data);

            })
    })
}

Here’s how I invoked them:

    //This one works because params aren't involved
    async all() {
        await onFetch(app.get.bind(app), "select * from products", "/products")
            .then(() => console.log("Successfully fetched products"))
            .catch(e => console.error(e))
    }
   //This one didn't work Because the function needs to called first before
   //persisting
   getProductById = async () => {
        await storage.init()
        const paramsObj = await storage.getItem("params"); //returns empty object {}
        await onFetch(app.post.bind(app), "select * from products where id = ?", "/product/:id", paramsObj.id)
    }

And the last trick I tried was to have req.params from client upfront, then redirect them to another router

  • Helper function to send req.params:

export function generateParams(
    httpMethod: HTTPMethod,
    path: string,
    params: string,
) {
    httpMethod(path, (req, res) => {
        const paramsObject = JSON.stringify(req.params);
        return res.redirect(`/params/api/?${params}=${paramsObject}`)
    })
}

Calling:

generateParams(app.post.bind(app), "/product/:id", "product")

It works but it’s still the same problem I was trying to avoid beforehand

app.get('/params/api', async (req, res)=> {
  var product: string | string[] | any | undefined = req.query.product;
  var id:any = JSON.parse(product).id
  
  conn.query("select * from products where id = ?", [id], (err, data)=>{
    if (err) {
      return
    }
    res.json(data)
  })
});

Thanks in advance

I want to embed pdf file

I want to show pdf file in my website and my friends tell me about this method and all communities also tell me this method

 <body>
    <embed src="files/oldEhsa.pdf" type="application/pdf" />
  </body>

But when i use this code and open my website it start to download my pdf file not show it

what is wrong i might have done ?

How to make a matrix from two arrays column and rows in JS?

I have a json data format:
[{'note':'n1','subject':'subject1','value':10},{'note':'n3','subject':'subject2','value':19}];
from that I have generate two arrays one for header column cols and other for row rows

let notes = [{'note':'n1','subject':'subject1','value':10},{'note':'n3','subject':'subject2','value':19}];

let cols = ['n1', 'n2', 'n3'];
let rows = ['subject1', 'subject2'];

let matrix = Array(cols.length).fill(Array(rows.length).fill(0));
for(const x of notes){
    let {note, subject, value} = x;
    matrix[cols.indexOf(note)][rows.indexOf(subject)] = note;
}
console.log(matrix)

Expected result:

[[10,0,0],[0,0,19]]

But My goal is to render it as an HTML table looks like this:

SubjNote Note1 Note2 Note3
Subj1 10 0 0
subj2 0 0 19

How could I do that, Any suggestion or help is much appreciated!