Request for Help: Enhancing Script for Better Visual Presentation

is anyone here who can help improve my script? I want the results to be more visually presentable. Is is possible to include in HTML code?

function showAEdata() {
  var ui = SpreadsheetApp.getUi();
  var input = ui.prompt("Please enter your First Name and Last Name.", ui.ButtonSet.OK_CANCEL);

  if (input.getSelectedButton() == ui.Button.OK) {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var ws = ss.getSheetByName("Monitoring (Database)");
    var data = ws.getRange("A2:X" + ws.getLastRow()).getValues();
    var userSelectedRep = input.getResponseText().toLowerCase();

    var newData = data.filter(function (r) {
      return r[6].toLowerCase() == userSelectedRep;
    });

    var yearInput = ui.prompt("Please enter the year (e.g., 2024):", ui.ButtonSet.OK_CANCEL);

    if (yearInput.getSelectedButton() == ui.Button.OK) {
      var selectedYear = yearInput.getResponseText();
      var filteredYearData = newData.filter(function (r) {
        var date = new Date(r[5]);
        return date.getFullYear() == selectedYear;
      });

      var selectedColumns = filteredYearData.map(function (r) {
        return [r[1], r[2], r[4], r[5], r[9], r[10], r[11], r[17]];
      });

      if (filteredYearData.length > 0) {
        var newWs = ss.insertSheet(userSelectedRep);
        var headers = ["INSTITUTION", "MONTH", "JO NUMBER", "DATE RELEASED", "TYPE OF USER", "PLATFORM", "TYPE OF ACCESS", "NUMBER OF ACCESS CODE"];

        newWs.getRange(4, 3, selectedColumns.length, selectedColumns[0].length).setValues(selectedColumns);
        newWs.getRange(3, 3, 1, headers.length).setValues([headers]);

      } else {
        ui.alert("No matching data found for the entered year.");
      }
    } else {
      ui.alert("Year input canceled.");
    }
  } else {
    ui.alert("Operation Canceled.");
  }
}

This the current result of my Script I want to enhance it by using HTML etc.

enter image description here

javascript function inside loop doesnt works [closed]

for (sicocxle > 1; sicocxle--;) {
  console.log(sicocxle);
  srol();
};

var od = 0;

function srol() {
  var lem = document.getElementById("arrow");
  clearInterval(od);
  od = setInterval(aim, 10);

  function aim() {
    if (dos != -100) {
      dos--;
      dosl++;
      lem.style.top = dos + 'px';
      console.log(dos);
      lem.style.left = dosl + 'px';
    }
  }
}

i want this action to repeat itself aroow element to do same movement

for loop doesnt works its consol logs 9 8 7 6 5 meaning loop is working but function doesnt repeats itself

javascript function inside loop doesnt works [closed]

for (sicocxle > 1; sicocxle--;) {
  console.log(sicocxle);
  srol();
};

var od = 0;

function srol() {
  var lem = document.getElementById("arrow");
  clearInterval(od);
  od = setInterval(aim, 10);

  function aim() {
    if (dos != -100) {
      dos--;
      dosl++;
      lem.style.top = dos + 'px';
      console.log(dos);
      lem.style.left = dosl + 'px';
    }
  }
}

i want this action to repeat itself aroow element to do same movement

for loop doesnt works its consol logs 9 8 7 6 5 meaning loop is working but function doesnt repeats itself

.nodeColor() not updating node color for 3d-force-graph

i am having trouble changing the node color for my visualization using 3d-force-graph.

<head>
    <style> body { margin: 0; } </style>
  
    <script src="//unpkg.com/3d-force-graph"></script>
    <!--<script src="../../dist/3d-force-graph.js"></script>-->
  </head>
  
  <body>
    <div id="3d-graph"></div>
    
    <script type="importmap">{ "imports": { "three": "//unpkg.com/three/build/three.module.js" }}</script>
    <script type="module">

        const Graph = ForceGraph3D()
        (document.getElementById('3d-graph'))
          .jsonUrl('jsondata.json')
          .nodeColor('rgb(255, 255, 255)')
          .nodeLabel(node => `${node.name}`)
          .d3Force('link').distance(link => 1 / link.value * 30)
          
          
    </script>
  </body>

what do i need to change? i’ve tried clearing my browser’s cache too but it still doesn’t seem to update. here’s the link to the library i am using: https://github.com/vasturiano/3d-force-graph

.nodeColor() not updating node color for 3d-force-graph

i am having trouble changing the node color for my visualization using 3d-force-graph.

<head>
    <style> body { margin: 0; } </style>
  
    <script src="//unpkg.com/3d-force-graph"></script>
    <!--<script src="../../dist/3d-force-graph.js"></script>-->
  </head>
  
  <body>
    <div id="3d-graph"></div>
    
    <script type="importmap">{ "imports": { "three": "//unpkg.com/three/build/three.module.js" }}</script>
    <script type="module">

        const Graph = ForceGraph3D()
        (document.getElementById('3d-graph'))
          .jsonUrl('jsondata.json')
          .nodeColor('rgb(255, 255, 255)')
          .nodeLabel(node => `${node.name}`)
          .d3Force('link').distance(link => 1 / link.value * 30)
          
          
    </script>
  </body>

what do i need to change? i’ve tried clearing my browser’s cache too but it still doesn’t seem to update. here’s the link to the library i am using: https://github.com/vasturiano/3d-force-graph

API Fetch only updates one data, why [closed]

Friends, fetch api updates only once. I couldn’t find a solution for this. Can experienced friends help me? When the project runs, it updates only once, but it doesn’t update another product. I made a break point on the controller side. The products are coming successfully, but they don’t update.

text ticker stutters when resized on mobile

fairly new to css. I spent a long time trying to figure out how to do a nice smooth text ticker, and one that resizes neatly from desktop to mobile

The scroller is pulled in where “textticker” / “textticker” appears, and the JS is at the bottom.

It seems to generally work fine on desktop.

But when I try it on iPhone… the text scrolls, jitters, or suddenly starts over, breaking the smooth scroll effect. Any ideas how to fix?

body {
    background-color:;
  padding: 0px;
      margin:0px;
  font-family: 'Times New Roman', Times, serif
    font-size: 1.1rem;
    color: #333333; /* Set default text color to #333333 */
    line-height: 1;
    overflow-x: hidden;
   }

   .container {
    margin: 0px;
   width: 100%;
    background-color: #e5e5e5;
    padding: 0px;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column; /* Change flex direction to column */
    box-sizing: border-box; 
  }



/* product starts <<<<<<<<<<<<<<<<<<< */

/* Product container */
/* Product container */
.product-container {
  margin: auto;
  width: 100vw;
  height: 80svh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #e5e5e5;
  padding: 0px;
  border-bottom: 1px solid black;
  position: relative; /* Allows positioning of product-info */
}
/* Product inner */
.product-inner {
  margin: auto;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: flex-start; /* Align the product-image to the left */
  align-items: center; /* Vertically center the content */
  padding: 0px;
}




/* Flex container for product-stats and product-ticker */
.product-info {
  position: absolute; /* Keeps the container in the top right */
  top: 40px;
  right: 40px;
  display: flex;
  flex-direction: column; /* Stacks child elements vertically */
  width: 400px; /* Fixed width for both elements */
  gap: 10px; /* Adds space between the product-stats and product-ticker */
}


/* Product ticker */
.product-ticker {
  width: 100%; /* Takes full width of the flex container */
  border: 1px solid #333333;

  padding: 8px;
  margin: 0px;
  box-sizing: border-box;
  overflow: hidden;
  user-select: none;
  --gap: 5px;
  display: flex;
  gap: var(--gap);

  font-family: 'BookmanRoman';
  font-size: 1.1rem;
  color: black;
line-height: 1;
letter-spacing: -0.6px;
}

.product-ticker textticker {
  flex-shrink: 0;
  min-width: 100%;
  display: flex;
  gap: var(--gap);
  animation: scroll 30s linear infinite;
  box-sizing: border-box;
  margin: 0;
  padding: 0;
    font-family: 'BookmanRoman';
    font-size: 1.1rem;
    color: black;
  line-height: 1;
  letter-spacing: -0.6px;
}

@keyframes scroll {
  to {
    transform: translateX(calc(-100% - var(--gap)));
  }
}


    /* Outer table container */
    .outer-table-container {
      border: 10px solid white;
      width: 100%; /* Fixed width for the outer table */
      background-color: white;
      box-sizing: border-box;


    }


    /* Outer table styling */
    .outer-table {
      border-collapse: collapse;
      width: 100%; /* Ensure outer table takes up the full container width */
    }

    /* Outer table cells */
    .outer-table td {
      border: none;
      padding: 5px; /* Match the cellpadding of the inner table */
    }

   

     /* Button styling for the 'BUY NOW' button */
     .product-buy-now-btn {
      width: 100%;
      height: auto;
      background: silver; /* Green background */
      border-radius: 0px;
      padding-top: 10px;
      padding-bottom: 10px;
      color: blue;
      border: 2px solid blue; /* Blue border */
      cursor: pointer;
      text-align: center;
      vertical-align: middle;
      font-family: 'BookmanJF';
      letter-spacing: 0px;
      font-size: 1.3rem;
      text-decoration: underline;
    }

    /* Button hover effect */
    .product-buy-now-btn:hover {
      background-color: blue;
      color: white !important;
    }

    /* Styling for the link that wraps the button */
    .product-buy-now-link {
      display: block; /* Make the link fill the entire cell */
      text-decoration: none; /* Remove underline from the link */
    }



/* product ends <<<<<<<<<<<<<<<<<<< */


 






/* <<<<<<<<< MEDIA QUERIES <<<<<<<<< */
/* <<<<<<<<< MEDIA QUERIES <<<<<<<<< */
/* <<<<<<<<< MEDIA QUERIES <<<<<<<<< */

@media (width <= 768px) {



  /* Header section <<<<<<<<<<<<<<<< */

   


  /* product  <<<<<<<<<<<<<<<< */

    /* Product container */
    .product-container {
      width: 100vw;
      height: auto;
      display: flex;
      flex-direction: column; /* Ensure divs stack in mobile view */
      align-items: center;    /* Center items horizontally */
      justify-content: flex-start; /* Align items to the top */
      position: static;
       box-sizing: border-box;


    }

        .product-info {
          width: 100vw;
          height: auto;
          display: flex;
          flex-direction: column; /* Ensure divs stack in mobile view */
          align-items: center;    /* Center items horizontally */
          justify-content: flex-start; /* Align items to the top */
          position: static;
          box-sizing: border-box;
          gap: 0px;
    
        }
      
  
    /* Product inner */
    .product-inner {
      width: 100%;
      height: auto;
      display: flex;
      justify-content: center; /* Center horizontally */
      align-items: center; /* Center vertically */
      margin: auto;
      margin-top: 12svh;
      margin-bottom: 5svh;
      box-sizing: border-box;
    }


    /* Product stats */
    .product-stats {
      position: static; /* Keep it in the normal document flow */
      width: 100%;
      height: 100%;
      margin: 0; /* Ensure there's no extra margin pushing it */
      padding: 0;
      box-sizing: border-box;

    }

/* Product ticker */
.product-ticker {
  width: 100%; /* Takes full width of the flex container */
  border: 0px;
  border-radius: 0;
  background-color:;
  padding: 12px 5px;
  margin: 0px;
  box-sizing: border-box;
  border-top: 1px solid black;
}

  /* ends   <<<<<<<<<<<<<<<<<<<<<<<<< */

  }
  
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

 
</head>
<body>

 
  
    <div class="container" style="background-color: ;">



   <!-- Product -->
    <div class="product-container">
        <div class="product-inner">
        </div>

        <!-- New Flex Container for product-stats and product-ticker -->
        <div class="product-info">
            <div class="product-stats">
                <!-- Outer Table -->
                <div class="outer-table-container">
                    <table class="outer-table">
                        <tr>
                            <td>
                            
                            lorem ipsum text
                            </td>
                        </tr>
                        <tr>
                            <td>
                     
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <!-- Cell with clickable button styled link -->
                                <a href="https://example.com" class="product-buy-now-link" target="_blank">
                                    <button class="product-buy-now-btn">
                                            BUY NOW
                                    </button>
                                </a>
                            </td>
                        </tr>
                    </table>
                </div>
            </div>

            <!-- Ticker directly below the product-stats >> text in js at end-->
            <div class="product-ticker">
                 <textticker>
  </textticker>
    <textticker>
  </textticker>
            </div>
        </div>
    </div>

                  </div>


 




<!-- Smooth scroll script -->
<script>
    function smoothScroll(targetId) {
      const target = document.getElementById(targetId);
      if (target) {
        const targetPosition = target.getBoundingClientRect().top;
        const startPosition = window.pageYOffset;
        const distance = targetPosition - 50; // Optional offset for smoother position
        const duration = 2000; // Increased duration for slower scroll
        let start = null;

        // Easing function for smoother ease-in-out effect (Quartic)
        function easeInOutQuart(t, b, c, d) {
          t /= d / 2;
          if (t < 1) return c / 2 * t * t * t * t + b;
          t -= 2;
          return -c / 2 * (t * t * t * t - 2) + b;
        }

        // The animation loop
        function animation(currentTime) {
          if (start === null) start = currentTime;
          const timeElapsed = currentTime - start;
          const run = easeInOutQuart(timeElapsed, startPosition, distance, duration);
          window.scrollTo(0, run);
          if (timeElapsed < duration) requestAnimationFrame(animation);
        }

        requestAnimationFrame(animation);
      }
    }

    document.getElementById('shop-link').addEventListener('click', function(e) {
      e.preventDefault();
      smoothScroll('shop');
    });
  </script>


<script src="https://unpkg.com/aos@next/dist/aos.js"></script>
<script>
    AOS.init();
  </script>


<script>
    // Define the text content once
    const tickerText = "This is the text ticker. It mostly works ok on desktop and android, but stutters and skips on iphone &#8226; This is the text ticker. It mostly works on desktop and android, but stutters and skips on iphone &#8226;";

    // Find all <textticker> elements and insert the text content
    document.querySelectorAll('textticker').forEach(el => {
        el.innerHTML = tickerText;
    });
</script>
 

</body>
</html>

Chrome extension not interacting with search bar on UpToDate.com properly

Pharmacist and programming newbie here. I’m trying to make a chrome extension operate on the website UpToDate.com to utilize the drug interaction checker. It takes a block of text input from a user (copy+pasted from a med list) and then splits it into individual words separating by spaces. It then enters each word into the drug interaction search bar and enters the ‘return’ key (have tried with clicking the add button instead).

The problem is that when I run the extension it finishes with only the final word in the text input entered into the search bar with none of the previous drugs being successfully added to the interaction checker.

Here is my current js code (added some delays to see if that fixed with no luck):

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === 'userInput') {
      const words = request.data; // Receive the list of words

      const searchInput = document.querySelector('.search-input');

      words.forEach(async (word, index) => {
        searchInput.value = word; // Set the input value

        searchInput.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter' }));

        if (index < words.length - 1) { 
          await new Promise(resolve => setTimeout(resolve, 1500)); // Wait 1.5 seconds
        }
      });
    }
  });

  async function waitForElementToBeClickable(element) {
    return new Promise(resolve => {
      const interval = setInterval(() => {
        if (element && element.disabled === false && element.style.display !== 'none') {
          clearInterval(interval);
          resolve();
        }
      }, 100); 
    });
  }

Any help is much appreciated! Looking to improve time spent on patient care and spend less time with clerical work during reviews/audits

Knexjs pooling – set session variables for a connection

I’m working on a nodejs server using Knex.js to connect to a postgres DB.
On some of the tables I’ve set some RLS policies based on the current session values (app.user_id and app.tenant_id) to isolate data correctly.

I would like to be able to pass the userId and tenantId from my model/service methods to a db util method that grabs a pool connection, sets the session variables and returns the connection to be used (all in Knex ideally).

Currently I have the following:

const buildSetSessionQuery = ({userId, tenantId}) => {
    let queryString = "";
    if(userId) {
        queryString += format(`SET SESSION app.user_id=%L;`, userId);
    }

    if(tenantId) {
        queryString += format(`SET SESSION app.tenant_id=%L;`, tenantId);
    }

    return queryString;
};

exports.getUserConnection = ({userId, tenantId}={}) => {
    const conn = knex({
        client: 'pg',
        connection: getConfig(), // Assume this returns the correct connection config
        pool: {
            min: 0,
            max: 40,
            afterCreate: function (conn, done) {
                const setSessionQuery = buildSetSessionQuery({userId, tenantId});
                conn.query(setSessionQuery);
                done (null, conn);
            }
        }
    });

    return conn;
};

But this code creates a whole Knex pool for each query that’s executed (as opposed to grabbing an available pool connection from a single pool), which quickly exhausts the max_connections limit on my pg server.

Is there a way to make it so getUserConnection() returns a knex pool connection with the session variables set, so that I can use it easily like so:

exports.getData = async ({tenantId, userId}) => {
    const conn = db.getUserConnection({ tenantId, userId });

    const rows = await conn
        .select('*')
        .from('data')
        .orderBy([{
            column: 'timestamp',
            order: 'desc',
            nulls: 'last'
        }]);

    return rows;
};

number variable becoming a string even when parsefloat/int is used

I’m trying to make a little javascript game where you guess a hex code (yes the code currently tells you the hex answer that is so that I can get it wrong/right on purpose) I have a lot of variables with stupid names please don’t criticize on that I’ve had tons of problems with how my variable names are messing up my stuff in the past and so I changed them, basically the variables rar,rbr,gar,gbr,bar,bbr are all strings when I have multiple lines of code redefining them as numbers, I get zero errors in console and have no idea what is wrong. No I am not a profesional coding veteran, please don’t flame me for how awful my code is, I know.

 var ra = Math.floor(Math.random() * 16)
var rb = Math.floor(Math.random() * 16)
var ga = Math.floor(Math.random() * 16)
var gb = Math.floor(Math.random() * 16)
var ba = Math.floor(Math.random() * 16)
var bb = Math.floor(Math.random() * 16)

var raa = 0
var rba = 0
var gaa = 0
var gba = 0
var baa = 0
var bba = 0

var rac = 0
var rbc = 0
var bac = 0
var bbc = 0
var gac = 0
var gbc = 0

var rar= 0
var rbr= 0
var gar= 0
var gbr= 0
var bar= 0
var bbr= 0

var rag= 0
var rbg= 0
var gag= 0
var gbg= 0
var bag= 0
var bbg= 0



if (ra == 11){
raa = "A"
    } else if (ra == 12){
raa = "B"
    } else if (ra == 13){
raa = "C"
    } else if (ra == 14){
raa = "D"
    } else if (ra == 15){
raa = "E"
    } else if (ra == 16){
raa = "F"
    } else if (ra == 10){
raa = 0 }else {
raa = ra
    }

if (rb == 11){
rba = "A"
    } else if (rb == 12){
rba = "B"
    } else if (rb == 13){
rba = "C"
    } else if (rb == 14){
rba = "D"
    } else if (rb == 15){
rba = "E"
    } else if (rb == 16){
rba = "F"
    } else if (rb == 10){
rba = 0 }else {
rba = rb
    }

if (ga == 11){
gaa = "A"
   } else if (ga == 12){
gaa = "B"
    } else if (ga == 13){
gaa = "C"
    } else if (ga == 14){
gaa = "D"
    } else if (ga == 15){
gaa = "E"
    } else if (ga == 16){
gaa = "F"
    } else if (ga == 10){
gaa = 0 }else {
gaa = ga
    }

if (gb == 11){
gba = "A"
    } else if (gb == 12){
gba = "B"
    } else if (gb == 13){
gba = "C"
    } else if (gb == 14){
gba = "D"
    } else if (gb == 15){
gba = "E"
    } else if (gb == 16){
gba = "F"
    } else if (gb == 10){
gba = 0 }
else {
gba = gb
    }

if (ba == 11){
baa = "A"
    } else if (ba == 12){
baa = "B"
    } else if (ba == 13){
baa = "C"
    } else if (ba == 14){
baa = "D"
    } else if (ba == 15){
baa = "E"
    } else if (ba == 16){
baa = "F"
    }else if (ba == 10){
baa = 0 }else {
baa = ba
    }

if (bb == 11){
bba = "A"
    } else if (bb == 12){
bba = "B"
    } else if (bb == 13){
bba = "C"
    } else if (bb == 14){
bba = "D"
    } else if (bb == 15){
bba = "E"
    } else if (bb == 16){
bba = "F"
    } else if (bb == 10){
bba = 0
    }else if (bb == 10){
bba = 0 }else {
bba = bb
    }

answer = ""+raa+""+rba+""+gaa+""+gba+""+baa+""+bba
document.body.style.backgroundColor = "#" + answer;

var percen = 0

function colorstuff() {

    
    alert("guess the color of the background")
    alert(answer)
    var mayb = prompt("enter the hex code")

 rag = mayb.charAt(0)
 rbg = mayb.charAt(1)
 gag = mayb.charAt(2)
 gbg = mayb.charAt(3)
 bag = mayb.charAt(4)
 bbg = mayb.charAt(5)        



raa = answer.charAt(0);
rba = answer.charAt(1);
gaa = answer.charAt(2);
gba = answer.charAt(3);
baa = answer.charAt(4);
bba = answer.charAt(5);

if (rag === "A"){
rar= 11
    } else if (rag === "B"){
rar= 12
    } else if (rag === "C"){
rar= 13
    } else if (rag === "D"){
rar= 14
    } else if (rag === "E"){
rar= 15
    } else if (rag === "F"){
rar= 16
    } else if (rag === 0){
rar= 10 }else {
rar= rag
    }

if (rbg === "A"){
rbr= 11
    } else if (rbg === "B"){
rbr= 12
    } else if (rbg === "C"){
rbr= 13
    } else if (rbg === "D"){
rbr= 14
    } else if (rbg === "E"){
    rbr= 15
    } else if (rbg === "F"){
rbr= 16
    } else if (rbg === 0){
rbr= 10 }else {
rbr= rbg
    }
if (gag === "A"){
gar= 11
    } else if (gag === "B"){
gar= 12
    } else if (gag === "C"){
gar= 13
    } else if (gag === "D"){
gar= 14
    } else if (gag === "E"){
gar= 15
    } else if (gag === "F"){
gar= 16
    } else if (gag === 0){
gar= 10 }else {
gar= gag
    }

if (gbg === "A"){
gbr= 11
        } else if (gbg === "B"){
gbr= 12
    } else if (gbg === "C"){
gbr= 13
    } else if (gbg === "D"){
gbr= 14
    } else if (gbg === "E"){
gbr= 15
    } else if (gbg === "F"){
    gbr= 16
    } else if (gbg === 0){
gbr= 10 }else {
gbr= gbg
    }
if (bag === "A"){
bar= 11
    } else if (bag === "B"){
bar= 12
    } else if (bag === "C"){
bar= 13
        } else if (bag === "D"){
bar= 14
    } else if (bag === "E"){
bar= 15
    } else if (bag === "F"){
bar= 16
    } else if (bag === 0){
bar= 10 }else {
bar= bag
    }

if (bbg === "A"){
bbr= 11
    } else if (bbg === "B"){
bbr= 12
    } else if (bbg === "C"){
bbr= 13
    } else if (bbg === "D"){
bbr= 14
    } else if (bbg === "E"){
bbr= 15
    } else if (bbg === "F"){
bbr= 16
    } else if (bbg === 0){
bbr= 10 }else {
bbr= bbg
    }

    if (raa === "A"){
ra = 11
    } else if (raa === "B"){
ra = 12
    } else if (raa === "C"){
ra = 13
    } else if (raa === "D"){
ra = 14
    } else if (raa === "E"){
ra = 15
    } else if (raa === "F"){
ra = 16
    } else if (raa === 0){
ra = 10 }else {
ra = raa
    }

if (rba === "A"){
rb = 11
    } else if (rba === "B"){
rb = 12
    } else if (rba === "C"){
rb = 13
    } else if (rba === "D"){
rb = 14
    } else if (rba === "E"){
rb = 15
    } else if (rba === "F"){
rb = 16
        } else if (rba === 0){
rb = 10 }else {
rb = rba
    }

if (gaa === "A"){
ga = 11
   } else if (gaa === "B"){
ga = 12
    } else if (gaa === "C"){
ga = 13
    } else if (gaa === "D"){
ga = 14
    } else if (gaa === "E"){
ga = 15
    } else if (gaa === "F"){
ga = 16
    } else if (gaa === 0){
ga = 10 }else {
ga = gaa
    }

if (gba === "A"){
gb = 11
    } else if (gba === "B"){
gb = 12
    } else if (gba === "C"){
gb = 13
    } else if (gba === "D"){
gb = 14
    } else if (gba === "E"){
gb = 15
    } else if (gba === "F"){
gb = 16
    } else if (gba === 0){
gb = 10 }
else {
gb = gba
    }

if (baa === "A"){
ba = 11
    } else if (baa === "B"){
ba = 12
    } else if (baa === "C"){
ba = 13
    } else if (baa === "D"){
    ba = 14
    } else if (baa === "E"){
    ba = 15
    } else if (baa === "F"){
ba = 16
    }else if (baa === 0){
ba = 10 }else {
ba = baa
        }

if (bba === "A"){
bb = 11
    } else if (bba === "B"){
bb = 12
    } else if (bba === "C"){
bb = 13
    } else if (bba === "D"){
bb = 14
    } else if (bba === "E"){
bb = 15
    } else if (bba === "F"){
bb = 16
    } else if (bba === 0){
bb = 10
    }else {
bb = bba
    }

rag = parseFloat(rag)
rbg = parseFloat(rbg)
gag = parseFloat(gag)
gbg = parseFloat(gbg)
bag = parseFloat(bag)
bbg = parseFloat(bbg)

rar = parseFloat(rar)
rbr = parseFloat(rbr)
gar = parseFloat(gar)
gbr = parseFloat(gbr)
bar = parseFloat(bar)
bbr = parseFloat(bbr)

rag = parseInt(rag)
rbg = parseInt(rbg)
gag = parseInt(gag)
gbg = parseInt(gbg)
bag = parseInt(bag)
bbg = parseInt(bbg)

rar = parseInt(rar)
rbr = parseInt(rbr)
gar = parseInt(gar)
gbr = parseInt(gbr)
bar = parseInt(bar)
bbr = parseInt(bbr)
    
rag = Number(rag)
rbg = Number(rbg)
gag = Number(gag)
gbg = Number(gbg)
bag = Number(bag)
bbg = Number(bbg)

rar = Number(rar)
rbr = Number(rbr)
gar = Number(gar)
gbr = Number(gbr)
bar = Number(bar)
bbr = Number(bbr)
    
   
    
  if (rar = ra){
rac = 100
} else if (rar < ra){
rac = (rar/ra)*100
} else if (rar > ra){
rac = (ra/rar)*100
}
if (rbr = rb){
rbc = 100
} else if (rbr < rb){
rbc = (rbr/rb)*100
} else if (rbr > rb){
rbc = (rb/rbr)*100
}

 if (gar = ga){
gac = 100
} else if (gar < ga){
gac = (gar/ga)*100
} else if (gar > ga){
gac = (ga/gar)*100
}

if (gbr = gb){
gbc = 100
} else if (gbr < gb){
gbc = (gbr/gb)*100
} else if (gbr > gb){
gbc = (gb/gbr)*100
}

if (bar = ba){
bac = 100
} else if (bar < ba){
bac = (bar/ba)*100
} else if (bar > ba){
bac = (ba/bar)*100
}

if (bbr = bb){
bbc = 100
} else if (bbr < bb){
bbc = (bbr/bb)*100
} else if (bbr > bb){
bbc = (bb/bbr)*100
}


percen = (rac+rbc+gac+gbc+bac+bbc)/6
alert(percen)
alert(""+ra+""+rb+""+ga+""+gb+""+ba+""+bb)

    }

Mistmatching Checksums between CPP client and Cloudflare Worker

I’m trying to upload a file to cloudflare from an embedded device.

There a C++ application that generates a SHA-1 checksum before uploading the file

std::string generate_checksum(const std::string& file_path) {
    std::string test_file_path = file_path;

    std::ifstream file(test_file_path, std::ios::binary);

    if (!file) {
        throw std::runtime_error("Cannot open file for checksum.");
    }

    SHA_CTX sha1;
    SHA1_Init(&sha1);
    
    char buffer[8192];
    while (file.read(buffer, sizeof(buffer))) {
        SHA1_Update(&sha1, buffer, file.gcount());
    }

    unsigned char hash[SHA_DIGEST_LENGTH];
    SHA1_Final(hash, &sha1);

    std::ostringstream result;
    for (int i = 0; i < SHA_DIGEST_LENGTH; ++i) {
        result << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(hash[i]);
    }
    
    return result.str();
}

The generated checksum is then stored in a database and the upload starts, Uploaded with santdard CURL settings (can prepare a code snippet if thats relevent?)

A worker processes the file upload and checks the checksum of the uploaded file against the checksum in the database

async function validateChecksum(fileContent, expectedChecksum) {
  const sha1Buffer = await crypto.subtle.digest("SHA-1", fileContent);
  const sha1Array = Array.from(new Uint8Array(sha1Buffer));
  const computedChecksum = sha1Array.map(b => b.toString(16).padStart(2, '0')).join('');

  return computedChecksum === expectedChecksum;
}

// handle upload method ...

    const url = new URL(request.url);
    const checksum = url.searchParams.get('checksum');

    const uploadStream = await request.body;
    const originalFileName = request.headers.get('X-Original-File-Name');

    const uploadResponse = await env.STREAM_BUCKET.put(`some-folder/${originalFileName}`, uploadStream);

    if (!uploadResponse) {
      await updateTransferStatus(site_id, camera_id, "FAILURE", env);
      
      return new Response(
        JSON.stringify({ transfer_status: "FAILURE" }), 
        { status: 500, headers: { 'Content-Type': 'application/json' } }
      );
    }

    const uploadedFile = await env.STREAM_BUCKET.get(`${site_id}/${camera_id}/${originalFileName}`);
    const fileContent = await uploadedFile.arrayBuffer();
    const isChecksumValid = await validateChecksum(fileContent, checksum);

I was expecting the checksums to match but am brand new to this kind of task, what have I missed or not considered?

integrity is good; can download and open the file, the filenames are the same, the paths between client and cloud storage do differ but the filename is the same

jQuery: how do I exclude divs that have a name link?

My sample HTML markup is below. In each of the three nested sets of divs, I’m removing all <p> tags except for the first <p>.

But now I find I want to not remove all the <p> tags from just the first nested divs that have the anchor link a name="123"

How do I use an if statement and the name="123" attribute to exclude the first set of nested divs from having all their <p> tags removed?

This jQuery doesn’t work:

$('.post-body').each(function() {
   const $this = $(this);
if ($(this).closest('[name="123"]').length !== 0) {
   $(this).find('p').not(":first").remove();
}
});

HTML:

<div class="post"><a name="123"></a>
<h3 class="post-title">Post</h3>
<div class="NewPermalinkUrl">Text</div>    // I want to exclude this block
<div class="post-body">
<p>Content</p>
</div>
</div>
       

<div class="post"><a name="456"></a>
<h3 class="post-title">Post</h3>
<div class="NewPermalinkUrl">Text</div> 
<div class="post-body">
<p>Content</p>
</div>
</div>


<div class="post"><a name="789"></a>
<h3 class="post-title">Post</h3>
<div class="NewPermalinkUrl">Text</div> 
<div class="post-body">
<p>Content</p>
</div>
</div>

How to get the Amplify Data example to work

I’m building an app using React on Amplify and I’m adding a database. I followed the instructions here. List seems to work and returns an empty array. But, create is not working with no error. I’m using NoSQL Workbench and I see the tables but no data. With no error to go on I don’t know what to try next.

import { useState, useEffect } from "react";
import { generateClient } from "aws-amplify/data";

const client = generateClient();

const TodoList = () => {
  const [todos, setTodos] = useState([]);

  const fetchTodos = async () => {
    const { data: items, errors } = await client.models.Things.list();
    console.log(items, errors);
    setTodos(items);
  };

  useEffect(() => {
    void fetchTodos();
  }, []);

  const createTodo = async () => {
    try {
      await client.models.Things.create({
        content: window.prompt("Todo content?"),
        isDone: false,
      });

      void fetchTodos();
    } catch (error) {
      console.error(error);
    }
  }

  return (
    <div>
      <button onClick={createTodo}>Add new todo</button>
      <ul>
        {todos.map(({ id, content }) => (
          <li key={id}>{content}</li>
        ))}
      </ul>
    </div>
  );
}

export default TodoList;