Iterative implementation of Binary Search

please i have a question about the Iterative implementation of Binary Search

This is the function i create in c:

int BinarySearch(int arr[], int l, int r, int x)
{
  while(l <=  r) {
      int mid = l + (r - l) / 2;
      if(arr[mid] == x)
          return mid;
      if(arr[mid] > x)
          r = mid - 1;
      else
          l = mid + 1;
  }
  return -1;
}

This is my main function :

int main()
{
    int arr[] = {1,2,3,5,16,15,20};
    int n = sizeof(arr) / sizeof(arr[0]);
    int x = 16;
    int result = BinarySearch(arr, 0, n-1, x);
    (result == -1)
        // WE CALL THIS ternary operator.
        ? printf("Element is not present in array")
        : printf("Element is present at index %d", result);
    return 0;
}

The question is: when i search 16 the function return -1.
If you see the number 16 is on the list any help please ??

JS is Concatenating instead of Adding Variables [duplicate]

I’m trying to figure out why this block of code isn’t behaving the way I’d expect. This is for a simple online financing calculator with trade in. Everything worked until I added the ‘accessories’ section to the code. Instead of returning product + accessories (e.g. $100 + $50 = $150) it’s concatenating the results (e.g. $100 + $50 = $10050). The trade in and month calculation seem to work correctly if I don’t enter any value into the accessories field.

function Calculate() {
        var months = document.querySelector("#months").value;

        var product = document.querySelector("#product").value;

        var accessories = document.querySelector("#accessories").value;

        var trade = document.querySelector("#trade").value;

        var basket = product + accessories;

        var total =  ((basket - trade) / months).toFixed(2);

        document.querySelector("#total")
                .innerHTML = "Estimated Monthly Payment: $" + total;
}

How can I loop through a Map which contains a hashmap in angularjs?

I have a Map<String(religion), Map<String(name), Person>> where Person contains Name, Age and Date – yes name is stored twice.

I return this map and store into a [] in my controller.

I’m trying to do a repeater for every entry in people and then another repeater within that for every entry in the map inside but cant access the values. I need to create a table that creates a showing the religion, person.name, person.date for every single entry

Lerna bootstrap doesn’t install symlink

I have a project and updated from node v14 (npm 6) to node LTS (npm 8.3)

Lerna bootstrap doesn’t install my dependencies as symlink.

Structure:

.X
├── lerna.json
├── package.json (My node_modules contains A and B packages)
├── packages
│   ├── A
│   │   └── package.json (install two as symlink (taking from root node_modules)- but 
│   │                     it's not working)
│   └── B
│       └── package.json
.Y
├── lerna.json
├── package.json (My node_modules contains A and B packages)
├── packages
│   ├── C
│   │   └── package.json (it should installs A and B as symlink)
│   │
│   └── D
│       └── package.json (it should installs A as symlink)

When I use node v14, lerna bootstrap install correctly but when I use v16 it’s not..

Cypress: Use leaflet in cypress test?

I am trying to utilize the setView method in leaflet in a cypress test but having a web-pack error. I’m not sure how to import this correctly to be able to use it. In the main app everything is working correctly but I don’t understand how to utilize it in cypress. I am trying something simple just to start off and see if it works. Here it is.

import L from 'react-leaflet';

const map = L.map('mapid')
            map.setView([4881264.780784771,-9929607.312884448], 2)

but it will not even load the cypress test and fails at

Error: Webpack Compilation Error
./cypress/integration/explorer/test.spec.js
Module not found: Error: Can't resolve 'react-leaflet' in '/Users/Documents/github/dashboards/cypress/tests'

Has anyone done this before?

Google Apps Script to obtain the index if any of the words on a string match another string?

I have a long list of roles obtained from a sheet range stored as strings in an array, to give an example the array looks something like this:

arr1 = ["football manager","hockey coach", "fb player","fb coach","footballer"];

and I have another array in which I have a list of words and a classification code
it represents something like the following table.

Table # 2
| Profession | Class |
| ——————–| ————– |
| football | FB01 |
| fb | FB01 |
| hockey | HK01 |
| footballer | FB01 |

I am trying to match the roles of the first array to the professions on the second one and assign a class to each of the roles.

I have been trying to do this by obtaining the index of the matched row:

for(let i in arr1){
arr2.findIndex(s => s.indexOf(arr1[i]) >= 0);
}

But this only works for “footballer” as it is an exact match, I need for all of the partial matches to be classified as well.

Allow only alphabet in input Html – Angular

I want to know how to only allow alphabet in an input, if a number or special character is entered in the input, ignore it, i work with Angular.

I work with reactive form but if I use pattern this just validates the field when submit is done, what I need is that for example if I press the number “1” in keyboard it simply does not show, when the key is pressed ignore everything that is not alphabet letter

React firebase database rendering data

I am using react-firebase-hooks useList which wraps around onX(..) listening to data in real time.

This is my insert method:

export const insertItem = () => {
  let key = createUniqueId();
  return set(ref(db, `chat/${key}`), {
    chat_id: key,
  })
    .then((data) => {
       push(ref(db, `chat/${data.key}/messages`),{
          sender: "foo",
          text: "hello"
       })
    })
    .catch((error) => {
      return error;
    });
};

This is my component:

export const Chat = () => {
  const [snapshots, loading, error] = useList(ref(db, 'chats'));
  
  let chats = snapshots.map(data => {
      let chat = data.val()
      let checkNewMessage = Object.keys(chat["messages"]);
      let newest = checkNewMessage[checkNewMessage.length - 1];
      let item = chat["messages"][newest]
      return (
          <div>{item.text}</div>
      )
  })

  return (
      <div>{chats}</div>
  )
};

Databse:

enter image description here

When it comes to rendering the chat along with the message I run into two issues.

Cannot convert undefined or null to object

Can’t perform a React state update on an unmounted component. This is
a no-op, but it indicates a memory leak in your application. To fix,
cancel all subscriptions and asynchronous tasks in a useEffect cleanup
function.

From my understanding, I think the reason why it is still null/undefined is due to the message item has not yet been created due to async/promise actions. How can I correctly wait for all db changes to be inserted?

Once I refresh my page it renders it as expected. without any errors.

java script to react js [closed]

can someone pls write a react js way for this javascript code pls

const menuBtn = document.querySelector('.menu-btn');
let menuOpen = false;
menuBtn.addEventListener('click', () => {
  if(!menuOpen) {
    menuBtn.classList.add('open');
    menuOpen = true;
  } else {
    menuBtn.classList.remove('open');
    menuOpen = false;
  }
});

Why does some of my columns in my HTML table display cells as undefined while other columns display correctly?

Table output picture
I couldn’t figure out why some of the cells are undefined even though they have similar data types to some of the cells that are displaying values correctly? What can I try to make them display properly? The code should take the list of dictionaries and populate the tables with them. I am fairly new to javascript and web development. I usually work in backend with SQL and python. thank you.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<style>
    th{ 
        cursor: pointer;
        color:#fff;
            }
</style>


<table class="table table-striped">
    <tr  class="bg-info">
        <th  data-colname="date" data-order="desc">date &#9650</th>
        <th  data-colname="exposed" data-order="desc">exposed (mn) &#9650</th>
        <th  data-colname="displaced (k)" data-order="desc">displaced (k) &#9650</th>
        <th  data-colname="killed" data-order="desc">killed &#9650</th>
        <th  data-colname="duration(days)" data-order="desc">duration(days) &#9650</th>
        <th  data-colname="cause" data-order="desc">cause &#9650</th>
        <th  data-colname="Country Name" data-order="desc">Country Name &#9650</th>
        <th  data-colname="ISO code" data-order="desc">ISO code &#9650</th>
    </tr>
    <tbody id="myTable">
        
    </tbody>
</table>


<script>
var myArray =[{'date': '7/21/2007', 'exposed': 27712991, 'displaced (k)': 5000000, 'killed': 1071, 'duration(days)': 86, 'cause': 'Heavy rain', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '9/9/2010', 'exposed': 23137894, 'displaced (k)': 140000, 'killed': 0, 'duration(days)': 21, 'cause': 'Heavy rain', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '8/30/2008', 'exposed': 21631628, 'displaced (k)': 600000, 'killed': 0, 'duration(days)': 9, 'cause': 'Heavy rain', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '8/18/2008', 'exposed': 21529060, 'displaced (k)': 10000000, 'killed': 400, 'duration(days)': 37, 'cause': 'Heavy rain', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '7/12/2007', 'exposed': 21488636, 'displaced (k)': 11100000, 'killed': 96, 'duration(days)': 90, 'cause': 'Heavy rain', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '6/20/2004', 'exposed': 19855086, 'displaced (k)': 40000000, 'killed': 3000, 'duration(days)': 109, 'cause': 'Heavy rain', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '10/1/2010', 'exposed': 19362985, 'displaced (k)': 500000, 'killed': 15, 'duration(days)': 11, 'cause': 'Tropical StormSurge', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '7/25/2016', 'exposed': 18456496, 'displaced (k)': 25000, 'killed': 42, 'duration(days)': 32, 'cause': 'Heavy rain', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '9/1/2018', 'exposed': 17213562, 'displaced (k)': 1000, 'killed': 20, 'duration(days)': 6, 'cause': 'Heavy rain', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '6/11/2003', 'exposed': 16822143, 'displaced (k)': 9500000, 'killed': 600, 'duration(days)': 121, 'cause': 'Heavy rain', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '7/21/2002', 'exposed': 16541422, 'displaced (k)': 250000, 'killed': 380, 'duration(days)': 25, 'cause': 'Heavy rain', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '7/3/2007', 'exposed': 16486188, 'displaced (k)': 3000000, 'killed': 958, 'duration(days)': 81, 'cause': 'Heavy rain', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '9/16/2012', 'exposed': 15526445, 'displaced (k)': 200, 'killed': 45, 'duration(days)': 2, 'cause': 'Heavy rain', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '8/15/2011', 'exposed': 14830495, 'displaced (k)': 70000, 'killed': 158, 'duration(days)': 48, 'cause': 'Heavy rain', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '8/10/2017', 'exposed': 13271467, 'displaced (k)': 300000, 'killed': 117, 'duration(days)': 16, 'cause': 'Heavy rain', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '9/18/2010', 'exposed': 12414310, 'displaced (k)': 15000, 'killed': 88, 'duration(days)': 12, 'cause': 'Heavy rain', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '9/22/2008', 'exposed': 12372235, 'displaced (k)': 0, 'killed': 2400, 'duration(days)': 7, 'cause': 'Dam', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '10/7/2004', 'exposed': 11965543, 'displaced (k)': 100000, 'killed': 210, 'duration(days)': 11, 'cause': 'Heavy rain', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '8/20/2014', 'exposed': 11058729, 'displaced (k)': 500000, 'killed': 17, 'duration(days)': 19, 'cause': 'Heavy rain', 'Country Name': 'Nepal', 'ISO code': 'NPL'}, {'date': '9/22/2008', 'exposed': 8627859, 'displaced (k)': 13000, 'killed': 49, 'duration(days)': 7, 'cause': 'Heavy rain', 'Country Name': 'Nepal', 'ISO code': 'NPL'}]

buildTable(myArray)



 $('th').on('click', function(){
     var column = $(this).data('colname')
     var order = $(this).data('order')
     var text = $(this).html()
     text = text.substring(0, text.length - 1);
     
     
     
     if (order == 'desc'){
        myArray = myArray.sort((a, b) => a[column] > b[column] ? 1 : -1)
        $(this).data("order","asc");
        text += '&#9660'
     }else{
        myArray = myArray.sort((a, b) => a[column] < b[column] ? 1 : -1)
        $(this).data("order","desc");
        text += '&#9650'
     }

    $(this).html(text)
    buildTable(myArray)
    })


   
 
    
function buildTable(data){
    var table = document.getElementById('myTable')
    table.innerHTML = ''
    for (var i = 0; i < data.length; i++){
        var colname = `date-${i}`
        var colname = `exposed-${i}`
        var colname = `displaced (k)-${i}`
        var colname = `killed-${i}`
        var colname = `duration(days)-${i}`
        var colname = `cause-${i}`
        var colname = `Country Name-${i}`
        var colname = `ISO code-${i}`

        var row = `<tr>
                        <td>${data[i].date}</td>
                        <td>${data[i].exposed}</td>
                        <td>${data[i].displaced}</td>
                        <td>${data[i].killed}</td>
                        <td>${data[i].duration}</td>
                        <td>${data[i].cause}</td>
                        <td>${data[i].CountryName}</td>
                        <td>${data[i].ISOcode}</td>
                   </tr>`
        table.innerHTML += row
    }
}

</script>
<div id="time-range">
    <p>Time Range: <span class="slider-time"></span> - <span class="slider-time2"></span>
    </p> 
    
    <div class="sliders_step1">
        <div id="slider-range"></div>
    </div>
</div>

]2

TypeError: date.getFullYear is not a function

I’m getting this error in this function

for(var row=0; row<data.length; row++){
   
    var d1 = new Date();
    Utilities.sleep(100);
    var d2 = new Date();
    console.log(d1);
    console.log(d2);  // Notice in console log they look alike but are different by 100 msec.
    console.log( d1.valueOf() === d2.valueOf() );
    function removeTime(date) {
      return new Date(date.getFullYear(),date.getMonth(),date.getDate());
    }
    data[row][17] = removeTime(data[row][17]);
    d1 = removeTime(d1);
    console.log(d1);
    console.log(data[row][17]);
    console.log(  );
    if(d1.valueOf() === data[row][17].valueOf()){
        Logger.log(" I'm in!")
          ss.getRange('B3:AA').setValue(data[row]);
      }
  }

where data includes big number of data and column 17 has the dates

here is a picture of column 17

enter image description here

and this is what i get when i render it

enter image description here

  • there are more dates.

been struggling with this for too long, so would really appreciate the help.

SSR with NextJS not working for some pages

I have just deployed a nextjs application with Vercel. Everything works fine but I’m having some issues with SSR. I have two pages, the index / homepage and one registration page.

When I check the source code for the registration page I can see all the content (SSR working fine) but when I check for the homepage, it looks like it is being rendered by the client (can’t see the content).

Does anyone know what may be causing this behavior?

vue client side axios router

i’m trying to get vue-router to work with blogger feeds json api, i managed to make it work but on reload it goes back to the first page, i tried to add html components and template in routes parameter but it did not work, i tried everything i begun to wonder if it is even possible, here is my code:

  new Vue({
    el: '#app',
    router: new VueRouter({}),
    vuetify: new Vuetify({}),
    data() {
      return {
        feedAPI: '/feeds/posts/default?alt=json&start-index=',
        items_all: [],
        items: [],
        Totalposts: null,
        Totalpages: null,
        Startindex: 1,
        pageNumber: null,
        keyword: '',
        results: [],
        Postsperpage: 5,
      }
    },
    methods: {
      getPosts() {
        axios.get(this.feedAPI + this.Startindex + '&max-results=' + this.Postsperpage).then(async (response) => {
          const items = await response.data;
          this.items_all = items.feed;
          this.items = this.items_all.entry;
          var totalPosts = this.items_all.openSearch$totalResults.$t;
          this.Totalposts = totalPosts;
          var itemsPerPage = this.items_all.openSearch$itemsPerPage.$t;
          this.Postsperpage = itemsPerPage;
          var totalPages = Math.ceil(this.Totalposts / this.Postsperpage);
          this.Totalpages = totalPages;
          this.$router.push({
            query: Object.assign({}, this.$route.query.pageNumber, {
              page: this.pageNumber || 1
            })
          });
          this.$nextTick(() => {
            this.pageNumber
          });
        })
      },
      onPageChange() {
        this.Startindex = Math.ceil((this.pageNumber * this.Postsperpage) - (this.Postsperpage - 1));
        this.getPosts();
      },
      top() {
        window.scrollTo({
          top: 0,
          behavior: 'smooth'
        });
      },
      getResults() {
        if (this.keyword.length > 2) {
          axios.get("/feeds/posts/default?alt=json&q=" + this.keyword).then(res => (this.results = res.data.feed.entry)).catch(err => console.log(err));
        }
      }
    },
    watch: {
      keyword: function(newVal) {
        if (newVal.length > 3) {
          this.getResults();
        }
      }
    },
    computed: {},
    created() {
      this.getResults()
    },
    mounted() {
      this.getPosts();
    }
  });

for the html :

          <v-text-field v-model="keyword" @input="getResults" placeholder="Type to Search"></v-text-field>
          <div v-if="getResults">
            <span v-for="result in results">
              <a v-for="i in result.link" v-if="i.rel == 'alternate'" :href="i.href" :title="result.title.$t" v-html="i.title"></a>
              <br />
            </span>
          </div>
<div v-for="item in items">
<h3><a v-for="i in item.link" v-if="i.rel == 'alternate'" :href="i.href" :title="item.title.$t" v-html="i.title"></a></h3>
</div>
<v-pagination v-model="pageNumber" :length="Totalpages" @input="onPageChange" prev-icon="mdi-menu-left" next-icon="mdi-menu-right" v-on:click.native="top"></v-pagination>

ngModel does not work on modal page in Ionic 6

I am developing an Ionic/Angular app and wanted to use ngModel as alwayls. I am opening a modal from a modal and then want to use it like:

<ion-list>
<ion-item>
  <ion-label position="stacked">Name des Rezepts</ion-label>
  <ion-input [(ngModel)]="model" ></ion-input>
</ion-item>
</ion-list>
<ion-button (click)="save()">Save</ion-button>

i declared the variable in typescript like:

public model="";

But when i click save, my output IS ALWAYS the empty string?!

I imported ReactiveFormsModule in my app.module.ts and on normal pages it works, but in modals it seems like that it does not work?!

Do you guys have any ideas?
Thank you!