jquery ajax header sending error Access to XMLHttpRequest at https://discord.com/api/guilds/1234567890

<script>
    const URL = "https://discord.com/api/guilds/899175503565553714";
    $.ajax({
        url: URL,
        type: "GET",
        headers: { Authorization: 'Bot ' + token } })
</script>

Here is my code

index.html:1 Access to XMLHttpRequest at 'https://discord.com/api/guilds/899175503565553714' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

How can I send headers and receive values ​​successfully with jquery ?

Get data from google firebase’s firestore, put into global object/array javascript, react

I am trying to read from firestore and push that data into a global variable. I am able to push however the array acts differently outside the function (I’ve attached a screenshot from the console showing the dif). For example I can call data[0] or data[1] inside the function just fine but outside it returns “undefined“. Can anyone help with this?
This is for a react project, so if there is a way to do it using react hooks or something like that, I can implement no problem.

let fbData = [];

const GetData = async () => {
    const q = query(collection(db, "surveys"), where("surveyComplete", "==", true));
    const querySnapshot = await getDocs(q);
    querySnapshot.forEach((doc) => {
        fbData.push({
            [doc.data().surveyId]: {
                "name": doc.data().surveyName,
                "id": doc.data().surveyId
            }            
        });
    }, 
    function (error) {
        console.log("Error getting documents: ", error);
    });
}

And yes I know the way I structure my data is weird, I’m planning on fixing it once I figure this issue out.

thanks

image of console log outside function and inside function

Devskiller Angular test questions [closed]

Angular Interview Questions from Devskiller?

  1. In Angular 2+, the method bypassSecurityTrustResourceUrl marked value as ____
    (a) Low Risk
    (b) trusted
    (c) Compatible
    (d) acceptable
2. Which of the following are proper ways to create an interface/type Point3D which would include all properties of Point and additionally z: number?
(a) type Point3D = Point <{
             z: number
        }>
(b) type Point3D = Record<"x" | "y" | "z", number>
(c) type Point3D = Point & {z: number}
(d) interface Point3D extends Point {
        z:number
      }

3. Which of the following statements are correct about relations between observables and promises?
(a) The promises can return to their pending state, contrary to observables.
(b) Observables can be cancelled, there is no way to cancel promise
(c) A promise can easily be converted to an observable using from pipeable operator
(d) They are the same and such can be used interchangeably
(e) A promise changes state only once, an observable can receive several events

Decrement the value of a variable at every function call

I am creating a slot machine program using JavaScript, and want to decrement the value of coins at every function call. For example, coins = 20. It should decrement after every time the casino() function is called. Basically the function can be called as many times until coins = 0.
Is this a situation where the application of let vs var comes into play?
Here is a snippet of my code:

let reel1 = ["cherry", "lemon", "apple", "lemon", "banana", "banana", "lemon", "lemon"]
let reel2 = ["lemon", "apple", "lemon", "lemon", "cherry", "apple", "banana", "lemon"]
let reel3 = ["lemon", "apple", "lemon", "apple", "cherry", "lemon", "banana", "lemon"]
let slotReel = []
let coins = 20

function casino(r1, r2, r3) {
    coins = coins - 1
    let random1 = reel1[Math.floor(Math.random() * reel1.length)]
    let random2 = reel2[Math.floor(Math.random() * reel3.length)]
    let random3 = reel3[Math.floor(Math.random() * reel3.length)]
    slotReel.push(random1, random2, random3)
    //.....some logic
}

casino(reel1, reel2, reel3)

set Dynamic Default Value for select dropdown in react

I have a form, where I need to set the default value of the select dropdown in formik.

SelectDropDown.js

{props.options.map((option) => {
    return (
        <option key={option.id} value={option.id} title={option.title}>
            {option.name}
        </option>
    );
})}

Code Sandbox LINK

App.js

<SelectDropdown
    control="select"
    name="episodeType"
    data-testid="episodeType"
    id="episodeType"
    label="Episode Type"
    options={dropDownValues} // how to pass defualt a props
/>

How to pass the default values as props so the page is loaded the values is selected.

Thank you.

How to select variant class in styled components?

In styled-components we can have contextual styles using component selector patterns. But how do we parents variant to contextual the child component? For example, we have three components here, Child, NoteWrapper, and Note.

const Child = styled.div<{ editing?: boolean }>`
  ${props => props.editing && css`some styles`}
`

const NoteWrapper = styled.div<{ compact?: boolean }>`
  ${props => props.compact && css`some styles`}
`

const Note = styled.input`

/* How do I style this when Child is editing and NoteWrapper is compact */

`

const App = () => {
  return (
   <Child editing>
    <NoteWrapper compact>
     <Note/>
    </NoteWrapper>
   </Child>
  )
}

`

With plain CSS we could do something like this


.child.editing .note-wrapper.compact .note {
  /* Contextual styles here */
}

My question is how do I style Note when Child is editing and NoteWrapper is compact in styled components selector pattern ?

how to retrieve key and value from object search?

I want to find a page url searching by an input. I have an object that contains keywords and urls. Then when press enter it will do a check, if the keywords are the same or exist, it will display the url, if not it will display not found.

So for example in the input I type “home”, when I enter it will display the url “/homepage” because the keywords are exist, if I type “contact” it will show not found because the keywords doesn’t exist.

I’ve made the code like below but why the map doesn’t work? can anyone help me?

$(document).ready(function(){
  $("#searchKeywords").on("keypress", function(e){
    if(e.which == 13){     
      const pageKeywords = {
        "home" : "/homepage",
        "about" : "/about-us"
      }

      pageKeywords.map((key,value) => {
        console.log(key)

        if($(this).val() == key){
          console.log(value)
        }else{
          console.log('not found')
        }
      })
    }
  });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" id="searchKeywords">

populate items from promotion node express js

promotion Modele

    const mongoose = require("mongoose");

const PromotionSchema = mongoose.Schema({
    name: { type: String, required: true },
    item1: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "itemPromotion",
        required: true,
    },
    item2: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "itemPromotion",
        required: false,
    },
    item3: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "itemPromotion",
        required: false,
    },
    

    startDate: { type: Date, required: false },
    endOfDate: { type: Date, required: false },
    status: { type: Boolean, required: false },
    totalPrice: { type: Number, required: false },
    discount: { type: Number, required: false },
});
module.exports = new mongoose.model("Promotion", PromotionSchema);

promotion Items its item with price and quantity and discount pourcent in promotion

    const mongoose = require("mongoose");

const ItemPromotionSchema = mongoose.Schema({
    item: { type: mongoose.Schema.Types.ObjectId, ref: "Item", required: true },
    price: { type: Number, required: true },
    quantity: { type: Number, required: true },
    discount: { type: Number, required: true },
});

module.exports = new mongoose.model("itemPromotion", ItemPromotionSchema);

items its the orginal item

const mongosse = require("mongoose");

const ItemSchema = mongosse.Schema({
code: {
type: String,
required: true,
},
label: {
type: String,
required: true,
},

itemCategory: {
    type: mongosse.Schema.Types.ObjectId,
    ref: "ItemCategory",
    required: false,
},
// category: {
//     type: CategorySchema,
//     required: false,
// },
itemFamilly: {
    type: mongosse.Schema.Types.ObjectId,
    ref: "ItemFamilly",
    required: false,
},
description: {
    type: String,
    required: false,
},
picture: {
    type: String,
    required: false,
},

Price: [{
    type: mongosse.Schema.Types.ObjectId,
    ref: "Price",
    required: false,
}, ],
tempPrice: { type: Number, required: false },

active: {
    type: Boolean,
    required: true,
},

});

module.exports = new mongosse.model(“Item”, ItemSchema);

and I have also the methode get (route)
where I need to get my data
promotion with itemsPromotions with label of item

   router.get("/config", async(req, res) => {
    try {
        const PromotionInDataBase = await Promotion.find().populate("item1").populate("item1.item");

        res.json(PromotionInDataBase);
    } catch (error) {
        res.json({ message: error });
    }
});

Detect pixelated images by using opencv and javascript

I’m trying to find out whether user uploaded photo is blur/pixelated. For that i’m using OpenCV4Nodejs package. It only detects blur not the pixelated one. So i found a python code to detect pixelated images but i wanted to do it in node/javascript. I tried converting it but couldn’t as i’m new to python. Can someone help me convert it. if cannot then could you please suggest is there any other way we can detect pixelated images?

Python Code:

import numpy as np
import Image, ImageChops

im = Image.open('fireworks-pixelate-02.gif')    
im2 = im.transform(im.size, Image.AFFINE, (1,0,1,0,1,1))
im3 = ImageChops.subtract(im, im2)
im3 = np.asarray(im3)
im3 = np.sum(im3,axis=0)[:-1]
mean = np.mean(im3)
peak_spacing = np.diff([i for i,v in enumerate(im3) if v > mean*2])
mean_spacing = np.mean(peak_spacing)
std_spacing = np.std(peak_spacing)
print 'mean gap:', mean_spacing, 'std', std_spacing

How to insert a javascript file in another javascript at build time file using a comment

Is there something on npm or in VS Code or anywhere that can bundle or concatenate Javascript files based on comments, like:

function myBigLibrary(){
    //@include util.js
    //@include init.js

    function privateFunc(){...}

    function publicFunc(){
      //@include somethingElse.js
      ...
    }

    
    
    return {
        init, publicFunc, etc
    }
}

Or something like that? I would think that such a thing is common when your javascript files get very large. All I can find are complicated things like webpack.

Optimize Angular Distribution

I have an Angular project and it uses a bunch of Javascript Libraries, starting with jQuery, going through Modal Forms, Tooltips and many more, mostly from third party providers. The thing is that, even when my Angular website makes use of these Libraries, the Website does not make exactly FULL use of the complete Libraries, but at the moment of Building the Dist files, the styles.xx.css and main.js are quite big files containing all these Libraries and Styles inside.

So, I was thinking there must be a way to only include in the final Distribution, only the “actual” code that is used by the Website and not the complete Libraries that includes the used and unused code. There are many features in those Libraries that the Website actually does not use, but these are at the same time, big files that make it difficult to just get in there and remove code by hand.

If there would be some sort of Code Coverage test that I can run on the complete website, just to “mark” all the actual used code and remove/discard from Dist compilation, all the unused code, that would be just awesome. This would be no-doubt a very efficient way to put on diet the Production compilations on any website.

Anyone knows if something like this exists?

How to print page exactly it looks on screen using window.print()?

I have designed a form for my project and I want to print the form. The form looks like below:
Actual Form

I was trying to use window.print() method to print it. But it changed the style in print preview like below: print preview

Here’s my code that I’ve done. Let me know if there any possible way to solve this issue and print exactly it shown in the window. Thanks in advance.

<!DOCTYPE html>

<html>
<head>
    <meta charset="utf-8">
    <title></title>
    
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    
    <link rel="stylesheet" type="text/css" href="Registrationform.css">
</head>
<body>



<div style="width:670px; padding:30px; box-shadow: 5px 5px 5px 5px #888888;" class="container">
        <table style="margin: auto;">
            <tr>
                <td><img width="60px" height="60px" src="imagesNSTU-logo.png"></td>
                <td>
                <div class = "header-name">
                <h6 style="text-align: center; margin: 0 auto;">NOAKHALI SCIENCE AND TECHNOLOGY UNIVERSITY</h6>
                <p style="text-align: center; margin:auto;">Noakhali-3814, Bangladesh</p>
                <h6 style="text-align: center;margin: auto;">COURSE REGISTRATION FORM</h6>
                </div>
            </td>
            </tr>
        </table>
        <hr>
        

    
        <form action="" method="POST">
            <!-- <div style=" align-content: center;" class = "std-header-info"> -->
                 <div>
                     <label>Name</label>
                     <input class="text" style = "width: 365px; text-align: center;" type="text" id = 'name' placeholder="" value="Khair" readonly>
                     <label>Roll</label>
                     <input class="text" style = "width: 160px; text-align: center;" type="text" id = 'roll' placeholder="" value="12" readonly> <br>
                 </div>
                 <div>
                    <label>Department</label>
                     <input class="text" style = "width: 230px; text-align: center;" type="text" id = 'department' placeholder="" value="IIT" readonly>
                     <label>Institute/Faculty</label>
                     <input class="text" style = "width: 165px; text-align: center;" type="text" id = 'institute' placeholder="" value="IIT" readonly>
                     <br/>
                 </div>

                 <div>
                     <label>Year</label>
                     <input class="text" style = "width: 120px; text-align: center;" type="text" id = 'year' placeholder="" value="2012" readonly>
                     <input type="hidden" name="year" value="" />

                     <label>Term</label>
                     <input class="text" style = "width: 150px; text-align: center;" type="text" id = 'term' placeholder="" value="2" readonly>

                     <label>Session</label>
                     <input class="text" style = "width: 200px; text-align: center;" type="text" id = 'session' placeholder="" value="2017" readonly>
                 </div>
                 <br/>


            


                 <div class="table-responsive">
                    <table class="table table-bordered">
                        <thead>
                            <tr>
                                <th>Course Code</th>
                                <th>Course Title</th>
                                <th>Credits</th>
                                <th>Remarks</th>
                            </tr>
                        </thead>
                        <tbody>
                            
                            <tr>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                            </tr>
                            <tr>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                            </tr>
                            <tr>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                            </tr>
                            <tr>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                            </tr>
                            
                        </tbody>
                    </table>
                 </div>
                 
                 <div>
                     <table style="font-size: 10px;" class="table table-bordered" id="table">
                        <tr class="borderless">
                            <td style="border: none;"></td>
                            <td style="border: none;"></td>
                            <td colspan="2">Year 1</td>
                            <td colspan="2">Year 2</td>
                            <td colspan="2">Year 3</td>
                            <td colspan="2">Year 4</td>
                            <td colspan="2">Year 5</td>
                        </tr>
                        <tr style="font-size: 8px">
                            <td style="border: none;"></td>
                            <td style="border: none;"></td>
                            <td>Term-I</td>
                            <td>Term-II</td>
                            <td>Term-I</td>
                            <td>Term-II</td>
                            <td>Term-I</td>
                            <td>Term-II</td>
                            <td>Term-I</td>
                            <td>Term-II</td>
                            <td>Term-I</td>
                            <td>Term-II</td>
                        </tr>
                     
                        <tr>
                            <td colspan="2">Credit <br> Completed </td> 
                            
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                        </tr>
                        <tr>
                            <td colspan="2">GPA</td>
                            <td>3.23</td>
                            <td>3.21</td>
                            <td>3.43</td>
                            <td>3.52</td>
                            <td>3.12</td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>

                        </tr>

                     </table>
                 </div>
</form>
</div>

<script type="text/javascript">
    window.print()
</script>
</body>
</html> 

threejs 3d model textures not loading

hey guys i am new to threejs and i am trying to load a 3d animated model with textures, but i am facing issues trying to do so as the textures are not loading into gltf. both the files are in textures folder while index.html is in the main folder. thanks in advance!

textures/Material_diffuse.png:1 Failed to load resource: the server responded with a status of 404 (Not Found)

textures/Material_specularGlossiness.png:1 Failed to load resource: the server responded with a status of 404 (Not Found)

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>3d model</title>
    <style>
      body {
        margin: 0;
      }
      canvas {
        display: block;
      }
    </style>
  </head>
  <body>
    <!-- <script src="three.js"></script> -->
    <!-- <script type="module" src="GLTFLoader.js"></script>  -->
    <script type="module">
      import * as THREE from 'https://cdn.skypack.dev/[email protected]/build/three.module.js';
      import { GLTFLoader } from 'https://cdn.skypack.dev/[email protected]/examples/jsm/loaders/GLTFLoader.js';

      var scene = new THREE.Scene();

      var camera = new THREE.PerspectiveCamera(
        75,
        window.innerWidth / window.innerHeight,
        0.01,
        1000
      );
      var renderer = new THREE.WebGLRenderer();
      renderer.setSize(window.innerWidth, window.innerHeight);
      document.body.appendChild(renderer.domElement);

      var loader = new GLTFLoader();

      var obj;
      loader.load("scene.gltf", function (gltf) {
        obj = gltf.scene;
        scene.add(gltf.scene);
      });
      scene.background = new THREE.Color(0xffffff);
      var light = new THREE.HemisphereLight(0xffffff, 0x444444);
      scene.add(light);
      // camera.position.set(0, 5, 30);
      camera.position.set(0, 5, 20);

      function animate() {
        requestAnimationFrame(animate);
        renderer.render(scene, camera);
      }
      animate(); 

      function rotateFunction() {
        obj.rotation.y += 0.01;
      }

     document.addEventListener('scroll', function(e) { rotateFunction() });
    </script>
    <div>
      
    </div>
  </body>
</html>

Make fake multilanguage subfolders for website

I’d like to know if it is possible to make fake subfolders for my multilanguage website, right now I use this code to switch between the two languages I have (Italian and English)

<?php
session_start();

$langs = [ "en", "it" ];

$current_lang = "en";

if (isset($_GET["lang"]))
{
    $lang = $_GET["lang"];
    if (in_array($lang, $langs, true))
        $current_lang = $lang;
    
}
elseif (!isset($_SESSION["lang"]))
{
    
    if (isset($_SERVER["HTTP_ACCEPT_LANGUAGE"]))
    {
        $acceptLang = $_SERVER["HTTP_ACCEPT_LANGUAGE"];
        if (strlen($acceptLang) > 2)
        {
            $acceptLang = strtolower(substr($acceptLang, 0, 2));
            if (in_array($acceptLang, $langs, true))
                $current_lang = $acceptLang;
        }
    }
}
else
    $current_lang = $_SESSION["lang"];

$_SESSION["lang"] = $current_lang;


require_once "languages/$current_lang.php";
?>

So whenever I want to switch language I add to the end of the URL ?lang=neededLanguage.php

I also use these rewrite rules to hide the .php

Options +SymLinksIfOwnerMatch 

RewriteEngine on

RewriteCond %{REQUEST_URI} ^(.*)//(.*)$
RewriteRule . %1/%2 [R=301,L]

RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule (.*) $1.php [L]

This is what I have to do to switch language right now:
https://example.com/?lang=en
https://example.com/blog?lang=en

I’d like to know if it’s possible to make the previous two URLs look something like these:
https://example.com/en/
https://example.com/en/blog