Jquery dataTable not save row position scroll after page reload?

I am using jquery datatable using asp.net mvc core framework. Its working fine and showing data. DataTable also saving state of pagination, like if i am on page 2 and click on any row button after page relaod it will show same page.
But my issue is i want to show same row with scroll position but right now its showing top of record after page reload.

$('#offersTable').dataTable({
    "bStateSave": true,
    "fnStateSave": function (oSettings, oData) {
        localStorage.setItem('offersDataTables', JSON.stringify(oData));
    },
    "fnStateLoad": function (oSettings) {
        return JSON.parse(localStorage.getItem('offersDataTables'));
    }
});

Its working fine with save state with paging but i want to scroll to same position row when i did changes or click on button row.
I am sorry for my bad english. Also i am using model to populate datatable.

Changing fill color of SVG on scroll

I have an SVG which is sticky, within a column that streches from top to bottom of the website.

How do I change the fill colour of the SVG when at exactly 50% of the way down the page on scroll?

I can see how it can be done with javascript when scrolling a defined number of pixels down the page, but I need percentage of page.

I would show my workings so far, but so far I have completely drawn a blank.

Any help would be appreciated.

What is the best way to iterate over an array in react?

I get something like this from api

[0, 1000], [1, 2000], [2, 1500]

where the first digit is the type and the second is the price.

And I iterated through the array like this:

const discountStud = discounts?.find((el) => el[0] === 1)?.filter((item) => item !== 1)

Is there a more elegant way? I write in React, and you can use lodash

P.S. I only need to get the price

How to use Drive Api and Sheets Api together in Javascript

I want to use the Drive Api and the Sheets Api together but I am getting error while implementing it. Many solution are there with Node.js,etc language but i want with front end javascript. The code used by me is overview of Api from the docs. https://developers.google.com/drive/api/v3/quickstart/js and https://developers.google.com/sheets/api/quickstart/js. And the error is Error Image. While there is no error in using drive api its works fine ,but while using the Sheet Api together it make the above error, is there any soultion.
` function handleClientLoad() {
gapi.load(‘client:auth2’, initClient);
}

/**
 *  Initializes the API client library and sets up sign-in state
 *  listeners.
 */
function initClient() {
  gapi.client.init({
    apiKey: API_KEY,
    clientId: CLIENT_ID,
    discoveryDocs: DISCOVERY_DOCS,
    scope: SCOPES
  }).then(function () {
    // Listen for sign-in state changes.
    gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);

    // Handle the initial sign-in state.
    updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
    authorizeButton.onclick = handleAuthClick;
    // signoutButton.onclick = handleSignoutClick;
  }, function (error) {
    appendPre(JSON.stringify(error, null, 2));
  });
}

/**
 *  Called when the signed in status changes, to update the UI
 *  appropriately. After a sign-in, the API is called.
 */
function updateSigninStatus(isSignedIn) {
  if (isSignedIn) {
    authorizeButton.style.display = 'none';
    // signoutButton.style.display = 'block';
    listFiles();
  } else {
    authorizeButton.style.display = 'block';
    // signoutButton.style.display = 'none';
  }
}


/**
 *  Sign in the user upon button click.
 */
function handleAuthClick(event) {
  gapi.auth2.getAuthInstance().signIn();
}

function handleSignoutClick(event) {
  gapi.auth2.getAuthInstance().signOut();
}
 function appendPre(name, id) {
  // var pre = document.getElementById('content');
  // var textContent = document.createTextNode(message + 'n');
  // pre.appendChild(textContent);
  var x = document.createElement("INPUT");
  x.setAttribute("type", "radio");
  x.setAttribute("id", id)
  x.setAttribute("name", "rad")
  x.setAttribute("value", id)
  x.setAttribute("class", "form-check-input mt-2")
  x.setAttribute("style", "margin-left: 47%;")
  x.setAttribute("onclick", "getid(this)")
  var y = document.createElement("label");
  y.setAttribute("for", "id");
  y.setAttribute("class", "form-check-label")
  y.setAttribute("style", "margin-left: 5px;")
  y.innerText = name;
  var division = document.getElementById("radi");
  division.append(x)
  division.append(y)
  var z = document.createElement("br");
  division.append(z)
}

/**
 * Print files.
 */
function listFiles() {
  gapi.client.drive.files.list({
    'q': "mimeType='application/vnd.google-apps.spreadsheet'",
    'pageSize': 10,
    'fields': "nextPageToken, files(id, name)"
  }).then(function (response) {
    // appendPre('Files:');
    var files = response.result.files;
    if (files && files.length > 0) {
      for (var i = 0; i < files.length; i++) {
        var file = files[i];
        appendPre(file.name, file.id);
      }
    } else {
      appendPre('No files found.');
    }
  });
}
   </script>
    <script>
var currentId;
function getid(value) {
  currentId = value.value;
  console.log(currentId);
  var btn = document.getElementById("importData");
  if (btn.style.display == "none") {
    btn.style.display = "block";
  }
}


 var authorizeButton1 = document.getElementById('authorize_button1');
  if (authorizeButton1.style.display == "none") {
    authorizeButton1.style.display = "block";
  }
  handleClientLoad2();
  function handleClientLoad2() {
    console.log("handleClientLoad");
    gapi.load('client:auth2', initClient2);
  }
  // var CLIENT_ID = ;
  
  var signed = false;
  function initClient2() {
    console.log("initClient2-1");

    gapi.client.init({
      apiKey: API_KEY,
      clientId: Client,
      discoveryDocs: discoverydoc,
      scope: scop
    }).then(function () {
      console.log("initClient2-2");
      gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
      console.log("initClient2-3");
      updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
      authorizeButton1.onclick = handleAuthClick1;
      // signoutButton.onclick = handleSignoutClick;
    }, function(error) {
      appendPre(JSON.stringify(error, null, 2));
    });
  }
  function updateSigninStatus(isSignedIn) {
    if (isSignedIn) {
      console.log("updateSigninStatus if");
      // authorizeButton1.style.display = 'none';
      // listMajors();
    } else {
      authorizeButton1.style.display = 'block';
      console.log("updateSigninStatus else");
    }
    
  }
  async function handleAuthClick1(event) {
    console.log("handleAuthClick");
    var responce = await gapi.auth2.getAuthInstance().signIn();
    console.log(responce);
    var response1 = await listMajors();
  }
  // function handleSignoutClick(event) {
  //   gapi.auth2.getAuthInstance().signOut();
  // }
  /**
   * Append a pre element to the body containing the given message
   * as its text node. Used to display the results of the API call.
   *
   * @param {string} message Text to be placed in pre element.
   */
  function appendPre(message) {
    var pre = document.getElementById('content');
    var textContent = document.createTextNode(message + 'n');
    pre.appendChild(textContent);
  }
  // initClient2()
  function listMajors() {
    console.log("listMajors");
    console.log(currentId);
    gapi.client.sheets.spreadsheets.values.get({
      spreadsheetId: currentId,
      range: 'Class Data!A2:C',
    }).then(function(response) {
      var range = response.result;
      if (range.values.length > 0) {
        appendPre('Name, Major:');
        for (i = 0; i < range.values.length; i++) {
          var row = range.values[i];
          appendPre(row[0] + ', ' + row[2]);
        }
      } else {
        appendPre('No data found.');
      }
    }, function(response) {
      appendPre('Error: ' + response.result.error.message);
    });
  }

}`

here in above code I removed the variables of init but i am garanteed that they are right ,the docs is [“https://sheets.googleapis.com/$discovery/rest?version=v4”] and scope is ‘https://www.googleapis.com/auth/spreadsheets.readonly’. As I don’t wanna reveal my api key and Client Id id I removed it. Pls help if you understand. And as I am logged in in drive api the status is sayed logged in so I changed the code little bit of sheet api than docs . Hope you reply

Update with findOneAndUpdate does not run

I’m trying to update using the ID of the object inside the array but I can’t do it passing the objects in $set through a variable. This is my code that I can’t get to work:

        const itemToUpdate = {
            concept: req.body.concept,
            incomeAmount: req.body.incomeAmount,
            description: req.body.description,
            expenseAmount: req.body.expenseAmount,
            'createdBy':{
                uid: req.uid,
                username: 'poshed',
            }
        };
    
    let pettyCashItem = await PettyCashItems.findOneAndUpdate({
        _id: id, 
        "items._id": idItem },
    {
        $set: { itemToUpdate }
    }, { new: 'true'});

But it happens that if I do it in the following way indicating object pot object it works but you have to write one by one:

    let pettyCashItem = await PettyCashItems.findOneAndUpdate({
        _id: id, 
        "items._id": idItem },
    {
        $set: { "items.$.concept": 'Test' }
    }, { new: 'true'});

Thanks!

Max call stack is greater in while loop

all.
Would be grateful if someone could clarify the following.

We have a basic factorial function and a for loop with a try catch block which runs the function until error
“Maximum call stack size is exceeded” is thrown.

When run in while loop max N is consistently 15699.

However when run without for loop, max call stack size is 11416.

Everything greater then 11416 number throws the “Maximum call stack size exceeded” error.

I would assume that the factorial function will be able to run with anything lesser than 15699, but it’s not the case.

Please see the code and screenshots of results below.
Code executed in in IDEA terminal, node -v – 14.16.1.

Would be very grateful if someone could clarify that to me.
Thank you very much in advance,
Katya

Max N of below is 15699

const nFactorial = (n) => {
    if (n === 1) {
        return 1;
    }
    return n * nFactorial (n - 1);
};

let n = 1;
while (n <= 100000) {
    try {
        nFactorial (n);
        n++;
    } catch (e) {
        console.log(`${e.message} with N = ${n}`);
        break;
    }
}

enter image description here

Below code only runs with N = 11416 and throws with anything greater than that number.

const nFactorial = (n) => {
    if (n === 1) {
        return 1;
    }
    return n * nFactorial (n - 1);
};

const n = 11416;
try {
    nFactorial (n);
} catch (e) {
    console.log(`${e.message} with N = ${n}`);
} 

enter image description here

not able to iterate through sub list in a list for search filter

So basically, I have a sidebar that contains a search feature like when you type a certain keyword on the input box, it’s supposed to iterate through all the list items and show if anything with that keyword exists. The problem is I’ve sub-options like Github is a dropdown list and contains sub lists (not the li HTML tag) like clone repo, setup ssh, and so on. The problem is I ain’t able to iterate through the sub-options. If I type up anything of the sub options, it doesn’t show up (except the first sub-option).

const dropdown = document.getElementsByClassName("dropdown-btn");

for (let i = 0; i < dropdown.length; i++) {
  dropdown[i].addEventListener("click", function() {
  this.classList.toggle("active");
  const dropdownContent = this.nextElementSibling;
  if (dropdownContent.style.display === "block") {
  dropdownContent.style.display = "none";
  } else {
  dropdownContent.style.display = "block";
  }
  });
}

function searchServices() {
  // Declare variables
  let input, filter, ul, li, a, i;
  input = document.getElementById('myInput');
  filter = input.value.toUpperCase();
  ul = document.getElementById("myUL");
  li = ul.getElementsByTagName('li');

  // Loop through all list items, and hide those who don't match the search query
  for (i = 0; i < li.length; i++) {
    a = li[i].getElementsByTagName("a")[0];
    txtValue = a.textContent || a.innerText;
    if (txtValue.toUpperCase().indexOf(filter) > -1) {
      li[i].style.display = "";
    } else {
      li[i].style.display = "none";
    }
  }
}
.sidenav {
  height: 100%;
  width: 250px;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #1B1D23;
  overflow-x: hidden;
  padding-top: 20px;
  margin-top: 48px;
}

.sidenav a, .dropdown-btn {
  padding: 15px 30px;
  text-decoration: none;
  color: #aaaaaa;
  display: block;
  border: none;
  background: none;
  width: 100%;
  text-align: left;
  cursor: pointer;
  outline: none;
}

.sidenav a:hover, .dropdown-btn:hover {
  color: #f1f1f1;
}

.main {
  margin-left: 300px; 
  padding: 0px 10px;
}

.active {
  background-color: #2ad9a6;
  color: white;
}

.dropdown-container {
  display: none;
  background-color: #21232a;
  padding-left: 8px;
}

.fa-caret-down {
  float: right;
  padding-right: 8px;
}

@media screen and (max-height: 450px) {
  .sidenav {padding-top: 15px;}
  .sidenav a {font-size: 18px;}
}

#myInput {
  background-image: url('../img/search.png'); 
  background-position: 15px 12px; 
  background-repeat: no-repeat; 
  background-color: #21232a;
  width: 100%;
  color: white;
  outline: none;
  padding: 12px 20px 12px 45px;
  border: 1px solid #343B48;
  margin-bottom: 12px; 
}

#myInput::placeholder{
  color: #52555d;
}

#myUL {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

#setupMainName{
  font-size: 0.8rem;
  margin-top: -15px;
}

.dropdown-container a{
   margin-top: -11px;
}

.sidebarLogo{
  text-align: center;
  padding: 20px 0 40px 0;
  cursor: pointer;
}

.sidebarLogo img{
  width: 150px;
  margin: 0 auto;
}

.logoCont{
  padding: 0px !important;
}
<div class="sidenav">
          <a class="logoCont" href="index.html">

          </a>
          <input type="text" id="myInput" onkeyup="searchServices()" placeholder="Search">
          <ul id="myUL">
            <li><button  class="dropdown-btn">Github 
              <i class="fa fa-caret-down"></i>
            </button>
            <div class="dropdown-container" id="myList">
              <a href="#" style="margin-top: 0px;">
                <p id="setupSubName" >
                  Setup SSH
                </p>
                <p id="setupMainName">
                Github
                </p>
              </a>
              <a href="#" >
                <p id="setupSubName">
                  Clone Repository
                </p>
                <p id="setupMainName">
                Github
                </p>
              </a>
              <a href="#" >
                <p id="setupSubName" >
                  Commit Repository
                </p>
                <p id="setupMainName">
                Github
                </p>
              </a>
              </div>
            </li>
            <li><a href="#">To be added2</a></li>
            <li><a href="#">To be added</a></li>
            <li><a href="#">To be added</a></li>
            </ul>
        </div>

How to reduce vue.js component library build size

Please I’m currently developing a component library for my component using vue.js(2.x) to be published on npm after I have run the build-library script in my package.json file I ended up with a 4MB dist folder, this happens as a result of the dependencies imported in my helpers file and this helper function was used in one of my components src/components/VdaAccount.vue

Please how can I drastically reduce the build size to KB?

here is the file in my helper function :

src/helpers/veridaHelper.ts

import { EnvironmentType, Network } from "@verida/client-ts";
import { EventEmitter } from "events";
import store from "store";
import { hasSession, VaultAccount } from "@verida/account-web-vault";
import { Profile, Connect } from "../interface";

const VUE_APP_VAULT_CONTEXT_NAME = "Verida: Vault";

const CONTEXT_NAME_IN_LOCAL_STORAGE = "AppContext";

const VUE_APP_VERIDA_TESTNET_DEFAULT_SERVER =
  "https://db.testnet.verida.io:5002/";

const VUE_APP_LOGO_URL =
  "https://assets.verida.io/verida_login_request_logo_170x170.png";

class VeridaHelpers extends EventEmitter {
  private client: any;
  public profile?: Profile;
  public context: any;
  private account: any;
  public did?: string;
  public connected?: boolean;
  public contextName?: string;

  constructor() {
    super();
    this.contextName = store.get(CONTEXT_NAME_IN_LOCAL_STORAGE);
  }

  public async connect({ contextName, logo }: Connect): Promise<void> {
    this.account = new VaultAccount({
      defaultDatabaseServer: {
        type: "VeridaDatabase",
        endpointUri: VUE_APP_VERIDA_TESTNET_DEFAULT_SERVER,
      },
      defaultMessageServer: {
        type: "VeridaMessage",
        endpointUri: VUE_APP_VERIDA_TESTNET_DEFAULT_SERVER,
      },
      vaultConfig: {
        request: {
          logoUrl: logo || VUE_APP_LOGO_URL,
        },
      },
    });

    if (!this.contextName) {
      this.contextName = contextName;
      store.set(CONTEXT_NAME_IN_LOCAL_STORAGE, contextName);
    }

    this.context = await Network.connect({
      client: {
        environment: EnvironmentType.TESTNET,
      },
      account: this.account,
      context: {
        name: contextName,
      },
    });

    this.did = await this.account.did();

    await this.initProfile();

    if (this.context) {
      this.connected = true;
    }
    this.emit("connected", this.connected);
  }

  private async initProfile(): Promise<void> {
    const client = await this.context.getClient();
    const profile = await client.openPublicProfile(this.did, VUE_APP_VAULT_CONTEXT_NAME);
    const cb = async () => {
      const data = await profile.getMany();
      this.profile = data;
      this.emit("profileChanged", this.profile);
    };
    profile.listen(cb);
    await cb();
  }

  autoLogin() {
    return hasSession(this.contextName as string);
  }


  
}

const VeridaHelper = new VeridaHelpers();

export default VeridaHelper;

 package.json

{
    "name": "component-name",
    "version": "0.1.0",
    "private": false,
    "scripts": {
        "serve": "vue-cli-service serve",
        "build": "vue-cli-service build  --report",
        "test:unit": "vue-cli-service test:unit",
        "lint": "vue-cli-service lint",
        "build-library": "vue-cli-service build --mode production --target lib --name vue-account ./src/install.ts "
    },
    "dependencies": {
        "@verida/account-web-vault": "^1.1.8",
        "@verida/client-ts": "^1.1.11",
        "core-js": "^3.6.5",
        "events": "^3.3.0",
        "store": "^2.0.12",
        "vue": "^2.6.11",
        "vue-clipboard2": "^0.3.3",
        "vue-spinner": "^1.0.4"
    },
    "devDependencies": {
        "@types/events": "^3.0.0",
        "@types/jest": "^24.0.19",
        "@types/store": "^2.0.2",
        "@typescript-eslint/eslint-plugin": "^4.18.0",
        "@typescript-eslint/parser": "^4.18.0",
        "@vue/cli-plugin-babel": "~4.5.0",
        "@vue/cli-plugin-eslint": "~4.5.0",
        "@vue/cli-plugin-typescript": "~4.5.0",
        "@vue/cli-plugin-unit-jest": "~4.5.0",
        "@vue/cli-service": "~4.5.0",
        "@vue/eslint-config-prettier": "^6.0.0",
        "@vue/eslint-config-typescript": "^7.0.0",
        "@vue/test-utils": "^1.0.3",
        "eslint": "^6.7.2",
        "eslint-plugin-prettier": "^3.3.1",
        "eslint-plugin-vue": "^6.2.2",
        "node-sass": "^4.12.0",
        "prettier": "^2.2.1",
        "sass-loader": "^8.0.2",
        "typescript": "~4.1.5",
        "vue-template-compiler": "^2.6.11"
    }
}

 src/install.js

import VdaAccount from './components/VdaAccount.vue';
import VdaLogin from './components/VdaLogin.vue';

export default {
    
    install(Vue: any, options: any) {
        Vue.component('vda-account', VdaAccount);
        Vue.component('vda-login', VdaLogin);

        }
};

How to select an Item from an array in Javascript with prompt

I’m creating a menu with Javascript. I want to be able to type out a food Item from the mainMenu array, in prompt and have it return an alert with a string. I tried creating a function but I’m unsure as to how to link user text within a prompt with an array

Here’s my code below

var mainMenu = [
    "Hamburger",
    "Cheeseburger",
    "Steakburger",
    "Teriyaki Chicken",
    "BBQ Chicken",
];


// var mainMenuItems = mainMenu.values();


var sideMenu = {
    firstSide: "Regular Fries",
    secondSide: "Seasoned Fries",
    thirdSide: "Mash Potatoes",
    fourthSide: "Mac&Cheese",
    fifthSide: "Nuggets",
    sixthSide: "Hotdog",
    seventhSide: "Coleslaw",
    eighthSide: "Chilli&Beans",
};

Object.defineProperty(mainMenu, "toString", {
    value: function() {
        return JSON.stringify(this)
    }
})

alert("Hey There Welcome to Los Hermanos Loco");

const customerName = prompt("Enter your name here", "<name goes here>");

if (customerName != null) {

    console.log("Hello" + customerName + "! How are you today?");
};

alert("What would you like to order?" + customerName);


function selectItems() {
    var select = mainMenu
    if (select != null)
        return alert("That will be 15$")
};

prompt(`What would you like, ${mainMenu}`);

I’m getting error that say “Throwing inside of an async function without a catch block or by rejecting a promise which was not handled with .catch().”

So I’m currently trying to code a giveaway bot for my discord server and the code is written in a mix of DJS v12 and v13 and so far it seems to works and executes the message in the code that says “Done! The giveaway for the Nitro is starting in (channel)” but it gets an errors sending the actually giveaway embed that people react to and the error stated in the title. Is anyone able to review my code and see what I’m doing wrong? I placed it in my google drive to make it easier to read the entire code rather than sections. https://drive.google.com/drive/folders/18HdN9eObtfnlWRvWU6rwtRXJH6qkzQt_?usp=sharing

subtract 1 minute from time Javascript [duplicate]

From my front end, somebody will submit the time using <input type="time">. So on the backend, it is retrieved like so:

let eventDetails = {
    eventStartTime: req.body.eventStartTime
}

so when I log this, it returns this (as a string), like so:

13:00

now what I need to happen is for it to subtract 1 minute from the time that gets returned, but I’m not sure where to start since it is technically a string. How can i do this?

Deploy a Webapp with Spring Boot Backend and HTML/JS Frontend

I’m currently building a website with a Spring Boot Backend, the Frontend is just plain HTML, CSS and JS (it only needs to be functional, not pretty). Now I’m wondering, how can I deploy the Frontend? I’m using WebStorm to develop, which appears to start a Web Service automatically while running (I’ve attempted to use NGrok to access the Content from outside my network, and it couldn’t find anything on the port when WebStorm was closed). So I guess my question is – How can I start a Web Service, like the one that runs in the Background of WebStorm, manually?

Kind regards

targeting the child element in jQuery

my html code is like this:

<div class="title" id="title1"> 
</div>

<div class="title" id="title2"> 
</div>

I am using .append() inside a for .each() and add a paragraph with some unique value to each of these id
like this:

$(`#title${index + 1}`).append("<p>" + title + "</p>")

now i am trying to target each of the paragraph using the class name which is common among them but it is not returning the value, i use any ways that came to my mind but it is not working:

$(".title").find("p")
$(".title").children("p")
$(".title > p") 

its just showing the entire div not the children like this

S.fn.init [prevObject: S.fn.init(6)]
length: 0
prevObject: S.fn.init(6) [div#title1.title.header, div#title2.title.header, div#recentNewsTitle1.recentNewsTitle.title.header, div#recentNewsTitle2.recentNewsTitle.title.header, div#recentNewsTitle3.recentNewsTitle.title.header, div#recentNewsTitle4.recentNewsTitle.title.header, prevObject: S.fn.init(1)]
[[Prototype]]: Object(0)