Dirt/Ground/Rock effect in CSS [closed]

I have to create a map for my game;
The problem is that the map is an array with 100×100 spots. If i use an Image and load it into every cell, it makes the game very memory intensive and slow.

Any way i can use CSS to speed it up? Im looking for a ground/rocks/dirt effect for my map. Has anyone made one before?

Why does DOMRect shows different values from the chrome’s computed values for CSS Absolute position?

I am trying to reposition an absolutely positioned element. If it appears partially or fully beyond the viewpoint then I want to reposition it to appear within the viewpoint. For that, I am trying to get the data using getBoundingClientRect() to know its position and checking the DOMRect bottom value against value of window.innerHeight.

Also, the absolute element’s parent is not positioned as relative also nothing in the hierarchy.

If I do,

let pos = el.getBoundingClientRect();
if (window.innerHeight < pos['bottom']) {
 style = `botton:${window.innerHeight}`; // set this to the style property of the element.
}

The above does not work and the absolutely positioned element appears in undesired location or does not appear at all. But meanwhile what I have noticed that there are some difference in values that I have got from getBoundingClientRect() and the values displayed in Chrome’s DevTools -> Elements -> Computed.

So for test, if I use values from the Chrome’s Computed window and try to set those values in the DevTools: left: 1047.3px – value from the Chrome; it appears exactly where it was positioned originally but when I try left: pos['left'] it displaces the element from its original position.

DOMRect:

  {
    'bottom': 377.68751525878906,
    'height': 159.1354217529297,
    'left': 1075.3333740234375,
    'right': 1231.3333740234375,
    'top': 218.55209350585938,
    'width': 156,
    'x': 1075.3333740234375,
    'y': 218.55209350585938,
  }

Positions from Chrome:
enter image description here

After all, I did not get why those values are different and how to calculate the values to position it within the viewpoint if it goes beyond the bottom edge of the screen.

Javascript Array to change variable

i need help for this script.

I would like the global variable to be updated when an element of the array is clicked. But this doesn’t work and I can’t find the way.

const img = document.querySelectorAll("#img");
let imgPos = 1;

img.forEach((element) => {
  element.addEventListener("click", () => {
    carousel.style.visibility = "visible";
    imgPos = parseInt(element.dataset.counter);
    return imgPos;
  });

carouselSlide.style.transform = "translateX(" + -size * imgPos + "px)";

in the final string the value of ImgPos remains at 1.

Thanks

I expect the value of ImgPos to change every time the array event executes.

JavaScript game running extra fast on newer MacBook

So I made a JavaScript clone of Flappy Bird. It runs beautifully on my 2021 M1 iMac, almost perfect…

It also runs fairly well on my 2023 M2 MacBook Pro, minus some minor glitches. HOWEVER, this is only the case when I use Safari. Opening the game in Chrome on this MacBook makes it run seemingly twice as fast.

Different mobile devices also have various glitches but other identical models using the same browser don’t.

I’m perplexed. Appreciate your help.

This is my gravity function:

function startGravity() {

    function gravity() {
        velocity += gravityConstant;
        let position = parseInt(getComputedStyle(bird).top) + velocity;
        bird.style.top = `${position}px`;

        loops.gravityAnimation = requestAnimationFrame(gravity);
    }

    loops.gravityAnimation = requestAnimationFrame(gravity);
}

And this is the function which slides the obstacles across the screen:

function runShips() {
    //create random ship every 5 seconds
    generateShipsInterval();

    function slideShipsAnimation() {
        document.querySelectorAll('.ships').forEach(ship => {
            ship.style.left = `${parseInt(getComputedStyle(ship).left) - 3}px`;
        });
        loops.slideShipsAnimation = requestAnimationFrame(slideShipsAnimation);
    }
    //run all ships across the screen
    loops.slideShipsAnimation = requestAnimationFrame(slideShipsAnimation);
}

I know it has something to do with the frame rate because trying to implement delta time changes the speed but gives rise to inconsistencies across devices and more glitches.

capacitor community sqlite: TypeError: x is not a function upon startup, after upgrading to capacitor version 6

Minimum reproducible example:

https://github.com/folsze/capacitor-v6-sqlite-x-is-not-a-function

capacitor community sqlite: TypeError: x is not a function upon startup, after upgrading to capacitor version 6

when I start my angular ionic capacitor community sqlite app, I get:

ERROR TypeError: x is not a function

in the browser console

Steps to reproduce the behavior:

  1. clone this repo: https://github.com/folsze/capacitor-v6-sqlite-x-is-not-a-function
  2. start the app in the desktop browser with npm start
  3. check the console, you will see the error “TypeError: x is not a function”
  4. Expected behavior: No error

Desktop (please complete the following information):

  • MacOS: 14.5 (23F79)
  • Browser: Chrome
  • Version 126.0.6478.183 (Official Build) (arm64)

related github issue:

https://github.com/capacitor-community/sqlite/issues/574

Is there a list of the unicode code points that will display in a fixed size monospace way?

I’m generating text based tables. In each cell I need a symbol. That symbol is associated with data listed after the table. Example

┌───┬───┬───┬───┬───┬───┬───┬───┐
│ a │   │   │   │   │   │ b │   │
├───┼───┼───┼───┼───┼───┼───┼───┤
│   │   │ c │   │   │   │   │   │
└───┴───┴───┴───┴───┴───┴───┴───┘

a: 0.123
b: 0.751
c: 0.914

The issue I’m running into is once in awhile I need lots of symbols. My current code is

const symbol = (idx: number) => String.fromCodePoint(idx < 30 ? 97 + idx : idx + 9600 - 30);

That works until it gets to symbols 9776. In that range, there are 8 symbols that don’t fit

 ┌───┬───┬───┬───┬───┬───┬───┬───┐
 │ ☢ │ ☣ │ ☤ │ ☥ │ ☦ │ ☧ │ ☨ │ ☩ │
 ├───┼───┼───┼───┼───┼───┼───┼───┤
 │ ☪ │ ☫ │ ☬ │ ☭ │ ☮ │ ☯ │ ☰ │ ☱ │
 ├───┼───┼───┼───┼───┼───┼───┼───┤
 │ ☲ │ ☳ │ ☴ │ ☵ │ ☶ │ ☷ │ ☸ │ ☹ │
 ├───┼───┼───┼───┼───┼───┼───┼───┤
 │ ☺ │ ☻ │ ☼ │ ☽ │ ☾ │ ☿ │ ♀ │ ♁ │
 └───┴───┴───┴───┴───┴───┴───┴───┘

I’m using the default font used for <pre> in Chrome on MacOS. I’m not sure about other browsers or other OSes.

Is there a list, ideally part of some web spec, of which code points work to maintain monospacing (or are supposed to work)?

PS: I suppose I could try to generate a list on demand using canvas 2d’s measureText function or other web API that lets me get the size. That would possible work in more situations.

How can I remove the margin of a chart in vue-apexcharts

I have a bar chart that looks like this:

enter image description here

And I want to make it look like this:

enter image description here

I managed to remove the labels, set the correct column width, column radius, color and so on, but the position and spacing are quite odd…

As you can see, there is a big margin around the chart, and it does not fit 100% the width nor it has the correct height, even with the chart.height and chart.width options set

This is my chart component:

<script setup lang="ts">
import BaseCard from '~/shared/components/molecules/BaseCard.vue'
import { CardType } from '~/shared/components/molecules/BaseCardProps'
import { useCurrencyFormatter } from '~/shared/composables/useCurrency'
import { addMoney, type Money } from '~/shared/models/Money'

const props = defineProps<{
  title: string,
  dataSeries: number[]
}>()
const chartOptions = {
  dataLabels: {
    enabled: false
  },
  chart: {
    toolbar: {
      show: false
    },
    zoom: {
      enabled: false
    },
    height: '32px',
    width: '100%'
  },
  colors: ['var(--color-bg-brand-primary)'],
  plotOptions: {
    bar: {
      columnWidth: 4,
      borderRadius: 1
    }
  },
  legend: {
    show: false
  },
  grid: {
    padding: {
      left: 0,
      right: 0,
      top: 0,
      bottom: 0
    },
    yaxis: {
      lines: {
        show: false
      }
    },
    xaxis: {
      lines: {
        show: false
      }
    }
  },
  yaxis: {
    labels: {
      show: false
    }
  },
  xaxis: {
    labels: {
      show: false
    },
    axisBorder: {
      show: false
    },
    axisTicks: {
      show: false
    }
  }
}
const series = [
  {
    data: props.dataSeries
  }
]

const total = computed<Money>(() => {
  return props.dataSeries.map((value) => { return { amount: value, currency: 'BRL' } }).reduce((acc, current) => addMoney(acc, current) ?? acc, { amount: 0, currency: 'BRL' })
})
</script>

<template>
  <BaseCard class="chart-card" :type="CardType.Elevated">
    <div class="title-small color-text-default">
      {{ props.title }}
    </div>
    <div class="headline6-strong color-text-default">
      {{ useCurrencyFormatter(total) }}
    </div>
    <apexchart
      type="bar"
      :options="chartOptions"
      :series="series"
    />
  </BaseCard>
</template>

<style lang="scss" scoped>
.chart-card {
  display: flex;
  flex-direction: column;
  gap: var(--space-4);
}

</style>

javascript Object is not defined in random code generator

I’m trying to make a random code generator that has a date attached to it when goes into one object like

let Object = {
  ed45gf : date
}

but for some reason whenever I try to log it in console it does code is not defined idk why its defined

document.addEventListener("DOMContentLoaded", function() {
  let codes = {
    happy: "69"
  };

  function generate() {
    let length = 6;
    let result = '';
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    const charactersLength = characters.length;
    let counter = 0;
    while (counter < length) {
      result += characters.charAt(Math.floor(Math.random() * charactersLength));
      counter += 1;
    }
    let date = new Date();
    codes[result] = `${date}`
    console.log(result);
  }

  function Submit() {

  }

  document.querySelectorAll('button').forEach(button => {
    button.addEventListener("click", function(event) {
      const target = event.target;
      switch (target.id) {
        case "generate":
          generate();
          break;
        case "submit":
          Submit();
          break;
      }
    });
  });
});
<button id="generate">Click me</button>

i was expecting the result to add itself to the object but it seems the object is not defined the object being codes

Video upload on CKEditor . YII project

I need help with CKEditor. I have dosamigos/ckeditor on this project. I need to upload local video, and show them on the editor like downloading images. How I can do this?

I tried to download plagin video and added extraplugin on editor.

How can i execute JavaScript’s with nodriver python?

I’m trying to make a code with python but I’m having some problems; for example, I log in to the cloudflare protected site using nodriver and I can print the values of the elements on the page. but my goal is to change them or execute javascript code from the console (it can be one of the 2, it doesn’t matter)

Note: if there’s any other way to bypassing cloudflare (I’ve already tried undetected-chromedriver but it’s not able to bypass) and executing console scripts / changing values ?

this one is for executing script (i thought chatgpt might know)

import keyboard
import asyncio
import nodriver as uc
from time import sleep


url = "https://example.com/"

async def main():
    # Nodriver ile sayfa aç
    driver = await uc.start()
    
    tab = await driver.get(url)
    while True:
        if keyboard.is_pressed('g'):
            script = """
            document.title = 'New Topic';
            """
            driver.execute_script(script) 
asyncio.run(main())

Progress control in Web Speech API

I am using Web Speech API to read a text (documentation link here).

Is there a way of displaying this kind of progress control?

Sound progress control

The idea is that user sees the progress of the read, and can jump to any point of it.

Any free alternative is also welcomed.

Thanks in advance!

Create a cookie with the secure and httonly flags to display a banner

I premise I am fairly inexperienced in php and javacript, but I am trying to create a small website for myself.

In this website, I want to display a small banner with some text inside when a new user enters my website (whichever the webpage is) for the first time. The banner has the following characteristics:

  1. When displayed for the first time, it remains on the screen for 7 seconds (so the user can read it)
  2. After its disappearance, the user can continue to browse the website and pages without seeing the banner anymore.

To do so, I thought to create a plugin (for WORDPRESS) that creates a cookie, let’s call it banner_read. After the banner disappers, the cookie is created and the presence of the cookie does not cause the banner to be created. The cookie is only valid for the session (session cookie).

The first time I created the banner and the cookie via javascript code, also setting the ‘secure’ flag. The javascript code checks for the existence of the cookie and if it does not exist it creates the banner (with its settings). If I limit myself to this, the code works. In particular, the banner is displayed for seven seconds and the cookie is created after its disappearance, whichever is the first webpage displayed by the user.

Then, to be on the safe side and also out of curiosity, I wanted to set the ‘httponly’ flag as well, but from what I understand, it has to be done through php code, since the javascript code (to check the existence of the cookie) does not work if the httponly flag is set.

I have tried to create some php code to check the existence of the cookie and create it and javascript code to display the banner, but the code does not seem to work. In particular, the banner is not displayed and the cookie is created immediately.

Maybe for this simple cookie I don’t need both the flags, but not knowing the subject in depth, I would like to play it safe.

First code – I report here the javascript code that works (the CSS file for styling is external):

<?php
/*
Plugin Name: Custom Cookie Manager
*/

if (!defined('ABSPATH')) {
    exit;
}


// Enqueue styles and scripts
function custom_cookie_manager_enqueue_styles() {
    wp_enqueue_style('custom-cookie-manager-style', plugins_url('css/custom-cookie-manager.css', __FILE__));
}
add_action('wp_enqueue_scripts', 'custom_cookie_manager_enqueue_styles');

// Add the cookie banner
function custom_cookie_manager_banner() {
    ?>
    <script type="text/javascript">
        document.addEventListener('DOMContentLoaded', function() {
            if (!document.cookie.split('; ').find(row => row.trim().startsWith('banner_read='))) {
                var banner = document.createElement('div');
                banner.id = 'cookie-banner';
                banner.className = 'cookie-banner';
                banner.innerHTML = '<p>TEXT HERE</p>';
                document.body.appendChild(banner);
                
                setTimeout(function() {
                    banner.classList.add('hide');
                    document.cookie = "banner_read=true; path=/; Secure; SameSite=Strict";
                }, 7000); // 7 seconds
            }
        });
    </script>
    <?php
}
add_action('wp_footer', 'custom_cookie_manager_banner');
?>

Second code – Here the PHP and Javascript code that does not work:

<?php
/*
Plugin Name: Custom Cookie Manager
*/

if (!defined('ABSPATH')) {
    exit;
}

// Enqueue styles and scripts
function custom_cookie_manager_enqueue_styles() {
    wp_enqueue_style('custom-cookie-manager-style', plugins_url('css/custom-cookie-manager.css', __FILE__));
}
add_action('wp_enqueue_scripts', 'custom_cookie_manager_enqueue_styles');

// Add the cookie banner
function custom_cookie_manager_banner() {
    if (!isset($_COOKIE['banner_read'])) {
        ?>
        <script type="text/javascript">
            document.addEventListener('DOMContentLoaded', function() {
                var banner = document.createElement('div');
                banner.id = 'cookie-banner';
                banner.className = 'cookie-banner';
                banner.innerHTML = '<p>TEXT HERE</p>';
                document.body.appendChild(banner);
                
                setTimeout(function() {
                    banner.classList.add('hide');
                }, 7000); // 7 seconds
            });
        </script>
        <?php

        // Set cookie with HttpOnly and Secure flags
        setcookie('banner_read', 'true', 0, "/", "", true, true); // session cookie
    }
}
add_action('wp_footer', 'custom_cookie_manager_banner');
?>

Here is the CSS fyle:

/* css/custom-cookie-manager.css */
.cookie-banner {
    position: fixed;
    bottom: 0;
    width: 100%;
    background-color: #000;
    color: #fff;
    text-align: center;
    height: auto;
    z-index: 1000;
    font-size: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 14px 20px 0 20px;
    box-sizing: border-box;
}

.cookie-banner.hide {
    visibility: hidden;
}

I have tried to create some php code to check the existence of the cookie and create it and javascript code to display the banner, but the code does not seem to work. In particular, the banner is not displayed and the cookie is created immediately.

I expect the second to work as well as the first one.

Deloitte USI vs KPMG which to choose [closed]

I have received an offer letter from Deloitte USI for an advisory analyst trainee position in risk and finance advisory with a total package of 4lpa including bonuses. I also have an offer letter from KPMG for an analyst role (related to software development) with a package of 5lpa plus bonuses. I’m very confused about which offer to accept. I need help making a decision about whether to join Deloitte or KPMG. I want to choose the firm that offers better salary prospects and valuable learning experiences in the future.

waiting in javascript context using dart

the goal is to be able to wait for dart code to process and receive its output in the javascript context but i am not being able to.

I am not able to wait with dart:js (code1).
I am able to wait using flutter_js(code2) .
the issue with flutter_js is that it does not work with flutter web.

is is possible to wait with dart:js or another package that works with flutter web?

i found this stack overflow that is similar ::

How to asynchronously call JavaScript in Flutter?

How to get callback or return value from async JS function to Dart in Flutter Web?

https://github.com/dart-lang/sdk/issues/50530

the second and third link were exatactly what i was looking for a think but i dont understand what the answer was.

any help is greatly appreciated it/

code1::

import 'package:flutter/material.dart';
import 'dart:js' as js;
import 'package:flutter/material.dart';
class JsCompilerUtil {
  Future<bool?> process_client_script({
    required String script,
    required Map<String, dynamic> current,
  }) async {
    js.JsObject jsObject = js.JsObject.jsify(current);
    js.context['c'] = jsObject;
    // js.context['c'] = current;
    var result = js.context.callMethod("eval", [script]);
    return result;
  }
}
class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
  JsCompilerUtil jsCompilerUtil = JsCompilerUtil();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    *initialize*data();
  }
  Future<void> *initialize*data() async {
    String script = """
console.log("Hi from js, this is the inputed name: "+c.name);
var res = c.dummyWait();
console.log("res:")
""";
    Map<String, dynamic> current = {
      "name": "Juan",
      "dummyWait": dummyWait
    };
    final res = await jsCompilerUtil.process_client_script(script: script, current: current);
  }
  @override
  Widget build(BuildContext context) {
    return SizedBox();
  }
  Future<String> dummyWait() async {
    print("dummyWait()n");
    await Future.delayed(const Duration(seconds: 1));
    return 'MESSAGE FROM DART';
  }
}

output of code1::

Restarted application in 28ms.
The debugEmulateFlutterTesterEnvironment getter is deprecated and will be removed in a future release. Please use `debugEmulateFlutterTesterEnvironment` from `dart:ui_web` instead.
Hi from js, this is the inputed name: Juan
dummyWait()
res:

code2:

import 'package:flutter/material.dart';
import 'package:flutter_js/flutter_js.dart';
import 'dart:convert';

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  late JavascriptRuntime flutterJs;

  @override
  void initState() {
    super.initState();
    flutterJs = getJavascriptRuntime();
    _setupJavaScriptBridge();
  }

  void _setupJavaScriptBridge() {
    flutterJs.onMessage('dummyAwait', (args) async {
      String result = await dummyAwaitFunction();
      return result;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('JavaScript in Dart'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: _logic,
          child: Text('Run JavaScript'),
        ),
      ),
    );
  }

  Future<void> _logic() async {
    String result = await runJavaScript();
    print("JavaScript result: $result");
  }

  Future<String> runJavaScript() async {
    // Dart map
    final current = {"name": "juan"};

    // Convert Dart map to JSON string
    String jsonString = jsonEncode(current);

    // JavaScript script to parse JSON string, call Dart function, and print result
    String script = '''
      var current = JSON.parse('$jsonString');
      async function waitForDart() {
        var res = await sendMessage('dummyAwait');
        console.log("INSDE OF JS: " + res);
        return res;
      }
      waitForDart();
    ''';

    // Evaluate JavaScript script
    JsEvalResult jsResult = await flutterJs.evaluateAsync(script);

    return jsResult.stringResult;
  }

  Future<String> dummyAwaitFunction() async {
    await Future.delayed(const Duration(seconds: 1));
    return 'MESSAGE FROM DART';
  }
}