PHP mcrypt Equivalent

Python equivalent of PHP Mcrypt

I wrote the following DES encryption scheme in PHP . It uses a static Initialization Vector to make sure the output and input is one to one mapped PHP code : function encrypt($plaintext, $key) { # use an explicit encoding for the plain text $plaintext_utf8 = …

Web Components: attributeChangedCallback() function not triggered even after mentioning the observedAttributed()

I have created a Web Component which has 2 inputs: btnText and btnDisabled. I have mentioned these 2 attributed in the static get observedAttributes() {}. Yet, the attributeChangedCallback() does not get triggered. Below is my Web Component:

// import sheet from './button.css' assert { type: 'css' };

/* eslint-disable @typescript-eslint/no-non-null-assertion */
export class ButtonElement extends HTMLElement {
  static get observedAttributes() {
    return ['btnText', 'btnDisabled'];
  }

  get btnText() {
    return this.getAttribute('btnText')?.trim() || 'Next';
  }

  set btnText(value: string) {
    console.log('Setting button text value...', value);
    this.setAttribute('btnText', value);
    this.render();
  }

  get btnDisabled() {
    return Boolean(this.getAttribute('btnState'));
  }

  set btnDisabled(value: boolean) {
    console.log('Setting button state value...', value);
    if (value) {
      this.setAttribute('btnState', value.toString());
    } else {
      this.removeAttribute('btnState');
    }
    this.render();
  }

  constructor() {
    super();
    this.attachShadow({ mode: 'open' });
  }

  connectedCallback() {
    // super.connectedCallback();
    // this.renderRoot.adoptedStyleSheets = [sheet];

    console.log('Element added to the DOM');

    this.setAllAttributes();

    /* This method renders the button */
    this.render();
  }

  disconnectedCallback() {
    console.log('Element removed from the DOM');
  }

  attributeChangedCallback(
    attributeName: string,
    oldValue: string,
    newValue: string
  ) {
    console.log(
      `Attribute ${attributeName} changed from ${oldValue} to ${newValue}`
    );
  }

  render() {
    if (!this.shadowRoot) return;

    console.log('My button text is ', this.btnText);

    this.shadowRoot.innerHTML = `
      <style>
        :host {
          display: block;
        }

        :host-context([btnState='true']) button {
          background-color: var(--button-disabled-color);
          border-color: var(--button-disabled-border-color);
          color: var(--color-disabled);
          cursor: not-allowed;
        }

        button {
          display: flex;
          justify-content: center;
          place-items: center;
          outline: none;
          background-color: var(--button-primary-color);
          border: 1px solid transparent;
          border-color: var(--button-primary-border-color);
          color: var(--color-primary);
          user-select: none;
          font-size: 1.1rem;
          padding: 0.375rem 0.75rem;
          border-radius: var(--button-border-radius, var(--button-default-border-radius));
          cursor: pointer;
          height: 50px;
          width: 100%;
        }
      </style>
      <button>
        <slot name="left-icon"></slot>
        <slot>${this.btnText}</slot>
        <slot name="right-icon"></slot>
      </button>
    `;

    this.addEventListeners();
  }

  private setAllAttributes() {
    this.btnText = this.getAttribute('btnText') || this.btnText;
  }

  private addEventListeners() {
    console.log('Adding event listeners...');
    const btn = this.shadowRoot?.querySelector('button');
    console.log('$$$$ ', btn);

    btn?.addEventListener('click', this.handleClick.bind(this));
  }

  handleClick() {
    console.log('Button is clicked inside the custom element...');

    /* Dispatching a custom event */
    const eventData = { theme: document.documentElement.getAttribute('theme') };
    const event = new CustomEvent('buttonClicked', {
      detail: eventData,
      bubbles: true,
    });
    this.dispatchEvent(event);
  }
}

customElements.define('ag-button', ButtonElement);

Upon entering text in the text box and checking disabled checkbox, I am expecting the attributeChangedCalleback() to be triggered.

I tried mentioning the attributes in observedAttributes() using camel case and kebab case. Both of them didn’t work.

Modal JS – Dificuldade na pratica [closed]

I hope you are well! =)

I’m having difficulty in relation to the modal, I want an event that when clicking on the element overrides the content, however, using the same element, I want it to remain as the main content, still working with the js functions, both the number generator, as well as the history of drawn numbers. [Slide before the event takes place] https://i.stack.imgur.com/fMKyB.png Slide after being clicked to expand

Se possível, quem conseguir me explicar como posso estar fazendo ficarei muito grato!

Já tentei ver alguns tutoriais, porém, não consegui sanar essa dificuldade.

make resize property in css push the neighboring th in a table outside of the div instead of resizing them

I have a 3 column table in a main container. If I change the size of the middle column, when it reaches the edge of the container it shrinks the 2 other columns to keep all columns in the div.

Is there a way to make it push the 3rd column out of the div with a scroll bar. I tried overflow: auto or hidden but it does not work.

Note that if I add enough columns so the columns can’t shrink anymore, the scroll bar will appear but the size of the columns can’t be changed anymore.

<!DOCTYPE html>
<html>
<head>
<style> 
div {
  border: 1px solid;
}

.mainContainer{
  width: 250px;
  height: 50px;
  overflow: auto;
}

th {
  resize: horizontal;
  overflow: auto;
  border-width: 1px;
  border-style: solid;
  width: 70px;
}


</style>
</head>
<body>

<div class = "mainContainer">
  <table>
  <tr>
    <th> col1</th>
    <th> col2</th>
    <th> col3</th>
      </tr>
  </table>
  </div>
  <div class = "mainContainer">
    <table>
  <tr>
    <th> col1</th>
    <th> col2</th>
    <th> col3</th>
    <th> col4</th>
    <th> col5</th>
    <th> col6</th>
    <th> col7</th>
    <th> col8</th>
  </tr>
  </table>
  
</div>
</body>
</html>

having trouble collapsing these li without clicking the ul

function createFolderStructure($path, $root = true) {
    $html = '<ul' . ($root ? ' style="display:block;"' : '') . '>';

    // Get the list of files and directories in the current path
    $items = scandir($path);

    foreach ($items as $item) {
        // Skip current and parent directory references
        if ($item == '.' || $item == '..') {
            continue;
        }

        $itemPath = $path . '/' . $item;
        $isFolder = is_dir($itemPath);

        $html .= '<li onclick="toggleFolder(this)">' . $item;

        if ($isFolder) {
            // If it's a folder, recursively call the function to create child structure
            $html .= createFolderStructure($itemPath, false);
        }

        $html .= '</li>';
    }

    $html .= '</ul>';

    return $html;
}

// Set the root path to your images folder
$rootPath = 'users';

?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Folder Structure</title>
  <style>
ul {
    list-style: none;
    padding-left: 20px;
    display: none;
}

li {
    cursor: pointer;
    padding: 10px; /* Increase the padding to make the entire li area clickable */
    margin-bottom: 5px;
    border: 1px solid #ddd;
    border-radius: 5px;
}
</style>
  <script>
    // Function to toggle visibility of the folder content
    function toggleFolder(element) {
      // Toggle visibility of the clicked folder content
      var ul = element.querySelector('ul');
      ul.style.display = ul.style.display === 'none' ? 'block' : 'none';
    }
  </script>

</head>
<body>

<div id="folderStructure">
 
 <?php echo createFolderStructure($rootPath); ?>

</div>

</body>
</html>

So when I collapse the first folder, it does what it needs to do showing the child folder and its files, and so on. but it seems to be difficult to continue collapsing without accidently closing the parent folders.

I expect it to go down in heirchial order and up in heirchial order. as it does, but for some reason as said the li and ul seem to stick when clicking the lower folders…

.textContent property updating differently in two event listeners?

I’m a beginner at JS attempting to build a calculator for practice/learning. I’ve managed to cover the basic click functionality and now in the process of adding keyboard input. I’m having issues mimicking the behavior of a iOS calculator where once the operator key is pressed, the display area ‘holds’ operand 1 and then begins displaying operand 2 on the next number key press.

My issue lies in that I’ve managed to capture this behavior under my .number_key click handler, but not my keyboard input handler. In the keyboard input, it captures the operator string instead of clearing it, then concatenating e.key. i.e. it will show +44 for the second operand, whereas the click behavior will begin the new string without the operator. Even though the code is the same, and the only difference is the type of event, why is the behavior different? I feel I am overlooking something critical but can’t identify it.

source code:

// declaring variables

let n1;
let n2;
let operator;
let pressed = [];
let keydown = [];

//selectors

const calcDisplay = document.querySelector('#display');
const calcKeys = document.querySelectorAll('.buttons');

//selectors + event listeners

const numberClicked = document.querySelectorAll('.number_key').forEach((item) => {
  item.addEventListener('click', (e) => {
    if (pressed.slice(-1) == '+' || pressed.slice(-1) == '-' || pressed.slice(-1) == '*' || pressed.slice(-1) == '÷') {
      calcDisplay.textContent = '' + e.target.textContent;
      pressed.push(e.target.textContent);
    } else {
      calcDisplay.textContent += e.target.textContent;
      pressed.push(e.target.textContent);
    }
  });
});

const operatorClicked = document.querySelectorAll('.operator').forEach((item) => {
  item.addEventListener('click', (e) => {
    n1 = calcDisplay.textContent;
    operator = e.target.textContent;
    pressed.push(e.target.textContent);
    console.log(n1, operator);
  });
});

const equalsClicked = document.querySelector('#equals').addEventListener('click', (e) => {
  n2 = calcDisplay.textContent;
  console.log(n2);
  calcDisplay.textContent = calculate(n1, n2, operator);
});

// clear display
document.querySelector('#clear').addEventListener('click', () => {
  clear();
});

// operation is performed

const calculate = (n1, n2, operator) => {
  if (operator === '+') {
    return parseInt(n1) + parseInt(n2);
  } else if (operator === '-') {
    return parseInt(n1) - parseInt(n2);
  } else if (operator === '*') {
    return parseInt(n1) * parseInt(n2);
  } else if (operator === '÷' || operator === '/') {
    return parseInt(n1) / parseInt(n2);
  }
};

// clear function
const clear = () => {
  calcDisplay.textContent = '';
  n1 = '';
  n2 = '';
  operator = '';
  pressed = [];
};

// listen for keyboard input
document.addEventListener('keydown', (e) => {
  acceptableKeys = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '-', '*', '/'];
  if (e.key in acceptableKeys) {
    calcDisplay.textContent += e.key;
    pressed.push(e.key);
  }

  //mimic 'operatorClicked behavior'
  else if ((e.shiftKey && e.key === '+') || (e.shiftKey && e.key === '*') || e.key === '/' || e.key === '-') {
    n1 = calcDisplay.textContent;
    operator = e.key;
    pressed.push(e.key);
    console.log(n1, operator);
    if (pressed.slice(-1) == '+' || pressed.slice(-1) == '-' || pressed.slice(-1) == '*' || pressed.slice(-1) == '/') {
      calcDisplay.textContent = '' + e.key;
      pressed.push(e.key);
    }
  }

  if (e.key === 'Enter') {
    n2 = calcDisplay.textContent;
    console.log(n2);
    calcDisplay.textContent = calculate(n1, n2, operator);
  }

  if (e.key === 'Backspace') {
    calcDisplay.textContent = calcDisplay.textContent.slice(0, -1);
  }
})

full code with HTML/CSS: https://jsfiddle.net/icycold/Laq1ers6/201/

I can ‘fix’ the issue by setting calcDisplay.textContent = '' + e.key; to calcDisplay.textContent = ''; however, then the first operand isn’t displayed until the next one is entered and is instead cleared fully. I would want it to behave exactly as when I use clicks.

I’d appreciate any and all help as this entry-level project has taught me a lot via trail/error.

When I try to access an element in an array of objects, it writes to all elements at once

I have a nested object with arrays in it and I also have an array of that object. When I try to access to the first element of that object, I see that all the elements of the array are written. How can I fix it?
My code is like this (my original code was using “for” loops but I wanted to simplyfy to see what’s wrong)



level = Array(heroStatus.length); 
  name = Array(heroStatus.length);
  levelnum = Array(heroStatus.length);
  equipped = Array(heroStatus.length);
  inInventory = Array.from(Array(5), () => new Array(heroStatus.length));

  equipmentType = {level,name,levelnum,equipped,inInventory};
  let equipment = Array.from(Array(6), () => equipmentType );
  
  i = 0;
  equipment[0].level = heroStatus.map((x) =>  x[2+(2*i)]);
  equipment[0].name = heroStatus.map((x) =>  x[3+(2*i)]);
  equipment[0].levelNum = equipment[0].level.map((x) => equipmentLevelNames.findIndex((y)=> y==x ));
  equipment[0].equipped = heroEquippedItems.map((x) =>  x[i]);
  equipment[0].inInventory[0] = equipment[0].level.map((x)=> inventoryItemList.findIndex(y => y[1] ==        equipment[0].name[equipment[0].level.indexOf(x)] && y[0] == equipment[0].level[equipment[0].level.indexOf(x)]));
  equipment[0].inInventory[0] = equipment[0].inInventory[0].map((x)=> {if(x ==-1){ return false}else{ return  true} });
  
  i = 1;
  equipment[1].level = heroStatus.map((x) =>  x[2+(2*i)]);
  equipment[1].name = heroStatus.map((x) =>  x[3+(2*i)]);
  equipment[1].levelNum = equipment[1].level.map((x) => equipmentLevelNames.findIndex((y)=> y==x ));
  equipment[1].equipped = heroEquippedItems.map((x) =>  x[i]);
  equipment[1].inInventory[0] = equipment[1].level.map((x)=> inventoryItemList.findIndex(y => y[1] == equipment[1].name[equipment[1].level.indexOf(x)] && y[0] == equipment[1].level[equipment[1].level.indexOf(x)]));
  equipment[1].inInventory[0] = equipment[1].inInventory[0].map((x)=> {if(x ==-1){ return false}else{ return  true} });
 
  i = 2;
  equipment[2].level = heroStatus.map((x) =>  x[2+(2*i)]);
  equipment[2].name = heroStatus.map((x) =>  x[3+(2*i)]);
  equipment[2].levelNum = equipment[2].level.map((x) => equipmentLevelNames.findIndex((y)=> y==x ));
  equipment[2].equipped = heroEquippedItems.map((x) =>  x[i]);
  equipment[2].inInventory[0] = equipment[2].level.map((x)=> inventoryItemList.findIndex(y => y[1] == equipment[2].name[equipment[2].level.indexOf(x)] && y[0] == equipment[2].level[equipment[2].level.indexOf(x)]));
  equipment[2].inInventory[0] = equipment[2].inInventory[0].map((x)=> {if(x ==-1){ return false}else{ return  true} });

Here is the nested structure of the object:
And here is what I see just before the line that starts with “i=1”. My test code doesn’t even go up to index 5

Initially I wanted to write to every element in an array of objects in a for loop. When I saw that every element has the same value which is the values of the last element of the array, I wanted to see it more clearly and removed the “for loop”. I also tried using .push() method but it also pushed the calculated object to all the objects in the array of objects.

How to have line labels on both sides of a Y-axis?

I would like to have line labels on both sides of a Y-axis, as in the following example:
enter image description here
I looked on ECharts examples and documentation, but I couldn’t find which series type or options would allow me to do that…

Here are the data used in the example:

|------------+--------+--------+--------+--------+-------+--------+--------+--------|
| Entity     | 1950.0 | 1960.0 | 1970.0 | 1980.0 |  1990 | Rank50 | Rank90 | Factor |
|------------+--------+--------+--------+--------+-------+--------+--------+--------|
| Mitzerland |  30000 |  32000 |  40000 |  50000 | 60000 |      1 |      3 |      2 |
| Ataly      |  20000 |  40200 |  60500 |  72000 | 85000 |      2 |      1 |    4.3 |
| Bangolia   |  10000 |  20100 |  30500 |  42000 | 75000 |      3 |      2 |    7.5 |
|------------+--------+--------+--------+--------+-------+--------+--------+--------|

How to instantiate a class that requires DOM with Puppeteer?

I want to instantiate a class called DataBinding that uses document.querySelector inside a CoffeeScript file. To achieve this, I’m using Puppeteer to create the DOM environment. However, inside page.evaluate, the code didn’t recognize the class DataBinding. I’m performing this to test the DataBinding class. I tried to run the following code, but it didn’t work:

import puppeteer from 'puppeteer'
import { DataBinding } from // correct path

browser = await puppeteer.launch({headless: 'new', executablePath: "/usr/bin/google-chrome-stable"});
page = await browser.newPage();
await page.goto 'http://127.0.0.1:9000';

await page.evaluate(() =>
    data_binding_instance = new DataBinding();
) 

await browser.close();
  1. I’m running a blank index.html page just to create the DOM.
  2. This code is transpiled by esbuild to generate a .js file.
  3. I’m running the transpiled code with node test_data_binding.js (where test_data_binding.js is the transpiled file).

I tried a lot of things, such as using page.exposeFunction to pass a function to the Puppeteer context that returns a DataBinding class, but it didn’t work.

I do not understand why my timer is stopping on javascript keydown event. That is what I want but I just do not know why it is stopping

I have a keyup event to start a timer but I do not understand why it stops on keydown. It is working as intended but I am having trouble understanding why its working. Why does the timer stop on keydown? I am not calling the stopWatch function anywhere in the keydown event listener. I have gone through every possible scenario I can think of but it is still not making sense to me.

let cubeTimer = document.getElementById("cubeTimer");
let appendMinutes = document.getElementById("minutes");
let appendSeconds = document.getElementById("seconds");
let appendMilliseconds = document.getElementById("milliseconds");
let scramble = document.getElementById("scramble");

let minutes = 0;
let seconds = 0;
let milliseconds = 0.00;
let start = true;
let stop = false;
let arr = [];
let interval;
let scrambleArray = ["R", "L", "R'", "L'", "U", "D", "U'", "D'", "F", "B", "F'", "B'", "R2", "L2", "U2", "B2", "D2", "F2"];

function scrambleCube () {
    let newArr = []
    for (let i = 0; i < 21; i++) {
        if (newArr.length >= 1) {
            newArr.push(scrambleArray[Math.floor(Math.random() * 18)]);
            do {
                newArr[i] = scrambleArray[Math.floor(Math.random() * 18)]
            } while (newArr[i][0] === newArr[i - 1][0]);
        }; 
        if (newArr.length < 1) {
            newArr.push(scrambleArray[Math.floor(Math.random() * 18)]);
        };
        
    };

    for (let i = 0; i < newArr.length; i++) {
        newArr[i] = " " + newArr[i]
    };

    scramble.innerHTML = newArr;
    
    //console.log(newArr)
    
}
scrambleCube()

document.addEventListener("keydown", () => {
    
    arr.push("a");
    if (arr.length > 10) {
        cubeTimer.style.color = "green";
        cubeTimer.style.fontSize = "40px";
        start = true;
        stop = false;
        minutes = 0;
        seconds = 0;
        milliseconds = 0.00;
        appendMinutes.innerHTML = "00";
        appendSeconds.innerHTML = "00";
        appendMilliseconds.innerHTML = "00";
    } else if (arr.length < 10) {
        cubeTimer.style.color = "red";
    }

    if (start === false) { stop = true };
    
    
});

document.addEventListener("keyup", () => {
    start = false;
    cubeTimer.style.color = "green";
    if (arr.length > 10) {
        interval = setInterval(stopWatch, 10);    
    }
    arr = [];
});



function stopWatch () {
    if (stop === true) {  
        clearInterval(interval);
        scrambleCube()
    };

    milliseconds++;

    if (milliseconds == 100) {
        seconds++;
        milliseconds = 0;
    };
    
    if  (seconds == 60) {
        minutes++;
        seconds = 0;
    };

    let milliString = milliseconds;
    let secondString = seconds;
    let minuteString  = minutes;
    
    if (minutes < 10) {
        minuteString = "0" + minuteString;
    };

    if (seconds < 10) {
        secondString = "0" + secondString;
    };

    if (milliseconds < 10) {
        milliString = "0" + milliString;
    };

    appendMinutes.innerHTML = minuteString;
    appendSeconds.innerHTML = secondString;
    appendMilliseconds.innerHTML = milliString;
    
};

Trying to get my custom google sheet script to update the value in the cell every time it is triggered

I have an onEdit trigger set up for this script:

function ifBold() {

var cell = SpreadsheetApp.getActiveSpreadsheet().getRange(“‘Prospect List’!A:A”);

if(cell.getFontWeight() == ‘bold’)

return true;

else

return false;
}

I have one sheet that I enter data into and it creates a unique ID on the sheet “Prospect List”. I am trying to get my script to constantly update every time I update the other sheet and constantly check if there is a bold cell. Right now, it works the first time, the trigger says it works, but the TRUE/FALSE value in the cell does not update. I would also rather type the a1Notations into the ifBold() function but that didn’t seem to work. Any help is appreciated.

I tried to run the script and it did not update the cell value.

Remove POI Marker

Is there a way to deactivate these “POI markers”? For my use it is not relevant to show local restaurants, stores and public facilities, so I would like to hide them.

Example Image of London, United Kingdom

How can I do that? I’m using react-leaflet. Many thanks in advance!

I have already done some research but have not found a way to deactivate it.

Is it possible to force browser to render mobile version of only one element?

Using fetch, I’m fetching some external HTML and inserting it into a div. The thing is, the div is quite small, and so would like the browser to render the HTML using the mobile version (which looks fine), even though I’m not in control of the CSS that’s fetched with the HTML.

Is that possible? Can I somehow change the viewport of that div only? Is an iframe the only option (I’m trying to avoid using it)?

I tried adding a new meta tag, as well as updating the user agent data before the fetch, but none of it seems to work.

Store user data in local storage

Is it correct to store all user data. In localstorge after entering the site so that I can use it when needed instead of doing a fetch. It has it every time or on every page I use it on. Knowing that user data may contain… Location, phone number, email, favorite products, and blocked users. Please advise me

store user information in localstorge