Is there a way to scale a complex based on window size using HTML/CSS/JS?

I am currently making a website, and have created a set of complex div elements. They look great on my browser’s native size, but resizing the browser caused weird wrapping issues, and made the elements fall out of place.

Here’s what my looks like right now…

<body id='table'>
    <div class="input-wrapper">
        <div class="search-wrapper">
            <label for="search"></label>
            <input type="search" id="search" placeholder="Search for a level..." data-search>
            <select id="searchBy">
                <option value="levelName">Name</option>
                <option value="creator">Creator</option>
                <option value="song">Song</option>
            </select>
        </div>
        <div class="page-wrapper">
            <div class="resultNum"></div>
            <div class="pageSelector">
                <button onclick="this.parentNode.querySelector('input[type=number]').stepDown()" id="l-arrow">◀</button>
                <input type="number" class="page" min="1" value="1">
                <button onclick="this.parentNode.querySelector('input[type=number]').stepUp()" id="r-arrow">▶</button>
            </div>
        </div>
    </div>
    <div id="data-output"></div>
</body>

I insert the elements using a JS script, which inserts them like this…

      out += `
         <div id="wrap"><div class='row'>
            <div class='innerRow' style='background-image: linear-gradient(to right, rgba(33, 37, 41, 0.75), rgba(255, 255, 255, 0.1)), url(images/${level.levelId}.png), url(images/default.png)'>
               <div class='row1'>
                  <div class='row1a'>
                     <div class='levelName'>${level.levelName}</div>
                     <div class='levelId'>${level.levelId}</div>
                  </div>
                  <div class='creator'>${level.creator}</div>
               </div>
               <div class='levelInfo'>
                  <div class='row2'>
                     <div class='row2a'>Difficulty</div>
                     <div class='row2b'>
                        <div class='difficulty'>${level.difficulty + " " + rewardNum}</div>
                        <div class='reward'><img src = 'difficulties/${reward}.png'></div>
                     </div>
                  </div>
                  <div class='row3'>
                     <div class='row3a'>Coins</div>
                     <div class='coins'><img src = 'difficulties/${coin}.png'></div>
                  </div>
                  <div class='row4'>
                     <div class='row4a'>Song</div>
                     <div class='song'><span>${level.song}</span></div>
                  </div>
               </div>
               <div class='face'>
                  <img src = 'difficulties/${difficultyFace}.png'
               </div>`;

For reference, this is what the page looks like…

Ideally, I want these ‘cards’ to resize cleanly when the window is made smaller.

At first, I had tried to combat this by making all of the margins and padding of the divs within my outer div reliant on vw. However, this is proving to be incredibly tedious, and the elements do not align with each other right, and still cause text wrapping issues, just different ones.

Eventually, I decided to just try using transform: scale(). This obviously worked for constant numbers, and resized the entire element without any weird positioning issues. However, I need to be able to use transform: scale() based on vw. Here’s what that looked like…


/* This is the CSS for the wrapper. */

.innerRow {
    
    transition: all 0.2s ease-in-out; 

    padding-left: 20px;
    padding-top: 30px;
    padding-bottom: 20px;

    margin-left: 18.65vw;
    margin-right: 18.65vw;
    margin-top: 10px;

    background-size: 100%;
    background-position: 40% 50%;

    vertical-align: middle;
    
    border-radius: 5px;

    display: flex;

}

/* This doesn't work. */
.row {
    transform: scale(calc(100% * calc(18 / 100vw)));
}

I tried doing this to no avail. Is that not a property I can use? I had seen in some other similar posts that people found success using it, but I have not.

JavaScript error – “Cannot read properties of undefined” in Shopify theme

I’m encountering a JavaScript error in my Shopify theme related to variant selection. The error message is “Cannot read properties of undefined.” The issue seems to be occurring at line 1226 in the global.js file. I’m using a variant-radios element for color selection and a variant-selects element for size selection on the product page. The error is preventing the selected variant from working correctly.

Below is the relevant code:

{%- unless product.has_only_default_variant -%}
  <variant-radios
    class="no-js-hidden"
    data-section="{{ section.id }}"
    data-url="{{ product.url }}"
    {{ block.shopify_attributes }}>
    {%- for option in product.options_with_values -%}
      <fieldset name="Color" class="js product-form__input {% unless option.name == 'Color' %} %}hidden{% endunless %}">

        <legend class="form__label">{{ option.name }}</legend>

        {%- for value in option.values -%}


          {% if option.name == 'Color' %}
            <input
              type="radio"
              id="{{ section.id }}-{{ option.position }}-{{ forloop.index0 }}"
              name="{{ option.name }}"
              value="{{ value | escape }}"
              form="{{ product_form_id }}"
              {% if option.selected_value == value %}
              checked
              {% endif %}>
          {% endif %}


          {% if option.name == 'Color' %}
            {% assign variant_image_url = product.variants[forloop.index0].metafields.variant.image_url %}
            <label
              class="swColor"
              for="{{ section.id }}-{{ option.position }}-{{ forloop.index0 }}"
              style="background-image: url({{ variant_image_url }});">
              {{ value }}
            </label>
          {% endif %}


        {%- endfor -%}
      </fieldset>
    {%- endfor -%}
    <script type="application/json">
      {{ product.variants | json }}
    </script>
  </variant-radios>

  <variant-selects
    id="variant-selects-{{ section.id }}"
    class="no-js-hidden"
    data-section="{{ section.id }}"
    data-url="{{ product.url }}"
    {% if update_url == false %}
    data-update-url="false"
    {% endif %}
    {{ block.shopify_attributes }}>
    {% for option in product.options_with_values %}

      {% if option.name == 'Size' %}
        <label for="Option-{{ section.id }}-{{ forloop.index0 }}">{{ option.name }}</label>
        <div class="my-2">
          <select
            name="options[{{ option.name | escape }}]"
            id="Option-{{ section.id }}-{{ forloop.index0 }}"
            class="w-full border py-3 px-3">
            {% for value in option.values %}
              <option
                value="{{ value | escape }}"
                {% if option.selected_value == value %}
                selected="selected"
                {% endif %}>{{ value }}</option>

            {% endfor %}


          </select>
        </div>
      {% endif %}

      <script type="application/json">
        {{ product.variants | json }}
      </script>

    {% endfor %}

  </variant-selects>
{%- endunless -%}

class VariantRadios extends VariantSelects {
  constructor() {
    super();
  }

  setInputAvailability(listOfOptions, listOfAvailableOptions) {
    listOfOptions.forEach((input) => {
      if (listOfAvailableOptions.includes(input.getAttribute('value'))) {
        input.classList.remove('disabled');
      } else {
        input.classList.add('disabled');
      }
    });
  }

  updateOptions() {
    const fieldsets = Array.from(this.querySelectorAll('fieldset'));
    this.options = fieldsets.map((fieldset) => {
      return Array.from(fieldset.querySelectorAll('input')).find((radio) => radio.checked).value;
    });
  }
}

The error log mentions an issue in the VariantRadios.updateOptions method. I’ve already tried updating the code based on suggestions, but the problem persists. Any insights on how to resolve this issue would be greatly appreciated!

Real-time search in the DataTables when the user types into the Select2 input

When I select a drop down box, to type in anything & search, I click on the box again. We should be able to type straight away without having to click anything extra(like realtime search type any value select2 inputbox to filter datatable)

i am using “keyup” , but not working

Js code

$(document).ready(function () {
    $(".select2").select2({
        placeholder: "Select",
        allowClear: false,
        closeOnSelect: false

    });
    var table;
    table = $('#agents').DataTable({
        ajax: '/designer_work/assets/json/agentsData.json',
        columns: [
            { data: 'id', visible: false, searchable: false, },
            { data: 'name', class: 'nowrap' },
            { data: 'city' },
            { data: 'air', 
              render: function (data, type) {
                console.log(data);
                if(data){
                    return `<span class='d-none'>${data}air</span><img src='/designer_work/assets/img/tick.png'/>`
                }
                return `<span class='d-none'>${data}air</span>`;
              }
            },
            { data: 'sea', 
              render: function (data, type) {
                if(data){
                    return `<span class='d-none'>${data}sea</span><img src='/designer_work/assets/img/tick.png'/>`
                }
                return `<span class='d-none'>${data}sea</span>`;
              }
            },
            { data: 'orig', 
              render: function (data, type) {
                if(data){
                    return "<img src='/designer_work/assets/img/tick.png'/>"
                }
                return "";
              }
            },
            { data: 'dest', 
              render: function (data, type) {
                if(data){
                    return "<img src='/designer_work/assets/img/tick.png'/>"
                }
                return "";
              }
            },
            { data: 'agent' },
            { data: 'contact' },
            { data: 'contact_title' },
            { data: 'phone' },
            { data: 'fax' },
            { data: 'email' },
        ],
       
        
    });

    $(".select2-search__field").on("keyup", function () {
      updateDataTable();
    });

    $('body').on('click', '.getSelect', function(){
        $('#agents_wrapper').css('visibility', 'visible');
        $('#agents_wrapper').css('height', 'auto');
        $('#agents_wrapper').css('overflow', 'unset');
        $('#agents').removeClass('invisible');
        $('#agent_icon').addClass('d-none');
        var country = $('#country').val();
        country = country == "" || country == 'all' ? '' : country;
        var mode = $('#mode').val();
        mode = mode == "" || mode == 'all' ? '' : mode;
        var port = $('#port').val();
        if(country != ''){
            table.column(1).search(country, true, false).draw();
        }else{
            table.column(1).search('', true, false).draw();
        }
        if(mode == 'air'){
            table.column(3).search('1air', true, false).draw();
        }else{
            table.column(3).search('', true, false).draw();
        }
        if(mode == 'sea'){
            table.column(4).search('1sea', true, false).draw();
        }else{
            table.column(4).search('', true, false).draw();
        }
        updateDataTable();
    });

function updateDataTable() {
  var country = $("#country").val() || "";
  var mode = $("#mode").val() || "";

  // Update DataTable based on Select2 input value
  table.column(1).search($(".select2-search__field").val(), true, false).draw();
  if (mode === "air") {
    table.column(3).search("1air", true, false).draw();
  } else {
    table.column(3).search("", true, false).draw();
  }
  if (mode === "sea") {
    table.column(4).search("1sea", true, false).draw();
  } else {
    table.column(4).search("", true, false).draw();
  }
}
    
     
    table.columns().iterator('column', function (ctx, idx) {
        $(table.column(idx).header()).append('<span class="sort-icon"/>');
    });
    table.responsive.recalc();
    $('div.title').html('');
    $('div.top .dataTables_filter input').after('<span class="tsicon"></span>');
    $('div.top .dataTables_length select').after('<span class="tseicon"></span>');
});

Html

<div class="d-flex flex-column flex-lg-row justify-content-center align-items-start align-items-lg-center px-3 py-2">
    <div class="form-group col-12 col-xxl-4 col-lg-3 mb-2 mb-lg-0 d-flex flex-column flex-lg-row align-items-start align-items-lg-center pe-sm-22px">
        <label for="country" class="fs-6-5 text-black fw-500 pe-6px pb-1 pb-xl-0">Country</label>
        <select class="form-control fs-6-75 select-color filter-select select2 w-100" id="country">
            <option value="">Select Country</option>
            <option value="all">All</option>
            <option value="afghanistan">AFGHANISTAN (AF)</option>
            <option value="albania">ALBANIA (AL)</option>
            <option value="algeria">ALGERIA (DZ)</option>
        </select>
    </div>
    <div class="form-group d-flex flex-column flex-lg-row align-items-start align-items-lg-center col-12 col-lg-3 mb-2 mb-lg-0 pe-sm-22px">
        <label for="port" class="fs-6-5 text-black fw-500 pe-6px pb-1 pb-xl-0">Mode</label>
        <select class="form-control fs-6-75 select-color filter-select select2 w-100" id="port">
            <option value="">Select Port</option>
            <option value="all">All</option>
        </select>
    </div>
    <div class="form-group d-flex flex-column flex-lg-row align-items-start align-items-lg-center col-12 col-lg-3 pe-sm-22px mb-2 mb-lg-0">
        <label for="mode" class="fs-6-5 text-black fw-500 pe-6px pb-1 pb-xl-0">Port</label>
        <select class="form-control fs-6-75 select-color filter-select select2 w-100" id="mode">
            <option value="">Select Mode</option>
            <option value="all">All</option>
            <option value="air">Air</option>
            <option value="sea">Sea</option>
        </select>
    </div>
    <div class="form-group col-12 col-xl-2 col-md-3 ps-0">
        <button class="btn btn-success rounded-pill px-6 getSelect fw-500 fs-13px">
            GET SELECTED
        </button>
    </div>
</div>

i tyred using

$(".select2-search__field").on("keyup", function () {
      updateDataTable();
    });

but not working

after using “keyup” result after select value on select2 to show the filter datatable.
i want user type the any value on select2 inputbox to realtime filter on datable rows

How can I get rid of the gap between adjacent triangles in triangle rasterization?

Currently in my output, I get a blank diagonal line going from the top left vertex to the bottom right vertex. In the input, I’m calling the drawTriangle twice and the second triangle for some reason skips a row and a column. The problem is that there’s a gap between my adjacent triangles.

Triangle with blacnk diagonal line

I’m pretty sure the problem lies in my drawingTriangle function and the way I’m potentially iterating over my bounding box points? Any tips and direction would help

function drawingTriangle(v1,v2,v3){
   // Extract vertex coordinates and colors
  const [x1, y1, [r1, g1, b1]] = v1;
  const [x2, y2, [r2, g2, b2]] = v2;
  const [x3, y3, [r3, g3, b3]] = v3;

  // Determine bounding box of the triangle
  const xValues = [v1[0], v2[0], v3[0]];
  const yValues = [v1[1], v2[1], v3[1]];
  const xMin = Math.min(...xValues);
  const xMax = Math.max(...xValues);
  const yMin = Math.min(...yValues);
  const yMax = Math.max(...yValues);

  // Iterate over pixels in the bounding box
  for (let pixelX = xMin; pixelX <= xMax; pixelX++) {
    for (let pixelY =yMin; pixelY <= yMax; pixelY++) {    
      let condition1=pointIsInsideTriangle(v1,v2,v3,[pixelX,pixelY]);
      let condition2=pointIsInsideTriangle(v3,v1,v2,[pixelX,pixelY]);
      let condition3=pointIsInsideTriangle(v2,v3,v1,[pixelX,pixelY]);
      // Check if the pixel is inside the triangle
      if (condition1 && condition2 && condition3) {
        // Calculate barycentric coordinates
        const barycentric = calculateBarycentricCoordinates(v1, v2, v3, [pixelX, pixelY]);
    
        // Interpolate color
        const interpolatedColors = [
            r1 * barycentric[0] + r2 * barycentric[1] + r3 * barycentric[2],
            g1 * barycentric[0] + g2 * barycentric[1] + g3 * barycentric[2],
            b1 * barycentric[0] + b2 * barycentric[1] + b3 * barycentric[2],
        ];
    
        // Set the color of the pixel
        this.setPixel(pixelX,pixelY, interpolatedColors);
    }
    }
  }
};

Here’s my pointIsInsideTriangle, it checks whether the point is inside the triangle. It is if its to the left of the triangle, it isnt if its to the right and if ax+by+c==0, the edge cases must be considered, if its a top edge case or a left edge case, the point is inside the triangle:

function pointIsInsideTriangle(v1,v2,topedgepoint,p)

const [x1, y1, [r1, g1, b1]] = v1;
  const [x2, y2, [r2, g2, b2]] = v2;
  const [x3, y3, [r3, g3, b3]] = v3;

  // Determine bounding box of the triangle
  const xValues = [v1[0], v2[0], v3[0]];
  const yValues = [v1[1], v2[1], v3[1]];
  const xMin = Math.min(...xValues);
  const xMax = Math.max(...xValues);
  const yMin = Math.min(...yValues);
  const yMax = Math.max(...yValues);

  // Iterate over pixels in the bounding box
  for (let pixelX = xMin; pixelX <= xMax; pixelX++) {
    for (let pixelY =yMin; pixelY <= yMax; pixelY++) {    
      let condition1=pointIsInsideTriangle(v1,v2,v3,[pixelX,pixelY]);
      let condition2=pointIsInsideTriangle(v3,v1,v2,[pixelX,pixelY]);
      let condition3=pointIsInsideTriangle(v2,v3,v1,[pixelX,pixelY]);
      // Check if the pixel is inside the triangle
      if (condition1 && condition2 && condition3) {
        // Calculate barycentric coordinates
        const barycentric = calculateBarycentricCoordinates(v1, v2, v3, [pixelX, pixelY]);
    
        // Interpolate color
        const interpolatedColors = [
            r1 * barycentric[0] + r2 * barycentric[1] + r3 * barycentric[2],
            g1 * barycentric[0] + g2 * barycentric[1] + g3 * barycentric[2],
            b1 * barycentric[0] + b2 * barycentric[1] + b3 * barycentric[2],
        ];
    
        // Set the color of the pixel
        this.setPixel(pixelX,pixelY, interpolatedColors);
}
    }
  }
};

Three.js Collisions GLTF

I have a GLTF scene/level that is impoted in my game and I want to block player from going inside walls.
The level : https://sketchfab.com/3d-models/backrooms-level-0-3a43c43be8864c09aa0dff37c0b82001

and my loader code:

loader.load(
// resource URL
"../../models/scene.gltf",
// called when the resource is loaded
function (gltf) {
  scene.add(gltf.scene);
  level = gltf.scene;
  gltf.animations; // Array<THREE.AnimationClip>
  gltf.scene; // THREE.Group
  gltf.scenes; // Array<THREE.Group>
  gltf.cameras; // Array<THREE.Camera>
  gltf.asset; // Object
},
// called while loading is progressing
function (xhr) {
  console.log((xhr.loaded / xhr.total) * 100 + "% loaded");
},
// called when loading has errors
function (error) {
  console.error(error);
}
return { level };

);

Action Sheet’s initial position is at the center of the screen Android React Native Glue Stack UI

I was working on my project using Expo React Native and a UI library named Glue Stack UI and when I added a Popover or Actionsheet the initial position of the opened content always starts at the center or above of the screen in the case of Popover and Actionsheet respectively and then snaps back to the right place of its trigger button (which is the orange mail button) I have no idea what’s causing this behavior but I’m assuming it’s because of how Android or React Native is set-up. Any recommended fix?

I was able to find a somewhat related issue: https://github.com/SteffeyDev/react-native-popover-view/issues/28 but I’m not sure if it’s the solution to my problem as it’s using old react conventions.

I’ve also tried removing the messagesScreenContainer styling which centers every element on the screen but the same problem still exists.

enter image description here
enter image description here

Other than replacing the Button with a Fab button, I pretty much used the exact code template from the Actionsheet docs of Glue Stack UI
Code:

export default function MessagesScreen() {
    const [isLoading, setIsLoading] = useState(true);
    const [showActionsheet, setShowActionsheet] = useState(false);
    const handleClose = () => setShowActionsheet(!showActionsheet);
    useEffect(() => {
        setTimeout(() => {
            setIsLoading(false);
        }, 2000);
    }, []);
    return (
        <View style={styles.messagesScreenContainer}>
            {isLoading ? (
                <Spinner size={"xl"} color={"#EC472E"} />
            ) : (
                <Box h={"95%"} w={"95%"} borderRadius="$md">
                    <VStack space="md">
                        <Alert
                            mx="$2.5"
                            action="info"
                            variant="accent"
                            bg="$info200"
                            borderColor="$info700"
                        >
                            <AlertIcon as={InfoIcon} mr="$3" color="$info700" />
                            <AlertText color="$textLight900">
                                Suspect is small. May have robbed a couple of trash cans. We
                                los...
                            </AlertText>
                        </Alert>
                        <Alert
                            mx="$2.5"
                            action="warning"
                            variant="accent"
                            bg="$warning200"
                            borderColor="$warning700"
                        >
                            <AlertIcon as={AlertOctagon} mr="$3" color="$warning700" />
                            <AlertText color="$textLight900">
                                so my husband climbed up to get the cat and now he's stuck
                                too...
                            </AlertText>
                        </Alert>
                        <Alert
                            mx="$2.5"
                            action="error"
                            variant="accent"
                            bg="$error200"
                            borderColor="$error700"
                        >
                            <AlertIcon as={AlertTriangle} mr="$3" color="$error700" />
                            <AlertText color="$textLight900">
                                over turned vehicle, flames showing, and body parts everywhere,
                                how...
                            </AlertText>
                        </Alert>
                    </VStack>
                    <Fab
                        bg="#EC472E"
                        size="lg"
                        placement="bottom right"
                        onPress={handleClose}
                    >
                        <FabIcon as={MailPlus} size="xl" />
                    </Fab>
                    <Actionsheet
                        isOpen={showActionsheet}
                        onClose={handleClose}
                        zIndex={999}
                    >
                        <ActionsheetBackdrop />
                        <ActionsheetContent h="$72" zIndex={999}>
                            <ActionsheetDragIndicatorWrapper>
                                <ActionsheetDragIndicator />
                            </ActionsheetDragIndicatorWrapper>
                            <ActionsheetItem onPress={handleClose}>
                                <ActionsheetItemText>Delete</ActionsheetItemText>
                            </ActionsheetItem>
                            <ActionsheetItem onPress={handleClose}>
                                <ActionsheetItemText>Share</ActionsheetItemText>
                            </ActionsheetItem>
                            <ActionsheetItem onPress={handleClose}>
                                <ActionsheetItemText>Play</ActionsheetItemText>
                            </ActionsheetItem>
                            <ActionsheetItem onPress={handleClose}>
                                <ActionsheetItemText>Favourite</ActionsheetItemText>
                            </ActionsheetItem>
                            <ActionsheetItem onPress={handleClose}>
                                <ActionsheetItemText>Cancel</ActionsheetItemText>
                            </ActionsheetItem>
                        </ActionsheetContent>
                    </Actionsheet>
                </Box>
            )}
        </View>
    );
}
const styles = StyleSheet.create({
    messagesScreenContainer: {
        flex: 1,
        alignItems: "center",
        justifyContent: "center",
    },
});

How do I implement login using passportjs

I’m making a login page for my web app and I cant figure out how to get any user to properly login. I want when ever the user submits the form it will use post to then check mongoDB for the matching email and password and if its there to log them in and redirect to the next page.

//Passportjs stuff
const crypto = require('crypto');
const passport = require('passport');
const LocalStrategy = require('passport-local');
const passportLocalMongoose = require('passport-local-mongoose');

// Connect to MongoDB
mongoose.connect('mongodb://localhost:87887/members-only-proj', {
// useNewUrlParser: true,
// useUnifiedTopology: true
}, console.log("connected to database"));

const UsersModel = mongoose.model('Users', new mongoose.Schema({
// Define your data schema here
    email: { type: String, required: true},
    password: { type: String, required: true },
    admin: {type: Boolean}
// Add more fields as needed
}));

//Sign Up
    app.post("/sign-up.html", async (req, res, next) => {//Post needs to be the same as the file page location
        try {
                if (req.body.password != req.body.confirmPassword ) {
                    console.log("Password and Confirm Password do not match");
                    res.redirect("errorSignUp.html");
                    return;
            }
            const hashedPassword = await bcryptjs.hash(req.body.password, 13);
            const users = new UsersModel({
                email: req.body.email,
                password: hashedPassword,
                admin: false
            });
            const result = await users.save();
            res.redirect("log-in.html");
            console.log(result);
        } catch (err) {
            console.log("Error");
            res.redirect("errorSignUp.html");
            return next(err);
            };
    });
// Log-in
app.post("/log-in",
   passport.authenticate("local", {
      successRedirect: "secret-pass.html",
      failureRedirect: "log-in.html"
  })
);

passport.use(new LocalStrategy(
     function(email, password, done) {
       users.findOne({ email: email }, function (err, users) {
        if (err) {
            return done(err);
       }
        if (!users) {
          return done(null, false);
       }
        if (!users.verifyPassword(password)) {
          return done(null, false);
       }
          return done(null, users);
       });
    }
));

Sudoku Tricky Board Populator

I am trying to write a program that reads a JSON file and populates a Sudoku board based on the contents of the file. The JSON file has an array with 9 items containing key, value pairs. See image here: JSON file with board data. Each string will populate a 3×3 quadrant of the board.

The tricky part:
For example, the first string “232234327” has 9 numbers. We can see them as sets of 3 numbers. The first 2 numbers are the column and row position, respectfully of the 3×3 quadrant and the third number is the value that will go in that position. This pattern repeats for the second and third set of 3 numbers.

How can I write a code that understands this pattern and populates the entire Sudoku board dynamically (even if the JSON data is changed)?

I have no idea how to approach this, so any recommendations would be greatly appreciated!

Text Input Placeholder Overflowing in HTML

<input
    class="form-control"
    style="width: 15rem; height: 15rem;"
    v-model="formData.booking_code"
    placeholder="Masukkan Kode Booking, contoh : XYBJLL"
/>

so, I want to add a placeholder to my input text. but it gets too long so it overflows and the text gets cut off.

I want to make the placeholder text continue to the bottom when it reaches the edge.

I don’t want to use a text area, because it can’t be vertically aligned

How to retrieve the specific records that failed using create()/insertMany() on Mongoose

I’m trying to retrieve the specific record that failed for the non-WriteErrors. I’ve tried using db.collection.create(req.body, {ordered: false}) and db.collection.insertMany(req.body, {ordered: false}}. I’ve also tried looking with aggregateErrors: true or rawResult: true, but still unsuccessful

For the WriteErrors, i.e Duplicate Keys, I found the ‘errmsg’ and ‘op’ that shows the actual record that failed to be inserted

"writeErrors": [{
    "err": {
        "index": 0,
        "code": 11000,
        "errmsg": "E11000 duplicate key error collection: test.collection index: _id_ dup key: { _id: "0000010" }",
        "op": {
            "system": "Dev",
            "user": "00000980",
            "item": "0010",
            ...
        }
    }
}]

I’m looking for a way to get something similiar but for the ValidationErrors, i.e. incorrect key name, wrong data type, etc.
So far I’m only able to catch the error message and the path/value, but I haven’t found something similar to the ‘op’ from the WriteErrors

{
    "errors": {
        "system": {
            "name": "ValidatorError",
            "message": "QA is not a valid system",
            "properties": {
                "message": "QA is not a valid system",
                "type": "user defined",
                "path": "system",
                "value": "QA"
            },
            "kind": "user defined",
            "path": "system",
            "value": "QA"
        }
    },
    "_message": "collection validation failed",
    "name": "ValidationError",
    "message": "collection validation failed: system: QA is not a valid system"
}

Is there a way to get the error message + the specific record that failed for the ValidationErrors/non-WriteErrors?

Thanks in advance!

Passing information through js files running on different HTML

i’m building up a chrome extension which blocks ads from youtube, and it has a popup menu with the following style: My popup menu

Whenever i access this popup menu i have no problems using local storage to keep all the information from the radio buttons and the button, when i open the popup i send myself an alert() and it shows the right values of the variable.

however, because of the structure of these extensions, i’m messing with 2 htmls, one is the popup, and the other one is the Youtube HTML, whenever i try to access these informations using the local storage data, it always returns false (at least it’s not returning null anymore, so i guess i’m on the right way”), and i just can’t find a way to access this information variables on my other js script which manipulates the youtube html.

heres the popup html:

<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="main.css">
</head>
<body>
<div class="top-container">
    <img src="icon_48.png">
    <h2>Yazigi Ad Skipper</h2>
</div>
<div class="container">
<h3>Section of functionalities</h3>
<b>Skip video AD:</b>
<label>
    <input type="radio" name="option" value="after">
    After 5 seconds
</label>
<label>
    <input type="radio" name="option" value="instantly">
    Instantly&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
</label>
<br>
<b>Block banners and ad images:</b>
<label>
    <input type="radio" name="option1" value="activated">
    Activated&nbsp;&nbsp;&nbsp;
</label>
<label>
    <input type="radio" name="option1" value="deactivated">
    Deactivated
</label>
<button id="onoff">Turn off Ad Skipper</button>
</div>
<script src="popup.js" defer></script>
</body>
</html>

heres the popup js:

// popup.js

var AdSkipper;
var WaitVideoAd;
var closeBanner;

function initializeVariables() {
AdSkipper = localStorage.getItem('AdSkipper') === 'true';
WaitVideoAd = localStorage.getItem('WaitVideoAd') === 'true';
closeBanner = localStorage.getItem('closeBanner') === 'true';
}

// Initialize variables
initializeVariables();

// Function to update button text and localStorage
function updateAdSkipperButton() {
    let button = document.getElementById("onoff");
    if (AdSkipper) {
        button.innerText = 'Turn off Ad Skipper';
    } else {
        button.innerText = 'Turn on Ad Skipper';
    }
    localStorage.setItem('AdSkipper', AdSkipper);
}
// Event listener for the "Turn on/off Ad Skipper" button
document.getElementById("onoff").addEventListener("click", function () {
    AdSkipper = !AdSkipper;
    // Update localStorage after AdSkipper is changed
    localStorage.setItem('AdSkipper', AdSkipper);
    // Update button text
    updateAdSkipperButton();
});

// Event listener for the radio button with name "option"
document.querySelectorAll('input[name="option"]').forEach(function (radio) {
    radio.addEventListener("change", function () {
        WaitVideoAd = this.value === "after";
        localStorage.setItem('WaitVideoAd', WaitVideoAd);
    });
});

// Event listener for the radio button with name "option1"
document.querySelectorAll('input[name="option1"]').forEach(function (radio) {
    radio.addEventListener("change", function () {
        closeBanner = this.value === "activated";
        localStorage.setItem('closeBanner', closeBanner);
    });
});

// Initialize the button text based on the stored value
updateAdSkipperButton();

// Alerts after initializing variables
alert(AdSkipper);
alert(WaitVideoAd);
alert(closeBanner);

if needed, that’s how i structured the manifest:

 "action": {
    "default_popup": "popup.html"
},
"content_scripts": [{
    "run_at": "document_start",
    "matches": ["*://*.youtube.com/*"],
    "js": ["script.js"]
}]

and that was my fair attempt to access the variables data from the main script file:

window.addEventListener('yt-page-data-updated', function () {
AdSkipper =   localStorage.getItem('AdSkipper') === 'true';
WaitVideoAd = localStorage.getItem('WaitVideoAd') === 'true';
closeBanner = localStorage.getItem('closeBanner') === 'true';
});

Is there a property on the window that shows when network calls are being made?

Is there a property on the window object or document that indicates if a network call is being made?

I have this code all over my pages that displays an icon when a network call is made:

  showNetworkIcon();
  var response = await fetch(url);
  var data = await response.json();
  showNetworkIcon(false);

But if there are two calls at once then one of them will hide the network call indicator while there are still network calls happening.

Is there a property like this:

var networkCall = window.requestsOpen;

Then I can not hide the network icon if that value is true.

Or if there is an event I can listen for:

window.addEventListener("networkCallOpen", ()=>{ showNetworkIcon() });
window.addEventListener("networkCallClosed", ()=>{ hideNetworkIcon() });

The problem with the above is that if two calls are still one will close before the other so there still needs to be a property to check. Unless there was a an all calls closed event.

window.addEventListener("allNetworkCallsClosed", ()=>{ hideNetworkIcon() });

Web Push Notifications InvalidSignature

I cannot seem to get push notifications to work whatever I try…

This is the error code.
{"code":401,"errno":109,"error":"Unauthorized","message":"InvalidSignature","more_info":"http://autopush.readthedocs.io/en/latest/http.html#error-codes"}

It appears that the issue has something to do with ether a key mismatch or invalid signature.

Here are some of the resources I was using:
https://blog.mozilla.org/services/2016/08/23/sending-vapid-identified-webpush-notifications-via-mozillas-push-service/

https://autopush.readthedocs.io/en/latest/http.html#error-codes

https://datatracker.ietf.org/doc/rfc8292/

I’m generating the public/private keys as so:

    function base64url_encode($data) {
        return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
    }

    function generateVapidKeys(){
        if(file_exists('vapid.json')){
            $vapidKeys = json_decode(file_get_contents('vapid.json'));
            return base64url_encode(hex2bin('04'.$vapidKeys->x.$vapidKeys->y));

        }else{
            $keyPair = openssl_pkey_new([
                'digest_alg' => 'sha256',
                'private_key_type' => OPENSSL_KEYTYPE_EC,
                'curve_name' => 'prime256v1', // P-256 curve
            ]);
        }

        $privateKeyDetails = openssl_pkey_get_details($keyPair);

        $x = str_pad(bin2hex($privateKeyDetails['ec']['x']), 64, '0', STR_PAD_LEFT);
        $y = str_pad(bin2hex($privateKeyDetails['ec']['y']), 64, '0', STR_PAD_LEFT);
        $d = str_pad(bin2hex($privateKeyDetails['ec']['d']), 64, '0', STR_PAD_LEFT);

        file_put_contents('vapid.json', json_encode([
            'x' => $x,
            'y' => $y,
            'd' => $d,
        ], JSON_PRETTY_PRINT));

        return base64url_encode(hex2bin('04'.$x.$y));
    }

    $publicKey = generateVapidKeys();

And finally here is my Notification send:

<?php
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);

    header('Content-Type: application/json; charset=utf-8');

    function generate_jwt($headers, $payload, $privateKey){
        $headers_encoded = base64url_encode(json_encode($headers));
        $payload_encoded = base64url_encode(json_encode($payload));
        
        //$signature = hash_hmac('SHA256', "$headers_encoded.$payload_encoded", $secret, true);
        openssl_sign("$headers_encoded.$payload_encoded", $signature, $privateKey, OPENSSL_ALGO_SHA256);
        $signature_encoded = base64url_encode($signature);
        
        return "$headers_encoded.$payload_encoded.$signature_encoded";
    }

    function is_jwt_valid($jwt, $publicKey){
        $tokenParts = explode('.', $jwt);
    
        // check the expiration time - note this will cause an error if there is no 'exp' claim in the jwt
        $expires = json_decode(base64_decode($tokenParts[1]))->exp < time();//($expires - time()) < 0;

        $signature = openssl_verify($tokenParts[0].'.'.$tokenParts[1], base64_decode($tokenParts[2]), $publicKey, OPENSSL_ALGO_SHA256);
        
        if($expires || !$signature){
            return false;
        }
        return true;
    }


    function generateVapidToken($url, $privateKey) {
    
        $expiration = time() + (12 * 60 * 60);  // 12 hours
    
        $header = [
            'alg' => 'ES256',
            'typ' => 'JWT',
        ];

        $body = [
            'aud' => $url,
            'exp' => $expiration,
            'sub' => 'mailto:[email protected]',
        ];

        return generate_jwt($header, $body, $privateKey);
    }
    
    function base64url_encode($data) {
        return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
    }


    // Assuming you have a database connection established

    // Function to send a push notification
    function sendPushNotification($subscription, $payload)
    {

        $parse = parse_url($subscription->endpoint);
        $url = $parse['scheme'].'://'.$parse['host'];//.pathinfo(parse_url($parse['path'], PHP_URL_PATH))['dirname'];
        echo $url.PHP_EOL.PHP_EOL;

        $vapidKeys = json_decode(file_get_contents('vapid.json'));

        //print_r(json_encode($vapidKeys, JSON_PRETTY_PRINT));


        $keyPair = openssl_pkey_new([
            'ec' => [
                'digest_alg' => 'sha256',
                'private_key_type' => OPENSSL_KEYTYPE_EC,
                'curve_name' => 'prime256v1', // P-256 curve
                'x' => hex2bin($vapidKeys->x),
                'y' => hex2bin($vapidKeys->y),
                'd' => hex2bin($vapidKeys->d)
            ]
        ]);

        $privateKeyDetails = openssl_pkey_get_details($keyPair);

        openssl_pkey_export($keyPair, $privateKey);
        $token = generateVapidToken($url, $privateKey);
        //openssl_sign('HELLO WORLD', $signature, $privateKey, OPENSSL_ALGO_SHA256);
        echo $token;

        echo PHP_EOL;
        echo PHP_EOL;

        $publicKey = openssl_pkey_get_public($privateKeyDetails['key']);
        $verified = is_jwt_valid($token, $publicKey);
        //$verified = openssl_verify('HELLO WORLD', $signature, $publicKey, OPENSSL_ALGO_SHA256);


        echo 'Token Valid: '.(($verified) ? "TRUE" : "FALSE");
        echo PHP_EOL;
        echo PHP_EOL;


        $publicKey = base64url_encode(hex2bin('04'.$vapidKeys->x.$vapidKeys->y));
        echo $publicKey;


        echo PHP_EOL;
        echo PHP_EOL;

        $headers = [
            //'Authorization: WebPush '.$token,
            'Authorization: vapid t='.$token.',k='.$publicKey,
            //'Authorization: key=' . $subscription->keys->auth,
            //'Crypto-Key: p256ecdsa='.$publicKey.';dh='.$subscription->keys->auth,//$subscription->keys->p256dh,
            'Content-Type: application/json',
        ];

        /*
        $notification = [
            'title' => 'Your Notification Title',
            'body' => 'Your Notification Body',
            'icon' => 'path/to/icon.png',
        ];
        */

        $data = [
            'notification' => $payload,
            //'applicationServerKey' => $vapidKeys->publicKey
        ];

        $options = [
            CURLOPT_URL => $subscription->endpoint,
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($payload),
            CURLOPT_RETURNTRANSFER => true,
        ];

        $ch = curl_init();
        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);
    
        if ($result === false) {
            echo 'Error: ' . curl_error($ch) . PHP_EOL;
        } else {
            echo 'Push notification sent successfully!' . PHP_EOL;
        }


        print_r($result);
    }

    // Example payload
    $notificationPayload = [
        'title' => 'New Notification',
        'body' => 'This is the body of the notification.',
        'icon' => 'icon.png'
    ];

    if(file_exists('endpoints.json')){
        $subscriptions = json_decode(file_get_contents('endpoints.json'));

        // Send push notifications to all stored subscriptions
        foreach ($subscriptions as $subscription) {
            sendPushNotification($subscription, $notificationPayload);
        }
    }

?>

In GoJS how can I set a node visible when clicking button of it’s any preceding node?

I want to implement a function: when I click button in a node A, all the nodes having link from A will appear. I have tried TreeExpanderButton but the effect is not what I expected.

I’ll use an example to show what problem I meet:

myDiagram.nodeTemplate =
    $(go.Node, "Spot",
        $(go.Panel, "Auto",
        $(go.Shape, "Rectangle",
            { fill: "gold" }),
        $(go.TextBlock, "Click small buttonnto collapse/expand subtree",
            { margin: 5 },
            new go.Binding("text", "key"))
        ),
        $("TreeExpanderButton",
        { alignment: go.Spot.Bottom, alignmentFocus: go.Spot.Top },
        { visible: true })
    );

    myDiagram.layout = $(go.TreeLayout, { angle: 90 });

    myDiagram.model = new go.GraphLinksModel(
        [ { key: 1 },
          { key: 2 },
          { key: 3 },
        ],
        [ { from: 1, to: 3 },
          { from: 2, to: 3 }] );
    myDiagram.nodes.each(function(n) {
        n.wasTreeExpanded = false; 
        n.isTreeExpanded = false;
    })

Above is the structure of my diagram. When I click the TreeExpanderButton of node 1, the node 3 will appear. But when I click such button of node 2, node 3 will not appear. I guess that’s because node 3 is child of node 1 in tree structure, but I want that a node appear when clicking Button of it’s any preceding node. How can I achieve this goal?

React jsx file not showing HTML on page

For the past couple of days I’ve been trying to figure out why my code isn’t showing in the react page. My backend is already running and when I run ‘npm run dev’ on my frontend it shows:

VITE v4.5.0 ready in 171 ms

➜ Local: http://localhost:5173/
➜ Network: use –host to expose
➜ press h to show help

but when I check my network tab there’s no requests being sent from my backend API URL

Please Help.

I tried lots of things like refiguring my backend url link, created a new jsx file, etc.