Javascript – Find all pairs of indexes in an array

Given an array such as

['a', 'b', 'c', 'd', 'e', 'a', 'c'],

am I able to find all pairs of indexes for a given “start” and “end” index.

Therefore, the above array would return the pairs [0, 2] and [5, 6] for the start character ‘a’ and the end character ‘c’. There can be one to many pairs.

I know I can get the indexes of all ‘a’ and all ‘c’ in separate lists: a = [0, 5], c = [2,6] and then grab the first item of each list and so forth, but was curious if it was possible to get the indexes at the same time.

Thanks!

Typing game with svelte caret/cursor doesnt move to the next word

the problem is the caret doesnt want to move to the next word after press the space keydown

here the code

this it for space function

function handleKeyDown() {
        if (event.code === "Space") {
            event.preventDefault();

            if (game === "in progress") {
                nextWord();
            }
        }

        if (event.code === "Backspace") {
            checkPrevLetter();
        }

        if (game === "waiting for input") {
            startGame();
        }
    }

this is function for go to the next word

 function nextWord() {
        const isNotFirstLetter = letterIndex !== 0;
        const isOneLetterWord = words[wordIndex].length === 1;

        if (isNotFirstLetter || isOneLetterWord) {
            wordIndex += 1;
            letterIndex = 0;
            increaseScore();
            moveCaret();
        }
    }

this is the moveCaret function

function moveCaret() {
        const offset = 4;
        caretEl.style.top = `${letterEl.offsetTop + offset}px`;
        caretEl.style.left = `${letterEl.offsetLeft + letterEl.offsetWidth}px`;
    }

i have tried to adding a space between the word and removing the Space code and experiment all the code but none of them working correctly,

caret image

i want when user click space the caret should move to the first letter of the next word just like monkeytype.com if you familiar with it, thanks you so much

this is the repo for the full code :
https://github.com/firzalay/type-master

PIXI.js Graphics reduce, or set mask for mask

I want to achieve a scratch effect,An effect similar to this:
enter image description here

Now I can increase the area of Graphics through events to increase the visible range, but I still need to make the visible range smaller. What do I need to do to reduce the area of Graphics?

this is my code:

import {
    FederatedPointerEvent,
    Graphics, LINE_CAP, LINE_JOIN, Point, type Application,
    Sprite,
    Assets
} from "pixi.js"

import data from './data'
export async function useTink(app: Application) {
    const ids = (await Assets.load('../images/treasureHunter.json')).textures

    console.log(ids)
    const dungeon = Sprite.from(ids['dungeon.png'])

    app.stage.addChild(dungeon)


    const graphics = new Graphics()
    graphics.lineStyle({
        width: 80,
        color: 0xff8888,
        alpha: 1,
        cap: LINE_CAP.ROUND,
    })
    for (let i = 0; i < data.length - 1; i++) {
        const item = data[i];
        graphics.moveTo(item[0], item[1])
        graphics.lineTo(data[i + 1][0], data[i + 1][1])
    }

    if (data.length > 1) {
        graphics.lineTo(data[data.length - 1][0], data[data.length - 1][1])
    }
    dungeon.mask = graphics

    app.stage.addChild(graphics)
    app.stage.eventMode = 'static'
    app.stage.cursor = 'crosshair'
    let drawing = false

    let start = { x: 0, y: 0 }
    const points: number[][] = []
    app.stage.on("pointerdown", (event: FederatedPointerEvent) => {
        drawing = true
        start.x = event.global.x
        start.y = event.global.y
    })

    app.stage.on("pointermove", (event: FederatedPointerEvent) => {
        if (drawing) {
            points.push([start.x, start.y])
            graphics.moveTo(start.x, start.y)
            graphics.lineTo(event.global.x, event.global.y)
            start.x = event.global.x
            start.y = event.global.y
        }
    })
    app.stage.on("pointerup", (event: FederatedPointerEvent) => {
        drawing = false
    })
}

this is example data:
enter image description here

Thank you so much.

Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No “exports” main defined in @authsequelize-adapterpackage.json

Environment

Node: 18.17.1
Yarn: 1.22.19
npm: 9.6.7

Describe the issue

The project I am on recently changed from another authentication to nextAuth.js. After adding the Sequelize adapter by nextAuth.js, I have experienced the Error shown below when using unit tests or customized tools to call Server-side API

Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main defined in C:[email protected]
    at new NodeError (node:internal/errors:405:5)
    at exportsNotFound (node:internal/modules/esm/resolve:359:10)
    at packageExportsResolve (node:internal/modules/esm/resolve:639:13)
    at resolveExports (node:internal/modules/cjs/loader:567:36)
    at Function.Module._findPath (node:internal/modules/cjs/loader:636:31)
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:1063:27)
    at Function.Module._resolveFilename.sharedData.moduleResolveFilenameHook.installedValue [as _resolveFilename] (C:srcappnode_modules@cspotcodesource-map-supportsource-map-support.js:811:30)
    at Function.Module._load (node:internal/modules/cjs/loader:922:27)
    at Module.require (node:internal/modules/cjs/loader:1143:19)
    at require (node:internal/modules/cjs/helpers:121:18)
    at Object.<anonymous> (C:srcappsrcpagesapiauth[...nextauth].ts:2:1)
    at Module._compile (node:internal/modules/cjs/loader:1256:14)
    at Module.m._compile (C:srcappnode_modulests-nodesrcindex.ts:1618:23)
    at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
    at Object.require.extensions.<computed> [as .ts] (C:srcappnode_modulests-nodesrcindex.ts:1621:12)
    at Module.load (node:internal/modules/cjs/loader:1119:32)
    at Function.Module._load (node:internal/modules/cjs/loader:960:12)
    at Module.require (node:internal/modules/cjs/loader:1143:19)
    at require (node:internal/modules/cjs/helpers:121:18)
    at Object.<anonymous> (C:srcappsrcapiauth.ts:9:1)
    at Module._compile (node:internal/modules/cjs/loader:1256:14)

Solutions tried

I have tried downgrading/upgrading the packages using yarn or npm, customizing the export directly in sequelize-adapter package.json, along with trying different nodejs versions such as 16,18, and 20 but this problem persists.

How to reproduce

execute package.json scripts that call server-side API

Expected behavior

Before changing to nextAuth,js and using the Sequelize adapter to manage models, the unit tests and tools function normally when running package.json scripts

Actual behavior

I have found that whenever a script is imported and executed a server-side API, the error above will show.
However, the web app and APIs work normally when under development or production.

If you would like to contribute to Github page

File not found error when trying to read in contents of a text file in svelte app

I am trying to read in the contents of a text file and display it in my svelte application. I am getting a 404 console error that says the file cannot be found even though I know the path is correct. Can anyone help with this please?

<script>
    let text;
    
    import { onMount } from 'svelte';
        onMount(()=> {
            loadItems();
        });
    
        const loadItems = async()=>{
            const response = await fetch ("aboutSimwb.txt");
            text = await response.text();
            
        };


</script>

<div class = "scrollable-container">
    
    <slot>
       <p>
        {text}
       </p>
    </slot>
</div>

<style>
    .scrollable-container{
        height: 300px;
        overflow-y: scroll;
        border: 1px solid #ccc;
    }
</style>

” or ‘activeTab’ permission is required

I’m trying to capture the visible tab, but every time I try that, I get this error:
'<all_urls>' or 'activeTab' permission is required.

My code is below:

background.js

chrome.tabs.captureVisibleTab((dataUrl) => {
    console.log(dataUrl)
});

manifest.json

{
    "manifest_version": 3,
    "name": "AppName",
    "description": "A early-access extension.",
    "version": "1.0",
    "permissions": [
        "activeTab"
      ],

      "background": {
          "service_worker": "background.js"
      },

      "action": {},

      "content_scripts": [
        {
          "matches": ["<all_urls>"],
          "js": ["content-script.js"] 
        }
      ],
    
      "host_permissions": [
        "http://*/*",
        "https://*/*"
      ]
  }

I tried changing the background code, I tried changing “service_worker” to “script” but it didn’t work.
Hopefully someone can help me on this.

Thanks.

JavaScript to Validate Form if certain selections are made and show dialog box

I have a HTML form which has 3 sections of yes/no questions for the user to complete. There’s an existing script to ensure they only select answers to one of the 3 sections.

I would now like to add an additional validation for when the user selects no for all the answers in any section. If they do select no for the section questions I would like to throw a dialog box with 2 buttons (OK and Cancel) and text “You have selected No for your answers. Do you wish to continue?”

Here’s my form and the current scripts I have:

$(document).ready(function() {
  $("#editRecord").on("submit", function(e) {
    var buttonClicked = $("input[type=submit][clicked=true]").val();

    if (buttonClicked === "Continue") {
      if (!validateFinish(e)) {
        e.preventDefault();
        console.log("Continue");
      }
    } else if (buttonClicked === "Save Draft") {
      if (!validateSaveDraft()) {
        e.preventDefault();
        console.log("Save Draft");
      }
    }
  });

  $("input[type=submit]").click(function() {
    $("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
    $(this).attr("clicked", "true");
  });

  function validateFinish(ev) {
    // Add your validation logic for the Finish button here
    //alert("Form Validation is starting!");

    var sectionsTouched = $('tbody').has(':checked'),
      inputs = {},
      errorMessage = '';

    if (sectionsTouched.length === 0) {
      errorMessage = 'Please check something before submitting.';
    } else if (sectionsTouched.length > 1) {
      errorMessage = 'Please complete A or B or C only';
    } else {
      sectionsTouched.find('input').each(function(i, e) {
        var me = $(e),
          name = me.attr('name');
        inputs[name] = !!inputs[name] || me.is(':checked');
      });
      $.each(inputs, function(k, v) {
        if (!v) {
          errorMessage = 'It appears you have not completed all questions.';
        }
        return v;
      });
    }
    if (errorMessage !== '') {
      $('#error').html(errorMessage);
      ev.preventDefault();
      return false;
    }
    return true;
  }

  function validateSaveDraft() {
    // Add your validation logic for the Save Draft button here
    //alert("Just saving a Draft!");
    return true;
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<form action="rateArticleCodes.php" method="post" class="" id="editRecord">
  <input type="hidden" name="recid" value="123445">


  <div class="rate-buttons left py2">
    <input type="submit" name="buttonType" id="saveDraft" value="Save Draft" class="mr1">
    <input type="reset" name="buttonType" value="Reset" class="mx1">
    <input type="submit" name="buttonType" id="submit" value="Continue" class="ml1">
  </div>
  <div id="error" style="color: red"></div>

  <table>
    <thead>
      <tr>
        <th class="nowrap text-left" colspan="2">Section 1</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>A1.</td>
        <td class="nowrap form-radio"><label>
                                                        <input name="CriteriaA1" type="radio" value="Yes"><span>Yes</span></label><label class="ml3"><input name="CriteriaA1" type="radio" value="No"><span>No</span></label></td>
      </tr>
      <tr>
        <td>A2.</td>
        <td class="nowrap form-radio"><label>
                                                        <input name="CriteriaA2" type="radio" value="Yes"><span>Yes</span></label><label class="ml3"><input name="CriteriaA2" type="radio" value="No"><span>No</span></label></td>
      </tr>
      <tr>
        <td>A3.</td>
        <td class="nowrap form-radio"><label>
                                                        <input name="CriteriaA3" type="radio" value="Yes"><span>Yes</span></label><label class="ml3"><input name="CriteriaA3" type="radio" value="No"><span>No</span></label></td>
      </tr>
      <tr>
        <td>A4.</td>
        <td class="nowrap form-radio"><label>
                                                        <input name="CriteriaA4" type="radio" value="Yes"><span>Yes</span></label><label class="ml3"><input name="CriteriaA4" type="radio" value="No"><span>No</span></label></td>
      </tr>
      <tr>
        <td>A5.</td>
        <td class="nowrap form-radio"><label>
                                                        <input name="CriteriaA5" type="radio" value="Yes"><span>Yes</span></label><label class="ml3"><input name="CriteriaA5" type="radio" value="No"><span>No</span></label></td>
      </tr>
    </tbody>
  </table>

  <p class="m2"><strong>OR</strong></p>

  <table>
    <thead>
      <tr>
        <th class="nowrap text-left" colspan="2">Section 2</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>B1. </td>
        <td class="nowrap form-radio"><label>
                                                        <input name="CriteriaB1" type="radio" value="Yes"><span>Yes</span></label><label class="ml3"><input name="CriteriaB1" type="radio" value="No"><span>No</span></label></td>
      </tr>
      <tr>
        <td>B2.</td>
        <td class="nowrap form-radio"><label>
                                                        <input name="CriteriaB2" type="radio" value="Yes"><span>Yes</span></label><label class="ml3"><input name="CriteriaB2" type="radio" value="No"><span>No</span></label></td>
      </tr>
      <tr>
        <td>B3.</td>
        <td class="nowrap form-radio"><label>
                                                        <input name="CriteriaB3" type="radio" value="Yes"><span>Yes</span></label><label class="ml3"><input name="CriteriaB3" type="radio" value="No"><span>No</span></label></td>
      </tr>
    </tbody>
  </table>

  <p class="m2"><strong>OR</strong></p>

  <table>
    <thead>
      <tr>
        <th class="nowrap text-left" colspan="2">Section 3</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>C1.</td>
        <td class="nowrap form-radio"><label>
                                                        <input name="CriteriaC1" type="radio" value="Yes"><span>Yes</span></label><label class="ml3"><input name="CriteriaC1" type="radio" value="No"><span>No</span></label></td>
      </tr>
      <tr>
        <td>C2.</td>
        <td class="nowrap form-radio"><label>
                                                        <input name="CriteriaC2" type="radio" value="Yes"><span>Yes</span></label><label class="ml3"><input name="CriteriaC2" type="radio" value="No"><span>No</span></label></td>
      </tr>
      <tr>
        <td>C3. </td>
        <td class="nowrap form-radio"><label>
                                                        <input name="CriteriaC3" type="radio" value="Yes"><span>Yes</span></label><label class="ml3"><input name="CriteriaC3" type="radio" value="No"><span>No</span></label></td>
      </tr>
      <tr>
        <td>C4. </td>
        <td class="nowrap form-radio"><label>
                                                        <input name="CriteriaC4" type="radio" value="Yes"><span>Yes</span></label><label class="ml3"><input name="CriteriaC4" type="radio" value="No"><span>No</span></label></td>
      </tr>
      <tr>
        <td>C5. </td>
        <td class="nowrap form-radio"><label>
                                                        <input name="CriteriaC5" type="radio" value="Yes"><span>Yes</span></label><label class="ml3"><input name="CriteriaC5" type="radio" value="No"><span>No</span></label></td>
      </tr>
      <tr>
        <td>C6. </td>
        <td class="nowrap form-radio"><label>
                                                <input name="CriteriaC6" type="radio" value="Yes"><span>Yes</span></label><label class="ml3"><input name="CriteriaC6" type="radio" value="No"><span>No</span></label></td>
      </tr>
    </tbody>
  </table>


  <div class="rate-buttons left py2">
    <input type="reset" name="buttonType" value="Reset" class="mx1">
    <input type="submit" name="buttonType" id="submit" value="Continue" class="ml1">
  </div>
  <div id="error" style="color: red"></div>

  <!-- to here -->

</form>

I’m not sure how to check for “no” answers when the Continue button if clicked and then show a dialog box if they are?

undefined (reading ‘x’) at Control.polygonPositionHandler

I have a code where I can draw and edit a polygon using javascript and fabric JS. I want it to work into angular and tried converting it but other fucntions does not work and the original code works fine to add and edit.

By the way I am using fabric js to draw on the canvas and I am also using angular version 12 >>

Anyone there has an idea how to solve the issue in the edit polygon function? Thank you.

I would appreciate anyone that can help and point the issue.

#original code

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>

<script src="https://unpkg.com/[email protected]/dist/fabric.js"></script>

    <button type="button" onclick="toggleDrawPolygon()">Draw Polygon</button>
    <button type="button" onclick="editPolygon()">Edit Polygon</button>
    <button type="button" onclick="resizePolygon()">Resize/Move Polygon</button>
    <button type="button" onclick="clearPolygon()">Clear</button>

    <canvas id="c"></canvas>


    <script type="text/javascript">
        let activeLine;
    let activeShape;
    let canvas;
    let lineArray = [];
    let pointArray = [];
    let drawMode = false;

    function initCanvas() {
        canvas = new fabric.Canvas('c');
        // canvas.backgroundColor = 'rgba(0,0,0,0.3)';
        canvas.setHeight(720);
        canvas.setWidth(1280);
        var imageUrl = "https://images.wallpaperscraft.com/image/road_asphalt_marking_130996_1280x720.jpg";

        // Define 
        canvas.setBackgroundImage(imageUrl, canvas.renderAll.bind(canvas), {
            // Optionally add an opacity lvl to the image
            backgroundImageOpacity: 0.5,
            // should the image be resized to fit the container?
            backgroundImageStretch: true
        });

        //fabric.Object.prototype.originX = 'center';
        //fabric.Object.prototype.originY = 'center';


        canvas.on('mouse:down', onMouseDown);
        canvas.on('mouse:up', onMouseUp);
        canvas.on('mouse:move', onMouseMove);
        canvas.on('object:moving', onObjectMove);
        // canvas.on('mouse:wheel', onMouseWheel);
    }

    function onMouseDown(options) {    
        if (drawMode) {
            if (options.target && options.target.id === pointArray[0].id) {
                // when click on the first point
                generatePolygon(pointArray);
            } else {
                addPoint(options);
            }
        }
        
        var evt = options.e;
        if (evt.altKey === true) {
            this.isDragging = true;
            this.selection = false;
            this.lastPosX = evt.clientX;
            this.lastPosY = evt.clientY;
        }
    }

    function onMouseUp(options) {
      this.isDragging = false;
      this.selection = true;
    }

    function onMouseMove(options) {
        if (this.isDragging) {
            var e = options.e;
            this.viewportTransform[4] += e.clientX - this.lastPosX;
            this.viewportTransform[5] += e.clientY - this.lastPosY;
            this.requestRenderAll();
            this.lastPosX = e.clientX;
            this.lastPosY = e.clientY;
        } 
        if (drawMode) {
            if (activeLine && activeLine.class === 'line') {
                const pointer = canvas.getPointer(options.e);
                activeLine.set({
                    x2: pointer.x,
                    y2: pointer.y
                });
                const points = activeShape.get('points');
                points[pointArray.length] = {
                    x: pointer.x,
                    y: pointer.y,
                };
                activeShape.set({
                    points
                });
            }
            canvas.renderAll();
        }
    }

    function onMouseWheel(options) {
      var delta = options.e.deltaY;
      var pointer = canvas.getPointer(options.e);
      var zoom = canvas.getZoom();  
      if (delta > 0) {
        zoom += 0.1;
      } else {
        zoom -= 0.1;
      }
      if (zoom > 20) zoom = 20;
      if (zoom < 0.1) zoom = 0.1;
      canvas.zoomToPoint({ x: options.e.offsetX, y: options.e.offsetY }, zoom);
      options.e.preventDefault();
      options.e.stopPropagation();
    }

    function onObjectMove(option) {
        const object = option.target;
        object._calcDimensions();
        object.setCoords();    
        canvas.renderAll();
    }

    function toggleDrawPolygon(event) {
        if (drawMode) {
            // stop draw mode
            activeLine = null;
            activeShape = null;
            lineArray = [];
            pointArray = [];
            canvas.selection = true;
            drawMode = false;
        } else {
            // start draw mode
            canvas.selection = false;
            drawMode = true;
        }
    }

    function addPoint(options) {
        const pointOption = {
            id: new Date().getTime(),
            radius: 5,
            fill: '#ffffff',
            stroke: '#333333',
            strokeWidth: 0.5,
            left: options.e.layerX / canvas.getZoom(),
            top: options.e.layerY / canvas.getZoom(),
            selectable: false,
            hasBorders: false,
            hasControls: false,
            originX: 'center',
            originY: 'center',
            objectCaching: false,
        };
        const point = new fabric.Circle(pointOption);

        if (pointArray.length === 0) {
            // fill first point with red color
            point.set({
                fill: 'red'
            });
        }

        const linePoints = [
            options.e.layerX / canvas.getZoom(),
            options.e.layerY / canvas.getZoom(),
            options.e.layerX / canvas.getZoom(),
            options.e.layerY / canvas.getZoom(),
        ];
        const lineOption = {
            strokeWidth: 2,
            fill: '#999999',
            stroke: '#999999',
            originX: 'center',
            originY: 'center',
            selectable: false,
            hasBorders: false,
            hasControls: false,
            evented: false,
            objectCaching: false,
        };
        const line = new fabric.Line(linePoints, lineOption);
        line.class = 'line';

        if (activeShape) {
            const pos = canvas.getPointer(options.e);
            const points = activeShape.get('points');
            points.push({
                x: pos.x,
                y: pos.y
            });
            const polygon = new fabric.Polygon(points, {
                stroke: '#333333',
                strokeWidth: 1,
                fill: '#cccccc',
                opacity: 0.3,
                selectable: false,
                hasBorders: false,
                hasControls: false,
                evented: false,
                objectCaching: false,
            });
            canvas.remove(activeShape);
            canvas.add(polygon);
            activeShape = polygon;
            canvas.renderAll();
        } else {
            const polyPoint = [{
                x: options.e.layerX / canvas.getZoom(),
                y: options.e.layerY / canvas.getZoom(),
            }, ];
            const polygon = new fabric.Polygon(polyPoint, {
                stroke: '#333333',
                strokeWidth: 1,
                fill: '#cccccc',
                opacity: 0.3,
                selectable: false,
                hasBorders: false,
                hasControls: false,
                evented: false,
                objectCaching: false,
            });
            activeShape = polygon;
            canvas.add(polygon);
        }

        activeLine = line;
        pointArray.push(point);
        lineArray.push(line);

        canvas.add(line);
        canvas.add(point);
    }

    function generatePolygon(pointArray) {
        const points = [];
        // collect points and remove them from canvas
        for (const point of pointArray) {
            points.push({
                x: point.left,
                y: point.top,
            });
            canvas.remove(point);
        }

        // remove lines from canvas
        for (const line of lineArray) {
            canvas.remove(line);
        }

        // remove selected Shape and Line 
        canvas.remove(activeShape).remove(activeLine);

        // create polygon from collected points
        console.log(points)
        const polygon = new fabric.Polygon(points, {
            id: new Date().getTime(),
            stroke: '#0084ff',
            fill: false,
            objectCaching: false,
            moveable: false,
            //selectable: false
        });
        canvas.add(polygon);

        toggleDrawPolygon();
        editPolygon();
    }

    /**
     * define a function that can locate the controls.
     * this function will be used both for drawing and for interaction.
     */
    function polygonPositionHandler(dim, finalMatrix, fabricObject) {
      var x = (fabricObject.points[this.pointIndex].x - fabricObject.pathOffset.x),
            y = (fabricObject.points[this.pointIndex].y - fabricObject.pathOffset.y);
        return fabric.util.transformPoint(
            { x: x, y: y },
      fabric.util.multiplyTransformMatrices(
        fabricObject.canvas.viewportTransform,
        fabricObject.calcTransformMatrix()
      )
        );
    }

    /**
     * define a function that will define what the control does
     * this function will be called on every mouse move after a control has been
     * clicked and is being dragged.
     * The function receive as argument the mouse event, the current trasnform object
     * and the current position in canvas coordinate
     * transform.target is a reference to the current object being transformed,
     */
    function actionHandler(eventData, transform, x, y) {
        var polygon = transform.target,
            currentControl = polygon.controls[polygon.__corner],
            mouseLocalPosition = polygon.toLocalPoint(new fabric.Point(x, y), 'center', 'center'),
        polygonBaseSize = polygon._getNonTransformedDimensions(),
                size = polygon._getTransformedDimensions(0, 0),
                finalPointPosition = {
                    x: mouseLocalPosition.x * polygonBaseSize.x / size.x + polygon.pathOffset.x,
                    y: mouseLocalPosition.y * polygonBaseSize.y / size.y + polygon.pathOffset.y
                };
        polygon.points[currentControl.pointIndex] = finalPointPosition;
        return true;
    }

    /**
     * define a function that can keep the polygon in the same position when we change its
     * width/height/top/left.
     */
  function anchorWrapper(anchorIndex, fn) {
    return function(eventData, transform, x, y) {
      var fabricObject = transform.target,
          absolutePoint = fabric.util.transformPoint({
              x: (fabricObject.points[anchorIndex].x - fabricObject.pathOffset.x),
              y: (fabricObject.points[anchorIndex].y - fabricObject.pathOffset.y),
          }, fabricObject.calcTransformMatrix()),
          actionPerformed = fn(eventData, transform, x, y),
          newDim = fabricObject._setPositionDimensions({}),
          polygonBaseSize = fabricObject._getNonTransformedDimensions(),
          newX = (fabricObject.points[anchorIndex].x - fabricObject.pathOffset.x) / polygonBaseSize.x,
            newY = (fabricObject.points[anchorIndex].y - fabricObject.pathOffset.y) / polygonBaseSize.y;
      fabricObject.setPositionByOrigin(absolutePoint, newX + 0.5, newY + 0.5);
      return actionPerformed;
    }
  }

    function editPolygon() {
        let activeObject = canvas.getActiveObject();
        if (!activeObject) {
            activeObject = canvas.getObjects()[0];
            canvas.setActiveObject(activeObject);
        }

        activeObject.edit = true;
        activeObject.objectCaching = false;

        const lastControl = activeObject.points.length - 1;
        activeObject.cornerStyle = 'circle';
        activeObject.controls = activeObject.points.reduce((acc, point, index) => {
            acc['p' + index] = new fabric.Control({
                positionHandler: polygonPositionHandler,
                actionHandler: anchorWrapper(index > 0 ? index - 1 : lastControl, actionHandler),
                actionName: 'modifyPolygon',
                pointIndex: index,
            });
            return acc;
        }, {});

        activeObject.hasBorders = false;

        canvas.requestRenderAll();
    }

    function resizePolygon() {
        let activeObject = canvas.getActiveObject();
        if (!activeObject) {
            activeObject = canvas.getObjects()[0];
            canvas.setActiveObject(activeObject);
        }

        activeObject.edit = false;
        activeObject.objectCaching = false;
        activeObject.controls = fabric.Object.prototype.controls;
        activeObject.cornerStyle = 'rect';
        activeObject.hasBorders = true;

        canvas.requestRenderAll();
    }

    function clearPolygon(){
        canvas.remove(...canvas.getObjects());
    }

    initCanvas();
    </script>
</body>
</html>

#converted html code

<div>
  <button type="button" (click)="toggleDrawPolygon()">Draw Polygon</button>
  <button type="button" (click)="editPolygon()">Edit Polygon</button>
  <button type="button" (click)="resizePolygon()">Resize/Move Polygon</button>
  <button type="button" (click)="clearPolygon()">Clear</button>
</div>

<canvas id="c"></canvas>

#converted ts code


import { AfterViewInit, Component, ElementRef, Input, OnInit, ViewChild } from '@angular/core';
const fabric = require("fabric").fabric;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements  OnInit, AfterViewInit {
  
  activeLine: any;
  activeShape: any;
  canvas: any;
  lineArray: any[] = [];
  pointArray: any[] = [];
  drawMode = false;
  pointIndex: any;

  constructor() { }

  ngOnInit(): void {
  }

  ngAfterViewInit(): void {
    this.initCanvas();
  }

  initCanvas() {
    this.canvas = new fabric.Canvas('c');
    this.canvas.setHeight(720);
    this.canvas.setWidth(1280);
    const imageUrl = "https://wpmedia.roomsketcher.com/content/uploads/2021/12/14164614/RoomSketcher-House-Floor-Plans-2452430-800.jpg";

    this.canvas.setBackgroundImage(imageUrl, this.canvas.renderAll.bind(this.canvas), {
      backgroundImageOpacity: 0.5,
      backgroundImageStretch: true
    });

    this.canvas.on('mouse:down', (options: any) => this.onMouseDown(options));
    this.canvas.on('mouse:up', () => this.onMouseUp());
    this.canvas.on('mouse:move', (options: any) => this.onMouseMove(options));
    this.canvas.on('object:moving', (option: any) => this.onObjectMove(option));
  }

  onMouseDown(options: any) {
    if (this.drawMode) {
      if (options.target && options.target.id === this.pointArray[0].id) {
        this.generatePolygon(this.pointArray);
      } else {
        this.addPoint(options);
      }
    }

    const evt = options.e;
    if (evt.altKey === true) {
      this.canvas.isDragging = true;
      this.canvas.selection = false;
      this.canvas.lastPosX = evt.clientX;
      this.canvas.lastPosY = evt.clientY;
    }
  }

  onMouseUp() {
    this.canvas.isDragging = false;
    this.canvas.selection = true;
  }

  onMouseMove(options: any) {
    if (this.canvas.isDragging) {
      const e = options.e;
      this.canvas.viewportTransform[4] += e.clientX - this.canvas.lastPosX;
      this.canvas.viewportTransform[5] += e.clientY - this.canvas.lastPosY;
      this.canvas.requestRenderAll();
      this.canvas.lastPosX = e.clientX;
      this.canvas.lastPosY = e.clientY;
    }
    if (this.drawMode) {
      if (this.activeLine && this.activeLine.class === 'line') {
        const pointer = this.canvas.getPointer(options.e);
        this.activeLine.set({
          x2: pointer.x,
          y2: pointer.y
        });
        const points = this.activeShape.get('points');
        points[this.pointArray.length] = {
          x: pointer.x,
          y: pointer.y,
        };
        this.activeShape.set({
          points
        });
      }
      this.canvas.renderAll();
    }
  }

  onObjectMove(option: any) {
    const object = option.target;
    object._calcDimensions();
    object.setCoords();
    this.canvas.renderAll();
  }

  toggleDrawPolygon() {
    if (this.drawMode) {
      this.activeLine = null;
      this.activeShape = null;
      this.lineArray = [];
      this.pointArray = [];
      this.canvas.selection = true;
      this.drawMode = false;
    } else {
      this.canvas.selection = false;
      this.drawMode = true;
    }
  }

  addPoint(options: any) {
    const pointOption = {
      id: new Date().getTime(),
      radius: 5,
      fill: '#ffffff',
      stroke: '#333333',
      strokeWidth: 0.5,
      left: options.e.layerX / this.canvas.getZoom(),
      top: options.e.layerY / this.canvas.getZoom(),
      selectable: false,
      hasBorders: false,
      hasControls: false,
      originX: 'center',
      originY: 'center',
      objectCaching: false,
    };
    const point = new fabric.Circle(pointOption);

    if (this.pointArray.length === 0) {
      point.set({
        fill: 'red'
      });
    }

    const linePoints = [
      options.e.layerX / this.canvas.getZoom(),
      options.e.layerY / this.canvas.getZoom(),
      options.e.layerX / this.canvas.getZoom(),
      options.e.layerY / this.canvas.getZoom(),
    ];
    const lineOption = {
      strokeWidth: 2,
      fill: '#999999',
      stroke: '#999999',
      originX: 'center',
      originY: 'center',
      selectable: false,
      hasBorders: false,
      hasControls: false,
      evented: false,
      objectCaching: false,
    };
    const line = new fabric.Line(linePoints, lineOption);

// Set a custom property 'customClass' on the line object
      (line as any).customClass = 'line';


    if (this.activeShape) {
      const pos = this.canvas.getPointer(options.e);
      const points = this.activeShape.get('points');
      points.push({
        x: pos.x,
        y: pos.y
      });
      const polygon = new fabric.Polygon(points, {
        stroke: '#333333',
        strokeWidth: 1,
        fill: '#cccccc',
        opacity: 0.3,
        selectable: false,
        hasBorders: false,
        hasControls: false,
        evented: false,
        objectCaching: false,
      });
      this.canvas.remove(this.activeShape);
      this.canvas.add(polygon);
      this.activeShape = polygon;
      this.canvas.renderAll();
    } else {
      const polyPoint = [{
        x: options.e.layerX / this.canvas.getZoom(),
        y: options.e.layerY / this.canvas.getZoom(),
      }];
      const polygon = new fabric.Polygon(polyPoint, {
        stroke: '#333333',
        strokeWidth: 1,
        fill: '#cccccc',
        opacity: 0.3,
        selectable: false,
        hasBorders: false,
        hasControls: false,
        evented: false,
        objectCaching: false,
      });
      this.activeShape = polygon;
      this.canvas.add(polygon);
    }

    this.activeLine = line;
    this.pointArray.push(point);
    this.lineArray.push(line);

    this.canvas.add(line);
    this.canvas.add(point);
  }

  generatePolygon(pointArray: any) {
    const points = [];
    for (const point of pointArray) {
      points.push({
        x: point.left,
        y: point.top,
      });
      this.canvas.remove(point);
    }
  
    for (const line of this.lineArray) {
      this.canvas.remove(line);
    }
  
    this.canvas.remove(this.activeShape).remove(this.activeLine);
  
    const polygon = new fabric.Polygon(points, {
      stroke: '#0084ff',
      fill: 'black',
    });
    this.canvas.add(polygon);
  
    this.toggleDrawPolygon();
    this.editPolygon();
  }


  polygonPositionHandler(dim : any, finalMatrix : any, fabricObject : any) {
    var x = (fabricObject.points[this.pointIndex].x - fabricObject.pathOffset.x),
          y = (fabricObject.points[this.pointIndex].y - fabricObject.pathOffset.y);
      return fabric.util.transformPoint(
          { x: x, y: y },
    fabric.util.multiplyTransformMatrices(
      fabricObject.canvas.viewportTransform,
      fabricObject.calcTransformMatrix()
    )
      );
  }

  actionHandler(eventData: any, transform: any, x: any, y: any) {
    const polygon = transform.target;
    const currentControl = polygon.controls[polygon.__corner];
    const mouseLocalPosition = polygon.toLocalPoint(new fabric.Point(x, y), 'center', 'center');
    const polygonBaseSize = polygon._getNonTransformedDimensions();
    const size = polygon._getTransformedDimensions(0, 0);
    const finalPointPosition = {
      x: mouseLocalPosition.x * polygonBaseSize.x / size.x + polygon.pathOffset.x,
      y: mouseLocalPosition.y * polygonBaseSize.y / size.y + polygon.pathOffset.y
    };
    polygon.points[currentControl.pointIndex] = finalPointPosition;
    return true;
  }

  anchorWrapper(anchorIndex: any, fn: any) {
    return (eventData: any, transform: any, x: any, y: any) => {
      const fabricObject = transform.target;
      const point = new fabric.Point(
        fabricObject.points[anchorIndex].x - fabricObject.pathOffset.x,
        fabricObject.points[anchorIndex].y - fabricObject.pathOffset.y
      );
      const absolutePoint = fabric.util.transformPoint(point, fabricObject.calcTransformMatrix());
      const actionPerformed = fn(eventData, transform, x, y);
      const newDim = fabricObject._setPositionDimensions({});
      const polygonBaseSize = fabricObject._getNonTransformedDimensions();
      const newX = (fabricObject.points[anchorIndex].x - fabricObject.pathOffset.x) / polygonBaseSize.x;
      const newY = (fabricObject.points[anchorIndex].y - fabricObject.pathOffset.y) / polygonBaseSize.y;
      fabricObject.setPositionByOrigin(absolutePoint, newX + 0.5, newY + 0.5);
      return actionPerformed;
    };
  }

 

  editPolygon() {
    let activeObject =  this.canvas.getActiveObject();
    if (!activeObject) {
        activeObject =  this.canvas.getObjects()[0];
        this.canvas.setActiveObject(activeObject);
    }

    activeObject.edit = true;
    activeObject.objectCaching = false;

    const lastControl = activeObject.points.length - 1;
    activeObject.cornerStyle = 'circle';
    activeObject.controls = activeObject.points.reduce((acc:any,index:any) => {
        acc['p' + index] = new fabric.Control({
            positionHandler: this.polygonPositionHandler,
            actionHandler: this.anchorWrapper(index > 0 ? index - 1 : lastControl, this.actionHandler),
            actionName: 'modifyPolygon',
            pointIndex: index,
        });
        return acc;
    }, {});

    activeObject.hasBorders = false;
    this.canvas.requestRenderAll();
}

  resizePolygon() {
    let activeObject = this.canvas.getActiveObject();
    if (!activeObject) {
      activeObject = this.canvas.getObjects()[0];
      this.canvas.setActiveObject(activeObject);
    }

    activeObject.edit = false;
    activeObject.objectCaching = false;
    activeObject.controls = fabric.Object.prototype.controls;
    activeObject.cornerStyle = 'rect';
    activeObject.hasBorders = true;

    this.canvas.requestRenderAll();
  }

  clearPolygon() {
    this.canvas.remove(...this.canvas.getObjects());
  }
}

I am developing a software using reactJS where while fetching data from API using post method I was not able to fetch data [closed]

Below is the code in which I am facing error and unable to fetch data from the database using API. Also the request is being sent through the API but facing error to get data then I checked it on FIDDLER which showed error(mentioned below code) and is not showing any JSON output:

React component
AddOutlet.js:

import React, { useState } from 'react';
import './AddOutletStyle.css';
import { useNavigate } from 'react-router-dom';

const AddOutlet = () => {
  const [id, setId] = useState('');
  const [name, setOutletType] = useState('');
  const [discount, setDiscount] = useState('');
  const [responseMessage, setResponseMessage] = useState(''); // State to store the response message
  const Navigate = useNavigate();

  const handleIdChange = (e) => {
    setId(e.target.value);
  };
`your text`
  const handleOutletTypeChange = (e) => {
    setOutletType(e.target.value);
  };

  const handleDiscountChange = (e) => {
    setDiscount(e.target.value);
  };

  const handleSubmit = async () => {
    try {
      const response = await fetch('http://localhost:8080/v1/user/actor/provider/outlettype', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ id, name, discount }),
      });

      if (response.ok) {
        // Success: Parse and store the response message
        const responseData = await response.json();
        setResponseMessage(responseData.message);

        // Navigate back to OutletTypes page after successful submission
        Navigate('/');
      } else {
        // Handle non-successful response (e.g., validation errors)
        console.error('Error adding outlet type:', response.status, response.statusText);
        setResponseMessage('Error: ' + response.statusText);
      }
    } catch (error) {
      console.error('Error adding outlet type:', error);
      setResponseMessage('Error: ' + error.message);
    }
  };

  return (
    <div className="add-outlet-container">
      <h1>Add Outlet</h1>
      <div className="input-container">
        <input
          type="text"
          placeholder="Enter ID"
          value={id}
          onChange={handleIdChange}
        />
        <input
          type="text"
          placeholder="Enter Outlet Type"
          value={name}
          onChange={handleOutletTypeChange}
        />
        <input
          type="text"
          placeholder="Enter Discount"
          value={discount}
          onChange={handleDiscountChange}
        />
        <button className="submit-button" onClick={handleSubmit}>
          Submit
        </button>
        {responseMessage && <p>{responseMessage}</p>}
      </div>
    </div>
  );
};

export default AddOutlet;

FIDDLER:
Raw file:

OPTIONS http://localhost:8080/v1/user/actor/provider/outlettype HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Accept: */*
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Origin: http://localhost:3000
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 Edg/116.0.1938.69
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
Sec-Fetch-Dest: empty
Referer: http://localhost:3000/
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9

I tried by making changes in “handleSubmit” by using different ways of using fetch to fetch data using POST method, also made changes in “headers” by taking reference from some sources. I also tried by making changes in giving URL of API in different possible ways. Also checked API requests using fiddler.

What is the cause of this error I am receiving from a react frontend to a flask backend? [duplicate]

I have a flask backend running with an api to handle logins with jwt’s. The flask function is as follows:

@user.route('/login')
# @cross_origin()
def login():
    email = request.args.get("email", None)
    password = request.args.get("password", None)

    stored_user = User.query.get(email)
    if stored_user != None and check_password_hash(stored_user.password, password):
        print('logged in')

        access_token = create_access_token(identity=email)
        resp = jsonify({'login': True, 'Error': 'User Authentication Success'})

        set_access_cookies(resp, access_token)

        return "hello", 200
    
    print("failed to login")
    return jsonify({'login': False, 'Error': 'User Authentication Failed'})

It appears to create the token without issue, and respond successfully. The problem arises from the react frontend. Which at the moment is as follows:

import React, { useState, useEffect } from "react";
import Form from "react-bootstrap/Form";
import Stack from "react-bootstrap/Stack";
import Button from "react-bootstrap/Button";

export default function Login() {

    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    const [response, setResponse] = useState({})

    function validate(email, password) {
        if (email.length > 0 && password.length > 0) {
            return true
        }
        return false
    }

    function submit() {
        if (validate(email, password)) {
            var api_url = "http://localhost:5000/api/user/login?email=" + email + "&password=" + password
            console.log("The url:", api_url)
            fetch(api_url)
                .then(res => {
                    console.log("res:", res)
                    return res.json()
                })
                .then(res => setResponse(res))
                .catch(err => console.log(err))
        } else {
            console.log("login does not meet requirements")
        }
    }

    useEffect(() => {
        console.log(3)
        if (Object.keys(response).length === 0) {
            console.log("no response")
        } else {
            if (response.login === false) {
                // display "incorrect email or password"
                console.log("response:", response)
                console.log("incorrect login")
            } else {
                // redirect to wherever
                console.log("logged in")
            }
        }
    }, [response])

    return (
        <div className="Login">
             <Form onSubmit={submit}>
                <Stack gap={3}>
                    <Form.Group controlId="email">
                        <Form.Label>Email</Form.Label>
                        <Form.Control
                            autoFocus
                            size="lg"
                            type="email"
                            value={email}
                            onChange={(e) => setEmail(e.target.value)}
                        />
                    </Form.Group>
                    <Form.Group controlId="password">
                        <Form.Label>Password</Form.Label>
                        <Form.Control
                            size="lg"
                            type="password"
                            value={password}
                            onChange={(p) => setPassword(p.target.value)}
                        />
                    </Form.Group>
                    <Button size="lg" type="submit">
                        Login
                    </Button>
                </Stack>
             </Form>
        </div>
    )
}

The HTML awaits a submit action, at which it executes the submit function. The submit function awaits a response via fetch from the flask api point /login. To handle fetch being “async”, I await the return and set response to the response. When response is changed, the useEffect function is executed logging the appropriate message. The problem is that I am: a) always when logging in with valid credentials, b) sometimes when logging in with invalid credentials which throw the correct response at other times; receiving this error thrown by the fetch catch:

Error visible in google console

Why am I receiving this error, and if appropriate, where is my logic mistaken?

I at first thought this was a CORS error but am not receiving a CORS error message in google console.

How do I write a javascript calculation on html for iOS browser

I wrote a simple html page with some calculations written in javascript.
The html interface works, but the calculation doesn’t. It happens only on iOS.
Could any one, please, help me to find the solution for this problem?

Unfortunately, I can’t show the entire code (it’s for my job), but the code below has the same problem.

Thank you!

Here’s the code (please, ignore the layout details):

w_a = document.getElementById("id_a");
w_b = document.getElementById("id_b");

function Reset() {

  w_a.value = "";
  w_b.value = "";

}

Reset();

function BotaoCalcular() {

  a = parseFloat(w_a.value);
  b = 2 * a;

  w_b.value = b.toFixed(3);
}
* {
  box-sizing: border-box;
}

body {
  font-size: 10px;
  font-family: Sans-Serif;
  background-color: #222;
  color: #CCC;
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  text-align: right;
  background-color: #333;
  font-weight: bold;
}

@media (min-resolution: 192dpi) {
  body {
    font-size: 32px;
  }
}

div {
  padding: 1em;
  padding-top: 0;
  padding-bottom: 0;
  background-color: #333;
}

h1 {
  color: #FFF;
  font-size: 10px;
  background-color: #050;
  padding: 0.3em;
  padding-left: 0.7em;
  font-weight: bold;
}

h2 {
  color: #595;
  font-size: 10px;
  background-color: #333;
  font-weight: bold;
}

h3 {
  color: #888;
  font-size: 10px;
  text-align: right;
  background-color: #333;
}

input {
  font-weight: bold;
  border: 1px solid #777;
  font-size: 10px;
  text-align: center;
  width: 70;
}

input2 {
  color: #333;
}

label {
  display: block;
  width: 100%;
  text-align: right;
  padding: 0.2em;
  background-color: #333;
  font-weight: bold;
}

​
<html>

<head>

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Test</title>
</head>

<body>
  <h1>Teste</h1>
  <div>

    <br>

    <label><input type="text" value = "A " style = "text-align: left; background-color: #333; border: none; font-size: 10px; color: #AFA"><input type="number" id="id_a"></label>
    <label><input type="text" value = "B " disabled = "true" style = "text-align: left; background-color: #333; border: none; font-size: 10px; color: #AFA"><input type="number" id="id_b" disabled = "true"></label>

    <label><button onclick="BotaoCalcular()">Calcular</button></label>
    <label><button onclick="Reset()">Reset</button></label>
  </div>

</body>

</html>

How can I obtain information from an input with JavaScript to use it in a function? [closed]

good afternoon, I have a problem, I have my code with AngularJS and javascript but I can’t find a way to take that value in my function

I tried this for the start and end time but it does not take the values ​​that I set from my front

function() {
    console.log('Intervalo')
    let horaInicio = angular.element('#horaNuevaBloqueo')
    let horaFin = angular.element('#horaFinBloqueo')
    let hoursActive = [horaInicio, horaFin]
    const inactive = document.querySelectorAll('#inactive')
    const activated = isActivated(hoursActive);
    inactive.forEach(item => {
        item.style.display = activated ? 'none' : 'block'

Esta es mi parte HTML

                    <div style="position: absolute; margin-top: auto; left: 570px;" >
                    <label style="font-weight: bold;" for="horaNuevaBloqueo">Hora Inicial Bloqueo:</label>
                        <input id="horaNuevaBloqueo" name="horaNuevaBloqueo" ng-model="horaAplicaBloqueo" type="text"
                            maxlength="20" ng-disabled="true" class="form-control-sm" />
                        <button class="btn btn-sm btn-success"
                            ng-click="versCtrl.fillNewHoraAplicaBloqueo(horaAplicaBloqueo)" data-toggle="modal"
                            data-target="#updateHoraAplicaBloqueo">Editar</button>

This is my isActivated function

    function isActivated(hoursActive) {
        const dates = hoursActive.map(dateString => {
            const [hour, minute] = dateString.split(':')
            let date = new Date()
            date.setHours(hour, minute, 0, 0)
            return date;
        })

        //let isActive = false;
        const now = new Date();

             return now.valueOf() >= dates[0].valueOf()
                && now.valueOf() <= dates[1].valueOf()
                
        //return isActive;
    }

Will anyone have a solution?

Outlook Web Add-In: Display reply form with current mail item’s attachments

When you click “Reply” in outlook, it doesn’t preserve the attachments, so I’m working on a web add-in “Reply With Attachments” – Upon clicking my add-in button, a new reply window should be open, and the attachments of the selected mail item should be attached to that reply window.
According to Microsoft docs, this is how you display a reply form with attachments:

Office.context.mailbox.item.displayReplyForm(
{
    'htmlBody' : 'hi',
    'attachments' :
    [
        {
            'type' : Office.MailboxEnums.AttachmentType.File,
            'name' : 'squirrel.png',
            'url' : 'http://i.imgur.com/sRgTlGR.jpg'
        }
    ]
});

but is it possible to add attachments to the reply form in a way other than specifying the URL? I already have the attachments of the current email in code:

let attachments = Office.context.mailbox.item.attachments;

One approach I thought of is to upload the attachments to file storage system (Egnyte), and then specify each file’s URL in the ‘url’ property of an attachment, but then I would have to temporarily make those files public, and delete them after adding them to reply form. But I don’t want to make sensitive files public, even temporarily. And also this approach seems like overkill for something so simple and straightforward.
Any ideas?