How to calibrate length units for different display devices?

I need to be able to work with real length units for any display device and have to be able to rely on them. So I made myself a little ruler. On my laptop screen it comes out way too small. On my cellphone even smaller.

How can one calibrate this? I imagine the display device should have its physical dimension and then the resolution determines the distance of pixels. How can I do this?

        div {
          margin: 0 0 0 0;
          padding: 0 0 0 0;
        }
        div.ruler {
          counter-reset: major -1;
          width: 10cm;
            white-space: nowrap;
            font-size: 0;
        }
        div.number::after {
            content: counter(major);
          counter-increment: major;
          font-size: 3mm;
        }
        div.major {
          width: calc(1cm - 1px);
          height: 5mm;
          text-align: left;
          border-left: 1px solid black;
            display: inline-block;
            font-size: 0;
        }
        div.minor {
          width: calc(1mm - 1px);
          height: 1mm;
          border-right: 1px solid black;
            display: inline-block;
        }
        div.half {
          height: 2mm;
        }
<html>
    <head>
        <title>Screen Geometry and Gestures</title>
    </head>
    <body>
        <main>
            <h1>Screen Geometry and Gestures</h1>
            <section>
                <h2>Length Units</h2>
                <p>Let's make a ruler!</p>
                <div class="ruler">
                    <div class="major">
                        <div class="number"></div>
                        <div class="minor"></div>
                        <div class="minor"></div>
                        <div class="minor"></div>
                        <div class="minor"></div>               
                        <div class="minor half"></div>
                        <div class="minor"></div>
                        <div class="minor"></div>
                        <div class="minor"></div>               
                        <div class="minor"></div>               
                    </div>
                    <script type="text/javascript">
                        const self = document.currentScript;
                        const div = self.previousElementSibling;
                        for(let i = 0; i < 20; i++) {
                          const newdiv = div.cloneNode(true);
                          self.parentElement.insertBefore(newdiv, self);
                        }
                    </script>
                    <div class="major"></div>
                </div>
            </section>          
        </main>
    </body>
</html>

Query Params get removed from react route when click on button

I am facing an issue in react js, there is route to page e.g https://localhost:3000/profile?abc=123, the url is browsed successfully but the issue is when I click on button (I call api on click of this button using axios) in my website then the query params in the url gets removed automatically like this,
https://localhost:3000/profile. I have debugged, the params are removed when axios call is initiated. Any help would be highly appreciated.

How to send server sent events on database update

I want to send SSE event only when there is a DB update API called.
How do I achieve this? What is the standard market practise to achieve this?

my SSE endpoint looks like this

app.get('/send-events', (req, res) => {
    const headers = {
        Connection: "keep-alive",
        "Content-Type": "text/event-stream",
        "Cache-Control": "no-cache",
    };
    res.writeHead(200, headers);

    const data = `data: ${new Date()}nn`;

    res.write(data);
});

i want to trigger the above api when another api is being called. Eg below

app.post('/update-db', (req, res) => {
    res.send('db-updated');

    //perform db update
    //send the latest data thru sse endpoint
});

I want to change an object attribute value in an api request but it is not working

I am doing api calls with axios on express. I have an external API controller that has different functions to call and fetch data from the IGDB api.

I have a gameController.js that will build a finalized JSON object using the different data fetched from the different calls.

this is my gameController.js

const externalApiController = require("./externalApiController");

exports.getGames = async (req, res) => {
  var initialGameResult = await externalApiController.getGames(
    req.body.searchInput
  );
  await initialGameResult.forEach(async (game) => {
    if (game.cover) {
      const cover = await externalApiController.getCover(game.cover);
      console.log(cover[0]);
      // >>>>>>>>>>>>>>>>>>>
      game.cover = cover[0]; // MY ISSUE IS HERE. IT IS NOT CHANGING
      // >>>>>>>>>>>>>>>>>>>
    }
  });
  res.send(initialGameResult); //SEND THE UNCHANGED DATA
};

This is my externalApiController.js

var axios = require("axios");
require("dotenv").config();

exports.getGames = async (searchInput) => {
  var data = `fields id,name,cover,platforms,category,genres,collection ; search "${searchInput}"; limit 5;`;
  var config = {
    method: "post",
    url: "https://api.igdb.com/v4/games",
    headers: {
      "Client-ID": process.env.CLIENT_ID,
      Authorization: `Bearer ${process.env.ACCESS_TOKEN}`,
      "Content-Type": "text/plain",
    },
    data: data,
  };
  const result = await axios(config);

  //   console.log(result.data);
  return result.data;
};

exports.getCover = async (id) => {
  var data = `fields id, url; where id = ${id};`;
  var config = {
    method: "post",
    url: "https://api.igdb.com/v4/covers",
    headers: {
      "Client-ID": process.env.CLIENT_ID,
      Authorization: `Bearer ${process.env.ACCESS_TOKEN}`,
      "Content-Type": "text/plain",
    },
    data: data,
  };

  const result = await axios(config);

  //   console.log(result.data);
  return result.data;
};

Basically this is the data that I get from the initial request.
It is correct. But as seen in the picture, the cover is an ID value. I need to fetch another API request using that value to get the image URL. It works fine in the foreach line. When i log it i get this.

However, it does not change in this line: game.cover = cover[0];

I need the data to change from:

{
   "id": 110248,
   "category": 0,
   "cover": 225254,
   "genres": [
      31,
      32
   ],
   "name": "Stray",
   "platforms": [
      6,
      48,
      167
   ]
},

to:

{
   "id": 110248,
   "category": 0,
   "cover": {
      id: whatever_id_it_is,
      url: whatever_url_it_is
   },
   "genres": [
      31,
      32
   ],
   "name": "Stray",
   "platforms": [
      6,
      48,
      167
   ]
},

Also, I am not quite sure I am using the async and await correctly.

Coverage issues due to children component not being captured

I have the following component.

import React from 'react';
import { connect } from 'react-redux';
import { getLocale, getEnvironment } from '../utils/data';
import provide from '../scripts/provide';
import Provide from './Provide';
import Render from './Render';

const Widget = ({
  environment,
  locale,
  rOptions
}) => (rOptions ? (
  <Render
    rOptions={rOptions}
  />
) : (
  <Provide
    options={{
      environment,
      locale,
    }}
  >
    {(options) => (
      <Render
        rOptions={options}
      />
    )}
  </Provide>
));

Widget.provide = provide;

export const mapState = (state) => ({
  locale: getLocale(state),
  environment: getEnvironment(state),
});

export default connect(mapState)(Widget);

Trying to test it to get full coverage.

But I am currently not getting the coverage for the following:

{(options) => (
    <Render
      rOptions={options}
    />
  )}

This is cos I have mocked Provide as follows.

jest.mock('../../src/components/Provide', () => 'Provide');

How could I modify this mock for it to have children to be able to get coverage for it?

The test for this Provide with render as children bit.

import React from 'react';
import { mount } from 'enzyme';
it('should render', () => {
    const Widget = require('../../src/components/Widget').default;
    const renderedModule = mount(<Widget {...defaultProps} />);
    expect(renderedModule.find('Provide')).toMatchSnapshot();
});

The snapshot looks like this:

exports[`Widget should render 1`] = `
<Provide
  options={
    Object {
      "environment": "mock environment",
      "locale": "mock locale",
    }
  }
>
  <Component />
</Provide>
`;

If mocked correctly, the <Component /> should have been <Render ... />

Other mocks in the test not relevant I believe. Leaving it in for reference.

jest.mock('../../src/components/Render', () => () => 'Render');
jest.mock('../../src/scripts/provide', () => () => 'mock provide');

jest.mock('../../src/utils/data', () => ({
  getLocale: () => 'mock locale',
  getEnvironment: () => 'mock environment',
}));

Image not showing using react styled component

I have a problem , my logo image is not show , i am using React js.
and when i remove my display: flex; property then logo shown with very
bigger size. so this is the problem , why display: flex is not
working. ……………………here is my
code………………………

enter image description here

import React from ‘react’;
import styled from ‘styled-components’;

const Login = (props) =>{
    return(
        <Container>
            <Nav>
                <a href='/'>
                    <img src='/images/login-logo.svg' alt='' />
                </a>
                <div>
                    <Join>Join Now</Join>
                </div>
            </Nav>
        </Container>
    );
};

const Container = styled.div`
padding: 0px;
`;

const Nav = styled.nav`
max-width: 1128px;
margin: auto;
padding: 12px 0 16px;
display: flex;
align-items: center;
position: relative;
justify-content: space-between;
flex-wrap: nowrap;

& > a{
    width: 135px
    height: 34px;
    @media(max-width: 768px){
        padding: 0 5px;
    }
}

`;

const Join = styled.a`
font-size: 16px;
padding: 10px 12px;
text-decoration: none;
border-radius: 4px;
color: rgba(0, 0, 0, 0.6);
margin-right: 12px;
&:hover{
    background-color: rgba(0, 0, 0, 0.08);
    color: rgba(0, 0, 0, 0.9);
    text-decoration: none;
}
`;


export default Login;

How to Create a Dropdown Filter with C#, SQL Server and Ajax?

I have a database with properties in it, I would like to have a filter that with Order By sorts them by city, address or house number. I cannot create an SQL command with variables that change based on user input. Can anyone help me? Below is the code I wrote.

I think the error is here, I don’t know how to create an SQL command that has a value chosen directly by the user, I tried concatenating the string like this. But I don’t know if it is correct.

C# Code:

 public void listsOrderBy()
        {
            List<immobili> listOrderBy = new List<immobili>();

            string valueCity = Request.Form["valueCity"] ;
            string valueAddress = Request.Form["valueAddress"] ;
            string valueHousenumber = Request.Form["valueHousenumber"] ;



            string sql = "SELECT DISTINCT id, city, address, housenumber FROM realestate ORDER BY" + valueCity + valueAddress + valueHousenumber;

            string connection = "//connection string";

            using (SqlConnection con = new SqlConnection(conn))
            {
                con.Open();
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = con;
                    cmd.CommandText = sql;


                    SqlDataReader dr = cmd.ExecuteReader();

                    while (dr.Read())
                    {

                        realestate i = new realestate();
                        i.city = (dr["city"].ToString());
                        i.address = (dr["address"].ToString());
                        i.housenumber = (dr["housenumber"].ToString());

                        listOrderBy.Add(i);

                    }
                    con.Close();
                }
                string json = new JavaScriptSerializer().Serialize(listOrderBy.ToArray());
                Response.ContentType = "application/json";
                Response.WriteAsync(json);

            }

        }

HTML Code:

         <div>
             <select id="filterOrderByData" >
                 <option>Tutti</option>
                 <option name="valueCity">City</option>
                 <option name="valueAddress">Address</option>
                 <option name="valueHousenumber">House Number</option>
             </select>
            <button type="button" onclick="menuOrderBy();">Search</button>

         </div>

JS Code:

        function menuOrderBy() {
            let valueCity = document.querySelector("#valueCity");
            let valueAddress = document.querySelector("#valueAddress");
            let valueHousenumber = document.querySelector("#valueHousenumber");
            $.ajax({
                url: '/home/filter?&order=' + valueCity + valueAddress + valueHousenumber ,
                type: "GET",
                data: $("#filterOrderByData").serialize(),
                dataType: "json",
                success: function (data) {
                    $("#bodyTable").empty();

                    for (var i = 0; i < data.length; i++) {
                        var newTable = `
                                                                                               <tr>
                                                                                                    <td>${data[i].id}</td>
                                                                                                    <td>${data[i].city}</td>
                                                                                                    <td>${data[i].address}</td>
                                                                                                    <td>${data[i].housenumber}</td>
                                                                                                </tr>


                                                                                                    `
                        $("#bodyTable").append(newTable);
                    }
                }
            })
        }

Disable input box based on variable javascript html

I want to disable an input field, if the currentUser.name equals a certain string, so in this case, it is disabled if the user is Bob.

However this doesn’t seem to be working. Can anyone tell me what i’m doing wrong?

                <input
                  formControlName="{{ field.key }}"
                  type="{{ field.type }}"
                  placeholder="{{ field.name }}"
                  [class.is-invalid]="submitted && f[field.key].errors"
                  (change)="editedField()"
                  [disabled]="this.currentUser.name == 'Bob'"
                />

Kendo Stacked Bar Chart – StackValue doesn’t display correct sum incase of negative values

I have a kendo stacked bar chart defined as follows :

$("#chart").kendoChart({
    title: {
        text: ""
    },            
    legend: {
        visible: false
    },
    seriesDefaults: {
        type: "bar",
        stack: true
    },
    series: [{
        name: "Value1",
        data: [-40, 32, 34, 36, 45, 33, -34, 83, 36, 37, 44, 37, 35, 36, 46],
        color: "#f3ac32"
    }, {
        name: "Value2",
        data: [19, 25, -21, 26, 28, 31, 35, 60, 31, 34, 32, 24, 40, 38, 29],
        color: "#b8b8b8"
    }, {
        name: "Value3",
        data: [17, 17, 16, -28, 34, 30, 25, 30, -27, -37, 25, 33, 26, 36, 29],
        color: "#bb6e36",
        labels: {
            template: "#= stackValue #",
            visible: true
        },
    }],
    valueAxis: {
        max: 180,
        line: {
            visible: false
        },
        minorGridLines: {
            visible: true
        }
    },
    categoryAxis: {
        categories: [1952, 1956, 1960, 1964, 1968, 1972, 1976, 1984, 1988, 1992, 1996, 2000, 2004, 2008, 2012],
        majorGridLines: {
            visible: false
        }
    },
    tooltip: {
        visible: true,
        template: "#= series.name #: #= value #"
    }
});

The chart is formed as below.

enter image description here

Under the series for last value, I have added the labels which is supposed to calculate the sum of the stacked bars. However for bars with negative values it doesn’t include that in it’s sum.
How do I get it to display correct sum for each data?

Chromium can’t download PDF from integrated reader

I serve a BLOB from my server to the clients browser included PDF-Reader.

const file = new File([data], filename, { type: contentType });
const url = URL.createObjectURL(file);
const anchorElement = document.createElement("a");
document.body.appendChild(anchorElement);
anchorElement.href = url;
anchorElement.target = "_blank";

This worked great, but the filename when downloaded from the reader was the assigned GUID.
Since the newest patch for Chromium (or maybe a few before idk) this no longer works. The file is display correctly in the reader and all PDF-properties are written correctly.
But I can no longer download the file. When downloading the file, the .pdf extension, is no longer added and the download then fails with

couldn’t download – network issue

This also happens if I add the .pdf extension and Chromium recognizes the file as a PDF.
I can download the file by anchorElement.download without a problem and I can print an PDF from the reader without a problem.
It still works fine on FF or Safari.

I would be greateful for any advice on how to fix this.
I can not download the file to the server and then serve that link.
I do not want to go the route of auto download and then opening the file.

How to export mysql data as xlsx?

How to export the data from mysql as xlsx, mysql workbranch only support export as CSV as i see in workbranch.
I wan to have some programme which can directly get an mysql stored procedures result as .XLSX format file. Any Idea?

JS & HTML form validation -> error message taken from label element .innerText

Hi first time posting here, I guess it wont be the last. Please bear with me.

I’m trying to validate a form of wich i want to show an error if the requireds are not met.
In this error i want to re-use the lable text.

I dont get very far hence the error the console gives me:

Uncaught TypeError: Cannot read properties of null (reading
‘innerText’)
at onSubmit (app.js:40:71)
at HTMLFormElement.onsubmit (contact.html?userName=&userEmail=&userComment=:43:69)

As to my understanding the text in the element/label(name, email, comments) should be stored to let label. But it gives me and error at .innerText.

I know that everyone here is more knowledgeable than me so maybe you could point me in the right direction. thanks!

'use strict';
const onSubmit = event => {
    event.preventDefault()
    for (let element of event.target)
        if (element.required) {
            let label = document.getElementById(`${element.id}-label`).innerText
            let error = ""
            switch(element.type) {
                case 'text':
                    if (!isNullOrEmpty(element.value)) {
                        if (!isMinLength(element.value, element.dataset.requiredMin)) {
                            error = `Your ${label.toLocaleLowerCase()} must contain at least ${element.dataset.requiredMin} letters.`
                        }
                    } else {
                        error = `You must enter a ${label.toLocaleLowerCase()}`
                    }
                    console.log('validera text');
                    break;
                case 'email':
                    console.log('validera email');
                    break;
                case 'textarea':
                    console.log('validera lösenord');
                    break;
            }
            document.getElementById(`${element.id}-error`).innerText = error
        }
}

const isNullOrEmpty = value =>{
    if (value.length === 0)
        return true
    
    return false
}

const isMinLength = (value, minLength = 2) =>{
    if (value.length >= minLength)
        return true

    return false
}
<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="description" content="EC02_JavaScript-Frontend">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>EC02_JavaScript-Frontend</title>
   <script src="https://kit.fontawesome.com/41c8b474e2.js" crossorigin="anonymous"></script>
   <link href="css/main.css" rel="stylesheet">
   <script defer src="src/js/app.js"></script>
</head>
<body>
    <section class="form container">
            <h1>Come in Contact with Us</h1>
            <form onsubmit="onSubmit(event)" class="contact" novalidate>
                <div class="name_email">
                    <span>
                        <label id="userName-label" for="userName-input">Name</label>
                        <input type="text" name="userName" id="userName-input" placeholder="Your Name" required data-required-min="2">
                        <div id="userName-error"></div>
                    </span>
                    <span>
                        <label id="userEmail-label" for="userEmail-input">Email</label>
                        <input type="email" name="userEmail" id="userEmail-input" placeholder="Your Email" required>
                        <div id="userEmail-error"></div>
                    </span>
                </div>
                <div>
                    <label id="userComment-label" for="userComment-input">Comments</label>
                    <textarea type="text" name="userComment" id="userComment-input" placeholder="Comments" required data-required-min="10"></textarea>
                    <div id="userComment-error"></div>
                </div>
                <div class="submitbutton">
                    <button type="submit" class="button bg-red">Post Comments</button>
                </div>
            </form>
        </section>
</body>
</html>

How to change html list order when a new element gets added to the list array in vue 3

Html list doesn’t show elements correctly in descending order after I add a new element to the array but works fine on onMount

I have an array to render as html list in descending order of the values. So I used v-for to do that.

After rendering the array, I need to add more elements one by one and these elements need to be added in correct order. so I used sort method.

Now the problem is the list doesn’t get rendered correctly after I add a new element to the array although sort method works fine. The correct order gets rendered only when I reload the component/page

android 11 (targetSdkVersion 32) cant open sqlite database in ionic 3

cordova plugins are installed.but we are get this error,

'Ionic Native: tried accessing the SQLite plugin but it's not installed.
 Install the SQLite plugin: 'ionic cordova plugin add cordova-sqlite-storage'

package.json :

 "@ionic-native/sqlite": "^4.20.0",
 "cordova-sqlite-storage": "^6.0.0",

database.ts :

   if (!this.isOpen) {
   this.storage = new SQLite();
   this.storage.create({ name: "data.db", location: "default" }).then((db: SQLiteObject) => {
   this.db = db;
   console.log('DB :',this.db)
   db.executeSql("CREATE TABLE IF NOT EXISTS customer (id_customer int UNSIGNED NOT NULL, 
   reference_no varchar(100) DEFAULT NULL)", []);
   this.isOpen = true;
   console.log('open : ',this.isOpen)
   }).catch((error) => {
   console.log('error :',error);
   })
  }