dynamically reference for image in react

I create a JS file that I named airConditions, its array of objects and each object contain some property like status for check conditions and have an src property for use in src of img

[
    {
        "id":800,
        "fa":"آسمان صاف",
        "en":"clear sky",
        "status": "clean",
        "icon": require("../../../assets/images/weather4/clean-day.png").default,
    },
    {
        "id":801,
        "fa":"کمی ابری",
        "en":"few clouds: 11-25%",
        "status": "haze",
        "icon": require("../../../assets/images/weather4/haze-day.png").default,
    },
    { 
        .
        .
        .
    }

]

I use this js file for use icon in src of img tag

<img
  className="weather-icon-png"
  src={this.state.iconSrc}
  alt={this.state.weatherDescription}
/>

but when I import the js file (airConditions)before everything it throws an error ===> ./src/json/module.js Module not found: You attempted to import ../../../assets/images/weather4/clean-day.png which falls outside of the project src/ directory. Relative imports outside of src/ are not supported.

before everything please see this question too. ===> stackoverflow

@okta/oidc-middleware express loginCallback not working

I’m using okta login with Express. When I run it on a server, it does call the loginCallback function that I specify on new ExpressOIDC config. But when I use the same okta app on another server, it’s not being called, instead after login it shows a 404 saying that loginCallback path does not exist. I create a loginCallback to handle the redirect, but then I have no access to req.userContext.

const oidc = new ExpressOIDC({
    issuer: "{issuer}",
    client_id: "{client_id}",
    client_secret: "{client_secret}",
    appBaseUrl: "http://localhost:3000",
    redirect_uri: "http://localhost:3000/loginCallback",
    scope: "openid email profile",
    routes: {
      loginCallback: {
        path: "/loginCallback",
        handler: (req, res, next) => {
          console.log("req", req.userContext.tokens);
          res.redirect("/");
        },
      }
    }
  });

Above code is not running in a server but it’s on the other.

server.get('/loginCallback', async (req, res, next) => {
    console.log("here!", req)
});

this does get called but can’t access the userContext obj.

Trying to get event data to work with countdown

Trying to get an if statement based on data from a form submission to work with a countdown. I’m not getting any errors but this obviously isn’t working, it never redirects after the countdown no matter if I select yes or no. I’ve used wiki urls because I haven’t set up the 2 actual calendar urls yet. I realize this may have been a completely incorrect way to even attempt this, but I’m not well versed in java at all. Any and all help is appreciated.

 
   // Total seconds to wait
    var seconds = 10;
        function countdown() {
        seconds = seconds - 1;
        if (seconds < 0) {
            window.addEventListener('message', event => {
  if(event.data.type === 'hsFormCallback' && event.data.eventName === 'onFormSubmit') {

    for (item in event.data.data) {
      if (event.data.data[item]["name"] == "would_you_like_to_schedule_a_device_demo_") {

        if (event.data.data[item]["value"] == "Yes") {
          window.location = "https://en.wikipedia.org/wiki/Apple";
        }
      if (event.data.data[item]["value"] == "No") {
          window.location = "https://en.wikipedia.org/wiki/Banana";
        }
   
      }
    }

  }
});
         
        } else {
            // Update remaining seconds
            document.getElementById("countdown").innerHTML = seconds;
            // Count down using javascript
            window.setTimeout("countdown()", 1000);
                        }
    }
    
    // Run countdown function
    countdown();

How to use import along with require in Javascript/Typescript?

I have index.ts and inside of it I have something like:

const start = () => {...}

Now I have app.ts that looks like this:

const dotenv = require('dotenv');
dotenv.config();
const express = require('express');
const app = express();
const server = require('http').createServer(app);

const PORT = 4001 || process.env.PORT;

server.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
  // I want to import and call start like this : start()
});

My package.json looks like this:

{
  "name": "...",
  "version": "1.0.0",
  "description": "",
  "main": "index.ts",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "start": "node app.ts"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    ...
  }
}

and tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "allowJs": true,
    "checkJs": true,
    "outDir": "./built",
    "allowSyntheticDefaultImports": true,
    "module": "CommonJS"
  }
}

The thing is, I can’t use import directive at all with this setup, so I guess I am doing something wrong.

How to import this function in app.ts from index.ts?

using frontmatter as data in 11ty

I need some help setting a featured image frontmatter parameter. I’ve been trying for hours to get this working and can’t seem to figure it out.

---
title: My post
date: 2020-02-23
published: true
thumb: '/assets/img/img.jpg'
tags:
- Tag 1
- Tag2
---

This is my markdown code. What I’m trying to do on my posts page is show the featured image, but when the code renders the src of the image shows as (unknown). I have been looking through some of the repos for the 11ty starter blogs and a few of them have a lot of custom frontmatter, but I can’t see in any of their files where this is being configured.

I have tried using eleventyComputed which didn’t seem to work. I have also tried using a posts.11tydata.js file in my posts folder which also didn’t do anything. I suspect this might be something easy, but I’ve spent hours looking at it and I’m completely lost at this point.

module.exports = {
layout: 'post',
title: 'Untitled',
eleventyComputed: {
permalink: (data) => `${data.page.fileSlug}/index.html`,
thumb: (data) => {
  if (data.thumb) {
    if (data.thumb.search(/^https?:///) !== -1) {
      return data.thumb;
    }
    return `/assets/img/${data.thumb}`;
  } else {
    return false;
  }
}

}
};

Any help is appreciated!

How to create a reusable Vuetify Snackbar?

I’m trying to create a reusable alert/snackbar component. I declared them like this:

Snackbar.vue

<template>
    <v-snackbar transition="true" timeout="2000" :show="`${show}`" :color="`${color}`" absolute top outlined right>
        <strong>
            {{ message }}
        </strong>
    </v-snackbar>
</template>

<script>
export default {
    name: 'Snackbar',
    props: {
        show: String,
        color: String,
        message: String
    }
}
</script>
<template>
    <v-snackbar transition="true" timeout="2000" :show="`${show}`" :color="`${color}`" absolute top outlined right>
        <strong>
            {{ message }}
        </strong>
    </v-snackbar>
</template>

<script>
export default {
    name: 'Snackbar',
    props: {
        show: String,
        color: String,
        message: String
    }
}
</script>

I imported, and pass probs to them like so :

import Snackbar from '../../../components/Snackbar'

<Snackbar v-if="alert" color="alertColor" message="alertMessage" />
<Snackbar show="alert" color="alertColor" message="alertMessage" />

I’ve tried the 2 lines above, and these are the value of those 3 variables

  • alert = true
  • alertColor = green
  • alertMessage = create.vue?f4fe:631 DB error - insert_marketing_campaign: Duplicate entry 'TEST' for key 'MARKETING_CAMPAIGN_AK'

Result

I see no error in console, but see no snackbar either. pls help

Append SVG Text at the top of a Bubble Group/Cluster. d3.js

I have these group of bubbles.enter image description here

And I’m trying to add an svg:text at the top center of each cluster. The problem is I have no way of getting the height of each cluster. I have no problem getting the center.

I tried getting the max height bubble in each cluster after the simulation ends:

                .force("y", d3.forceY().strength(0.1).y(heightLevel2)).on('end', () => {
                    var index = 0;
                    clusterHeightList.push(0);
                    d3.selectAll('.chart-bubble circle').each(function () {
                        const el = d3.select(this);
                        
                        if (clusterHeightList[index] < el.attr('cy')) {
                            clusterHeightList[index] = el.attr('cy');
                        }
                        if (data.data.includes(groupBreak)) {
                            clusterHeightList.push(0);
                            index++;
                        }

                        groupBreak++;
                    })
                //More logic where I append SVG text based on the max height of each cluster.
               });

The problem is that it is slow, since I have to wait for the simulation to finish. Also it’s slightly inaccurate.

I can guesstimate the height but that’s never the right way to go about dynamic data.

ideal example of text:
enter image description here

Any help would be helpful.

Replace() help needed [duplicate]

I need to convert all the G’s into C’s and C’s to G’s. Can someone help me find a way to stop the G and C from contradicting themselves? What I have so far:(I am beginner level at coding)

var str = "ATGC";
var step1 = (str.replace (/A/g, 'U'));
var step2 = (step1.replace (/T/g, 'A'));
var step3 = (step2.replace (/C/g, 'G'));
var step4 = (step3.replace (/G/g, 'C'));
var convertedStr = step4;
console.log(convertedStr);

End result is UACC because the step3 changes the C’s to a G and then step4 changes both new G’s into C’s

Javascript – Drop Down not showing all selections

First, I am a rookie with JavaScript. So, in SharePoint using a web part, the drop down for D Jobs will not show all select-able items. It appears to only show 100 select-able items, but is needs to show all 150 items in the drop down. I’m not sure why. Any help would be appreciated. Here is the script.

<script type="text/javascript"
src="https://Sharepoint/SiteAssets/jquery.js"></script>

<script type="text/javascript"
src="https://SahrePoint/SiteAssets/HillbillyCascade.js"></script>   

<script type="text/javascript">
      $(document).ready(function() {
      
            var cascadeArray = new Array();
            
            cascadeArray.push({
                  parentFormField: "Shop", //Display name on form of field from
parent list
                  childList: "D Jobs", //List name of child list
                  childLookupField: "Title", //Internal field name in Child List
used in lookup
                  childFormField: "D Job", //Display name on form of the child
field
                  parentFieldInChildList: "Shop0", //Internal field name in Child
List of the parent field
                  firstOptionText: "(Filtered by Shop)", dropDownItemCount:"999"
//Number of Items to Display on dropdown to remove 100 item limitation
            });
                 
            $().HillbillyCascade(cascadeArray);

});

</script>

Property ‘style’ does not exist on type ‘CSSProperties’

I’m changing a component from jsx to tsx and I’m having a typescript problem with a component that is using MaterialUI Grid. This is the code:

const GridItem = ({ style }: React.CSSProperties) => (
    <Grid item style={{ ...{ textAlign: 'center', marginBottom: 0 }, ...style }}>
    {children}
    </Grid>
    )

I’m receiving this error:
enter image description here

Property ‘style’ does not exist on type ‘CSSProperties’.ts(2339)

I have tried changing from CSSProperties to Element but I get the same error menssage. And HTMLCollectionOf as well..

What I’m doing wrong?

How can I change this once clicked submit button it “Post” and redirect to thank you page?

How can I change this once clicked submit button it “Post” and redirect to thank you page? I’m new to this and I’m stock and need your help. Thank you.

<div class="row" data-ar-id="knPGryb10X">
        
        <div class="col-md-10 col-lg-8 col-xl-7 mx-auto" data-ar-id="2a8BIf57NA">
          
        <form method="POST" action="https://storage/projects/1/ohPw14Bn7yEqk8K3BHmUfj4LDUw7PwlweOou/default-form-handler" class="" data-ar-id="72Xz7Iimkn">
    <div class="control-group" data-ar-id="46igvgmRN2">
      <div class="form-group floating-label-form-group controls mb-0 pb-2" data-ar-id="CNJEStnEZk">
        
        
      </div>
    </div>
    <div class="control-group" data-ar-id="RBHvtUd4UV">
      <div class="form-group floating-label-form-group controls mb-0 pb-2" data-ar-id="2JsYZhLtPe">
        <label data-ar-id="p3n77pazVO">Email Address</label>
        <input class="form-control" id="email" name="email" type="email" placeholder="Email Address" required="required" data-validation-required-message="Please enter your email address." data-ar-id="bKETslityp">
      </div>
    </div>
    <div class="control-group" data-ar-id="3E9itexHyL">
      
    </div>
    <div class="control-group" data-ar-id="r3Tt4ulNfM">
      <div class="form-group floating-label-form-group controls mb-0 pb-2" data-ar-id="llWK5VUTQp">
        
        
      </div>
    </div>
    <div class="form-group" data-ar-id="gg7EinsWzs"><button class="btn btn-primary btn-xl" type="submit" data-ar-id="GmTydIJXpg">Send</button></div>
  </form></div>
      </div>

How to create a level checker in JS?

I’m facing a problem, let me explain :

  • I have 20 levels
  • I have users ( id )

I need to check which level is the user. How I do that in my use case :

  • I get the ID of the user and I need to check which level he has in order to assign him a special discount.

I can do 20 if(level1.include(id))... but that’s not clean, how could I do that in a better way ?