PhpWord generates paragraph breaks in addhtml

I am using PHPWord from within PHP to generate a word docment. I do use addHtml to transform some Mysql text containing multiple lines into a Word paragraph.

My input text contains:

<pre>
Lorem ipsum dolor sit amet, 
&lt;span style="font_weight:bold"&gt;consectetur adipiscing elit.&lt;/span&gt;
Quisque pretium mi a risus interdum, eu mollis nulla viverra. 
</pre>

Each line is separated with a carriage return (n). I tried to process the lines one by one (adding a n for each line, or use the complete text, result is the same.
Whatever I use (nl2br or str_replace) to transform the n into &lt;br /&gt; before handling addHtml generates:

Meaning a double paragraph separator instead of a single line separator.

How can this be solved? Or is this a known issue?

Best way to implement User Progress and Tracking their Progress? [closed]

I have a website where there are many users. There are some training involved. When users first start using the website (newbies).

I would like to lock or hide certain parts of the website or simply grey out the buttons UNTIL user has done the training module for that section before using that feature.

What is the best way to implment this type of structure?

There is not just a few sections. Also users may skip a module and do a different learning module first and do it in different order. So there is not ordered level number.

E.g. User might do learning Module A, B, C, E and F, M and O

So I would like to unlock / unhide features A B C, E and F. M and O feature. But for example Feature D would be greyed out or not available to them.

Also would it affect page load speed if I am checking all the time making a call to the database if they user has done the module or not? Would I user another field to store a true or false boolean?

I don’t wanna have a large table with heaps and heaps of fields just to store true or false 🙁 or this is industty standard?

Summary of Challenges:
There could be a large number of learning modules.
I wanna only unlock that part of the website after they have done the module.
By the end majority of all users would have done all the learning modules in the end.
I don’t want the website to be very slow for page load speed checking this for regular users.

What’s the best way to go about it? Or should I just have a level number. Where their level is the highest module that they have completed that doesn’t skip a module. e.g. Module A, B, C, E and F, M and O So even thou they have completed higher modules their level is only level 3 since they only completed A B and C?

I haven’t tried anything. I only began thinking about this design and thinking about the problem.

I would like to get insight on how profressional programmers would tackle this problem.

What database structure would you use?

What is the correct context to consume a RabbitMQ broker within the PHP/laravel ecosystem?

Well, to give you some context. We have a system that captures telemetry data in real time. The broker we hire sends telemetry data in real time from the device they place inside our cars. This operation has been running for two years, but we’ve been trying to troubleshoot and improve it for two years.

It turns out that after fixing numerous flaws, we started comparing what leaves their broker with what arrives at our database. We noticed that some packets simply don’t arrive, either in the data lake (raw message) or in the processed database. So we added more logs and started investigating. I noticed recurring Queue Error: Broken Pipe Or Closed Connection errors. But at the same time, when we see this error and go to the database, packets still arrive, so the consumer doesn’t crash and stop acquiring packets, losing that one. We set no_ack to true because we use the consumer in the Laravel schedule, running with cron 8x daily. And setting no_ack to false would trigger a race condition for the packet that ended up giving an error.

I’d like to know what’s the best context for the consumer? Should it run in the supervisor, with auto-restart policies and running 100% in the background?

    $schedule->command('pad:cron')->weekdays()->daily();
    
            $schedule->command('x:consumir')->cron('00 04 * * *');
            $schedule->command('x:consumir')->cron('00 07 * * *');
            $schedule->command('x:consumir')->cron('00 10 * * *');
            $schedule->command('x:consumir')->cron('01 12 * * *');
            $schedule->command('x:consumir')->cron('0 15 * * *');
            $schedule->command('x:consumir')->cron('0 17 * * *');
            $schedule->command('x:consumir')->cron('00 20 * * *');
            $schedule->command('x:consumir')->cron('00 00 * * *');

if run command on server – px aux | grep “x:consumir”

1195277  0.0  0.0   7124  3200 ?        S    00:00   0:00 sh -c '/usr/bin/php' 'artisan' x:consumir > '/dev/null' 2>&1
1195278  0.5  0.4 277348 66736 ?        S    00:00   3:56 /usr/bin/php artisan x:consumir
1199299  0.0  0.0   7124  3328 ?        S    04:00   0:00 sh -c '/usr/bin/php' 'artisan' x:consumir > '/dev/null' 2>&1
1199300  0.7  0.4 277352 67100 ?        S    04:00   3:38 /usr/bin/php artisan x:consumir
1203839  0.0  0.0   7124  3328 ?        S    10:00   0:00 sh -c '/usr/bin/php' 'artisan' x:consumir > '/dev/null' 2>&1
1203840  1.2  0.4 277360 66964 ?        S    10:00   1:45 /usr/bin/php artisan x:consumir
1310719  0.0  0.0   7124  3328 ?        S    12:01   0:00 sh -c '/usr/bin/php' 'artisan' x:consumir > '/dev/null' 2>&1
1310720  0.9  0.4 277360 64436 ?        S    12:01   0:11 /usr/bin/php artisan x:consumir
1332376  0.0  0.0   6436  2432 pts/1    S+   12:21   0:00 grep --color=auto x:consumir

And this is the method to create the consumer:

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle(){
        try{
            $connection = new AMQPStreamConnection('xxx.xxx.xxx', xxxx, env('user_rabbit'), env('password_rabbit'),'/', env('parameter1_rabbit'), 'AMQPLAIN', null, 'en_US', 3.0, 30.0, null, false, 60, 0);
            $channel = $connection->channel();

            echo " [*] Waiting for messages. To exit press CTRL+Cn";

            $callback = function ($msg) {
                
                $retorno = json_decode($msg->body);
                //dd($retorno);
        
                $this->processar($retorno);
                
            };

            $channel->basic_consume(env('user_rabbit'), '', false, true, false, false, $callback);
            //consumer_tag =
            //no_local=
            //no_ack = this is true
            //exclusive =
            //nowait =

            while ($channel->is_consuming()) {
                $channel->wait();
            }

            $channel->close();
            //$connection->close();
            return true;
        }catch(Throwable $e){
            Log::debug('QUEUE ERROR: ' . $e->getMessage());
            Log::debug($e->getTrace());
            return true;
            //dd("parar2");
        }
    }

What do you say? Where else can I look? I must say the accuracy of the data is about 80%. But we need to get to at least 95%.

How can I split a full webpage screenshot into separate UI blocks (PHP library or API)? [closed]

Does anyone know tools that can take a full-page website screenshot and automatically split it into logical UI blocks (hero, header, cards, footer, etc.) and return each block as a separate image segment?

Ideally I’m looking for either:

  • a PHP library I can run on my server, or
  • an online service with an API (paid is fine)

image explanation

I did some research but, unfortunately, couldn’t find any suitable tools.

Changing Delimeter of Multiple Items Returned by a osascript/javascript File Select Dialog

I have a little zsh script I’m coding to run on MacOS. Been a bash/shell scripter for 25+ years, so it hasn’t been all bad. Part of its function is to have the user select a file (or files) from a dialog using this little bit of osascript/javascript:

IMAGES="$(osascript -l JavaScript -e 'a=Application.currentApplication();a.includeStandardAdditions=true;a.chooseFile({withPrompt:"Select Image(s)",multipleSelectionsAllowed:"true"}).toString()')"

The selected files (three in this example) get dumped into the $IMAGES variable with a comma between each of them.

/Users/anderson/Pictures/1890-1899/1898/5-3-1898 John Gansemer & Lena Gansemer (nee Koltes).jpg,/Users/anderson/Pictures/1890-1899/1898/1898 Hans, Mary Anderson Wedding Photo 600dpi.jpg,/Users/anderson/Pictures/1890-1899/1898/1898 Hans. Mary Anderson Wedding Photo.jpg

Is there a way to get the delimiter to be something else (a pipe or something similar) that is less likely to show up in file or folder names that I am grabbing?

I’ve found references across the interwebs to the following the toString with a “.join” function, but I can’t get the syntax right and/or might be barking up the wrong tree anyway.

Thanks,

Bill

Injecting invisible metadata to gmail emails fails for certain gmail account [closed]

I have a chrome extension which appends some base64 metadata to gmail emails before sending them (and keeps the base64 metadata invisible for the user).
This is done through InboxSDK, and works as a charm for every but single account.
Only the emails sent from this account, get base64 metadata stripped off.
It doesn’t appear neither when message is opened in inbox nor sent emails.

I tried following ways of injecting it:

1)
<div style='display:none!important; mso-hide:all; max-height:0; overflow:hidden; font-size:1px; line-height:1px;' class='spx-meta'>${base64Metadata}</div>

2)
<img src="https://yourdomain.com/pixel.gif?policy=${base64Metadata}" width="1" height="1" style="display:none;" alt="">

3)
<span style="color:#ffffff;font-size:1px;">${base64Metadata}</span>

Each of these work on other accounts, but this one sanitizes it for some reason and completely removes it.
Any proven way to send data in email this way?

javascript function force round up the decimal [duplicate]

I looking for java-script function that will force round up the decimal.

for example value = 12.23123 will round to 12.24 .

toFixed() not return the value I want .
I want something like math.ceil but not round up to nearest numeric but to nearest decimal

for example 5.561 , when round 2 decimal will return 5.57 not 5.56

How to preview an image before uploading it? [duplicate]

I’m trying to let users preview an image before uploading it to the server.
I have an HTML , and I want to show a small preview of the selected image right after the user selects it.

I tried using FileReader, but I’m not sure if I’m doing it correctly.
The image is not displaying, or sometimes I get an empty preview.

Here’s my code below. Can someone tell me what I’m doing wrong or how to properly preview an image before upload using JavaScript?

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Image Preview Before Upload</title>
</head>
<body>
  <h2>Upload and Preview Image</h2>
  <input type="file" id="imageInput" accept="image/*">
  <br><br>
  <img id="preview" src="" alt="Image Preview" width="200" style="display:none;">

  <script>
    const imageInput = document.getElementById('imageInput');
    const preview = document.getElementById('preview');

    imageInput.addEventListener('change', function(event) {
      const file = event.target.files[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
          preview.src = e.target.result;
          preview.style.display = 'block';
        }
        reader.readAsDataURL(file);
      }
    });
  </script>
</body>
</html>`

Injecting invisible metadata to gmail emails fails for certain gmail account

I have a chrome extension which appends some base64 metadata to gmail emails before sending them (and keeps the base64 metadata invisible for the user).
This is done through InboxSDK, and works as a charm for every but single account.
Only the emails sent from this account, get base64 metadata stripped off.
It doesn’t appear neither when message is opened in inbox nor sent emails.

I tried following ways of injecting it:

1)
<div style='display:none!important; mso-hide:all; max-height:0; overflow:hidden; font-size:1px; line-height:1px;' class='spx-meta'>${base64Metadata}</div>

2)
<img src="https://yourdomain.com/pixel.gif?policy=${base64Metadata}" width="1" height="1" style="display:none;" alt="">

3)
<span style="color:#ffffff;font-size:1px;">${base64Metadata}</span>

Each of these work on other accounts, but this one sanitizes it for some reason and completely removes it.
Any proven way to send data in email this way?

eBay Subscribe to itemSold notification with RESTful API

I am trying to subscribe to several eBay notifications (itemSold, fixedPriceTransactionEnd, etc.). The users backend server should be informed about every sale. So far I got stuck between the two APIs and tons of documentation but have not seen any other example than MARKETPLACE_ACCOUNT_DELETION. When I call getTopics I only get this along with ESP_test_APP topic. How can I subscribe to the aforementioned topics?

There is a similar unanswered question using the old API here. I am trying to use this SDK. I think they use the ebay api definitions.

2D Perlin Noise function is creating chopped-up uneven rows

I’ve gone about using a (from what I can tell) rather different implementation of 2D Perlin Noise described in this paper by the University of Cambridge:Appendix B – Perlin Noise But the function produces inconsistencies between rows:
Inconsistent 2D Perlin Noise

Here’s my code, just barebones JavaScript in HTML5:

<!-- I've been trying to make functional classic perlin noise for years and this is
     the closest I've come to achieving that goal.

I used this paper:
https://www.cl.cam.ac.uk/teaching/1718/FGraphics/Appendix%20B%20-%20Perlin%20Noise.pdf
-->

<!DOCTYPE html>
<html>
  <canvas id = "canvas" width = "512" height = "512"></canvas>
  
  <script>
    let canvas = document.getElementById("canvas");
    let context = canvas.getContext("2d");
    
    
    const n = 8;
    
    
    const rand_uVec = function () {
      const a = Math.random() * (Math.PI * 2.0);
      return {x: Math.cos(a), y: Math.sin(a)};
    }
    
    const seedArray = function () {
      let s = [];
      for (let x = 0; x < n + 1; x++) {
        s[x] = [];
        for (let y = 0; y < n + 1; y++) s[x][y] = rand_uVec();
      } return s;
    }
    
    const seed = seedArray();
    
    
    function PerlinNoise2D(x, y) {
      const s = Math.floor(x), t = Math.floor(y);
      
      /*
      * (s + 0, t + 0),
      * (s + 1, t + 0),
      * (s + 1, t + 1),
      * (s + 0, t + 1)
      */
      
      // define the grid cell corner coordinates
      const s0 = s + 0, t0 = t + 0,
            s1 = s + 1, t1 = t + 1;
      
      // get the random gradient vectors
      const v00 = seed[s0][t0],
            v10 = seed[s1][t0],
            v11 = seed[s1][t1],
            v01 = seed[s0][t1];
      
      // get the difference between the cell corner and sample point
      const d00 = {x: x - s0, y: y - t0},
            d10 = {x: x - s1, y: y - t0},
            d11 = {x: x - s1, y: y - t1},
            d01 = {x: x - s0, y: y - t1};
      
      
      const dot = function (v0, v1) {
        return v0.x * v1.x + v0.y * v1.y;
      }
      
      const UL = dot(v00, d00),
            UR = dot(v10, d10),
            LR = dot(v11, d11),
            LL = dot(v01, d01);
      
      
      const S = function (t) {
        return 3 * t ** 2 - 2 * t ** 3;
      }
      
      
      // the problem isn't that I'm using an existing x and y variable in these two functions
      const L = function (sx, sy) {
        return LL + S(sx - Math.floor(sx)) * (LR - LL);
      }
      
      const U = function (sx, sy) {
        return UL + S(sx - Math.floor(sx)) * (UR - UL);
      }
      
      
      return L(x, y) + S(y - Math.floor(y)) * (U(x, y) - L(x, y));
    }
    
    
    ImageData.prototype.fragColor = function (x, y, s) {
      this.data[(y * this.width + x) * 4 + 0] = s;
      this.data[(y * this.width + x) * 4 + 1] = s;
      this.data[(y * this.width + x) * 4 + 2] = s;
      this.data[(y * this.width + x) * 4 + 3] = 255;
    }
    
    let noiseTexture = context.getImageData(0, 0, canvas.width, canvas.height);
    for (let x = 0; x < canvas.width; x++) {
      for (let y = 0; y < canvas.height; y++)
        // noiseTexture.fragColor(x, y, Math.random() * 255);
        noiseTexture.fragColor(x, y, PerlinNoise2D(x * (n / canvas.width), y * (n / canvas.height)) * 255);
    } context.putImageData(noiseTexture, 0, 0);
    
    const dataURL = canvas.toDataURL('image/png');
    
    const link = document.createElement('a');
    link.href = dataURL;
    link.download = 'noise.png';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link); // Remove the temporary link
  </script>
</html>

I’ve seen problems like this before with other Perlin Noise functions on Stack Overflow, and I have tried changing around the order of some of the input coordinates, but usually the outcome is an even more chopped up noise graph, whereas I expected something with smoother results.

I would appreciate if any answers could follow the implementation of the paper I’m following, rather than the usually implementation with nested linear interpolation functions (I get that it’s the same concept, I just think mine looks more simplistic). I would also appreciate it if your answers could concern only the basest implementation of Perlin Noise without seed implementation/permutation tables. Thanks!

Browser back button exits Single Page App despite pushState() on Chrome only

I’m working on a legacy single-page application that uses AJAX to load different internal views. After recent browser updates the Browser Back Button stopped behaving as expected.

The current problem:

When the user clicks the Back button in Firefox, everything works as intended — the app restores the previous in-app view without leaving the page.

In Chrome, the first Back click correctly restores the previous in-app view but the second Back click always kicks the user out of the app and back to the login screen.

I’m already using history.pushState and listening to popstate to restore the internal content and re-push guard states when needed.
It seems like Chrome doesn’t honor the guard state or simply navigates past it.
I’ve tried:
-Unique hash fragments for every state
-Replacing the base state
-Re-pushing guard states in popstate

None of it seem to make a difference in Chrome.

function sendAction(action, content) {
  // Capture current dynamic content
  const section = document.querySelector('.content section.rows');
  const html = section ? section.innerHTML : '';

  // Push in-app navigation state
  const newUrl = window.location.href.split('#')[0] + '#' + encodeURIComponent(content);
  history.pushState({ html, content }, null, newUrl);
  
  // (Ajax content loading happens here)
}

// Back button handling
window.addEventListener('popstate', function(event) {
  const section = document.querySelector('.content section.rows');

  if (event.state && event.state.html && section) {
    // Restore previous HTML content
    section.innerHTML = event.state.html;
    event.preventDefault();
    return;
  }

  // Prevent leaving the app
  history.pushState({ guard: true }, null, window.location.href);
  event.preventDefault();
});

// Initialize base history state
if (!history.state) {
  const section = document.querySelector('.content section.rows');
  history.replaceState(
    { initialized: true, html: section ? section.innerHTML : '' },
    null,
    window.location.href
  );
}

Apps Script Trigger Won’t Update My Function

I was trying to write a function to find the sum of a set of values in one list referencing a specified value in another list. Kind of like trying to find the total amount of an item bought in a table full of items bought chronologically.

The code seems to work when I first implement it, but whenever I try to apply and test a trigger, it gives the same error:

JavaScript runtime exited unexpectedly

I could really use some help. Let me know if you need any more info.

function myFunction(range1, range2, value) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var value_list_1 = sheet.getRange(range1).getValues()
  var value_list_2 = sheet.getRange(range2).getValues()
  var new_value = 0
  var total_value = 0
  for (var i = 0; i < value_list_1.length; i++) {
    if (value_list_1[i] == value) {
      new_value = Number(value_list_2[i])
      total_value = total_value+new_value
    }
  }
  return(total_value)
}