Pieces not visible when using chessboard.js

After following what the documentation says on chessboardjs.com using the unpkg CDN, the chessboard appears without the pieces. I’m assuming that this is because the library scripts don’t know how to find the images, but I don’t know how to reconcile this. Here is my code.

html file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Online Chess</title>
    <link rel="stylesheet" href="../styles/game.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto">
    <link rel="stylesheet"
          href="https://unpkg.com/@chrisoakman/[email protected]/dist/chessboard-1.0.0.min.css"
          integrity="sha384-q94+BZtLrkL1/ohfjR8c6L+A6qzNH9R2hBLwyoAfu3i/WCvQjzL2RQJ3uNHDISdU"
          crossorigin="anonymous">
</head>
<body>
    <div id="board1"></div>
    <div class="buttons">
        <a href="lobby.html"><button class="button">Exit</button></a>
    </div>

    <script src="https://code.jquery.com/jquery-3.5.1.min.js"
            integrity="sha384-ZvpUoO/+PpLXR1lu4jmpXWu80pZlYUAfxl5NsBMWOEPSjUn/6Z/hRTt8+pR6L4N2"
            crossorigin="anonymous"></script>
    <script src="https://unpkg.com/@chrisoakman/[email protected]/dist/chessboard-1.0.0.min.js"
            integrity="sha384-8Vi8VHwn3vjQ9eUHUxex3JSN/NFqUg3QbPyX8kWyb93+8AC/pPWTzj+nHtbC5bxD"
            crossorigin="anonymous"></script>
    <script src="../scripts/chess.js"></script>
</body>
</html>

javascript file

var config = {
    pieceTheme: '/img/chesspieces/wikipedia/{piece}.png',
    position: 'start'
}
var board1 = Chessboard('board1', config);

As you can see, I tried downloading the image files locally, but even this didn’t seem to resolve the issue.

How to create a flex-box container with max of 2 columns that scrolls down upon an items overflow?

I’m trying to build a specific UI that consists of a flexbox container with flex-direction: column and flex-wrap: wrap. For each flex item that is added, the item will take 100% of the container width – and upon an overflow (first items overflow), the container will wrap the items into 2 columns – but the container will not have more then 2 columns – in the next items overflow it should scroll down (overflow-y: auto)?
Is this possible?

I tried a lot of approaches, even using display: grid in a way, but the task i more complicated then it seems.

HTML clustering problem with no “point_count” attribute created despite setting “cluster”: true

I am trying to create an html cluster map using Mapbox, but “cluster”: true is not creating a “point_count” attribute. I can confirm that the geojson is loaded correctly and individual point markers appeared when “cluster”:true was removed.

Current approach

var geoData = {
                "type": 'FeatureCollection',
                "features": [
                    {
                        "type": "Feature",
                        "geometry": {
                            "type": "Point",
                            "coordinates": [-72.4050504,40.90369252]
                        },
                        "properties": {
                            "title": "title",
                            "description": "description"
                        }
                    },
                    {
                        "type": "Feature",
                        "geometry": {
                            "type": "Point",
                            "coordinates": [-72.40584471,40.89771544]
                        },
                        "properties": {
                            "title": "title",
                            "description": "description"
                        }
                    }
                ]
            };
map.addSource('crash', {
                        type: 'geojson',
                        data: geoData,
                        cluster: true,
                        clusterMaxZoom: 10, // Max zoom to cluster points on
                        clusterRadius: 50 // Radius of each cluster when clustering points (defaults to 50)
                    });

                map.addLayer({
                        id: 'clusters',
                        type: 'circle',
                        source: 'crash',
                        filter: ['has', 'point_count'],
                        paint: {
                            'circle-color': "#f1f075",
                            'circle-radius': 40
                        }
                    });
                    map.addLayer({
                        id: 'cluster-count',
                        type: 'symbol',
                        source: 'crash',
                        filter: ['has', 'point_count'],
                        layout: {
                            'text-field': '{point_count_abbreviated}',
                            'text-font': ['Arial Unicode MS Bold'],
                            'text-size': 12
                        }
                    });
                    map.addLayer({
                        id: 'unclustered-point',
                        type: 'circle',
                        source: 'crash',
                        filter: ['!', ['has', 'point_count']],
                        paint: {
                            'circle-color': '#11b4da',
                            'circle-radius': 5,
                            'circle-stroke-width': 0.8,
                            'circle-stroke-color': '#fff'
                        }
                    });

Desired approach

I was expecting hoping to recreate the styles in this mapbox example: https://docs.mapbox.com/mapbox-gl-js/example/cluster/

Mapbox example of HTML cluster map

jquery animation – shapes moving in linear motion

I want the shapes to reappear from the right as soon as they start to disappear on the left. For example, if I have square1, circle1, and star1 in a row moving from right to left, as soon as square1 begins to disappear on the left, it should immediately reappear on the right, without waiting for circle1 or star1 to disappear. I want to implement this using jquery.

function startAutoScroll() {
        const $track = $('.track');
        const $shapes = $('.shapes');
        const trackWidth = $track.width();
        const containerWidth = $('.track-container').width();
        const shapeWidth = $shapes.first().outerWidth(true); // Width including margin
    
        // Speed of scrolling based on slider value
        const scrollSpeed = 1; // Adjust as necessary for smoother scrolling
    
        // Continuous scrolling of the track
        autoScrollInterval = setInterval(function() {
            if (!isHovering) {
                let currentLeft = parseInt($track.css('left'), 10);
                let newLeft = currentLeft - scrollSpeed;
    
                // Reset track position to create a continuous effect
                if (Math.abs(newLeft) >= trackWidth) {
                    newLeft = 0;
                }
    
                $track.css('left', `${newLeft}px`);
            }
        }, 100 / autoScrollSpeed); // Interval time for smooth scrolling
    
        // Animate shapes with seamless looping
        function animateShapes() {
            const totalShapesWidth = $shapes.length * shapeWidth;
    
            // Position shapes outside the container initially
            $shapes.each(function(index) {
                $(this).css('left', containerWidth + index * shapeWidth + 'px');
            });
    
            // Animate shapes
            $({ offset: containerWidth }).animate(
                { offset: -totalShapesWidth },
                {
                    duration: 10000 / autoScrollSpeed, // Adjust duration based on speed
                    easing: 'linear',
                    step: function(now) {
                        $shapes.each(function(index) {
                            let offset = now + index * shapeWidth;
                            // Ensure the shapes wrap around seamlessly
                            if (offset <= -shapeWidth) {
                                offset += totalShapesWidth;
                            }
                            $(this).css('left', offset + 'px');
                        });
                    },
                    complete: function() {
                        // Ensure the animation loops correctly
                        animateShapes(); // Loop animation
                    }
                }
            );
        }
    
        animateShapes(); // Start shape animation
    }

How can I access information being stored on one page of my chrome extension on a separate page of my chrome extension

I’m currently working on a chrome extension and using the storage API to save inputs and values. I want the user to be able to input a goal number on the settings page and display that number on the index page. How do I go about doing this?

I’ve tried accessing the stored goal value however it comes up as null while on the index page. It is properly stored when on the settings page.

Pausing all audios HTML and JavaScript

I’m trying to create a button that, when it is clicked, it stops all the other audios from playing and plays another specific sound.

I created an array with the names of all the audios’ ids (there are just 2 right now but I’ll add others later) and i tried to iterate through it pausing all the audios (except rapstar, which needs to be played) but they keep playing.

JavaScript:

document.addEventListener('DOMContentLoaded', function() {

    const audios = ['gotg','rapstar'];

    document.getElementById('polo-g-play').addEventListener('click', function() {
      for (let i = 0, k = audios.lenght; i < k; i++) {
        if (audios[i] != 'rapstar') {
          document.getElementById(audios[i]).pause();
        }
      }
      let audio = document.getElementById('rapstar');
      if (audio.paused)
      {
        audio.play();
      }
      else
      {
        audio.pause();
      }
    }); 
  });

The part after the for loop deals with playing the audio if it is paused or pausing it if it is already playing (just like the classic spotify play button).

The HTML of the 2 audios are these:

<audio id="rapstar" src="audio/rapstar.mp3">
    No Music Here
</audio>
<audio id="gotg" src="audio/getyourlove.mp3">
    No Music Here 
</audio>

In Laravel Jetstream I cant upload a picture >2MB

I have a issue without answer. I created a new Laravel project with Jetstream and livewire stack. I dont make any modification,its fresh I just want to upload a photo profile and it work with any file less than 2mb, but not beyond it. My php.ini is well configurated with post_max_size, upload_max_filesize at 100M and 80M. My UpdateUserProfileInformation.php in app/Actions/Fortify is well configured with "'photo' => ['nullable', 'mimes:jpg,jpeg,png', 'max:10240']," It seems that a photo>2MB is directly reject when I load it with a red message "The photo failed to upload." without even be sending. I think the problem come from the input field in the update-information-form.blade.php line 41 "<x-secondary-button class="mt-2 me-2" type="button" x-on:click.prevent="$refs.photo.click()">", maybe they are something wrong with the function "$refs.photo.click()". Do you have a solution for it? I will help me and other Laravel Jetstream user.

I try to upload a profile picture in laravel jetstream but it work only with file sized less than 2MB

How to access data passed to jinija template from the webpage using javascript

I am passing a python list that contains two lists within it to a template. The code is as follows:

return render_template("result.html", result=pythonList)

where pythonList follows the structure:

[[a list of positive comments], [a list of negative comments]]

my result.html is as follows:

<div id = "commentsContainer">
</div>

<a onclick="displayPositive()">positive comments</a>
<a onclick="displayNegative()">negative comments</a>

<script>
   function displayPositive(){
      //code to assign the result[0] list to a const javascript variable called positive
      
   }
   function displayPositive(){
      //code to assign the result[1] list to a const javascript variable called negative
   }
</script>
                 

I tried to pass in the pythonList as json using

return render_template("result.html", result=json.dumps(pythonList))

but I am not sure if this is standard practice. I also dont know how to access this result json either. This is what I tried so far.

Window.open() doesn’t work in Safari in iPhone

window.open() doesn’t work in safari in iPhone.
“Doesn’t work” means it does not open a window when it is called. Nothing happens in Next.js.

It works in Safari in iPad.
It works in Safari in desktop.
It works in chrome in anywhere.
I can’t wrapper tag because url is changed according to response of backend.
This is my code.

let a = document.createElement("a");
document.body.appendChild(a);
a.setAttribute("style", "display: none");
a.href = address;
a.target = "_blank";
a.click();
document.body.removeChild(a);

Has anybody addressed this problem yet?

Postman – Async request within Test Function

I’ve been testing the asynchronous nature of the Postman sendRequest() function and I’m trying to get it working within an pm.test block but my initial efforts are failing

This is the first example to show the async nature of sendRequest()

for (let i = 1; i < 11; i++) {

    let testValue = `request${i}`

    let request = {
        url: 'https://postman-echo.com/get?test=' + testValue,
        method: 'GET',
    }

    pm.sendRequest(request, (err, res) => {
        if (err) {
            console.log(err);
        }
        pm.test(`Request ${i} - status code is 200`, () => {
            pm.expect(res).to.have.status(200);
            let resJson = res.json();
            console.log(resJson.args.test);
        });
    });

};

enter image description here

sendRequest now supports promises and top-level awaits, so this can be rectified by the following.

for (let i = 1; i < 11; i++) {
    const response = await pm.sendRequest(`https://postman-echo.com/get?test=request${i}`);

    pm.test(`Request ${i} - status code is 200`, () => {
        pm.expect(response).to.have.status(200);
        
        let resJson = response.json();
        console.log(resJson.args.test);
    });
};

enter image description here

You can add a catch for some error handing.

for (let i = 1; i < 11; i++) {
    const response = await pm.sendRequest(`https://postman-echo.com/get?test=request${i}`).catch(error => console.log(error));
    pm.test(`Request ${i} - status code is 200`, () => {
        pm.expect(response).to.have.status(200);
        let resJson = response.json();
        console.log(resJson.args.test);
    });
};

or

for (let i = 1; i < 11; i++) {
    try {
        const response = await pm.sendRequest(`https://postman-echo.com/get?test=request${i}`);
        pm.test(`Request ${i} - status code is 200`, () => {
            pm.expect(response).to.have.status(200);
            let resJson = response.json();
            console.log(resJson.args.test);
        });
    } catch (error) {
        console.log(error);
        pm.test(`Request ${i} - status code is 200`, () => {
            pm.expect(error, error.code).to.be.undefined;
        });
    }
};

Other versions that produce pretty much the same result.

const sendRequest = (req) => {
    return new Promise((resolve, reject) => {
        pm.sendRequest(req, (err, res) => {
            if (err) {
                console.log(err);
                return reject(err);
            }
            resolve(res);
        });
    });
};

(async () => {
    for (let i = 1; i < 11; i++) {
        let testValue = `request${i}`
        let request = {
            url: 'https://postman-echo.com/get?test=' + testValue,
            method: 'GET',
        }
        const response = await sendRequest(request); // wait for promise to be resolved before continuing
        pm.test(`Request ${i} - status code is 200`, () => {
            pm.expect(response).to.have.status(200);
            let resJson = response.json();
            console.log(resJson.args.test);
        });
    }
})();
const sendRequest = (req) => {
    return new Promise((resolve, reject) => {
        pm.sendRequest(req, (err, res) => {
            if (err) {
                console.log(err);
                return reject(err);
            }
            resolve(res);
        });
    });
};

async function asyncCall(request, i) {
    const response = await sendRequest(request);
    pm.test(`Request ${i} - status code is 200`, () => {
        pm.expect(response).to.have.status(200);
        let resJson = response.json();
        console.log(resJson.args.test);
    });
};

for (let i = 1; i < 11; i++) {
    let request = {
        url: 'https://postman-echo.com/get?test=' + `request${i}`,
        method: 'GET',
    }
    await asyncCall(request, i);
};

The final version I ended up with.

async function sendRequest(request, i) {
    try {
        const response = await pm.sendRequest(request);
        pm.test(`Request ${i} - status code is 200`, () => {
            pm.expect(response).to.have.status(200);
        });
        return {
            'data': response,
            'status': "success"
        };
    } catch (error) {
        console.log(error);
        pm.test(`Request ${i} - status code is 200`, () => {
            pm.expect(error, error.code).to.be.undefined;
        });
        return {
            "status": "error",
            "errorcode": error.code
        }
    }
};

for (let i = 1; i < 11; i++) {
    let response = await sendRequest(`https://postman-echo.com/get?test=request${i}`, i);
    if (response.status === "success") {
        console.log(response.data.json().args.test); // Postman Echo Response
    }
};

What I really want to do though is move the async sendRequest into the test block.

So if the request fails, it stops processing any more code

If you do the following, you get a syntax error.

for (let i = 1; i < 11; i++) {

    pm.test(`Request ${i} - status code is 200`, () => {
        const response = await pm.sendRequest(`https://postman-echo.com/get?test=request${i}`);
        pm.expect(response).to.have.status(200);
        let resJson = response.json();
        console.log(resJson.args.test);
    });

};

SyntaxError: await is only valid in async functions and the top level bodies of modules

If you do the following, it no longer errors, but the requests are no longer in order either.

for (let i = 1; i < 11; i++) {

    pm.test(`Request ${i} - status code is 200`, async () => {
        const response = await pm.sendRequest(`https://postman-echo.com/get?test=request${i}`);
        pm.expect(response).to.have.status(200);
        let resJson = response.json();
        console.log(resJson.args.test);
    });

};

Searching the Internet, I stumbled across the following.

https://jestjs.io/docs/asynchronous

So I then looked at the Postman docs which seems to indicate that its using the Mocha framework under the hood.

https://github.com/postmanlabs/postman-runtime/tree/develop/test

Another Internet Search later.

https://masteringjs.io/tutorials/mocha/async

This seems to indicate that I should be able to do something like I’m trying, but although I can get the code to run without errors, it’s never in order anymore.

Can someone please push me in the right direction on what I’m doing wrong here.

Shopware 6: Custom translations in en-GB.json not overriding default snippets

I’m having trouble overriding default Shopware 6 snippets with my custom translations in a plugin. Despite defining custom translations in my en-GB.json file, the default values are still being displayed.

Here’s my en-GB.json file:

{
    "sw-customer": {
        "baseInfo": {
            "labelBoundSalesChannel": "Bound Sales Channel",
            "emptyBoundSalesChannel": "None"
        }
    }
}

And here’s the relevant part of my Twig template (sw-customer-base-info):

{% block sw_customer_base_metadata_bound_sales_channel %}
    <sw-description-list>
        {% block sw_customer_base_metadata_bound_sales_channel_label %}
            <dt class="sw-customer-base-info__label sw-bound-sales-channel__label">
                {{ $tc('sw-customer.baseInfo.labelBoundSalesChannel') }}
            <sw-help-text :text="$tc('sw-customer.baseInfo.helpTextBoundSalesChannel')" />
        </dt>
    {% endblock %}
    {% block sw_customer_base_metadata_bound_saleschannel_content %}
        <dd class="sw-customer-base__label-bound-sales-channel">
            <template v-if="customer.boundSalesChannelId">
                {{ customer.salesChannel.translated.name }}
            </template>
            <template v-else>
                {{ $tc('sw-customer.baseInfo.emptyBoundSalesChannel') }}
            </template>
        </dd>
    {% endblock %}
</sw-description-list>
{% endblock %}

I expected to see ‘Bound Sales Channel’ as the label for labelBoundSalesChannel and ‘None’ for emptyBoundSalesChannel. However, I’m seeing ‘Sales Channel’ and ‘All’ respectively, which are the default values.

What am I missing? How can I get my custom translations to override the default snippets?
Environment:

Shopware version: [6.6.4.1]
PHP version: [8.2]

How to print zpl in web via javascript?

I have a zebra label printer. I am attempting to print labels for fun using javascript and webUSB.

The current setup prints blank labels.

Here is the excerpt:

// Get USB device (the zebra printer)
const printer = await navigator.usb.requestDevice({
  filters: [],
});
await printer.open();
await printer.selectConfiguration(deviceConfiguration);
await printer.claimInterface(interfaceNumber);

// Hello world print command
const source = `^XA
^FO100,80
^FDHello, World!^FS
^XZ
`;

// Send print command - Method 1
const encoded = new TextEncoder().encode(source);
await printer.transferOut(1, encoded); // 1 is the endpoint number. 1 is the only valid value for my printer. We can get this from the printer (type:USBDevice) object.
// => When executed, prints a blank label.

// Send print command - Method 2
const blob = new Blob([source], {
  type: "text/plain",
});

const arrayBuffer = await blob.arrayBuffer();
await printer.transferOut(1, arrayBuffer);
// => When executed, prints a blank label.

Can someone help me understand what am I doing wrong?

In the zpl documentation, they say:

Save the file as a .txt file and copy it to the printer from DOS command line.

enter image description here

I am attempting to find the equivalent in web.

Update: I don’t want to use 3rd party libraries. I’m attempting to understand the low level fundamentals.

Demo: https://github.com/vajahath/label-jet

ECharts: Candlestick width not increasing on zoom with time xAxis and ’empty’ filterMode

Using ECharts, I’ve noticed that candlesticks don’t widen when zooming in with these settings:

  1. xAxis type is ‘time’
  2. dataZoom filterMode is ’empty’
  3. Series type is ‘candlestick’
var option = {
    xAxis: { type: 'time' },
    yAxis: { type: 'value', scale: true },
    series: [{
        type: 'candlestick',
        data: ohlcData,
    }],
    dataZoom: [{
        type: 'inside',
        xAxisIndex: [0],
        filterMode: 'empty',
    }, {
        type: 'slider',
        xAxisIndex: [0],
        filterMode: 'empty',
    }]
};

Full example: https://codepen.io/xpatt/pen/RwzZwYR

How can I make candlesticks widen on zoom while keeping the ‘time’ xAxis and ’empty’ filterMode?

How to ‘polyfill’ `interactive-widget=resizes-content` for meta viewport tag on iOS Safari?

Chrome added support for interactive-widget=resizes-content in v108, and Firefox seems to support this as of writing. But I’ve tested up to iOS Safari 17.4 and it doesn’t seem to support it.

Is there some way to ‘polyfill’ this, ideally in versions iOS Safari v15, onwards?

Related:

Dynamically add color in ion-card text based on regex

I want to add a span around some text when a # or a @ is detected so I can change the color to make it look like usernames and hashtags in twitter. My code looks like this:

TS FILE:

ngOnInit(): void {
    this.glyphService.getAllGlyphs().subscribe(
      result => {
        this.items = result;
        // sort by rune id so list is newest to oldest
        this.items.sort((a, b) => Number(b.rune) - Number(a.rune));
        for (let i = 0; i < this.items.length; i++) {
          this.items[i].glyph_content = this.replaceIt(this.items[i].glyph_content);
          console.log(this.items[i])
        }
        console.log(this.items)
      }
    );
  }

  replaceIt = (str: string) => {
    const regex = /B([#@][a-zA-Z]+b)(?!;)/g;
    const subst = `<span style="color:blue">$1</span>`;
    const result = str.replace(regex, subst);
    return result;
 }

HTML FILE:

  <ion-card *ngFor="let item of items" >
    <ion-card-header>
      <ion-card-title>&#64;{{item.username}}</ion-card-title>
      <ion-card-subtitle>{{item.glyph_date}}</ion-card-subtitle>
    </ion-card-header>
    <ion-card-content>
      {{item.glyph_content}}
    </ion-card-content>
 </ion-card>

I’m successfully replacing the text like I want to, however it’s just winding up as text instead actual tags and looks like this:
test <span style="color:blue">@hey</span> <span style="color:blue">@uh</span> wow <span style="color:blue">#ah</span> words <span style="color:blue">#oh</span>
Is there a way for me to change my code so I’m actually dynamically wrapping the target text in real spans like I want? Is it possible to use *ngIf in some creative way here?