Struggling with this js Codewars challenge

I am learning js and struggling with a problem I encountered on Codewars.

I need to calculate how many numbers containing only binary digits exist between 1 and a random number n. For example, if n is 20, there are 3 such numbers: 1, 10, 11;

I have written a solution that works on codepen but Codewars is telling me it is too inefficient to be accepted. I can’t think of anything else I can do to optimize it. Thank you in advance for your help!

function incompleteVirus(n) {
  let countInMemory = 0;
  let isBinary = true;

  // Loop through all numbers below and including n
  for (let i = 1; i <= n; i++) { 

    let strCurrNum = String(i); 

    // Iterate through all digits in the current number
    for (const digit of strCurrNum) {
  
      let numDigit = Number(digit);
 
      // Check if each digit is binary; if not, exit loop
      if (numDigit > 1) {
        isBinary = false;
        break;
      } else {
        isBinary = true;
      }
    }

    // Update memory count
    if (isBinary) {
      countInMemory += 1;
    }
  } 
  return countInMemory
}

Markers not showing on Google Map

My custom markers aren’t coming up on a google map on my WordPress site. I’ve reviewed the code for bugs and I’ve seen the following error in the console: (index):573 Uncaught ReferenceError: myMarkers is not defined at initialize however I have another site with nearly the same exact code that is working fine and so I can’t figure out why myMarkers is not defined. I’ve tried rearranging the code to no avail. Has anyone seen this before? Thanks!

Map is at the bottom of the page here: https://excelsportspt.com/

Here is the code:

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBtKFXFKTieXTdke5jGk_KxZE6FYEADYxg"></script>
    <script type="text/javascript">// <![CDATA[
        jQuery(document).ready(function() {
            <?php if (have_rows('location_map', 'options')): ?>
                //set up markers
                myMarkers = {"markers": [
                    <?php while (have_rows('location_map', 'options')): the_row();
                        $loclatitude = get_sub_field('address_latitude', 'options');
                        $loclongitude = get_sub_field('address_longitude', 'options');
                        $locname = get_sub_field('address_name', 'options');
                        $locadd = get_sub_field('address', 'options');
                        $locmap = get_sub_field('loc_map_url');
                    ?>
                        {
                            'latitude': '<?= $loclatitude; ?>',
                            'longitude': '<?= $loclongitude; ?>',
                            'icon': '<?= esc_url(get_template_directory_uri()); ?>/images/map-pin.png',
                            'balloon_text': '<a target="_blank" href="<?= $locmap; ?>"><?= $locname; ?></a>'
                        },
                    <?php endwhile; ?>
                ]}
            <?php endif; ?>
            map = '';
            function initialize() {
                var myOptions = {
                    center: new google.maps.LatLng(38.7234409, -90.6383197),
                    zoom: 10,
                };
                map = new google.maps.Map(document.getElementById('map1'), myOptions);
                setMarkers(map,myMarkers.markers);
            }
           
            function setMarkers(map,markers) {
                var marker, i;
                for (i = 0; i < markers.length; i++) {
                    var lat = markers[i].latitude;
                    var long = markers[i].longitude;
                    var content =  markers[i].balloon_text;
                    var icon =  markers[i].icon;
                    latlngset = new google.maps.LatLng(lat, long);
                    var marker = new google.maps.Marker({
                        map: map,
                        title: content,
                        position: latlngset,
                        icon: icon
                    });
                    var infowindow = new google.maps.InfoWindow()
                    google.maps.event.addListener(marker, 'click', (function  (marker,content,infowindow) {
                        return function() {
                            infowindow.setContent(content);
                            infowindow.open(map,marker);
                        };
                    })(marker,content,infowindow));
                }
            }
           
            google.maps.event.addDomListener(window, 'load', initialize);
            jQuery(document).on('click', '.map-open', function(event) {
                event.preventDefault();
                map.setCenter(
                    new google.maps.LatLng(jQuery(this).data('lat'),  jQuery(this).data('long'))
                );
            });
        });
    </script>
       
    <div class="location-map" id="map1"></div>

Is there a way to communicate client to client in a static website

I want to make a game with room system, like kahoot or stop. Using a static website (github pages):

My plain is to have two links,

link 1 – sitename/host.github.io

link 2 – sitename.github.io

the host device will connect to the 1 link and the players to the 2. The clients (devices at the 2 link) should be able to send data to each other, for example, if client1 selects a button, client2 will be informed.

Ps. this site is for my math teacher, and not always all the devices will be connected to the same wifi, like if he is in a online class. or the school wifi is bad and they have to use mobile data(4g, 3g, etc.) so I dont think it is a good idea to use LAN.

JavaScript post request to PHP file – No content available because this request was redirected

Failed to load response data: No content available because this request was redirected

I have no idea what this response message means whatsoever. Maybe stack can help?

This is the most specific I can get. The context is that I made a website and made a javascript post request to the .php file then checked network and it responded with the error above

I do not have an example code because it is not necessary the .php file is blank.

My php file:

<?php ?>

Apollo Client GraphQL Unit Testing return Error: TypeError: (0 , _reactHooks.useQuery) is not a function

I was trying to write unit test with react component from Apollo Client Unit Testing, but I got an error when mocking call to the GraphQL endpoint to some hook functions.

My unit test implement:

import React from 'react';
import MockedProvider from '@apollo/react-testing';
import renderer from 'react-test-renderer';
import { GET_CHARACTER_DETAILS } from '../../containerHooks/useCharacterDetails';
import { UseCharacterDetails } from '../../containerHooks/useCharacterDetails';

const mocks = [
  {
    request: {
      query: GET_CHARACTER_DETAILS,
      variables: {
        id: 1,
      },
    },
    result: {
      data: {
        character: {
          id: '1',
          name: 'Rick Sanchez',
          status: 'Alive',
          gender: 'Male',
        },
      },
    },
  },
];

it('renders without error', () => {
  renderer.create(
    <MockedProvider mocks={mocks} addTypename={false}>
      <UseCharacterDetails id='1' />
    </MockedProvider>
  );
});

Here is my Test Component

import gql from 'graphql-tag';
import { useQuery } from '@apollo/react-hooks';

export const GET_CHARACTER_DETAILS = gql`
  query CharacterDetails($id: ID!) {
    character(id: $id) {
      id
      name
      status
      species
      type
      gender
      origin {
        name
      }
      location {
        name
      }
      image
      episode {
        name
      }
      created
    }
  }
`;

export const UseCharacterDetails = ({ id }) => {
  const { loading, error, data } = useQuery(GET_CHARACTER_DETAILS, {
    variables: { id },
  });

  return {
    data,
    error,
    loading,
  };
};

When I run a test, it throws an error

TypeError: (0 , _reactHooks.useQuery) is not a function

Resize CSS Grid Layout

So I am attaching a sandbox to help with this question.
https://codesandbox.io/s/xenodochial-benz-2333fv?file=/src/ResizeColumns.tsx:185-196

I have 2 control Divs.
one for Rows,
one for Columns, and
a Central grid area.

I would like for the black bars in the control divs on the side and bottom to allow for adjusting the CSS grid.

  • Not sure how to allow for the black bars to move.
  • Grid layout on control divs should update with bar movement.
  • Central grid layout needs to update with bar movement.

Any help would be greatly appreciated even if its just more learning/research material.

html2canvas artifacts and inconstancy

Few things with html2canvas are not predictable:
Below is a screenshot of pdf map.

I am using html2canvas to take a screenshot of google map, and then putting it on pdf by using php.

  • sometimes html2canvas will display a grayish faded rectangular shape close to the center (in the image below the shape is to the right of DV-2 marker). Sometimes it is there, sometimes it it is not, inconsistent on all modern browsers.
  • Most of the times one or more markers will not have label displayed. In image below the blue marker to the right does not have marker.

On the map, before taking the screenshot, the gray shape is not there and all markers have label visible.

Any thoughts / suggestions why it is happening? Like I mentioned earlier, it is unpredictable, sometimes that shape does not show up and sometimes all marker labels are visible.

I notice that the markers without label are put on the map first (when I console.log()). It is happening in html2canvas not after. Below is the vue.js method which grabs the screenshot.

genAndSubmit() {
            let xCrop = (this.dimensions.vw - this.dimensions.pw) / 2
            this.form.processing = true;
            html2canvas(document.querySelector("#mapWrapper"),
                {
                    useCORS: true,
                    logging: true,
                    width: this.dimensions.pw,
                    x: xCrop,
                    // allowTaint: true,
                    // foreignObjectRendering: true,
                    // imageTimeout: 30000,
                    // scale: 2,
                })
                .then(canvas => {
                    this.form.image = canvas.toDataURL('image/png');
                    this.submit();
                });
        },

enter image description here

Tapestry 3.58: How to display a tooltip during mouseover on a select Option

I’m actually working on a form that include a list box with Select options.

In the tml file, the select box is build as followed:

<t:select t:id="selectPo" t:value="selectPo" model="poSelectModel" encoder="encoderPo" id="selectPo"/>

in the Java File, i have a setUpRender as the following

@Property
private SelectModel poSelectModel;

@Inject
SelectModelFactory selectModelFactory;

public void setupRender() {
    poSelectModel = selectModelFactory.create(listePo, "label"); 
}

on a mouseover event, Is ist possible to display a tooltip with entire value of label if this label is too long to be displayed in the list box?

Thanks.

How to detect device is mobile when the website is clicked through TikTok and instagram?

I am trying to detect that a device is mobile in order to render the screen differently. We have a 4 column grid layout on desktop and want to display only 1 or 2 columns if the device is mobile.

This is the existing code:

  window.addEventListener(
    "resize",
    function (event) {
      if (event.target.innerWidth > 700) {
        setColumns(4);
      } else if (
        event.target.innerWidth < 700 &&
        event.target.innerWidth > 600
      ) {
        setColumns(3);
      } else if (
        event.target.innerWidth < 600 &&
        event.target.innerWidth > 400
      ) {
        setColumns(2);
      } else {
        setColumns(1);
      }
    },
    true
  );

It seems that this logic is good enough to only show 2 columns when I am on my iPhone via my Chrome browser. However, when I try clicking on the link to our website through a TikTok profile, it seems that we still display 4 columns. Why is this different than opening it via my mobile Chrome browser and how would you recommend fixing this? Thanks!

Axios and Vue Js Get Request With Aws (Public, Read Permissions) [duplicate]

I’m rather stuck with getting images using Axios from AWS. I’m receiving an error that I’m unfamiliar with:

enter image description here

I have hosted the image here: https://do-not-delete-ct-images.s3.us-west-2.amazonaws.com/1024-2.png with the rules set to publicly available for read only.

And this is the code I’m using:

axios.get("https://do-not-delete-ct-images.s3.us-west-2.amazonaws.com/1024-2.png").then(response=>{
    console.log("get data: ", response.data);
}).catch(err =>{
    console.log("get data err: ", err);
})

Thanks in advance and apologies if this is an unwise mistake.

Migrate from GWT to JS frameworks

I have a JS library that is embedded into multiple other websites.
This library creates

  1. Widgets (like the usual chat widget seen on multiple apps). These widgets are primarily iFrames
  2. Also it monitors the application state to show certain messages to users on certain actions. This is primarily logic that listens
    to events on page, tracks all mutations etc.

This library is entirely coded in GWT. Facing problems in retaining and hiring FrontEnd developers to work in Java.
Thinking of moving to React for widgets and Typescript for logic.
Queries:

  1. Is React + Typescript a good choice ? I evaluated Vue, Svelte. Are there any other frameworks/libraries that can be considered ?
    [Note that this library sits on top of multiple websites built in variety of ways. Primary requirement is to avoid any kind of javascript namespace conflicts]

  2. For widgets where most of the logic is UI related, and which are restricted to iFrames, we are thinking of rewriting the code in React. Is there something else we can do ?

  3. For logic(where there is no UI related code) , is there a way I can directly convert all GWT code to human readable and maintainable Typescript at once ?

  4. Any other way to undertake this overall migration ?

I need help forwarding a javascript request to my php file to another website with the same headers and everything

I am trying to get the contents of https://thumbnails.roblox.com/v1/batch using a javascript request but obviously CORS is going to block it because the origin does not allow javascript requests. I need help forwarding the javascript request to https://thumbnails.roblox.com/v1/batch with the same headers and request and everything.

How can I call a function for each array item BUT NOT have them all run at the same time [duplicate]

I was surprised I couldn’t find an example of this anywhere, Im sure there is one but I seem to be having a hard time finding one.

I have an array of links…
const array = ["www.google.com", "www.yahoo.com", "www.disney.com"];

and a function that takes a link and goes to the page and does some stuff and then closes with a resolve. I want to run the function using each array item but I don’t want the functions to run all at once.

I tried array.forEach((item) => { functionThatUsesArrayData(item) }) but this runs each scraper all at once.

In one function id like to be able to use an array of links and pass each link the the function but launch them one at a time…so when the first link is done being scraped, the next array item will be used in a function and be scraped.

function(arrayItem).then(()=> function(arrayItem2)).then(()=> function(arrayItem3);
Somthing like this…I feel like I should be able to do this with promises but I just cant seem to figure it out.

This is a small example…the real code I have is a web scraper that has an array of links to scrape but I dont want to have 10 pages of puppeteer up scraping at once, I need it to happen one after the other. Any ideas? Thank you!

async function functionThatUsesArrayData(link) {

    const chromeOptions = {
        headless: false,
        slowMo: 60,
        defaultViewport: null,
        args: ["--no-sandbox", "--disable-setuid-sandbox"],
    };
    const promise = new Promise(async (resolve, reject) => {
        const browser = await puppeteer.launch(chromeOptions);
        const page = await browser.newPage();
        await page.goto(link);
        await browser.close();
        resolve(setTimeout(() => {
            console.log(" TASKS FINSIHED COMPLETED")

        }, 3000))
    })
    console.log(promise)

}

functionThatUsesArrayData()```

Minimum distributables to get typeahead.js working

I’m trying to get started with typeahead.js.

I’m trying some of the examples on the examples page, but nothing is working. The menu wouldn’t come up. And when I finally did get the menu to display, it has a transparent background.

Does anyone know where the minimal steps are documented to get this component working? Do I need some CSS files? Which js files are needed?

Again, I don’t want Bloodhound or anything else beyond the absolute minimum Which files do I need?

Playing a IPTV live tv stream with VideoJS or similar

I’m trying to play live tv channel with videojs. I’ve tried various ways but always get “No compatible source was found for this media.” error. Other videos are playing fine.

The url plays fine in VLC and the codec shows the stream as “MPEG-H Part2/HEVC (H.265) (hevc)”.

I’ve tried across a range of browsers too, chrome, firefox, safari and edge.

This is the bones of the code. Is there a way to play it ?

<link href="https://vjs.zencdn.net/7.17.0/video-js.css" rel="stylesheet" />
<script src="https://vjs.zencdn.net/7.17.0/video.min.js"></script>
<script src="https://unpkg.com/videojs-contrib-dash/dist/videojs-dash.js"></script>
<script src="https://unpkg.com/videojs-contrib-hls/dist/videojs-contrib-hls.js"></script>

<video id='live-video' class='video-js vjs-default-skin' controls>
</video>

<script>
  var player = videojs('live-video');
  player.src({ src:'https://www.example.com/play.php?OTUxE2NDUN', type:'application/x-mpegurl'});
  player.play();
</script>