Hi, I need to pass a base 64 encoded string to javascript function and wants the function to display image in new tab

I need to pass a base 64 encoded string to javascript function and wants the function to display image in new tab. I’m generating the html dynamically from java and calling the JS function there.I’m getting syntax error as unexpected token, whenever i try to call that function by clicking that hyperlink.

My java code:

String base64Image = Base64.getEncoder().encodeToString(CscmFcnaRes1.getImage()).trim();

Dynamic html generated using stringBuffer:

                            .append("<A href="#"")
                            .append(" onClick=displayImage(")
                            .append(base64Image)
                            .append(")>"

JS function:

function displayImage(base64Image) {
    var newTab = window.open();   
    newTab.document.open();   
    var isPdf = base64Image.substring(0, 4) === 'JVBER';
    var mimeType = isPdf ? 'application/pdf' : 'image/jpeg';      
    var htmlContent = '<html><body>';
    htmlContent += '<embed width="100%" height="100%" src="data:' + mimeType + ';base64,' + base64Image + '">';
    htmlContent += '</body></html>';      
    newTab.document.write(htmlContent);
    newTab.document.close();

}

I cant change anything in terms of bringing additional frameworks as its a prod running application. I need this image to be displayed in a new tab. When i manually decode the base64 string, I’m able to see the image. Note the base64 string is around 80k characters.

How can I enclose content between two divs in a div

How can I enclose the content between div_1 and div_2 in a div_3

<div id="div_1"></div>
<strong>stuff here that always begins with same string but does not end that way</strong>
some unknown text here
<div id="div_2"></div>

The real issue is that it seems you cannot insert the beginning of a div without the end of div showing up automatically.

For example, if I do something like this:

$(document).ready(function(){
$('#div_1').after('<div id="div_3">');
$('#div_2').before('</div>');
});

div_3 gets inserted after div_1 but with a closing tag i.e.

<div id="div_1"></div>
<div id="div_3"></div>
    <strong>stuff here that always begins with same string but does not end that way</strong>
    some text here with no consistent string
    <div id="div_2"></div>

Cannot pass data via Axios GET method

I am trying to pass an array as shown below with the help of Axios GET request:

{
    "values": [1, 2, 3]   
}

For this purpose, I tried the following approach that is suggested on Stackoverflow:

const config = {
  headers:{
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'Authorization': AUTH_TOKEN
  },
  params: {
    values: []
  },
  paramsSerializer: {
    indexes: null // by default: false
  }
};

export const getWithAuth = (url) => {
    const request = axios.get(url, config);
    return request.then(response => response.data);
}

But it still gives “”Required request body is missing” error. So, how can I pass values using Axios.GET ?

ussage of typeof method in javascript

When I put only one parameter in typeof() method of a javascript it gives proper response
e.g. typeof(10) is number.
But when I pass multiple parameters to the same method e.g

typeof("test",10)

it again gives a number
and when I pass 3 parameters e.g. typeof("test",10,"test3") it gives string.

Looking at this behavior it is clear that it returns the type of last parameter passed.

Why this method is even accepting the multiple parameters? What is the relevance of that ?

Show/hide multiple spans using a single javascript code

I have the following pure JS code to show/hide span:

jQuery(document).ready(function ($) {
$(".loginArea").hide();
$(".showLoginArea").click(function(){
    console.log('login');
    $(".loginArea").toggle();
});
    });

The html code works if used once, but I need to use it multiple times:

<span class="showLoginArea">Login</span> <span class="loginArea">This is Login Area</span>

I need to make something this work without writing JS code for each span class:

<span class="showLoginArea1">Login</span> <span class="loginArea1">This is Login Area</span>
<span class="showLoginArea2">Login</span> <span class="loginArea2">This is Login Area</span>
<span class="showLoginArea3">Login</span> <span class="loginArea3">This is Login Area</span>
...

Is there a fast method to extract bits by index (not just masking)?

I have a certain binary number for example: 11110000
And a mask with exactly 4 bits set: 10101010
Im searching for a fast operation that would return the 4 bits of the input corresponding to the positions where the mask is set:

11110000
10101010
output:1100

In here I use a u8 to u4 but imagine this for u64 to u32. Is there a fast way to do this (in Rust or C) without looping?

I tried looping the indexes, and linear decomposition. Both are very slow as one requires looping the other requires a matrix decomposition.

looping thru table rows and executing jquery ajax not working

Hi I am trying to execute this code:

    var table = document.getElementById("tab");
    for (var i = 0, row; row = table.rows[i]; i++) {
       //rows would be accessed using the "row" variable assigned in the for loop
       let idd = row.cells[1].textContent;
       
       if(idd != 'Id' && idd != '') {
           $.ajax({
                type: "POST",
                url: "/numordiniperiodoagenti",
                data: {id : idd, start: sstart, end: eend},
                success: function(response){
                    row.cells[10].textcontent = 'p'; //or response as it should be
                }
            });
        }
    }

But it seems that row is unaccessible inside this ajax call.

What am I missing here?

How can I passed a function to cloned element which i loop

I am writing a code can add sum of three inputs in a table i want to add test1, test2 and exam together and output the sum to total, i cloned the first table i created using loop to give me multiple duplicate of the table but the code only work on the original table i created and the first cloned iterated table, my code is below
`

<!DOCTYPE html>
<html>
  <head>
  <meta name="viewpoint" content="width = device-width, initial-scale=1">
  <style>
    input{width:30px;margin:2px;}
  .input{width:30px; position:relative;left:60px;bottom:15px;margin:4px; color:}
 
  </style>
  </head>
  <body>
    <p id ='ht'>
    <form action ="" id ="forms">
  <table>
    <th>Name</th>
    <th>test1</th>
    <th>test2</th>
    <th>exams</th>
    <th>total</th>
    <tr>
      <td id="yt">Fidelis</td>
      <td><input type="number" class ="a"id='b'/></td>
      <td><input type="number"class="a"id='c'/></td>
      <td><input type ="number"class="a"id='d' /></td>
      <td class ="four"><input type="number"id="e" onclick= 'g()' /></td>
    </tr>
  </table>
  </form>
  </div>
  
  <script>
    var test1 = document.querySelector('#b');
    var test2 = document.querySelector('#c');
    var exam = document.querySelector('#d');
    var total = document.querySelector("#e");
    var nam = document.querySelector ('#yt')
    function g(){
   var msg = Number(test1.value);
     var pk = Number(test2.value);
     var jk = Number(exam.value);
     var tk = total;
     var sum = msg + pk + jk
// return(sum)
     tk.value = sum
    }
   for(var i = 0; i < 10; i++){
    var clonedName = nam.cloneNode(true);
   // clonedName.classList =('input');
    clonedName.id = 'name'
    document.body.appendChild(clonedName);
    
    var clonedTest1 = test1.cloneNode(true);
    clonedTest1.classList =('input');
    clonedTest1.id ='test1';
    document.body.appendChild (clonedTest1);
    var clonedTest2 = test2.cloneNode(true);
    clonedTest2.classList = ('input');
    clonedTest2.id ='test2'
    document.body.appendChild (clonedTest2)
    var clonedExam = exam.cloneNode(true);
    clonedExam.classList=('input')
    clonedExam.id ='exam'
    document.body.appendChild (clonedExam)
    var clonedTotal = total.cloneNode(true);
    clonedTotal.classList =('input');
    clonedTotal.id ='tota'
    document.body.appendChild(clonedTotal);
   // total2.addEventListener('click', add)
   }

  var tex1 = document.querySelector ('#test1');
  var tex2 = document.querySelector ('#test2');
  var tex3 =document.querySelector ('#exam');
  var tex4 = document.querySelector('#tota');
function add(){
  var te1 = Number(tex1.value);
  var te2 = Number(tex2.value);
  var te3 = Number(tex3.value);
  var te4 = tex4.value;
  sum2 = te1 + te2 + te3;
  tex4.value = sum2
}
var total2 = document.querySelector('#tota')
total2.addEventListener('click', add);
  </script>
  </body>
</html>


I tried loop through the a table with input i created but my function which want it to add sum of input1(test1), input 2 (test2) and input 3(exam). But the function only work on the first and the first cloned element

How do I use multiple html files with one javascript file(index.js)?

I have two html files; index.html and b.html. I linked my index.js file with <script src="index.js"></script> in the index.html file and did the same in second html (b.html). But DOM manipulation isn’t working on the second html file(b.html).

I tried this, but it’s not working

<!-- HTML file 1 (index.html) -->
<html>
     <body>
         <a href="b.html">b</>
         <script src="index.js"></script>
     </body>
</html>


<!-- HTML file 2 (b.html) -->
<html>
     <body>
         <script src="index.js"></script>
     </body>
</html>

Prisma: Automatically add entry to one relation if it is used in another relation

I am currently working on a recipe application. A recipe(Recipe) consists of multiple steps(Step), which each contain references to multiple step-ingredients(StepIngredient), that reference an Ingredient(Ingredient) and hold the amount and unit to use for that ingredient. The relevant part of my prisma schema looks like this:

...
model Recipe {
  id          Int          @id @default(autoincrement())
  title       String
  description String?      @db.LongText
  user        User         @relation(fields: [userId], references: [id], onDelete: Cascade)
  userId      Int
  steps       Step[]
}

model Step {
  id          Int              @id @default(autoincrement())
  position    Int
  recipe      Recipe?          @relation(fields: [recipeId], references: [id], onDelete: Cascade)
  recipeId    Int?
  ingredients StepIngredient[]
  description String?          @db.LongText
}

model StepIngredient {
  id           Int        @id @default(autoincrement())
  step         Step?      @relation(fields: [stepId], references: [id], onDelete: Cascade)
  stepId       Int?
  ingredient   Ingredient @relation(fields: [ingredientId], references: [id], onDelete: Cascade)
  ingredientId Int
  amount       Float
  unit         String?
  description  String?    @db.LongText
}

model Ingredient {
  id             Int              @id @default(autoincrement())
  name           String           @unique
  StepIngredient StepIngredient[]
}
...

while this works fine for the usual CRUD stuff, i’d like to have the ability to search for recipes that use certain ingredients. While this is certainly achievable with this data structure it kind of strucks me as a massive performance bottleneck. My initial idea was to add an additional realtionship between recipe and ingredient, which would lead to duplicated information but improved querying. The models for Recipe and Ingredient would look like this:

model Recipe {
  id          Int          @id @default(autoincrement())
  title       String
  description String?      @db.LongText
  user        User         @relation(fields: [userId], references: [id], onDelete: Cascade)
  userId      Int
  steps       Step[]
  ingredients Ingredient[]
}

model Ingredient {
  id             Int              @id @default(autoincrement())
  name           String           @unique
  StepIngredient StepIngredient[]
  recipes        Recipe[]
}

My questions are:

  1. Are there other, smarter, or more performant solutions to do this without having to duplicate information?
  2. If I would go for my proposed solution, is there a way in prisma to add a ingredient to the Recipe.ingredients-relation every time an ingredient is added to the Recipe.steps.ingredients-relation? I know I can do this in my server code, but if prisma provides a way for doing this, I would like to use it.

Why some border is overlapped by the previous cell border?

The following is the output of the react code:

.borderCell {
    border: 1px solid #e0e0e0;
}
.shiftCell{
    background-color:#ff99cc;
    min-width:27px;
    text-align: center; 
}
.shiftContent:focus{
    outline: none
}
.shiftContent{
    padding: 0px;
    margin: 0px;
}
.shiftContent::-moz-selection{
    background: none; 
}
.shiftContent::selection{
    background: none; 
}
.littleSquareDiv {
    background-color: rgb(0, 140, 255);
    top: calc(100% - 3px);
    left: calc(100% - 3px);
    height: 6px;
    position: absolute;
    width: 6px;
    z-index: 10;
}

.littleSquareDiv:hover {
    cursor: crosshair;
}
.selectCellBorderBottom{
    border-bottom: 1px solid rgb(0, 140, 255);
}
.selectCellBorderLeft{
    border-left: 1px solid rgb(0, 140, 255);
}
.selectCellBorderRight{
    border-right: 1px solid rgb(0, 140, 255);
}
.selectCellBorderTop{
    border-top: 1px solid rgb(0, 140, 255);
}
    <table class="m-3">
      <tbody>
        <tr>
          <td class="borderCell shiftContent " contenteditable="true">0,0</td>
          <td class="borderCell shiftContent " contenteditable="true">1,0</td>
          <td class="borderCell shiftContent " contenteditable="true">2,0</td>
        </tr>
        <tr>
          <td class="borderCell shiftContent " contenteditable="true">0,1</td>
          <td class="borderCell shiftContent selectCellBorderTop selectCellBorderBottom selectCellBorderRight selectCellBorderLeft" contenteditable="true">1,1</td>
          <td class="borderCell shiftContent " contenteditable="true">2,1</td>
        </tr>
        <tr>
          <td class="borderCell shiftContent " contenteditable="true">0,2</td>
          <td class="borderCell shiftContent " contenteditable="true">1,2</td>
          <td class="borderCell shiftContent " contenteditable="true">2,2</td>
        </tr>
      </tbody>
    </table>    

When I place the code to jsfiddle, the central cell 4 border can be shown successfully.
Unfortunately, when the above code is outputted by react(please click the central cell) only the right, bottom border of the central cell can be shown successfully.

Would you tell me why?

how to add a nest array as one data attribute Javascript

This might not be possible but I have a nest array and what to add two values to a data attribute. At the moment when I add this it does it like data-genre= “comedy,romance”. I want to get them as two different values such as data-cat=”comedy” data-genre”romance” but for the one DOM.

const data = [{
    "id": 1,
    "movie_name": "last holiday",
    "date": "2023-10-29",
    "genre": ["comedy", "romance"],
  },

  {
    "id": 2,
    "movie_name": "pitch perfect",
    "date": "2023-04-24",
    "genre": [
      "comedy"
    ]
  }
]

box.dataset.genre = data.comedy;
const box = document.getElementById('box');

<div id="box"></div>

I want it to look like this

<div id="box" data-genre="comdy romance"></div>

I would like to be able to use it as two values if possible.

component function re-rendering onChange

I have a react application. This specific Component has many different forms. As such, I have created external functions and am calling these component functions when I want to display a particular form.

Example:

const Create = () => {
    const [formValid, setFormValid] = useState(true);

    const [noBoats, setNoBoats] = useState();
    const [noHouses, setNoHouses] = useState();

    const [isForm1, setIsForm1] = useState(true);

    const validateForm = ({ currentTarget: input }) => {
        if (input['name'] == 'no_boats') {
            setNoBoats(input.value)

            if (input.value != '') {
                if (between(input.value, 0, 4)) {
                    setFormValid(true)
                } else {
                    setFormValid(false)
                }
            }
        }

        if (input['name'] == 'no_houses') {
            setNoHouses(input.value)

            if (input.value != '') {
                if (between(input.value, 0, 8)) {
                    setFormValid(true)
                } else {
                    setFormValid(false)
                }
            }
        }
    }

    const Form1 = () => {
      return (
      <>

        <form className={styles.form} id="form1" onSubmit={(e) => handleSubmit(e)}>
          <div className={styles.form_group}>
            <label htmlFor="no_houses">Number of Houses</label>
            <input type="text" name="no_houses" autoFocus="autoFocus" onChange={validateForm} value={noHouses}/>
          </div>

          <div className={styles.form_group}>
            <label htmlFor="no_boats">Number of Boats</label>
            <input type="text" name="no_boats" autoFocus="autoFocus" onChange={validateForm} value={noBoats}/>
          </div>

          <button type="submit">Submit</button>
        </form>
        </>
      );
    }

    return (
            <div className={styles.all_forms}>
                  {isForm1 && <Form1 />}
            </div>

    );
}

When I go to fill out “Number of Boats” and “Number of Houses”, the input loses focus after the first character. I have tried adding autoFocus="autoFocus" to both inputs, but that does not work either. Can any please explain what is going on?

I suspect it may have something to do with the fact that I am loading in the Form1 component using <Form /> and when the state updates it re-renders that form. I unfortunately have about 10 different forms so I can’t really put them all in the main render()