Trying to deploy my Aave flashloan test but getting an error. https://github.com/aave/flashloan-box

whenever I run, “truffle test” I get this error below:

Error: Mnemonic invalid or undefined
    at checkBIP39Mnemonic (C:[email protected]:75:15)
    at new HDWalletProvider (C:[email protected]:105:23)
    at Object.<anonymous> (C:UsersJackctruffle-config.js:17:16)
    at Module._compile (node:internal/modules/cjs/loader:1376:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
    at Module.load (node:internal/modules/cjs/loader:1207:32)
    at Function.Module._load (node:internal/modules/cjs/loader:1023:12)
    at Module.require (node:internal/modules/cjs/loader:1235:19)
    at require (node:internal/modules/helpers:176:18)
    at Function.load (C:UsersJackcAppDataRoamingnpmnode_modulestrufflebuildwebpack:packagesconfigdistindex.js:152:1)
    at Function.detect (C:UsersJackcAppDataRoamingnpmnode_modulestrufflebuildwebpack:packagesconfigdistindex.js:144:1)
    at Object.module.exports [as run] (C:UsersJackcAppDataRoamingnpmnode_modulestrufflebuildwebpack:packagescorelibcommandstestrun.js:27:1)
    at runCommand (C:UsersJackcAppDataRoamingnpmnode_modulestrufflebuildwebpack:packagescorelibcommand-utils.js:297:1)
Truffle v5.11.5 (core: 5.11.5)
Node v20.10.0

https://github.com/aave/flashloan-box

I have all the correct info in my .env but im not sure if I need to add Mnemonic key into my .env file as it doesnt mention that on the Github page? All it uses in the .env is:

INFURA_API_KEY =
DEPLOYMENT_ACCOUNT_KEY =

I am also using require(“dotenv”).config() in my truffle-config.js file.

here is the truffle-config.js

// const path = require("path");
const HDWalletProvider = require("@truffle/hdwallet-provider")
require("dotenv").config()

module.exports = {
    // See <http://truffleframework.com/docs/advanced/configuration> to customize your Truffle configuration!
    // contracts_build_directory: path.join(__dirname, "client/src/contracts"),
    networks: {
      development: {
        host: "127.0.0.1",
        port: 8545,
        // gas: 20000000,
        network_id: "*",
        skipDryRun: true
      },
      ropsten: {
        provider: new HDWalletProvider(process.env.DEPLOYMENT_ACCOUNT_KEY, "https://ropsten.infura.io/v3/" + process.env.INFURA_API_KEY),
        network_id: 3,
        gas: 5000000,
        gasPrice: 5000000000, // 5 Gwei
        skipDryRun: true
      },
      kovan: {
        provider: new HDWalletProvider(process.env.DEPLOYMENT_ACCOUNT_KEY, "https://kovan.infura.io/v3/" + process.env.INFURA_API_KEY),
        network_id: 42,
        gas: 5000000,
        gasPrice: 5000000000, // 5 Gwei
        skipDryRun: true
      },
      mainnet: {
        provider: new HDWalletProvider(process.env.DEPLOYMENT_ACCOUNT_KEY, "https://mainnet.infura.io/v3/" + process.env.INFURA_API_KEY),
        network_id: 1,
        gas: 5000000,
        gasPrice: 5000000000 // 5 Gwei
      }
    },
    compilers: {
        solc: {
            version: "^0.6.6",
        },
    },
}

Starting to think it might be a dependency issue in my package.json but I am just guessing by this point.

any help would be greatly appreciated!!!

Mocha Rerun Tests X amount in script

I have my mocha command to execute in Node configured in my package.json file

**"NightBuildRegretionExecution":** "mocha ./Test/**/test.js --timeout 100000 --parallel --reporter mochawesome --require mochawesome/register"

My script it’s used in GITHUB actions to configure the job.

Now I want to tell in this script to run the test case 100 times for example.

Is there any property in Mocha framework that allow me to define this on the script?

Cannot decode Home Assistant WebSocket data with node.js

This is a question specifically related to the Home Assistant system.

I’m trying to look up messages sent and received on WebSocket interfaces between frontend and the backend of Home Assistant. For this purpose I built a very basic HTTP proxy using node.js.

I manage to succesfully record the data sent and received on this WebSocket, but it’s not decodable.

The code:

var http = require('http')
var httpProxy = require('http-proxy');

var proxy = new httpProxy.createProxyServer({
    target: {
        host: 'localhost',
        port: 8123
    }
});

var proxyServer = http.createServer(function (req, res) {
    console.log("Request Received");
    proxy.web(req, res);
});

proxyServer.on('upgrade', function (req, socket, head) {
    console.log("WS Upgrade Request Received");
    proxy.ws(req, socket, head);
    socket.on('data', function(data) {
        console.log('Data sent through WebSocket:', Buffer.from(data).toString());
        console.log('Data sent through WebSocket (JSON):', JSON.stringify(data, true, 2));
        console.log('Data represented as data to string: ', data.toString());
        // exception thrown
        //console.log('Data through JSON.parse(): ', JSON.parse(data));
        // exception thrown
        //console.log('Data represented as buffer: ', JSON.parse(Buffer.from(data)).toString());
    });
});

The problem is that it looks like the data I’m capturing here through the above function is not JSON decoded.

This is an example of output I’m getting:

Data sent through WebSocket: ��F��
Data sent through WebSocket (JSON): {
  "type": "Buffer",
  "data": [
    138,
    128,
    31,
    70,
    156,
    143
  ]
}
Data represented as data to string:  ��F��

According to the Home Assistant WebSocket documentation here: “Each API message is a JSON serialized object containing a type key.”, so the above code shouldn’t show this garbage. Or am I doing something wrong here?

I tried various JSON/Buffer decoding functions as documented above in the socket.on() function, but with no success.

JavaScript dialog delete error in Laravel 9

I want to create a confirmation dialog in JavaScript before deleting an item.

My JavaScript code

function confirmerSuppression() {
        var confirmation = confirm("Êtes-vous sûr de vouloir supprimer cet élément ?");

        if (confirmation) {
            window.location.href = '/tiers.destroy/' + id; // 
        } else {
            alert("Suppression annulée !");
        }
    }

Code for my delete button

<form action="{{route('tiers.destroy', $tiers->id)}}" method="POST">
@csrf  
<button onclick="confirmerSuppression()" class="btn btn-danger w-100 type="submit">DELETE</button>                                 
</form>

My route:

Route::post('/tiers/details/{id}', [AppHttpControllerstiersController::class, 'destroy'])->name('tiers.destroy');

My controller :

public function destroy($id)
    {
        Tier::where("id","=",$id)->delete();
        return redirect()->route('prospects.liste')->with("success","Tier supprimée avec succès.");
    }

When I click on the DELETE button the dialog appears and when I click on Cancel it deletes the element the same when I click on Yes.

Anyone have an idea please.

Set default bootstrap theme mode for print mode

Bootstrap allows theming via setting the data-bs-theme attribute on the body or parent element. All this works well, but we found that when light mode is the best for printing. Rather than write a whole set of styles for printing in dark mode, I wrote some stopgap JavaScript code that switches to light mode before any print operation and then switches back to the previous mode after the user begins printing.

This works, but it’s not the best user experience. In Chrome in particular the switch between light and dark modes while the print modal is open can be jarring.

Is there a better approach here between using JavaScript to catch the event and writing a whole new set of CSS just for printing in dark mode?

Storing Image with PHP

  1. Front-End (Client-Side):

    • I have a web application, built using JavaScript and a front-end framework: React.

    • Users have the ability to choose a profile picture file through a file input field on the website.

  2. Uploading Profile Picture (Client to Server):

    • I am sending the selected profile picture file from the client-side to a server-side script using a POST request.

    • The client-side code constructs a FormData object and appends the selected file and relevant data (e.g., username) to it.

  3. Server-Side Script (PHP):

    • On the server, I have a PHP script (storePFP.php) that handles the incoming POST request.

    • The PHP script processes the received data, including the username and the profile picture file, using the $_FILES and file_get_contents('php://input') methods.

    • The server script checks if the user exists in the database and, if found, generates a unique filename for the profile picture, moves the uploaded file to a designated directory, and records the picture details in the database.

  4. Debugging and Logging:

    • I’ve implemented error logging and debugging statements in my PHP script to log information such as received JSON data, headers, files, and query results.

    • I was checking for potential issues, such as invalid request data, undefined variables, or database query failures.

  5. Issues and Questions:

    • I’ve encountered some issues related to undefined variables ($uploadDirectory, $result) and database query results not being as expected.

    • I’ve explored and provided debug information through error logs.

  6. Alternative Storage:

    • I’m considering whether it’s possible to store the profile pictures on another public API.
const handleProfilePictureUpload = async (e) => {
    e.preventDefault();
    const fileInput = document.querySelector('#fileInput');
    const file = fileInput.files[0];

    // Check if a file was selected
    if (!file) {
      setMessage('Please select a profile picture to upload.');
      return;
    }

    // Check if the file type is supported (gif, png, or jpg)
    const allowedFileTypes = ['image/gif', 'image/png', 'image/jpeg', 'image/jpg'];
    if (!allowedFileTypes.includes(file.type)) {
      setMessage('Invalid file type. Please select a GIF, PNG, JPG or JPEG image.');
      return;
    }

    // Set the URL of the API endpoint
    const url = 'http://localhost:80/storePFP.php';

    try {
      // Create a FormData object to send the file
      const formData = new FormData();
      formData.append('username', user.username);
      formData.append('profilePicture', file);
      console.log(formData.get('profilePicture'));

      // Call the API to upload the profile picture
      const response = await fetch(url, {
        method: 'POST',
        body: formData,
        
      });
    
      const data = await response.json();
      console.log(data);

      // Check if the response is successful
      if (response.ok) {
        // Set the message based on the response data
        setMessage(data.message);
      } else {
        // Set the error message from the response
        setMessage(data.message || 'An error occurred while uploading the profile picture.');
      }
    } catch (error) {
      // Log and display a generic error message if an exception occurs during the API call
      console.error('Error uploading profile picture:', error);
      setMessage('An error occurred while uploading the profile picture.');
    }
  };

// HTML returned code
    <form onSubmit={handleProfilePictureUpload}>
      <label>
        Select Profile Picture:
        <input
          type="file"
          accept="image/gif, image/png, image/jpeg, image/jpg"
          id="fileInput"
          name="ProfilePicture"
        />
      </label>
      <button type="submit">Upload</button>
    </form>
<?php
header("Access-Control-Allow-Origin: http://localhost:3000");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type");
$json_data = file_get_contents('php://input');
$data = json_decode($json_data, true);

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$uploadDirectory = __DIR__ . "/profile_pictures/";


if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($data['username']) && isset($_FILES['profilePicture'])) {
        $username = $data['username'];
        $profilePicture = $_FILES['profilePicture'];
        
        // Check if the user exists
        $stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
    

        $stmt->bind_param("s", $username);
        $stmt->execute();
        $result = $stmt->get_result();
        

        if ($result->num_rows > 0) {
            // Generate a unique filename for the profile picture
            $filename = uniqid() . '_' . $profilePicture['name'];
            $destination = $uploadDirectory . $filename;

            // Move the uploaded file to the specified destination
            if (move_uploaded_file($profilePicture['tmp_name'], $destination)) {
                // Insert the picture details into the "pictures" table
                $insertStmt = $conn->prepare("INSERT INTO profile_pictures (filename, filetype, userid) VALUES (?, ?, ?)");
                $filetype = pathinfo($destination, PATHINFO_EXTENSION);
                $userid = $result->fetch_assoc()['id'];
                $insertStmt->bind_param("ssi", $filename, $filetype, $userid);
                $insertStmt->execute();

                if ($insertStmt->affected_rows > 0) {
                    $response = [
                        'success' => true,
                        'message' => 'Profile picture uploaded and saved successfully',
                    ];
                } else {
                    // Delete the uploaded file if the database insertion fails
                    unlink($destination);

                    $response = [
                        'success' => false,
                        'message' => 'Failed to save profile picture',
                    ];
                }

                $insertStmt->close();
            } 
        } 
    } else {
        $response = [
            'success' => false,
            'message' => 'Invalid request data',
        ];
    }
} else {
    $response = [
        'success' => false,
        'message' => 'Invalid request method',
    ];
}

$conn->close();
header('Content-Type: application/json');
echo json_encode($response);
?>

{“success”:false,”message”:”Invalid request data”}

Yes, I checked if the paths (destinationPath) are correct
From the log “Invalid request data i get that the else case “

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($data['username']) && isset($_FILES['profilePicture'])) {

ELSE:
occured

the console.log(formData) returned:

1.
File

  1. lastModified: 1703941829454

  2. lastModifiedDate: Sat Dec 30 2023 14:10:29 GMT+0100 (Mitteleuropäische Normalzeit) {}

  3. name: “361273270047920240_1595864818.jpg”

  4. size: 7197

  5. type: “image/jpeg”

  6. webkitRelativePath: “”

  7. [[Prototype]]: File

React Native app doesn’t lock the screen when app is left open

I have React Native app and it doesn’t lock the screen when app is inactive. The application doesn’t lock the screen after inactivity.

Tell me please the reasons for this problem and how it can be solved. This is my activity in AndroidManifest.xml:

      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:exported="true"
        android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"
        android:launchMode="singleTask"
        android:screenOrientation="portrait">

Is there a way to do a stacked bar chart in Chart.js with a secondary dataset overlaid?

It is difficult to explain so hopefully the images will clarify my question. I currently have a bar chart to display revenue by month where each dataset is for a different year. The client would like me to overlay each bar with their expenses for that year/month combo (see the black portions in the second image). Is it even possible to do this in Chart js? I’m struggling to visualize the structure of how the data would need to look. Thanks

revenue chart

revenue with expenses chart

How to Improve Logical Thinking? [closed]

Struggling to learn JavaScript

I already learn HTML and CSS which is not that difficult. But when I started learning JS it’s like I hit a dead end, although I’m learning something new everyday but when I encounter or think of a problem I don’t know how should I response and solve it. Also I often wonder how I will use diffrent methods in JS in real life projects. I want to improve how I think.

Bulk download in Aura lightning component

I am looking for bulk download functionality but not able to do it, please help me. I am trying to download records, if I select all the records from checkboxes.

Here I am using handleMassDownload for downloading records in below. I need to download all the files from table in zip format. Please help me out on above problem statment.
Here is my code:

<table class="slds-table slds-table_cell-buffer slds-table_bordered" aria-label="Example default base table of Opportunities">
<thead>
<tr class="slds-line-height_reset">
<th class="" scope="col">
<!---->
<lightning:input type="checkbox" aura:id="headerCheckbox" checked="{!v.isHeaderChecked}" name="headerCheckbox" onchange="{!c.headerCheckHandler}"/>
</th>

<th class="" scope="col">
<div class="slds-truncate" title="Decision">Decision</div>
</th>
<th class="" scope="col">
<div class="slds-truncate" title="Title">Title</div>
</th>
<th class="" scope="col">
<div class="slds-truncate" title="Type">Type</div>
</th>
<th class="" scope="col">
<div class="slds-truncate" title="Upload Date">Upload Date</div>
</th>

<th class="" scope="col">
<div class="slds-truncate" title="Owner">Owner</div>
</th>
<th class="" scope="col">
<div class="slds-truncate" title="Actions">Actions</div>
</th>
</tr>
</thead>

<tbody>
<aura:iteration items="{!v.documentList}" var="doc" indexVar="indx">
<tr  class="slds-hint-parent">
<td  class="slds-truncate">
<lightning:input type="checkbox" name="{!indx}" value="{!doc.Id}" aura:id="inputCheckbox" onchange="{!c.handleCheckboxChange}"/>
</td>
<td  class="slds-truncate">
<lightning:icon iconName="utility:success" size="small" />
<aura:set attribute="else">
<aura:if isTrue="{!doc.Decision__c == 'Rejected'}">
<lightning:icon iconName="utility:error" size="small" />
<aura:set attribute="else">
<lightning:icon iconName="utility:warning" size="small" />
</aura:set>
</aura:if>
</aura:set>
</aura:if>-->
</td>
<td  class="slds-truncate">
<a href="javascript:void(0);" onclick="{!c.navigateToAppPage}" data-record-id="{!doc.Id}">{!doc.Name}</a>
</td>
<td  class="slds-truncate">{!doc.DocumentType__c}</td>
<td  class="slds-truncate">{!doc.Upload_Date__c}</td>
<td  class="slds-truncate">{!doc.Owner.Name}</td>
<td  class="slds-truncate" >
<lightning:button label="Delete" iconName="utility:delete" onclick="{!c.handleDelete}" variant="destructive" value="{!doc.Id}" />
<lightning:button label="Download" iconName="utility:download" onclick="{!c.handleDownload}" value="{!doc.Id}" />
</td>
</tr>
</aura:iteration>
</tbody>
</table>
({
    doInit: function(component, event, helper) {
        helper.refreshDocumentList(component);
    },
    
    
    handleMassDownload : function(component, event, helper){
         let navService = component.find( "navService");
        let documentList = component.get('v.documentList');
        let docId = event.getSource().get('v.value');
        console.log('docId: ' + docId);
        
        let cvId = '';
        console.log('documentList: ', documentList); 
        
        documentList.forEach(function(item) {
            console.log('item.Id: ', item.Id);             
            if (item.Id == docId) {
                
                console.log('IF Match found!');
                cvId = item.ContentVersionId__c;
            }
        });
        
        console.log('cvId: ' + cvId);
        let filesDownloadUrl = '/sfc/servlet.shepherd/version/download/' + cvId;
        console.log('filesDownloadUrl : ' + filesDownloadUrl);
        let pageReference = {
            type: 'standard__webPage',
            attributes: {
                url: filesDownloadUrl
            }
        };
        navService.navigate(
            pageReference
        );
    },
    headerCheckHandler: function(component, event, helper) {
        var headerCheckbox = component.find("headerCheckbox");
        var checkboxes = component.find("inputCheckbox");
        
        if (!Array.isArray(checkboxes)) {
            checkboxes.set('v.checked', headerCheckbox.get('v.checked'));
        } else {
            checkboxes.forEach(function(checkbox) {
                checkbox.set('v.checked', headerCheckbox.get('v.checked'));
            });
        }
    },
    
    handleCheckboxChange: function(component, event, helper){
        let selectedDocId = [];
        let count = 0;
       // let name = event.getSource().get('v.name');
        let findAllInput = component.find('inputCheckbox');
        component.set('v.isHeaderChecked',false);
        console.log('findAllInput : ' + findAllInput.length);
        //console.log('name : ' + name);
        //let isChecked = findAllInput[name].get('v.checked');
        
        for(let i=0; i<findAllInput.length; i++){
            let isChecked = findAllInput[i].get('v.checked');
            if(isChecked){
                count++;
                selectedDocId.push(findAllInput[i].get('v.value'));
            }
        }
            /*if(count == findAllInput.length){
                component.set('v.isHeaderChecked',true);
            } else {
                component.set('v.isHeaderChecked',false);
            }*/
        component.set('v.isHeaderChecked', count === findAllInput.length);
        component.set('v.selectedDocId', selectedDocId);
        
        console.log('selectedDocId : ' + selectedDocId);
    },
    
    handleDownload: function(component, event, helper) {
        let navService = component.find( "navService");
        let documentList = component.get('v.documentList');
        let docId = event.getSource().get('v.value');
        console.log('docId: ' + docId);
        
        let cvId = '';
        console.log('documentList: ', documentList); 
        
        documentList.forEach(function(item) {
            console.log('item.Id: ', item.Id);             
            if (item.Id == docId) {
                
                console.log('IF Match found!');
                cvId = item.ContentVersionId__c;
            }
        });
        
        console.log('cvId: ' + cvId);
        let filesDownloadUrl = '/sfc/servlet.shepherd/version/download/' + cvId;
        console.log('filesDownloadUrl : ' + filesDownloadUrl);
        let pageReference = {
            type: 'standard__webPage',
            attributes: {
                url: filesDownloadUrl
            }
        };
        navService.navigate(
            pageReference
        );
    },
    
    handleFileChange: function(component, event, helper) {
         component.set('v.isLoading',true);
        let selectedFiles = component.find("fileId").get("v.files");
        let selectedFile = selectedFiles[ 0 ];
        console.log('File Name is',selectedFile.name);
        component.set("v.fileName",selectedFile.name);
        console.log('File Size is',selectedFile.size);
        let objFileReader = new FileReader();    
        objFileReader.onload = $A.getCallback( function() {
            let fileContent = objFileReader.result;
            let base64 = 'base64,';
            let dataStart = fileContent.indexOf( base64 ) + base64.length; 
            fileContent = fileContent.substring( dataStart );
            helper.processFileUpload( component, fileContent, selectedFile );
        } ); 
        objFileReader.readAsDataURL(
            selectedFile 
        );
        //helper.uploadFiles(component, files);
    },
    navigateToAppPage: function(component, event, helper) {
        //alert('navigateToAppPage');
         // Get the record Id from the data-record-id attribute
        var recordId = event.currentTarget.dataset.recordId;
        //alert('recordId'+recordId);

        // Use the navigation service to navigate to the app page
        var navService = component.find("navService");

        var pageReference = {
            type: "standard__app",
            attributes: {
                appTarget: "TEST_PAGE_2" 
            },
            state: {
                recordIds: recordId
            }
        };

        navService.navigate(pageReference);
    }
})

I have inherited code which includes Javascript/AJAX to display a progress bar – I can’t understand how it works

I have inherited the maintenance/development of a website. In a few places it makes use of Javascript/AJAX to display a progress bar while processing takes place. I have written my own scripts for extracting database records and I want to display a progress bar while this takes place.

I can’t understand how the Javascript component works. When I use it the progress bar immediately shows 100% but this is before any processing takes place. I can’t work out how to change this and to call the script functions at various stages in the processing. I have attached my PHP script and the Javascript script so you can see what I am working with.

My extract process is in two parts. The first part displays my standard web page structure and simply asks the user to hit the Extract button. This invokes the upload_image script when the user clicks the button and then ‘chains’ to the PHP script that actually extracts the sightings records.

<?php
/* export_sightings.php
Export all sightings records from cbcrecords as CSV file
*/

require_once($_SERVER['DOCUMENT_ROOT'] . '/inc/standard_page_start.php');
?>

<!-- ================================ -->
<!-- ***** MAIN CONTENT START ***** -->

<section class="main-container padding-bottom-clear">
<div class="container">
    <div class="row">
        <div class="main col-12">
            <h3 class="title">Export sightings to CSV</h3>
            <div class="separator-2"></div>
            <p>Use this tool to extract sightings data to a CSV which will be sent to you by email.</p>
        </div>
    </div>

    <div class="row">
        <div class="main col-12">
            <form action="src/export_sightings.php" 
                  id="myForm" 
                  name="frmupload" 
                  method="post" 
                  enctype="multipart/form-data">
                    <input type="submit" 
                           name='startextract' 
                           class="submit-button btn btn-sm btn-default" 
                           value="START EXTRACT"  
                           onclick='upload_image();'/>
            </form>

            <div class="progress" id="progress_bar">
            <div class="bar" id="bar"><p class="text-white text-center">extracting the data...<br><br></p></div>
            <div class="percent" id="percent">0%</div>
            </div>

            <p class="text-danger mt-4"><i class="fa fa-warning"></i> Please wait for the yellow confirmation box to appear below once you have clicked 'START EXTRACT'. Depending upon the number of records to be extracted, this may take a while!</p>

            <div class="output_image" id="output_image"></div>


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

<!-- ***** MAIN CONTENT END ***** -->
<!-- ================================ -->

<?php include 'inc/standard_page_end.php'; ?>

Here is the Javascript script progress.js

function upload_image() 
{
  console.log('Hit the progress.js scritpt');
  var bar = $('#bar');
  var percent = $('#percent');
  $('#myForm').ajaxForm({
    beforeSubmit: function() {
      document.getElementById("progress_bar").style.display="block";
      var percentVal = '0%';
      bar.width(percentVal)
      percent.html(percentVal);
    },

    uploadProgress: function(event, position, total, percentComplete) {
      var percentVal = percentComplete + '%';
      bar.width(percentVal)
      percent.html(percentVal);
    },

  success: function() {
      var percentVal = '100%';
      bar.width(percentVal)
      percent.html(percentVal);
      console.log(percentVal);
    },

    complete: function(xhr) {
      if(xhr.responseText)
      {
        document.getElementById("output_image").innerHTML=xhr.responseText;
      }
    }
  }); 
}

It looks to me (in my very limited experience) as though I should be able to call uploadProgress and success separately but I can’t work out how to do that. It seems at the moment as though these two functions are self executing.

I looked in detail at the other two parts of the website that use the progress bar but I can’t find any calls to the function other than in the core script progress.js

Chai assertion includes or for string

I am trying to traverse through a list of elements and want to assert that the body includes either of the 2 values.
I am trying to use the following but it only lets me assert one value.

expect(cellText).includes(toDateFormat);

How can I make an assertion that allows me to assert multiple values having OR condition?

How do I timeout someone with a twitch bot (client.timeout and client.say(channel, `/timeout @${tags.username} dont work)?

I can’t ban or timeout users with a Twitch chatbot who write certain words in js. However, I can send messages with the bot.

My code:
client.on(‘message’, async (channel, tags, message, self) => {
if (self) return;

console.log(`${tags['display-name']}: ${message}`);
console.log(tags.username)



const forbiddenWords = ['test1', 'test2', 'test3'];
for (let i = 0, len = forbiddenWords.length; i < len; i++) {
    if(forbiddenWords[i] == message){
        const timeoutReason = `Explicit language: ${message}`;
        client.timeout(channel, tags.username, 10, timeoutReason);
        client.say(channel, `You got timeout for using explicit language! @${tags.username}`);
        console.log(`${tags.username} has been timeouted for: "${message}"!`);
      }
  }

});

I recently tried to create a Twitch ChatBot and ran into a problem with bans and timeouts. I created an oauth token on https://twitchapps.com/tmi/ but am having either permission issues or the two methods:
const timeoutReason = Explicit language: ${message};
client.timeout(channel, tags.username, 1your text0, timeoutReason);
and:
/client.say(channel, `/timeout @${tags.username} 10
do not work anymore.

EEither the person who should be banned is not blocked or I get this error:
node:internal/process/promises:289
triggerUncaughtException(err, true /* fromPromise */);
^

[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason “No response from Twitch.”.] {
code: ‘ERR_UNHANDLED_REJECTION’
}

Create URL to unloaded mock-image in browser to simulate actual loading

In short, I would like to create a lazy-loaded-mock-image-src-url in browser. This is in order to simulate the loading of an image, to see how it loads.

Here is how I would like the flow to work, all done in-browser.

  1. Create a URL using URL.createObjectURL, canvas.toDataURL or similar, where the actual image that the returned url refers to, is not loaded yet (just like a real scenario).
  2. Pass the returned url that refers to the unloaded image to an html-img-tag.
  3. The image does not (visibly) load in the html-img-tag.
  4. Trigger a load of the image (that the url refers to) (preferably using some JS function) after some delay.
  5. The actual image is (visibly) shown in the html-img-tag.

I have managed to create a src string in the browser that refers to an image, that is passed to an html-img-tag, BUT the image loads instantly.

const canvas = document.createElement('canvas');
// ...create the image using getContext, fillRect etc...
const url = canvas.toDataURL('image/png');

How can I make sure the image that the url refers to is not loaded initially?

Is it better to use URL.createObjectURL or some other method instead?

Is it at all possible?


PS. I don’t want to edit the html-img-tag, using onload method as the img is a 3rd party component.

Why is it always undefined(when the request has no parameters and no geolocation search (lat and lng),it works

export const fetchIataViaGeo = createAsyncThunk(
  'iata/fetchIataViaGeo',

  async () => {
    const error = () => {
      alert('Sorry, we could not find your location. Please enter manually.');
    };
    const succuess = async (position) => {
      const lat = position.coords.latitude;
      const lng = position.coords.longitude;
      const res = await axios.get(
        `https://airlabs.co/api/v9/nearby?lat=${lat}&lng=${lng}&distance=45&api_key=...`
      );
      console.log(res.data.response.airports);
      return await res.data.response.airports;
    };
    navigator.geolocation.getCurrentPosition(succuess, error);
  }
);

This may be due to the fact that I’m returning it in the wrong place, but I don’t understand where it’s needed.when i try it without geolocation request,it work well