How to correlate the data when sending an Axios request with the data in the database?

template

            <input v-model="orderData.firstName" class="order_input" type="text" placeholder="Name" >
          </div>
          <div>
            <input v-model="orderData.phoneNumber" class="order_input" type="text" placeholder="Phone" >
          </div>
...
              <button class="make_order" @click="postOrder">Send</button>

store.js:

data(){
 return {
  orderData:{
        firstName: '',
        phoneNumber: '',
...
   }
 }
}

script:

methods: {
    postOrder() {
      const orderDataStr = JSON.stringify(this.orderData)
      axios.post(`{url}`, orderDataStr)
          .then((response) => {
            console.log(response);
          })
          .catch((error) => {
            console.log(error);
          });
    },
}

Is everything right?
I got data from backend and get:

{success: false, message: 'Ops! Some errors occurred', errors: {…}}
errors:
address: ['The address field is required.']
fio: ['The fio field is required.']
order_description: ['The order description field is required.']
phone: ['The phone field is required.']
t_count: ['The t count field is required.']
t_price: ['The t price field is required.']
time_delivery: ['The time delivery field is required.']
type_delivery: ['The type delivery field is required.']
type_payment: ['The type payment field is required.']
[[Prototype]]: Object
message: "Ops! Some errors occurred"
success: false

How should i correlate data that i need to sent with relevant fields in database?
(sorry for my eng)

UnicodeDecodeError, ‘utf-8’ codec can’t decode byte 0x80 despite using ignore as error handler in decode

I am running a redis_instance I just flushed. When I run keys * to check what key values I have I receive this output

1) "pairprogramming:1:views.decorators.cache.cache_page..GET.3ab7bc76b513f7063fc20ab3fdb2d22b.d41d8cd98f00b204e9800998ecf8427e.en-us.UTC"
2) "pairprogramming:1:views.decorators.cache.cache_header..3ab7bc76b513f7063fc20ab3fdb2d22b.en-us.UTC"
3) "pairprogramming:1:views.decorators.cache.cache_page..GET.146382e9a37a1da80e630eb042e9e924.83bf0aec533965b875782854d37402b7.en-us.UTC"
4) "pairprogramming:1:views.decorators.cache.cache_header..146382e9a37a1da80e630eb042e9e924.en-us.UTC"
5) "pairprogramming:1:views.decorators.cache.cache_page..GET.21d502855d4ad5b0f631c20fc5e899c6.65330eb47d0175f264fdb29633829c0b.en-us.UTC"
6) "pairprogramming:1:views.decorators.cache.cache_header..21d502855d4ad5b0f631c20fc5e899c6.en-us.UTC"

I assume each time I try to make a GET request that attempt is written into my redis_instance?

This is besides the point, the problem I am having is that when I try to do a GET request, I expect to receive this:

{"count":0,"msg":"Found 0 items.","items":{}}

However, I am getting this error:

UnicodeDecodeError at /cache/
'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte

This is the offending line/characters

The string that could not be encoded/decoded was: ���

I have tried to change the default error handler to: ignore, replace, backslash, but keep getting the same error.

This is how my code looks currently:

@api_view(['GET', 'POST'])
def manage_items(request, *args, **kwargs):
    if request.method == 'GET':
        items = {}
        count = 0
        for key in redis_instance.keys("*"):
            items[key.decode("utf-8", errors='ignore')] = redis_instance.get(key)
            count += 1
        response = {
            'count': count,
            'msg': f"Found {count} items.",
            'items': items
        }
        return Response(response, status=200)
    elif request.method == 'POST':
        item = json.loads(request.body)
        keys = list(item.keys())
        values = list(item.values())
        for i in range(0, len(keys)):
            redis_instance.set(keys[i], values[i])
        response = {
            'msg': f"{keys} successfully set to {values}"
        }
        return Response(response, 201)

I am using django-redis

In some instances I get the output I expect if I test my api_end point using Postman, but keep getting the same error when I try to GET data using axios in my frontend

Javascript – callback function with predefined argument

I have predefined function, which supports callback to the second argument.
I can’t modify this function.
How to pass callback function, so it will execute callback function with my argument and result it has received?

// predefined function, can't modify it ->>
function getEmail(uID, fn) {
    var result = { status: 'OK', data: { email: '[email protected]'} }; // answer for uID=13
    fn(result);
}
// <<- predefined function, can't modify it

var helper = {

    send: (uID, cb_function) => {
        getEmail( uID, helper.receive/*?[cb_function]?*/ ); // how to pass to the second argument cb_function?
    },

    receive: (/*?result, fn?*/) => {
        if ( result.status == 'OK' ) {
            fn(result.data);
        } else {
            alert('GetEmail result wasn't OK!');
        }
    },

}

helper.send(13, (a) => {
    // cb_function:
    alert( 'User email: ' + a.email );
});

How to add two values to the same index in map type array

let wordsArray;
let indexArray = []; 
let index;
let myMap = new Map();
const Storage = function(userInput){
    wordsArray = userInput.split(' ');
    
    //remove ',' and '.'
    for( let i = 0; i < wordsArray.length ; i ++){
        if(wordsArray[i].endsWith(',') || wordsArray[i].endsWith('.') || wordsArray[i].endsWith('!') || wordsArray[i].endsWith(':')) {
            let temp = wordsArray[i];
            wordsArray[i] = temp.slice(0, temp.length - 1 );
        }

        //ToLowerCase
        let temp = wordsArray[i]
        wordsArray[i] = temp.toLowerCase();

        //IndexCreation
        let letter = wordsArray[i].slice(0,1); 
        indexArray.push(letter);
       
        //Add to Array
        myMap.set(letter,wordsArray[i]);
    }
    console.log(myMap);
    
    
}
Storage("Hello, my name is Gleb. My hobby is to learn Javascript");

Expected output h stands for hello and hobby, but actually it contains only last word – hobby. How can i add word to index, instead of repleasing?

How do I make a painting application with WebGL?

The goal is pretty straight forward. I want to make a drawing application that is purely based on WebGL. I already have a canvas and I managed to get a shader working and to display colors.

The idea was, I render whatever is on the canvas to a texture and then “reuse” that texture in the next frame in the shader again, so that I could draw on top of that.

I am new to WebGL but already I have some experience with GLSL. However I am struggling setting up the with all textures and framebuffers and such, especially in what order. I couldn’t find a solution to my specific problem without overcomplicating things that I don’t need. I mean I don’t want to draw a cube with a texture on it. I don’t need a projection matrix. Everything in theory will be in 2D.

Can anyone give me a guide how to set up things to achieve my goal?
Any help would be highly appreciated!

Here’s what I have so far. I am using VueJS btw

import vertexShader from "raw-loader!../shader/vertex.glsl";
import fragmentShader from "raw-loader!../shader/fragment.glsl";

export default defineComponent({
  name: 'HomePage',
  setup() {
      let canvas = ref<HTMLCanvasElement>();

      const canvasSize = ref({ width: 1920, height: 1080 });

      let gl: WebGL2RenderingContext | null;
      let location: WebGLUniformLocation | null;
      let texture: WebGLTexture | null;
      let textureLocation: WebGLUniformLocation | null;

      onMounted(() => {
          if (canvas.value) {
              gl = canvas.value.getContext('webgl2');
              if (gl) {
                  // Set the view port
                  gl.viewport(0, 0, canvas.value.width, canvas.value.height);

                  //Create a vertex shader object
                  const vertShader = gl.createShader(gl.VERTEX_SHADER);

                  if (vertShader) {
                      gl.shaderSource(vertShader, vertexShader);
                      gl.compileShader(vertShader);

                      if (!gl.getShaderParameter(vertShader, gl.COMPILE_STATUS)) console.error(gl.getShaderInfoLog(vertShader));

                      // Create fragment shader object
                      const fragShader = gl.createShader(gl.FRAGMENT_SHADER);

                      if (fragShader) {
                          gl.shaderSource(fragShader, fragmentShader);
                          gl.compileShader(fragShader);

                          if (!gl.getShaderParameter(fragShader, gl.COMPILE_STATUS)) console.error(gl.getShaderInfoLog(fragShader));

                          // Create a shader program object to store combined shader program
                          const shaderProgram = gl.createProgram();

                          if (shaderProgram) {
                              gl.attachShader(shaderProgram, vertShader);
                              gl.attachShader(shaderProgram, fragShader);

                              gl.linkProgram(shaderProgram);

                              location = gl.getUniformLocation(shaderProgram, "mouse");
                              gl.uniform2f(location, 0, 0);

                              texture = gl.createTexture();
                              gl.bindTexture(gl.TEXTURE_2D, texture);
                              gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
                              gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);

                              textureLocation = gl.getUniformLocation(shaderProgram, "u_texture");

                              gl.activeTexture(gl.TEXTURE0);
                              gl.uniform1i(textureLocation, 0);

                              gl.useProgram(shaderProgram);

                              gl.drawArrays(gl.TRIANGLE_FAN, 0, 3);
                          }
                      }
                  }
              }
          }
      });

      const pointermove = (e:any) => {
          if (gl && canvas.value) {
              gl.uniform2f(location, e.clientX, canvas.value.height - e.clientY);

              gl.drawArrays(gl.TRIANGLE_FAN, 0, 3);
          }
      };

      return {
          pointermove,
          canvasSize,
          canvas,
      };
  }
});

Fragment shader:

#version 300 es

precision highp float;

in vec2 texcoord;
out vec4 fragmentColor;

uniform sampler2D u_texture;
uniform vec2 mouse;

void main(void) {
    //fragmentColor = vec4(0.0, 0.0, 0.0, 1.0);
    fragmentColor = vec4(texture(u_texture, texcoord).rgb, 1.0);
    float x = gl_FragCoord.x - mouse.x;
    float y = gl_FragCoord.y - mouse.y;
    fragmentColor.rgb += mix(1.0, 0.0, (x*x + y*y) * 0.001);
}

Vertex Shader:

#version 300 es

precision highp float;

out vec2 texcoord;

void main(void) {
    float x = float((gl_VertexID & 1) << 2);
    float y = float((gl_VertexID & 2) << 1);
    texcoord.x = x * 0.5;
    texcoord.y = y * 0.5;
    gl_Position = vec4(x - 1.0, y - 1.0, 0, 1);
}

Pagination with React doesn’t work, all items are still displayed on screen

I have a pagination made with a react-paginate package called react-paginate here is the link to the doc. https://www.npmjs.com/package/react-paginate

I have implemented it in my App which is a notes diary, the user creates notes and these are dynamically saved in the localStorage and displayed on screen, well, I have established that there are 6 notes per page, that is, when there is a seventh note, it should not be displayed unless the user goes to page 2, when there are 13 notes page 3 and so …

The functionality of my component that I have called Pagination works correctly, it is dynamic, I have right now testing 13 notes, so it shows me 3 pages, if I had 12, it would show me 2.

The problem is that although my pagination is correct, the 13 notes are being shown on the screen, when it should be 6 – 6 – 1.

I leave you the code to see if we can find the error, greetings and thanks in advance.

The prop that Pagination receives called data, are basically the notes that are created dynamically in App.js. const [notes, setNotes] = useState([]);

Component Pagination

import React, { useEffect, useState } from 'react'
import ReactPaginate from 'react-paginate';
import '../styles/Pagination.css';

const Pagination = (props) => {
  const { data } = props;
    
  // We start with an empty list of items.
  const [currentItems, setCurrentItems] = useState([]); 
  const [pageCount, setPageCount] = useState(0);
  // Here we use item offsets; we could also use page offsets
  // following the API or data you're working with.
  const [itemOffset, setItemOffset] = useState(0);
    const itemsPerPage = 6;

  useEffect(() => {
    // Fetch items from another resources.
    const endOffset = itemOffset + itemsPerPage;
    console.log(`Loading items from ${itemOffset} to ${endOffset}`);
    setCurrentItems(data.slice(itemOffset, endOffset));
    setPageCount(Math.ceil(data.length / itemsPerPage));
  }, [itemOffset, itemsPerPage, data]);

  // Invoke when user click to request another page.
  const handlePageClick = (event) => {
  const newOffset = (event.selected * itemsPerPage) % data.length;
  console.log(
    `User requested page number ${event.selected}, which is offset ${newOffset}`
  );
  setItemOffset(newOffset);
  };

  return (
    <>
      <ReactPaginate
        breakLabel="..."
        nextLabel="next >"
        onPageChange={handlePageClick}
        pageRangeDisplayed={3}
        pageCount={pageCount}
        previousLabel="< previous"
        renderOnZeroPageCount={null}
        containerClassName="pagination"
        pageLinkClassName="page-num"
        previousLinkClassName="page-num"
        nextLinkClassName="page-num"
        activeLinkClassName="activee boxx"
      />
    </>
  );
}

export default Pagination;

Component App

import { useState, useEffect } from "react";
import { nanoid } from 'nanoid';
import NoteList from "./components/NoteList";
import './App.css';
import Search from "./components/Search";
import Header from "./components/Header";
import Pagination from "./components/Pagination";

const App = () => {
  const [notes, setNotes] = useState([]);
  const [searchText, setSearchText] = useState('');
   const [darkMode, setDarkMode] = useState(false);
   //Se encarga de mostrar la nota para escribir 
   const [showNote, setShowNote] = useState(true); //eslint-disable-line
  useEffect(() => {
    const saveNotes = JSON.parse(localStorage.getItem('notes-data'));
    if (saveNotes){
      setNotes(saveNotes);
    }
    
  }, []);
  useEffect(() => {
    localStorage.setItem('notes-data', JSON.stringify(notes))
  },[notes])

  const addNote = (inputText, text) => { 
    const date = new Date();
    const newNote = {
      id: nanoid(),
      title: inputText,
      text: text,
      date: date.toLocaleString()
      
    }
    const newNotes = [newNote, ...notes];
    setNotes(newNotes)
  }
  const deleteNote = (id) => {
    var response = window.confirm("Are you sure that you want to remove the note?");
    if (response){
      const notesUpdated = notes.filter((note) => note.id !== id)
      setNotes(notesUpdated);
    }
  }
  return (
    <div className={darkMode ? 'dark-mode' : ''}>

    <div className="container">
      <Header 
        handleToggleTheme={setDarkMode}
      />
      <Search 
        handleSearchNote={setSearchText}
        setShowNote={setShowNote}
        />
      <NoteList 
        notes={notes.filter((noteText) => 
          noteText.title.toLowerCase().includes(searchText)
        )}
        handleAddNote={addNote}
        handleDeleteNote={deleteNote}
      />
      <Pagination data={notes}/>
    </div>
    </div>
  )
}

export default App;

How do I use Toggle method in Reactjs ? I have added sandbox link at the bottom

In this code, I want to toggle active class to icons div, I watched some youtube videos and they showed this method which is not what I want, this method does not add activeclass to a particular div it adds active class to every div that has icons class. I want whenever someone click onto the div active class should be added into it and when clicked again that class should get removed.

export default function Site() {
  const [notActive, setActive] = useState(false);

  const switchActive = () => {
    notActive ? setActive(false) : setActive(true);
  };

  return (
    <div id="container">
      <nav id="navbar">
        <a href="j" className="link">
          Buzzify
        </a>
        <a href="f">
          <FaRegUserCircle className="user-icon" />
        </a>
      </nav>
      

 
     
      <div id="playlist-container">
        <div id="playlist">
          <div
            className={notActive ? "icons active" : "icons"}
            onClick={switchActive}
          >
            <BsCloudRain />
            <VolSlider />
          </div>
          <div
            className={notActive ? "icons active" : "icons"}
            onClick={switchActive}
          >
            <GiForest />
          </div>
          <div className="icons">
            <MdOutlineWaterDrop />
          </div>
          <div className="icons">
            <BiWind />
          </div>
          <div className="icons">
            <GiCampfire />
          </div>
          <div className="icons">
            <GiThreeLeaves />
          </div>
          <div className="icons">
            <BsMoonStars />
          </div>
          <div className="icons">
            <BiWater />
          </div>
          <div className="icons">
            <BiTrain />
          </div>
          <div className="icons">
            <BiCoffeeTogo />
          </div>
          <div className="icons">
            <FaFan />
          </div>
          <div className="icons">
            <DiDigitalOcean />
          </div>
          <div className="icons">
            <GiWaterfall />
          </div>
          <div className="icons">
            <FaPlane />
          </div>
          <div className="icons">
            <IoIosPlanet />
          </div>
          <div className="icons">
            <GiOctopus />
          </div>
        </div>
      </div>
    </div>
  );
}

CodeSandbox.io

call back query send duplicate messages node-telegram-bot-api

Whenever inline button clicked by user call back query send duplicate messages so what type of changes I need to do to bot not send duplicate messages.

      var keyboard = [];
      movieRatingList.map((movie, idx) => {
        var movieRating = Math.round(movie.rating * 10) / 10;
        if (movieRating == bestRating) {
          var firstName = movieList[idx].firstName;
          keyboard.push([{ text: firstName, callback_data: idx }]);
        }
      });

      bot.sendMessage(userChatId, userText, {
        reply_markup: JSON.stringify({
          resize_keyboard: true,
          inline_keyboard: keyboard,
        }),
      });

      bot.on("callback_query", (callBackData) => {
        var idx = Number(callBackData.data);

        var fileID = movieList[idx].file_id;
        var firstName = movieList[idx].firstName;
        console.log(fileID);
        console.log(firstName);
        bot.sendDocument(userChatId, fileID, { caption: firstName });
        
      });

String in bracket all in caps

I have a use case where I want to control all the char in the bracket to uppercase.

For example, if there’s a string Laugh out Loud (lol) I want to convert it to Laugh Out Loud (LOL)

something like this, Where applying in a string first letter to be cap and if bracket then it should all convert into all caps.

Few examples:
Point of view (pov) to Point Of View (POV)

What the hell to What The Hell

it should also work if only string without brackets.

how can I achieve this in JS?

I am able to achieve it to put all the letter caps
_.startCase(_.toLower('Point of view (pov)'))

The result is Point Of View (pov)

Leaflet not show EPSG:3857 coordinates

I am totally stuck with my WGS 84 / EPSG:3857 coordinates and display them on Leaflet.

I have Geojson with coordinates.

{
  "type": "Feature",
  "geometry": {
    "type": "Point",
    "coordinates": [
      "6690861",
      "682187"
    ]
  },
  "properties": {
    "id": "908",
    "message": "105",
    "date": "",
    "place": "",
    "shape": ""
  }
}

Now i want it display on Leaflet. But nothing show up. I search already 5 hours and find something about Proj4. Also no errors showing up.

My script code:

    var map = L.map('map').setView([52.2129919, 5.2793703], 8);

    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {attribution: 'Map data &copy; <a href="https://openstreetmap.org">OpenStreetMap</a>'}).addTo(map);
// GeoJSON layer (UTM15)
proj4.defs('EPSG:3857');

async function addGeoJson() {
    const response = await fetch("geojs.php");
    const data = await response.json();
    L.geoJson(data).addTo(map); 
    
var layerGroup = L.geoJSON(data, {
  onEachFeature: function (feature, layer) {
    layer.bindPopup('<h1>'+feature.properties.message+'</h1><p>Datum: '+feature.properties.date+'</p>');    
  }

}).addTo(map);
    
}
addGeoJson();

It’s for my the first time i work with this coordinates. With lat/long coordinates was don’t have problems. And just started with javascript.

Kind regards,

Is there a way to declare a variable by adding a variable name with a variable value?

I have some arrays:

var orderObj1 = [], orderObj2  = [], orderObj3 = [], orderObj4 = [], orderObj5 = [], orderObj6= [];

And I’m trying to do something like this:

for (let [key, value] of Object.entries(req.user.orders[z])) {
  if (key == orderName[a] + "Name") {
  a + 1;
  var ordName = orderObj + a;
  ordName.push(value);
 }

The end goal is ordName = orderObj1, and as a increases, ordName will reference orderObj2, orderObj3 and so on. The value of a initially is 0.

How to pass data on page loading to components?

In my project I use Vue.js and Nuxt.js and I have this page.

This page is settings page, where user can changes his settings. As you can see, this is only one page, where user can switch between tabs.

<template>
  <div class="account-wrapper">

    <div class="avatar" @click="redirect('/account/me')">
      <img class='avatar-box' src="../../../assets/img/testava.jpg" alt="ava">
      <div class="avatar-text">
        <h2 class="nmp">{{ personalSettings.username }}</h2>
        <p class="paragraph opacity nmp">Public profile</p>
      </div>
    </div>

    <div class="side-bar">
      <div v-for="item in accountHeaderItems" :key="item.title" class="flex">
        <div v-if="item.active" class="vertical-line" />
        <p :class="[item.active ? 'item item-active' : 'item']" @click="changeSubsection(item)">
          {{ item.title }}
        </p>
      </div>
    </div>

    <personal-information v-if="currentSection === 'Public account'" :personal-settings="personalSettings" />
    <security-settings v-else-if="currentSection === 'Security settings'" :security-settings="securitySettings" />
    <site-settings v-else />

  </div>
</template>

<script>
import SecuritySettings from '~/components/pageComponents/settings/SecuritySettings'
import PersonalInformation from '~/components/pageComponents/settings/PersonalInformation'
import SiteSettings from '~/components/pageComponents/settings/SiteSettings'
import { getUserSettings } from "~/api";
export default {
  name: 'Settings',
  components: {
    SecuritySettings,
    PersonalInformation,
    SiteSettings
  },
  data() {
    return {
      accountHeaderItems: [
        { title: 'Public account', active: true },
        { title: 'Security settings', active: false },
        { title: 'Appearance settings', active: false },
        { title: 'Notifications', active: false }
      ],
      currentSection: 'Public account',

      personalSettings: {},
      securitySettings: {},
    }
  },
  async mounted() {
    if (localStorage.getItem('token') !== null) await this.getUsersSettings(localStorage.getItem('token'))
    else await this.$router.push('/')
  },
  methods: {
    async getUsersSettings(token) {
      const userSettings = await getUserSettings(token)

      if (userSettings.status === -1)
        return this.$router.push('/')

      this.personalSettings = userSettings.personalSettings
      this.securitySettings = userSettings.securitySettings
    },
    changeSubsection(item) {
      this.currentSection = item.title
      this.accountHeaderItems.forEach(header => {
        header.active = item.title === header.title
      })
    },
    redirect(path) {
      this.$router.push(path)
    },
  }
}
</script>

The problem is when page loads. When in async mounted() I get data I want to pass it to my components. And here is the problem, when I try to do that it seems to work fine, but there is strange behaviour, I always need to switch between tabs, to make data be visible on page.

For example – in personalSettings object there is field first_name. So, in personal-information component in custom Input I want to show this data in this way (in mounted I make copy of object to prevent mutations):

<Input
  v-model="personalInfo.first_name"
  :title="'First name'"
  :title-class="'small'"
  :additional-class="'small'"
/>
...
props: {
  personalSettings: {
    type: Object,
    default: () => {}
  }
},
data() {
  return {
    personalInfo: {},
    loading: false,
    showPopup: false
  }
},
mounted() {
  this.personalInfo = this.personalSettings
},

Everything seems to be fine, but, actually, I have to switch to another tab and switch back to this tab to see this data. What’s wrong? How can I prevent this behaviour and show data in correct way?

TextDecoder return empty string in JavaScript

There is an .stl file with charset us-ascii which must decode as string.

static decodeText( array ) {

    // array is ArrayBuffer

    return new TextDecoder( ).decode( new Uint8Array( array ) );

}

But return empty string "".

How can it be solved ?

Avoiding the `String.fromCharCode.apply(null, array)` shortcut, which
throws a "maximum call stack size exceeded" error for large arrays.

Incorporating JS in shiny with Jquery and without Jquery

I am trying to incorporate JS into Shiny that is without writing anything to server. Here is the code. Below are 2 methods (one with JQuery and another without JQuery). But without JQuery is not working. Can anyone help me here?

Not working

library(shiny)

ui <- fluidPage(
  tags$head(HTML('<p id="res">Value</p>'),
  tags$script("document.getElementById('res').innerHTMl=x")),
  textInput("x", label = "Text")
)

server <- function(input, output) {
}

shinyApp(ui, server)

Working

library(shiny)

ui <- fluidPage(
    HTML('<p id="res">Value</p>'),
    textInput("x", label = "Text"),
    tags$script("$('#x').on('input', function(){$('#res').text($(this).val());});")
)

server <- function(input, output) {}

shinyApp(ui, server)