How to filter products with by asc desc price in vue3

the sortOptions gets the value but the function doesnt work (composition api) im trying to sort by price

const sortOptions = ref([
{ name: "Now Trending", value: "all" },
{ name: "Price (Low - High)", value: "asc" },
{ name: "Price (High - Low)", value: "desc" }
])


const sortBy = () => {
products.value.sort((a, b) => {
let ascending = a.price - b.price;
let descending = b.price - a.price;
sortOptions.value.filter((item) => {
  if(item.value === 'all') return;
  if(item.value === 'asc') return ascending;
  if(item.value === 'desc') return descending;
})
})
}
<select name="sortBy" id="sortBy" @change.prevent="sortBy">
        <option v-for="(option, index) in sortOptions" :value="option.value" 
:key="index">
          {{ option.name }}
        </option>
      </select>

convert base64 string to base64 url in node.js

I was wonder how to convert a base64 string to a base 64 url that you could use in the browser for my project. I’ve already tried using base64.toString('base64url'), but that didn’t work. Below is some example code.

const fs=require("fs")

let base64image=fs.readFileSync("./image.png").toString("base64")
let base64txt=fs.readFileSync("./text.txt").toString("base64")

// converts base64 to a base 64 URL.
function toBase64URL(filetype, base64){ /* ... */ }

console.log(toBase64URL('png', base64image)) // => data:image/png;base64,iVBORw0KGgoAAAANSUhE...
console.log(toBase64URL('txt', base64txt)) // => data:text/plain;base64,dmVyeSBkZXRhaWxlZCA6KQ==

Angular Ivy – Adding dynamic controls to an existing form groups within form array

Using Angular Reactive Forms module, i have a case where my form array being populated with few form groups, in a specific case for example “on destroy” i would like to add controls to each of the form groups inside my form array, i tried iterating over the array and using addcontrol but something mess up smh, code below thanks for help

<FormArray>this.form.get('additionals')).controls.forEach(
    (control) => {console.log(
      control.addControl('new', new FormControl('', Validators.required))
    )}

in result i get > Property ‘addControl’ does not exist on type ‘AbstractControl’.
i dont know why i get such error, as far as i know from Angular io docs addControl is method of AbstractControl which FormGroup is instance of it. so why it error?

Vue.js change setTimeout to send the request until a value is received

In my app I’ve got functionality where user can import spreadsheet file. The file itself is sending to backend app and after some time it the result can be fetched from different endpoint based on ID. The thing is it can take a very long time for the backend to prepare a response and this time varies depending on the file size. So far I’ve been using setTimeout function but since the backend response time is different I can’t do it.

Here is my code:

new_batch.vue

export default {
  name: 'BackboneSyncProducts',
  data() {
    return {
      styleCodes: [],
      fetchedProductSyncResult: [],
      loadId: null,
    }
  },
  watch: {
    loadId(newValue, oldValue) {
      if (!oldValue && newValue) {
        setTimeout(() => {
          fetchSyncedProductsResultRequest(this, newValue).then(response => {
            this.fetchedProductSyncResult = response.data['result']
          })
        }, 3000)
      }
    }
  },

Whole functionality needs to be asynchronous. How to hit backend app using fetchSyncedProductsResultRequest function until response.data['result'] is not is null ?

Keycloak : Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource [duplicate]

I am using keycloakjs version 10.0.2 and my keycloak server is of version 10.0.2, I am not able to authorize user in keycloakjs, browser console gets the following error,I tried configuring keycloak for this realm web origins * + nothing did work. Please give me some idea on where I am going wrong :

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://yyyy.xxxx.com/auth/realms/test/protocol/openid-connect/token. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 401

code part :

         <html><head>

   <script src="http://localhost:81/auth/js/keycloak.js" type="text/javascript">             </script>

    <script type="text/javascript">
     const keycloak = Keycloak({
       "realm": "test",
       "auth-server-url": "https://yyyy.xxxx.com/auth",
       "ssl-required": "external",
       "resource": "account",
       "public-client": true,
       "confidential-port": 0,
       "url": 'https://yyyy.xxxx.com/auth',
        "clientId": 'account',
        "enable-cors": true
       });
      const loadData = () => {
         console.log(keycloak.subject);
         if (keycloak.idToken) {
           document.location.href = "?user="+keycloak.idTokenParsed.preferred_username;
          console.log('IDToken');
          console.log(keycloak.idTokenParsed.preferred_username);
          console.log(keycloak.idTokenParsed.email);
          console.log(keycloak.idTokenParsed.name);
          console.log(keycloak.idTokenParsed.given_name);
         console.log(keycloak.idTokenParsed.family_name);

      } else {
keycloak.loadUserProfile(function() {
    console.log('Account Service');
    console.log(keycloak.profile.username);
    console.log(keycloak.profile.email);
    console.log(keycloak.profile.firstName + ' ' + keycloak.profile.lastName);
    console.log(keycloak.profile.firstName);
    console.log(keycloak.profile.lastName);
}, function() {
    console.log('Failed to retrieve user details. Please enable claims or account role');
          });
         }
       };

        const loadFailure =  () => {
           console.log('Failed to load data.  Check console log');
        };
        const reloadData = () => {
            keycloak.updateToken(10)
                .success(loadData)
         .error(() => {
            console.log('Failed to load data.  User is logged out.');
        });
     }
        keycloak.init({ onLoad: 'login-required' }).success(reloadData);
      </script>
      </head>
       <body>

       </body>
      </html>

Regards
Kris

Preflight response is not successful. Status code: 501 JavaScript?

I have been trying to access a local json file in javaScript using fetch (as shown below).

fetch('./js/data.json')
  .then(response => response.json())
  .then((data) => {
    console.log(data);
  })
  .then((error) => {
    console.log(error);
  });

I found out from this that I can not access the json file localy and not to access it from a https sever on localhost.

I set this up using ngrok.

fetch('https://a9f8-86-133-120-217.ngrok.io/js/data.json', {
    method: 'GET',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    }, 
  })  .then(response => response.json())
        .then((data) => {
            console.log(data);
        })
        .then((error) => {
            console.log(error);
        });

When I now run the code I get the following errors.

[Error] Preflight response is not successful. Status code: 501

[Error] Fetch API cannot load https://a9f8-86-133-120-217.ngrok.io/js/data.json due to access control checks.

After some research I found this was due to working called cors.

I then added mode: ‘no-cors’ to my code. This then meant that the json file was being fetch but it was casing more error as shown.

Unhandled Promise Rejection: SyntaxError: The string did not match the expected pattern.

The error is from the following line.

.then(response => response.json())

I have been trying to fix this for a few hours but have had no luck.

I feel this is soemthing so simple that I’m missing.

generate a link to customized Map API with JS

i created a js map , i get all my marker x and y , from DataBase
this is my code ( part of my function) :

    zoom: 7,
    center: new google.maps.LatLng(34.41, 9.47),
    mapTypeControl: true,
    mapTypeControlOptions: {
      style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    },
  });
  var infowindow = new google.maps.InfoWindow();
  myObj.forEach((element) => {
        a = "marker.png";
    if (element.code_face != "") {
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(element.X, element.Y),
        map: map,
        icon: a,
      });
     ....``` 
the result is good but i have a lot of difficult to generate a link to share the result map ,i read the documentation of map API,i can't found a solution to , can anyone help me ? thanks

How can I solve the ACE value problem with JavaScript?

So Ace should have value 11 or value 1 depending on the other cards. Let’s say our starting cards are ACE and SIX. That’s 7 or 17. If we hit for another card and it’s FOUR,
we have Blackjack and the value of ACE should be 11.
And other scenarios like this

I’m converting the ACE value from the API in the convertToNum function.

Here is the whole code: https://jsfiddle.net/unote2zf/

Here is my JS code:

//DOM
let deckId = ""; //we store our deck in global variable
let playerCardOne,
  playerCardTwo,
  dealerClosedCard,
  dealerCardTwo,
  sumPlayersCards,
  sumDealersCards;

//first card for the dealer
let dealerCardOne = document.querySelector(".dealer-card1");

let result = document.querySelector(".result");

const dealerCards = document.querySelector(".dealer-cards");
const playerCards = document.querySelector(".player-cards");

const dealerScore = document.querySelector(".dealer-score");
const playerScore = document.querySelector(".player-score");

//Buttons
const dealButton = document.querySelector(".deal");
const hitButton = document.querySelector(".hit");
const standButton = document.querySelector(".stand");

//we store value from the cards here
let addPlayersCards = [];
let addDealersCards = [];

//Event listeners
dealButton.addEventListener("click", dealCards);
hitButton.addEventListener("click", hit);
standButton.addEventListener("click", stand);

async function getDeck() {
  try {
    let res = await fetch("https://www.deckofcardsapi.com/api/deck/new/shuffle/?deck_count=2");
    let data = await res.json()
    console.log(data);
    deckId = data.deck_id;
  } catch (err) {
    console.log(err)
  }
};
getDeck();

async function dealCards() {

  addDealersCards.push(await getCard());
  addPlayersCards.push(await getCard());
  addDealersCards.push(await getCard());
  addPlayersCards.push(await getCard());

  // dealerScore.textContent = convertToNum(addDealersCards[1].cards[0].value);

  dealButton.classList.toggle("hide");
  hitButton.classList.toggle("hide");
  standButton.classList.toggle("hide");
  dealerScore.classList.toggle("hide");
  playerScore.classList.toggle("hide");

  console.log(addPlayersCards)

  console.log(addDealersCards)

  renderCards();
  sumCards();
  if (sumPlayersCards === 21) {
    result.innerText = "BLACKJACK PLAYER WINS";
    flipDealersFirstCard();
    checkForWinner();
  }
}

async function hit() {
  addPlayersCards.push(await getCard());
  sumCards();
  renderPlayersCard();

  //If player goes over 21 to finish the game and open the dealers cards
  if (sumPlayersCards >= 21) {
    flipDealersFirstCard();
    checkForWinner(); 
  }
}


async function stand() {
  flipDealersFirstCard();

  //To hit the Dealer till he's over 17 or over
  while (sumDealersCards < 17) {
    addDealersCards.push(await getCard());
    sumCards();
    renderDealersCard();
  }

  // sumCards()
  checkForWinner();
}

//Deal one card
async function getCard() {
  try {
    let res = await fetch(`https://deckofcardsapi.com/api/deck/${deckId}/draw/?count=1`);
    let data = await res.json()
    console.log(data)
    return data.cards[0];

  } catch (err) {
    console.log(err)
  }
};

function sumCards() {
  sumPlayersCards = 0;
  addPlayersCards.forEach(element => {
  sumPlayersCards += convertToNum(element.value);
  console.log(element.value)
});
  sumDealersCards = 0;
  addDealersCards.forEach(element => {
    sumDealersCards += convertToNum(element.value);
    console.log(element.value)
  })
  dealerScore.textContent = convertToNum(addDealersCards[addDealersCards.length - 1].value);
  playerScore.textContent = sumPlayersCards;

  console.log(sumDealersCards)
  console.log(sumPlayersCards)

}

//Draw the cards in the arrays
function renderCards() {
  addDealersCards.forEach(element => {
    let cardElement = document.createElement("img");
    dealerCards.appendChild(cardElement);
    cardElement.src = element.image;
    dealerCards.firstElementChild.src = "https://opengameart.org/sites/default/files/card%20back%20red.png";
  })

  addPlayersCards.forEach(element => {
    let cardElement = document.createElement("img");
    playerCards.appendChild(cardElement);
    cardElement.src = element.image;
  })
}

function renderPlayersCard() {
  let cardElement = document.createElement("img");
  playerCards.appendChild(cardElement);
  cardElement.src = addPlayersCards[addPlayersCards.length - 1].image;
  // playerScore.textContent = sumCards();
}


function renderDealersCard() {
  let cardElement = document.createElement("img");
  dealerCards.appendChild(cardElement);
  cardElement.src = addDealersCards[addDealersCards.length - 1].image;
  dealerScore.textContent = sumDealersCards;
}

//To flip the first card for the dealer and sum dealers cards.
function flipDealersFirstCard() {
  dealerCards.firstElementChild.src = addDealersCards[0].image;
  dealerScore.textContent = sumDealersCards;
  console.log(sumDealersCards);
}

//To convert the cards with string Values
function convertToNum(val) {
  if (val === "ACE") {
    return 11;
  } 
  else if (val === "KING" || val === "QUEEN" || val === "JACK") {
    return 10;
  } 
  else {
    return Number(val);
  }
}

//Checks who won
function checkForWinner() {
  if (sumPlayersCards > sumDealersCards && sumPlayersCards < 21) {
    result.classList.toggle("hide");
    result.innerText = "PLAYER WINS";
  } else if (sumDealersCards > 21 && sumPlayersCards <= 20) {
    result.classList.toggle("hide");
    result.innerText = "PLAYER WINS";
  } else if (sumPlayersCards === 21 && sumDealersCards <= 20) {
    result.classList.toggle("hide");
    result.innerText = "BLACKJACK PLAYER WINS";
  } else if (sumDealersCards > sumPlayersCards && sumDealersCards < 21) {
    result.classList.toggle("hide");
    result.innerText = "DEALER WINS";
  } else if (sumPlayersCards > 21 && sumDealersCards <= 20) {
    result.classList.toggle("hide");
    result.innerText = "BUST! DEALER WINS";
  } else if (
    (sumDealersCards === 21 && sumPlayersCards <= 20) ||
    sumPlayersCards > 21
  ) {
    result.classList.toggle("hide");
    result.innerText = "BLACKJACK DEALER WINS";
  } else {
    result.classList.toggle("hide");
    result.innerText = "DRAW";
  }
}

Promise.all in browser does not run concurrently

I was getting some deeper in Promises and from all docs I found that Promise.all runs concurrently. I created a simple local API that responds in 3 seconds and tried following code.

const url = 'http://localhost:3000';

function callApi() {
  const resp1 = fetch(url);
  const resp2 = fetch(url);

  Promise.all([resp1, resp2]);
}

callApi();

What I see from Network tab is that, API calls runs sequentially and not concurrently. I tried it on Chrome and Firefox and both works the same. In addition to this, I run the same code with axios in Node.js and see that it runs concurrently.

Network Tab Image

Is there anything I am doing wrong?

Edit npm module

I installed keylogger.js and I want to fix the module. I edit src/windows/keylogger.cc file and save the changes (Want to catch mouse clicks).

enter image description here

After starting the program, nothing changes. What am I doing wrong?

Leaflet add local image to popup / marker

I have an issue where i can’t use local images in popUps and i also tried using a local image for a custom marker. This resulted in the following error:

GET file:///D:/Users/BKA/myPC/Documents/html/%3Cimg%20src%20=%20%22D:UsersBKAmyPCDesktoppngmarker-icon-black.png%22/%3E net::ERR_FILE_NOT_FOUND

When using a link ( google link for example ) as a source it works just fine.

I have tried using the downloaded Version of leaflet and using the hosted version of leaflet.
My code when setting up the images looks like this:
var schwarz = new L.Icon({ iconUrl: '<img src = "D:UsersBKAmyPCDesktoppngmarker-icon-black.png"/>', iconSize: [25, 41], iconAnchor: [12, 41], popupAnchor: [1, -34], shadowSize: [41, 41] });
and in the popUP it looks like this:

berlin_4.bindPopup('<img src="D:UsersBKAClemensLangerDesktopleafletimagesgelb.png"/>');

Also when using the fullscreen plug in it is also unable to load in the little icon on the button (called fullscreen.png), but the plug in itsself works just fine.

If you know whats wrong please let me know 🙂

How to display data from json into HTML using js table

How can I insert this code into js table

if (data.players.length) {data.players.forEach((ply)=>{
            
            let plycont = document.createElement('div')
            
            
            let plyspan = generate_colored_span(ply.name)
            plyspan.className = 'tracker_plyname'
            plycont.appendChild(plyspan)
            
            plycont.appendChild(wrap_span(ply.score, 'tracker_plyscore'))
            
            plycont.appendChild(wrap_span(ply.ping == '0' ? 'BOT' : ply.ping, 'tracker_plyping'))
            tracker_playerslist.appendChild(plycont)
        })} 

JSON api data I want to use:
“players”:[
{
“name”:””,
“score”:””,
“ping”:””
}]

HTML output:

<table class="table">
  <thead>
    <tr>
      <th>Players</th>
      <th>Score</th>
      <th>Ping</th>
    
    </tr>
  </thead>
  <tbody></tbody>
  </table>

Is it possible to open a URL in a client default mobile browser while the click originated from an in app browser?

The answer might be a resounding no, but I figured I’d ask anyway. I realize this might be a security nightmare.

I created the following test page that checks whether or not the user is using an in app browser or not and displays a link accordingly.

When the user does use an in app browser, I am displaying the “continue here” link and I would like him to be prompted to choose to open the link in his mobile’s default browser rather than in the in app browser he is currently using.

<html>
<body>
<a id="btn" href="#" onclick="window.open('https://www.google.com', '_system'); return false;">Continue here</a>
<a id="btn2">not in app browser</a>
</body>
</html>



<script>
    webviewCheck();
    function webviewCheck() {
        let standalone = window.navigator.standalone,
            userAgent = window.navigator.userAgent.toLowerCase(),
            safari = /safari/.test(userAgent),
            ios = /iphone|ipod|ipad/.test(userAgent);

        if (ios) {
            if (!standalone && safari) {
                // Safari
                console.log("safari browser is being used");
                document.getElementById("btn").hidden=true;
            } else if (!standalone && !safari) {
                // iOS webview
                console.log("IOS webview is being used");
                document.getElementById("btn2").hidden=true;
            };
        } else {
            if (userAgent.includes('wv')) {
                // Android webview
                console.log("Android webview is being used");
                document.getElementById("btn2").hidden=true;
            } else {
                // Chrome
                console.log("Other browser is being used (firefox/chrome/edge/etc)");
                document.getElementById("btn").hidden=true;
            }
        };
    }
</script>


How to open a django webpage from a vue js app?

I have an app that I created using django as a backend and vue js as frontend. I did all of the front end in Vue JS i.e I have no template html files in my django folder. But now I want the vue app to link to another django app(with html templates) which I had created before. I have added the app to the django folder in my project. Now how do I create a link that can route to this django app that I have just added. I am using axios.

How to update the HTML code in inspect element when changing the input fields?

I want the code shown in inspect element to be updated with the value shown in the input fields. What I am trying to do is, after the user fills in all the input fields when they submit I select the outerHTML of the whole form and put it into a text area, which is also submitted with the form. I store this source code in the Database, when user wants to view old forms, they can select the date and what I do is just paste the source code from the database.

But what I noticed is that the input field value is not being captured in the source code. is there any way to capture the value along with the code?
Currently the input field looks like this even though the user might have given a value of say ‘abc’.

Current issue:
<input name='field1' id='field1' required>

Desired Result:
<input name='field1' id='field1' required value='abc'>

I just need whatever the user types, it should get captured in the code. So that when I load it again, the page would have the value there.