Module import using npm typescript

I’m trying to do the following:
A method called newDice which uses the random library (‘random’) to generate and return a random integer between 1 and 6.

This is the code I have:

import random from 'random'

function rollDice(min:number, max:number) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}

let result = rollDice(1, 6)
console.log(result);

I don’t know how to call random to display the random number. Help, please!

What does this JavaScript code trying to do?

I came across a block of code in a project and I find it hard to understand:

let isSelected = false;
const results = items.filter(Boolean).map(item => {
  isSelected = !isSelected && id === item.id;
  return {
    id: item.id,
    name: item.name
  };
});

What’s the line isSelected = !isSelected && id === item.id; before the return is trying to do?

Thanks.

How do I search pattern match with knex

I’m searching through an sql database using knex.js query builder and I’m trying to create a model that searches for all rows where the title has the input title I pass.

async function getByTitle(title) {
  const result = await db('recipes')
    .select('*')
    .whereRaw('LOWER(title) LIKE ?', title);
  return result;
}

This seems to only give the exact matches to the title instead of pattern matching it. For example, I have

test
test1
test2
test3

when title is test, I expect to get all that back, but instead I only get test back. I’ve searched through many similar questions and this seemed to be the solution, but this isn’t working in my case.

Json Pretty formatting

would like to format my Json data. I have something like this
{n “companyName”: “Acme, Inc.”, “rMMAlertID”: null, “billingCodeID”: null, “assignedResourceUsername”: “defaultuser1”, “assignedResourceRoleName”: “Customer Service Representative”,”title”: “Auto-submitted via BeyondTrust Remote Support chat”n

would like it to show
enter image description here

some issue with min function of java script [duplicate]

I know this sounds silly but I don’t know why my min function is returning the max value instead of min value. Can someone please tell me here have I gone wrong?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
    let findMin=(1,2);
    const resultOfMin=Math.min(findMin)
    document.write(resultOfMin);
    </script>
</body>
</html>

React state undefined when used after being set

I have an application that is essentially a search with dropdown filters. The idea is to make them seamless with no buttons. When a user reaches the bottom of the page, fetchBooks is called again, except this time it adds on to the list instead of replacing it wholesale. Inversely, if a user types something else in or chooses a different dropdown option, the idea is to use all the selections (which are now parts of the state) to construct an API query with params and get a whole new set which can then increase in size as a user traverses it.

Upon render, there are several state variables that are created via useState().

const bookTitle, setBookTitle = useState()
const isFiction, setIsFiction = useState()

I’m using our homegrown component library to implement the dropdowns but they have simple controls – onChange, initialValue – nothing crazy.

I’m using something similar to detect if a user reaches the end of the list:

useEffect(() => {
   const onScroll = function () {
      if (window.innerHeight + window.scrollY >= document.body.offsetHeight) {
        fetchBooks(true) // true indicates we want to add to the list
      }
   }
   window.addEventListener('scroll', onScroll)
   return () => window.removeEventListener('scroll', onScroll)
}, [])

The problem is that whenever fetchBooks is called the second time around, all of the values of dropdowns stored in state are undefined. I could try to modify the code not to identify too much but that’d be a bit of a project.

My question is – does this ring any bells? Why would a function that exists in the same context of one component see stored state variables as undefined?

Message shows “Invalid JSON primitive: .”

I’m trying to solve an error that I’m running into in an ajax call. I’ve console logged the error and the error is as follow:

{“Message”:”Invalid JSON primitive: .”,”StackTrace”:”
at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()r
at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)rn
at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth)rn
at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)rn
at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)rn
at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)rn
at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)rn
at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)”,”ExceptionType”:”System.ArgumentException”}

Here is my call on the front end:

$.ajax({                
                type: "POST",
                url: "AppointmentRequestQueueItems.aspx/UpdateDocumentStatus",
                data: "{status: " + status + ", appointmentRequestQueueId: " + parameter + ", userId: " + userId + "}",
                async: false,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    return;
                },
                error: function (request) {
                    console.log(request.responseText);
                    alert("An error has occurred!");
                }
            });

And here is my backend code:

        [WebMethod]
    public static void UpdateDocumentStatus(int status, int appointmentRequestQueueId, int userId)
    {
        var mgr = ScheduledEventManagerFactory.CreateSchedulingManager(
            new SourceInformation(SystemSourceTypes.Intranet, userId, GetConfigSettingStatic("LangCulture")));
        

        if( status == 0 ) {
            mgr.UpdateDocumentStatus(appointmentRequestQueueId, null);

        } else {
            mgr.UpdateDocumentStatus(appointmentRequestQueueId, status);
        }
    }

Question: What character or string is it saying is invalid here: the white space ”? Empty string?

I’ve found a similar question here: message shows undefined when ajax post in ASP.net //similar issue

But the solution here sounds as if this is happening in an MVC solution, possibly an API, but my project is neither.

Change an image during a month

I want a certain logo to show up during a month. I tried the following but it never worked. One is a gif and the other is a PNG.

Javascript:

var logo = document.getElementById("logo");

const refreshStatus = () => {
  // Get dates/time/hours
  let today = new Date(); //today date

  //Show available if this matches
  if (today.getMonth == 5) {
    logo.src='../../img/logo2.gif';
  } else {
    logo.src='../../img/logo.png';
  }
}

// run when starting
refreshStatus();

// updates every 8 seconds
setInterval(refreshStatus, 8000);

HTML:

<a href="../index.html" class="index-link"><img src="../img/logo.png" alt="Logo" class="logo" id="logo"></a>
<script src="js/pride.js"></script>

Selector and react hook

I have a test (done with reactjs) where I have to make a weather app, where must have a selector that allows you to pick a range of days for the forecast, I’ve made the app, it fetches the forecast for whatever amount of days I pass on the endpoint of the api but I have to idea how to tie both so that if I pick 2 days it will show 2 and so on, can some one hint me on how I may do this? Ty in advance sorry for my English

Encrypting Url and deleting data in MongoDb

Is there anyway to like encrypt the url, I have a copy of a file that is stored somewhere else (var linkoffile = url where that file is saved) , and when a user requested for that file, I will make a copy of that url in another collection in mongodb and it has an expiration time , a time duration where that file will be available for that user, after that time , the copy of that url will be removed for that user (here I used TTL Indexes of mongodb). But Im thinking that since the url of that file is exposed in the frontend or in the client side, even if you removed the url copy in the mongodb , any user that already copied the url before it expired can still access the document, so im thinking of like encrypting the url so that user will not now where that file is coming.

Is there any way to achieve this? or is there any other solution that can also achieve what im planning to do?

step process with javascript doesn’t change colors

I am trying to make a step process with javascript
And I want it when it reaches the step 3 , the color changes to another color
I tried a lot but I didn’t succeed

Picture how step process works

Picture how step process works

Picture how I want it to work

enter image description here

$(document).ready(function() {
  var i = 1;

  var id = setInterval(steps, 700);

  function steps() {
    if (i == 4) {
      clearInterval(id);
    } else {
      $(".step" + i).css('background-color', 'rgb(134 209 109)');
      i++;
    }
  }
  $(".btn-next").on("click", function() {
    $('.page-1').fadeOut(1000, function() {
      $('.page-2').fadeIn(1000);

    });

    var interval = setInterval(slide, 1200)
    d = 1;

    function slide() {
      if (d == 6) {
        clearInterval(interval);
        $('.btn-next-two').fadeIn();
        $('.search').fadeOut();
      } else {
        $(".ship-" + d).addClass('slide-in-left');
        $(".ship-" + d).css('display', 'block');
        d++;
      }
    }
  });
  $(".btn-next-two").on("click", function() {
    $('.page-2').fadeOut(1000, function() {
      $('.page-3').fadeIn(1000);

    });
  });
  $('.btn-delivery').on('click', function() {
    $('.page-3').fadeOut(1000, function() {
      $('.page-4').fadeIn(1000);
    });
  });
  $('.btn-time').on('click', function() {
    $('.page-4').fadeOut(1000, function() {
      $('.page-5').fadeIn(1000);
    });
  });
});
step {
  min-height: 20px;
  margin-right: 2px;
  border-radius: 14px;
  background-color: #a9b7b9;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-2 col-sm-1  offset-2 offset-sm-4 step1 step">
</div>
<div class="col-2 col-sm-1  step2 step">
</div>
<div class="col-2 col-sm-1  step3 step">
</div>
<div class="col-2 col-sm-1  step4 step">

angular mat select openedchanged , check if items are selected

How do know using openedChange that when you close or open the mat select panel it will show if there is an item on the select box that was check or uncheck.

Right now I can only detect if it is open or close , I wanna to detect that when I close it if there is any activity or select items on the select menu. Thanks.

I want to check if there are any changes.

#html code

 <mat-form-field class="job-filter" appearance="fill">
          <mat-select #select [formControl]="marketDropdownMultiCtrl" placeholder="Market" [multiple]="true" #marketDropdownMultiSelect (openedChange)="changeFilterEvent($event,select)">
              <mat-option>
                <ngx-mat-select-search 
                [showToggleAllCheckbox]="true" 
                accesskey="" 
                placeholderLabel="Search Market filter" 
                noEntriesFoundLabel="'No results found'" 
                (toggleAll)="toggleSelectAllMarket($event)" 
                [toogleAllCheckboxTooltipPosition]="'above'"
                [toggleAllCheckboxChecked]="marketDropdownMultiCtrl?.value?.length === marketDropdownSize" 
                [toggleAllCheckboxIndeterminate]="marketDropdownMultiCtrl?.value?.length > 0 && marketDropdownMultiCtrl?.value?.length < marketDropdownSize"
                [toggleAllCheckboxTooltipMessage]="'Select / Deselect all Market filters'" 
                [formControl]="marketDropdownMultiFilterCtrl">
              </ngx-mat-select-search>
              </mat-option>
              <mat-option *ngFor="let market of filteredMarketListMulti | async" [value]="market">
                  {{market.description}}
              </mat-option>
          </mat-select>
        </mat-form-field>

enter image description here

#tscode

changeFilterEvent(opened:boolean,element:any){ }

How do I make this default text disappear on a timer?

So I’m just changing the background color with user input using this switch case statement. I’m trying to return my error timeout() for a specific amount of time so it no longer displays on the screen.

I’ve tried several different methods, but I’d like to see if someone here could help me!

Here is my code

const body = document.body;

function clicked(){

    function timeout(){
        setTimeout(para.innerHTML = "Please choose one of the following: red, blue, yellow, green, white, pink, purple.", 1000);
    }

    let text = document.querySelector('#input').value.toLowerCase();
    let para = document.querySelector('#para');
    switch(text){
        case "red":
            body.style.backgroundColor = "red";
            break;
        case "blue":
            body.style.backgroundColor = "blue";
            break;
        case "yellow":
            body.style.backgroundColor = "yellow";
            break;
        case "green":
            body.style.backgroundColor = "green";
            break;
        case "white":
            body.style.backgroundColor = "white";
            break;
        case "pink":
            body.style.backgroundColor = "pink";
            break;
        case "purple":
            body.style.backgroundColor = "purple";
            break;
        default :
            timeout();
            break;
    }
}

and my html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Learning Javascript</title>
    <link rel="stylesheet" type="text/css" href="css/bootstrap-grid.css">
    <link rel="stylesheet" href="main.css">
</head>
<body>
    <div class="row-cols-3">
        <input onkeydown = "if (event.keyCode == 13)
        clicked();" type="text" id="input">
        <button onclick="clicked()">Change Color</button>
    </div>
    <p id="para"></p>
    <script src="main.js"></script>
</body>
</html>

How to filter collection with multiple conditions (strings and array of values) using lodash javascript

I’m trying to filter a collection with multiple conditions using lodash, it works fine with strings, but I want to filter by an array of id’s for the part of the locations and string for status. I have tried to change the id to array of id’s "location":{"id" :["1","4"]}, but it doesn’t work

const collection = [ 
  {account: {id: "1", name: "a"}, location:{id: "1", name: "x"}, status: "ok"},
  {account: {id: "2", name: "b"}, location:{id: "2", name: "x"}, status: "ok"},
  {account: {id: "3", name: "c"}, location:{id: "4", name: "y"}, status: "failed"},
  {account: {id: "4", name: "d"}, location:{id: "4", name: "y"}, status: "ok"},]

 let filterByConditions = {
  "location":{"id" :"1"},
  "account":{ "id": "1"},
  "status": "ok",
};

let results = _.filter(collection, filterByConditions);

Regex (JS) read data between two symbols

My changelog.md data looks like below.

## 11.2.3
* xxx
* xxxx

## 11.2.2
* ttt
* ttt

I need a regex that can return only the first versions list ie.

* xxx
* xxxx

I tried multiple solutions but, didn’t reach the final result.

I tried matching, and replacing it, didn’t work.

const changelog = `
## Hello World
* This is a bold text
* This is a bold text

## Hello World
* This is a bold text

## Hello World
* This is a bold text
`;

const final = changelog.match( /([^(##)])(.*)[^(##)]/g );
console.log(final);