Trying to prevent duplicate entries not working

I am fetching data from an API (array of objects) and I want to then check in the database if any of the records exist, using the url as the basis for duplicates. When it comes to inserting the new records, I get this monogoDB error:

MongoBulkWriteError: E11000 duplicate key error collection: news.news
index: sourceUrl_1 dup key: { sourceUrl:
“https://example.com/article-abc123” }

  try {
    const covidDbArticles = await News.find({ category: "Coronavirus" });
    const filterCovidDuplicates = covidData.data.news.filter(
      (covidApiSource) =>
        !covidDbArticles.some(
          (covidDatabaseSource) =>
            covidApiSource.link === covidDatabaseSource.sourceUrl
        )
    );
    if (filterCovidDuplicates.length) {
      try {
        await News.insertMany(covidNewsObj);
      } catch (err) {
        console.log("Error inserting covid data: " + err);
      }
    }
  } catch (err) {
    console.log("saving data failed: " + err);
  }

Why did the browser never update itself from zombie service worker?

In this brillant talk Alexander Pope: ServiceWorkers Outbreak: index-sw-9a4c43b4b47781ca619eaaf5ac1db.js | JSConf EU 2017:
The presenter has a situation where a broken service worker gets installed, and its stuck in the broken state. The presenter tries a kill switch and an empty service worker to remedey it, but there are still some browsers permantely infected. I am trying to understand why it happened, and not do a similar thing.

Here is his code (from 22m:57s):

function onInstall(event) {
    event.waitUntil(
        install(config.version, config.assets)
            .catch((err) => {
                reportError(err);
                // Ok, you know what you're doing, Installing now....
            })
    );
}

It gets stuck because within the call to install he uses cache.addAll(), but long ago Chrome didnt support cache, so this error never bubbled up, and the browser thought it was installed correctly.

Now the browser is reponsible for fetching the sw.js file and checking if its byte different to the currently installed worker. The code to register the new sw.js file is outside of the service worker file. This means even if a service worker is broken, the browser should be able to fetch the new one, determine its different, register it, and activate it (eventually). The newer sw.js file could then check for the presence of cache API. So why are there some clients still in a broken state?

ReferenceError: Cannot access ‘AuthProvider’ before initialization

Can someone explain why I am getting this error in next js? The auth.js file is also not being run but it used to run before when I import.

ReferenceError: Cannot access ‘AuthProvider’ before initialization
This error happened while generating the page. Any console logs will be displayed in the terminal window.

This is my _app.js file

import React from "react";
import { AuthProvider } from "contexts/auth";
import { ProtectRoute } from "contexts/auth";
import Nav from "components/Nav";

function MyApp({ Component, pageProps }) {
  return (
    <AuthProvider>
      <Nav />
      <ProtectRoute>
        <Component {...pageProps} />
      </ProtectRoute>
    </AuthProvider>
  );
}

export default MyApp;

And this is my contexts/auth.js file

import React, { createContext, useState, useContext, useEffect } from "react";
import Cookies from "js-cookie";
import { fetchWrapper } from "helpers";

const AuthContext = createContext({});

export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const loadUserFromCookies = async () => {
      // authenticate code
    };
    loadUserFromCookies();
  }, []);

  const login = async (email, password) => {
   // login code
  };

  const logout = () => {
    // logout code
  };

  return (
    <AuthContext.Provider
      value={{ isAuthenticated: !!user, user, login, loading, logout }}
    >
      {children}
    </AuthContext.Provider>
  );
};

export const useAuth = () => useContext(AuthContext);

export const ProtectRoute = ({ children }) => {
  const { isAuthenticated, isLoading } = useAuth();
  if (
    isLoading ||
    (!isAuthenticated && window.location.pathname !== "/login")
  ) {
    return () => {
      "Loading...";
    };
  }
  return children;
};

How to bind correct s to dynamic columns created based on dynamic arrays?

I get an array of objects from API that contain, among other data, a targets_and_rewards array that can vary with a minimum of one occurence.
I created a material table showing these values, using static columns and dynamic columns based on the maximum length of targets_and_rewards array for each offer.
I need to bind tds correctly based on these dynamic columns.

Here is how it looks like:

app.component.ts

import { Component, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';

const dataReceivedFromAPI = [
  {
    id: 4000,
    name: 'My awesome offer',
    targets_and_rewards: [
      {
        reward: {
          max: 3.6,
          mean: 0.48,
          min: 0.4,
        },
        target: {
          max: 30,
          mean: 3.71,
          min: 3,
        },
      },
      {
        reward: {
          max: 5.7,
          mean: 1.17,
          min: 1,
        },
        target: {
          max: 5.7,
          mean: 5.88,
          min: 5,
        },
      },
      {
        reward: {
          max: 7.5,
          mean: 3.38,
          min: 3.3,
        },
        target: {
          max: 30,
          mean: 13.35,
          min: 13,
        },
      },
    ],
  },
  {
    id: 5000,
    name: 'My awesome second offer',
    targets_and_rewards: [
      {
        reward: {
          max: 3.5,
          mean: 0.55,
          min: 0.3,
        },
        target: {
          max: 35,
          mean: 5.67,
          min: 4,
        },
      },
      {
        reward: {
          max: 6.8,
          mean: 2.12,
          min: 2,
        },
        target: {
          max: 7.9,
          mean: 4.12,
          min: 3,
        },
      },
      {
        reward: {
          max: 8.2,
          mean: 5.24,
          min: 4.87,
        },
        target: {
          max: 32,
          mean: 17.13,
          min: 15.65,
        },
      },
      {
        reward: {
          max: 9,
          mean: 6.66,
          min: 5.87,
        },
        target: {
          max: 50,
          mean: 34.45,
          min: 21.12,
        },
      },
      {
        reward: {
          max: 8.2,
          mean: 5.24,
          min: 4.87,
        },
        target: {
          max: 32,
          mean: 17.13,
          min: 15.65,
        },
      },
    ],
  },
  {
    id: 6000,
    name: 'My awesome third offer',
    targets_and_rewards: [
      {
        reward: {
          max: 6.1,
          mean: 5.54,
          min: 4.13,
        },
        target: {
          max: 100,
          mean: 45.12,
          min: 31.1,
        },
      },
    ],
  },
];

interface Targeting {
  id: number;
  name: string;
  targets_and_rewards: Array<{
    reward: {
      max: number;
      mean: number;
      min: number;
    };
    target: {
      max: number;
      mean: number;
      min: number;
    };
  }>;
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  public dataSource: MatTableDataSource<Targeting>;
  public displayedColumns: Array<string> = ['id', 'name'];
  public targetAndRewardColumns: Array<string> = [];

  ngOnInit(): void {
    // API call binding data variable... (here `dataReceivedFromAPI`)
    // Populate columns with static part (basic `displayedColumns`) and dynamic part (`targetAndRewardColumns`)
    this.populateColumns(dataReceivedFromAPI);
    this.dataSource = new MatTableDataSource(dataReceivedFromAPI);
  }

  populateColumns(data: Array<Targeting>): void {
    let maxTargetsAndRewards: number = 0;
    data.map((offer: Targeting) => {
      const targetsAndRewardsLength: number = Object.keys(
        offer.targets_and_rewards
      ).length;
      if (targetsAndRewardsLength > maxTargetsAndRewards) {
        maxTargetsAndRewards = targetsAndRewardsLength;
      }
    });
    for (let i: number = 0; i < maxTargetsAndRewards; i++) {
      this.targetAndRewardColumns.push(
        `Min Target (${i})`,
        `Min Reward (${i})`,
        `Mean Target (${i})`,
        `Mean Reward (${i})`,
        `Max Target (${i})`,
        `Max Reward (${i})`
      );
    }
    this.displayedColumns = [
      ...this.displayedColumns,
      ...this.targetAndRewardColumns,
    ];
  }
}

app.component.html

<table mat-table [dataSource]="dataSource">
  <ng-container matColumnDef="id">
    <th mat-header-cell *matHeaderCellDef>Id</th>
    <td mat-cell *matCellDef="let offer">
      {{ offer.id }}
    </td>
  </ng-container>

  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef>Name</th>
    <td mat-cell *matCellDef="let offer">
      {{ offer.name }}
    </td>
  </ng-container>

  <ng-container
    *ngFor="let column of targetAndRewardColumns"
    [matColumnDef]="column"
  >
    <th mat-header-cell *matHeaderCellDef>
      {{ column }}
    </th>
    <!-- How to dynamically bind tds here ? -->
    <!-- Min target (0) should be equal to first offer.targets_and_rewards[0].target.min for example -->
    <td mat-cell *matCellDef="let offer">
      <!-- Just to populate with something by default -->
      {{ offer.targets_and_rewards[0].target.min }}
    </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let offers; columns: displayedColumns"></tr>
</table>

And here is a stackblitz snippet to make everything more clear.

Using IFrame to check if a NVR is online or not

I have a group of around 10 NVRs that I would like to be able to display on one page whether they are online or not.

Currently I do this with a HTML page containing 10 iframes each trying to load the default page of the NVR via their IPs, this either displays the default menu or just has a white error page.

Is it possible to interrogate what is in the iframe and display a green page if the connection is made and red page if not? or even to do away with the iframe and check if the IP of the NVR is live or not and display this as a visual list.

Javascript Reduce, missing values

I’ve been struggling with this all day and have finally given up as I see no reason why its not working.

I have the following code:

let groupedEvents: any[] = events.reduce((processedEvents: any[], event: Event) => {
    const day: string = dayjs(event.startDateTime).format('YYYY-MM-DD');
    const matchingDateIndex: number = processedEvents.findIndex(group => group.day === day);
    console.log(matchingDateIndex)

    if (matchingDateIndex > -1) {
        processedEvents[matchingDateIndex].events.push(event);
    } else {
        processedEvents.push({ day, events: new Array(event) })
    }
    return processedEvents;
}, []);
console.log(groupedEvents)

This takes an events array with calendar entries, then should group them by day. However what happens is the first day always ends empty, with subsequent days being fine as below:

enter image description here

There should be a total of 5 events but the 3 from the 21st are not showing, anyone know why this is happening?

Lerna version remove commit links

I’m using lerna version for the private gitlab repository, my CHANGELOG.MD will be visible on npm after publish, but commit links won’t be accessible for users, so I want to remove commit links altogether.
One way to do it is to add --no-push option, undo commit, then manually remove the links. Another option is the same as the first, but with the bash script, which will remove links automatically.

I was wondering if the same operation could be done using only lerna version configuration? Couldn’t find anything helpful in lerna docs.

Parent component does not rerender after updating its state through child component

I checked some of the threads about this and tried to fix it, but no succes yet.

I have a parent and a child component. In the parent component, I declare a state and pass the function to update this state on to my child component.

  function ProfileGallery() {
  const [selectedPet, setPet] = useState(null);
  const [filterText, setFilterText] = useState('');
  const [pets, setPets] = useState([]);
  const [componentState, setState] = useState('test');

  const updateState = (state) => {
        setState(...state);
      };

  return (
       <PetInformation
                selectedPet={selectedPet}
                componentState={componentState}
                triggerParentUpdate={updateState}
              />
);
}

In my child component, I do the following:

function PetInformation({ componentState, triggerParentUpdate, ...props }) {
  const [status, setStatus] = useState('Delete succesful');
  const { selectedPet } = { ...props } || {};
  const updatedComponentState = 'newState';

  useEffect(() => {
    if (status === 'Delete pending') {
      deletePet(selectedPet).then(() => setStatus('Delete succesful'));
    }
  }, [status]);

  const handleDelete = () => {
    setStatus('Delete pending');
  };

return (
    <button
            className="btn btn-primary pull-right"
            onClick={() => {
              handleDelete();
              triggerParentUpdate(updatedComponentState);
            }}
            type="button"
          >
            Delete Pet
    </button>

There’s of course more code in between, but this shows the gist of what I’m trying to achieve. I want to delete an item I selected in my gallery and have that delete reflected once I click the delete button -> my ProfileGallery needs to re-render. I’m trying to do this by passing that function to update my state on to the child component. I know JS won’t consider state changed if the reference remains the same, so that’s why I am passing a new const updatedComponentState on, since that should have a different reference from my original componentState.

Everything works, the item gets removed but I still need to manually refresh my app before it gets reflected in the list in my gallery. Why won’t ReactJS re-render my ProfileGallery component here? Isn’t my state getting updated?

Toggle elements with same classnames independently with pure js (tags on blog posts)

I have this jquery that I want to find a pure JS solution for – when pressing a button, it toggles the tags on blog each posts independently:

 $('.tags').hide();
    $('.toggle-tags').click(function(event) {
        $(this).closest('.info').find('.tags').slideToggle(400)
    });

Ideally I want to achieve what I’ve got from the following js I use for a nav-menu. I’m aware that I’ll need to use querySelectorAll() instead, but also loop it through the elements, right?

var tagswrap = document.getElementById("tags");
var height = tagswrap.clientHeight;
tagswrap.style.height = 0;

function toggleClass(tagswrap, height) {
    tagswrap.style.height = height + "px";
    var tagswrap = document.getElementById("tags");
    var className = "active";
    if (!tagswrap || !className) {
        return;
    }
    var classString = tagswrap.className,
        nameIndex = classString.indexOf(className);
    if (nameIndex == -1) {
        classString += " " + className;
    } else {
        classString = classString.substr(0, nameIndex) + classString.substr(nameIndex + className.length);
        tagswrap.style.height = 0;
    }
    tagswrap.className = classString;
}
var buttonTags = document.getElementById("toggle-tags");
buttonTags.onclick = function () {
    toggleClass(tagswrap, height);
};

the structure of each blog post:

<article>
.. blog text here ..
  
<div class="info">
  <div class="info-content">
    <div class="right">
      <div class="toggle-tags">show tags</div>
    </div>
    
  </div>
  
  <div class="tags">
    <a href="#">text</a>
    <a href="#">quote</a>
    <a href="#">testing</a>
  </div>
  
</div>
  
</article>

I’m still too new to js know how to implement this. Any pointers or suggestions would be great.

displaying data in modal using ajax in codeigniter not working

i have an html table in codeigniter which has different rows, when user clicks on any id of the table it should open a modal and display the details, id did the following:

in controller:

    public function select(){
                        
  $id = $this->segments->uri(3);
  $data['details'] = $this->user->selectdetails($id);

  
                        }

in model:

public function selectdetails($id) { 
$this->db->select('*'); 
$this->db->where('id', $id); 
$this->db->from('consignments'); 
$query = $this->db->get(); 
$result = $query->result(); 
return $result; 
}

and finally in view:

$(".detailsbtn").click(function(e){
  var modal = document.getElementById("details");
        e.preventDefault();
        var id = $(this).attr('id');
        $.ajax({
          type:'POST',
          url:'<?php echo base_url()?>homecontroller/select/'+id,

          success:function(data){
             $('#details').find('.modal-content').html(data);
             $('#details').modal('show');
          }
       });

    });
<td>

  <input id="<?= $val->id?>" class="detailsbtn btn-sm btn-info" type="button" value="<?= $val->awb?>">
  
</td>


   
 <div class="modal-body">
   <div class="container-fluid">
     <div class="row">
       <div class="col-md-12">




<?php foreach($details as $de){?>
<?php echo $de->consignee;?>
<?php }?>

       </div>
     </div>
   </div>
 

however this is giving me error,page not found error, can anyone please tell me how to fix this, thanks in advance

Laravel – Uncaught TypeError: Cannot read properties of null (reading ‘value’)

I’m trying to use lightpick datepicker on my application. Unfortunately this works when I don’t follow standards, and doesn’t work when I do.
Blade :

@section('page_script')
    <script src="{{ url('js/themeFiles/moment/moment.min.js') }}"></script>
    <script src="{{ url('js/themeFiles/lightpick/lightpick.js') }}"></script>
    <script src="{{ url('js/custom/datePicker.js') }}"></script>
    <script src="{{ url('js/custom/planningStats.js') }}"></script>
@endsection

@section('content')
    @include('planning.partials.planningStatsForm')
@endsection

datePicker.js:

var picker = new Lightpick({
    field: document.getElementById('ddebut_picker'),
    secondField: document.getElementById('dfin_picker'),
    repick: true,
    lang: 'fr',
    singleDate: false,
    selectForward: true
});

Error (if I use the above code) :
enter image description here

If I use the script tags inside @section('content') and do no use separate @section('page_script') section then everything works perfectly. But for the current code, it doesn’t work. I haven’t changed anything in the js, controller, blade or model.

Cannot set properties of undefined (setting ‘listeners’) mock socket library when mocking web socket in Cypress

I have a mock server in my cypress test file

const getServer = () => {
    return new Cypress.Promise(resolve => {
        const mockServer = Server('wss://notifier.shoutout.social/')

        let mockSocket
        mockServer.on('connection', (socketHandle) => {
           resolve(socketHandle)
        })
    })
}
const socketPromise =  getServer()

Every time I want to send a message to my client from my web socket I am calling it with a cy.wrap using

cy.wrap(socketPromise).then((mockSocket) => {
    mockSocket.send({fixture: 'WebSocketMocks/WebSocketInitialised.json'})
})

But I get this error coming from the mock socket library in my stack trace

 var EventTarget = function EventTarget() {
> 742 |   this.listeners = {};
      | ^
  743 | };

Cheers 🙂