Issues passing form data to ASP.Net Core Razor Page Handler Method via Fetch (Error 400)

I can’t seem to get this form data to submit to a handler method I have set up. I’m using an onlick attribute of a button that is in each row of a table to execute a JS function:

function approveRequest(id) {
var formData = new FormData();
formData.append('id', id);

fetch('/Admin/PMC/Recommendations?handler=ApproveAsync', {
    method: 'POST',
    body: formData,
    headers: {
        'Content-Type': 'multipart/form-data',
    },
})
    .then(response => response.json())
    .then(result => {
        console.log('Success:', result);
    })
    .catch(error => {
        console.error('Error:', error);
    });
}

The Handler method is as follows:

SyntaxError: Unexpected end of JSON input
at Recommendations:737:44

I’ve tried “/Admin/PMC/Recommendations/ApproveAsync” as well as “/Admin/PMC/Recommendations?handler=OnPostApproveAsync” and “/Admin/PMC/Recommendations/OnPostApproveAsync” for the url, but none of them do much. I’ve tried removing content-type header, or using a different value for it, also tried out mode: ‘same-origin’, and credentials: ‘same-origin.’ I do have standard routing options enabled for the application in program.cs:

app.UseRouting();
app.UseEndpoints(endpoints =>
{
    endpoints.MapRazorPages();
    endpoints.MapControllers();
    endpoints.MapBlazorHub();
});

Click on element using JScript

I have one hypertext link with a telephone number and Need a code with Js to click on the link (not mention to not use the telephone number itself as refference).

I have tried the following but didn´t work.

getElementsByClassName("slds-icon_container slds-icon-utility-call").click()

Uncaught ReferenceError: getElementsByClassName is not defined
at :1:1

getElementsByClassName  ("Hacer clic para marcar").click()

Uncaught ReferenceError: getElementsByClassName is not defined
at :1:1

document.getElementById("output-field").click()

Uncaught TypeError: Cannot read properties of null (reading ‘click’)

Button code.

<lightning-click-to-dial data-output-element-id="output-field" slot="outputField" lightning-clicktodial_clicktodial-host=""><a lightning-clicktodial_clicktodial="" href="javascript:void(0)"><span lightning-clicktodial_clicktodial="" class="slds-icon_container slds-icon-utility-call" title="Hacer clic para marcar"><svg lightning-clickToDial_clickToDial="" class="slds-icon slds-icon_xx-small" aria-hidden="true" style="fill: currentcolor;"><use lightning-clickToDial_clickToDial="" xlink:href="/_slds/icons/utility-sprite/svg/symbols.svg?cache=10.6.0#call"></use></svg><span lightning-clicktodial_clicktodial="" class="slds-assistive-text">Hacer clic para marcar</span></span><span lightning-clicktodial_clicktodial="">+34666666666</span></a></lightning-click-to-dial>

Get an Error when render Tensorflow Camera

i have a problem with my code, it is object detection app, when i run it camera loads okay but i get some Promise Errors:

[Unhandled promise rejection: TypeError: Cannot read property ‘ready’ of undefined]

[Unhandled promise rejection: Error: Backend ‘undefined’ has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods]

this is my code:

const { width, height } = Dimensions.get("window");
const TensorCamera = cameraWithTensors(Camera);

function App() {
  const [model, setModel] = useState(null);
  const context = useRef();
  const camera = useRef();

  useEffect(() => {
    (async () => {
      const { status } = await Camera.requestCameraPermissionsAsync();
      if (status !== "granted") {
        alert("not granted");
        return;
      }
      await tf.ready();
      const loadedModel = await cocoSsd.load();
      setModel(loadedModel);
    })();
  }, []);
  useEffect(() => {
    (async () => {
      const { status } = await Camera.requestCameraPermissionsAsync();
      if (status !== "granted") {
        alert("Разрешение на использование камеры не предоставлено.");
      }
    })();
  }, []);
  const handleCameraStream = (images) => {
    const loop = async () => {
      const nextImageTensor = images.next().value;

      if (!model || !nextImageTensor) return;

      const predictions = await model.detect(nextImageTensor);

      drawRectangles(predictions);

      requestAnimationFrame(loop);
    };

    loop();
  };

  const drawRectangles = (predictions) => {
    if (!context.current || !camera.current) return;

    const scaleWidth = width / camera.current.width;
    const scaleHeight = height / camera.current.height;

    context.current.clearRect(0, 0, width, height);

    for (const prediction of predictions) {
      const [x, y, width, height] = prediction.bbox;

      const boundingBoxX = x * scaleWidth;
      const boundingBoxY = y * scaleHeight;

      context.current.strokeRect(
        boundingBoxX,
        boundingBoxY,
        width * scaleWidth,
        height * scaleHeight
      );

      context.current.fillText(
        `${prediction.class} (${Math.round(prediction.score * 100)}%)`,
        boundingBoxX,
        boundingBoxY > 10 ? boundingBoxY - 5 : 10
      );
    }
  };

  const handleCanvas = (can) => {
    if (can) {
      can.width = width;
      can.height = height;
      const ctx = can.getContext("2d");
      context.current = ctx;
      ctx.strokeStyle = "red";
      ctx.fillStyle = "red";
      ctx.lineWidth = 2;
      camera.current = can;
    }
  };

  return (
    <View style={styles.container}>
      <TensorCamera
        style={styles.camera}
        type={Camera.Constants.Type.back}
        cameraTextureWidth={width}
        cameraTextureHeight={height}
        resizeWidth={width}
        resizeHeight={height}
        resizeDepth={3}
        onReady={handleCameraStream}
        autorender={true}
        useCustomShadersToResize={false}
      />

      <View style={styles.canvasContainer}>
        <Text style={styles.instructions}>Detected Objects:</Text>
        <Canvas style={styles.canvas} ref={handleCanvas} />
      </View>
    </View>
  );
}

How to make part of styles.css true, on given condition in react?

I want to make this part of code in styles.css true, only if toggleSwitch2 is true

/* if toggleswitch2 false then  */
.react-flow .react-flow__handle {
}

/* if toggleswitch2true then */
.react-flow .react-flow__handle {
  width: 30px;
  height: 14px;
  border-radius: 3px;
  background-color: #784be8;
}

the problem is, that the class that is being targeted by styles.css, doesn’t exist as an element (for example div tag) inside jsx.

const [toggleSwitch2, setToggleSwitch2] = useState(false);
    
      const handleToggleSwitch2 = () => {
        setToggleSwitch2(!toggleSwitch2);
      };


     <div className="toggle-switch-container2">
                              <input
                                id="toggle-switch2"
                                type="checkbox"
                                checked={toggleSwitch2}
                                onChange={handleToggleSwitch2}
                              />
                              <label htmlFor="toggle-switch2">
                                Make handles bigger
                              </label>
                            </div>
    
    

Linking custom JS to custom HTML and CSS in Shopify 2.0

I have an SVG map that I’ve created for my store that I would like to have on its own separate page. The HTML and CSS seem to be working fine – when I hover over a state the state becomes highlighted and loses its highlight when I hover off of it.

I am trying to add custom JS to the theme.liquid file in the theme code settings so that when I hover over a state some information is displayed as a popup by the cursor. This worked perfectly for an old Shopify store I worked on with an older theme, but it doesn’t seem to work with Shopify 2.0. The info is no longer displayed overtop the map as a smooth popup, but shifts the entire map down and displays at the top of the screen.

How would I go about linking this custom JS to the HTML/CSS that I’ve put on the page for Shopify 2.0?

Here is the JS, exactly how I am adding it to the theme.liquid file:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

<script>
$("path, circle").hover(function(e) {
  $('#info-box').css('display','block');
  $('#info-box').html($(this).data('info'));
});

$("path, circle").mouseleave(function(e) {
  $('#info-box').css('display','none');
});

$(document).mousemove(function(e) {
  $('#info-box').css('top',e.pageY-$('#info-box').height()-30);
  $('#info-box').css('left',e.pageX-($('#info-box').width())/2);
}).mouseover();

var ios = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
if(ios) {
  $('a').on('click touchend', function() { 
    var link = $(this).attr('href');   
    window.open(link,'_blank');
    return false;
  });
}
</script>

I’ve tried to “bundle” the JS code with the HTML/CSS on the product info page, creating a separate js.liquid file under “assets” in my theme code settings, and adding “defer=’defer'” to my JQuery info.

Executing two pieces of code in a sequence

I have two pieces of code in Express js. I want to execute them conditionally and I am not able to understand how to exactly do this. Code is:

//Check whether all of the Applied Discounts are combinable with Product Discount
cart.items.forEach(item => {
    if (item.discounts && typeof item.discounts !== "undefined") {
        item.discounts.forEach(discount => {
            if (discount.title && typeof discount.title !== "undefined") {
                get_details_for_automatic_discounts(discount.title, function (response) {
                    if (response.combinesWith && typeof response.combinesWith !== "undefined") {
                        const _combinesWith = response.combinesWith; // Pre applied Discount on cart page
                        if (discountClass === "PRODUCT") {
                            if (!_combinesWith.productDiscounts) {
                                console.log("False 1");
                                return callback({
                                    apply_coupon_code: false
                                });
                            }
                        }
                    } else {
                        console.log("True 0")
                        return callback({
                            apply_coupon_code: true
                        });
                    }
                });
            }
        });
    }
});

// Check if none of the inner callbacks were executed and then execute the final callback
console.log("Final callback executed");
return callback({ // This is the code I want to run only and only after the previous loop have completely been executed
    apply_coupon_code: true
});

Here the loop checks a condition and if for ANY ONE item in the cart, the condition is true, return callback as apply_coupon_code: false but ONLY if all the items have been checked thoroughly and the condition was not true for ANY SINGLE item in the array, return callback as apply_coupon_code: true, but the issue here is that the control transfers to this piece of code:

console.log("Final callback executed");
return callback({ // This is the code I want to run only and only after the previous loop have completely been executed
    apply_coupon_code: true
});

as soon as the loop starts and hence, the wrong value is returned in the callback and also, multiple return callbacks are called because the loop was still running in the background.
I have tried this:

var callbackExecuted = false;
async function check_for_cart_items () {
    await cart.items.forEach(item => {
        if (item.discounts && typeof item.discounts !== "undefined") {
            item.discounts.forEach(discount => {
                if (discount.title && typeof discount.title !== "undefined") {
                    get_details_for_automatic_discounts(discount.title, function (response) {
                        if (response.combinesWith && typeof response.combinesWith !== "undefined") {
                            const _combinesWith = response.combinesWith; // Pre applied Discount on cart page
                            const _discountClass = response.discountClass; // Pre applied Discount Class on cart page
                            if (discountClass === "PRODUCT") {
                                if (!_combinesWith.productDiscounts) {
                                    console.log("False 1");
                                    callbackExecuted = true;
                                    return callback({
                                        apply_coupon_code: false
                                    });
                                }
                            }
                        } else {
                            console.log("True 0")
                            callbackExecuted = true;
                            return callback({
                                apply_coupon_code: true
                            });
                        }
                    });
                }
            });
        }
    });  
}

check_for_cart_items().then(() => {
    // Check if none of the inner callbacks were executed and then execute the final callback
    if (!callbackExecuted) {
        console.log("Final callback executed");
        return callback({
            apply_coupon_code: true
        });
    }
})

but it is still creating issue for me. I am already using callback function. so i am inside a callback function. I cannot provide more of the code due to security reasons. You may ask questions if needed. Using VS Code as Code Editor. OS is Windows 11.

SSH connection – How to get algorithm for SFTP server before connection creation

Trying to connect to SFTP server, here is the connect code in NodeJS:

var conn = new ssh2();
    ......
    conn.connect(
        {
            "host": sftpHost,
            "port": sftpPort,
            "username": sftpUserName,
            // Trying to find "algorithm" value for the target SFTP server.
            "algorithms": {serverHostKey: ['ssh-dss'] }, 
            "password": sftpPassworde                 
        }

But the value of “algorithm” parameter is different for different SFTP servers. Is there any existing function available in sftp package using which we can get the value of Algorithm used on target SFTP server and pass dynamic value for this parameter?

Sending Audio file from Django to Vue

I’m trying to send gtts generated audio file from Django to Vue via HttpResponse.

Django’s views.py:

f = open('path/of/mp3/file', 'rb')
response = HttpResponse()
response.write(f.read())
response['Content-Type'] = 'audio/mp3'
response['Content-Length'] = os.path.getsize('path/of/mp3/file')

return response

and when vue receives the response data, it is like the below:

data: '��D�x00x11Cx19�x01F(x00x00x04 �&N�""""���ޓ�������x7F���Bx10���w�����…���_�F��1B��H���x16LAME3.100�����������������������' # and so on

I guess it is because the bytes have been converted to string over the transfer and I have to convert it back to the audio file. But no matter whether using blob or other suggested methods, I could not convert it to an mp3 file to be played in javascript.

How could I achieve this?

URL header appears in my TWA when Javascript Alert or Confirm box appears

Issue: Whenever a JavaScript confirm or alert box is being used in the code, the URL header appears and does not goes until the app is again opened after opening any other app on the mobile.(i.e. Sent to background and again brought to foreground)

Simply refreshing by pulling down does not helps.

My TWA app, downloaded from google play store, was working fine for several months up until few days back, without any issue of URL header appearing.

My .well-known/assetlinks.json is configured in my host.

It only appears while using JavaScript Alert and Confirm box.

How to resolve this?

Storybook 7 with nextjs keeps crashing with error ‘EBUSY: resource busy or locked’

Storybook works for a short bit but as soon as anything compiles in error it crashes. Sometimes it crashes for no reason. Sometimes it won’t even start for no reason and I just need to try again.

“dependencies”: {
“next”: “^13.5.3”,
“react”: “^18.2.0”,
“react-dom”: “^18.2.0”
},
“devDependencies”: {
“@radix-ui/react-label”: “^2.0.2”,
“@radix-ui/react-separator”: “^1.0.3”,
“@storybook/addon-a11y”: “^7.4.5”,
“@storybook/addon-essentials”: “^7.4.5”,
“@storybook/addon-links”: “^7.4.5”,
“@storybook/addon-styling”: “^1.3.7”,
“@storybook/blocks”: “^7.4.5”,
“@storybook/nextjs”: “^7.4.5”,
“@storybook/react”: “^7.4.5”,
“@storybook/testing-library”: “^0.2.1”,
“@types/node”: “^20.7.0”,
“@types/react”: “^18.2.23”,
“@types/react-dom”: “^18.2.7”,
“autoprefixer”: “^10.4.16”,
“class-variance-authority”: “^0.7.0”,
“eslint”: “^8.50.0”,
“eslint-config-next”: “^13.5.3”,
“eslint-config-prettier”: “^9.0.0”,
“eslint-plugin-storybook”: “^0.6.14”,
“postcss”: “^8.4.30”,
“prettier”: “^3.0.3”,
“storybook”: “^7.4.5”,
“tailwind-merge”: “^1.14.0”,
“tailwindcss”: “^3.3.3”,
“typescript”: “^5.2.2”
}

Thanks in advance!

This is an old problem but the old solution is no longer works with Storybook 7 – https://github.com/storybookjs/storybook/issues/19336

ManagerWebpack is no longer configurable https://storybook.js.org/docs/react/builders/webpack

Need an approach to Visualizing a Palletizing Process with JS

Task: Create an HMI for a Robot. I have a Robot that is Picking Boxes from a Pallet on the Right and Placing them on a Pallet on the Left. The Pallet contains 4 x 4 x 3 boxes, so 3 layers with 16 boxes per layer. Using Vanilla JS, what is the most efficient way to illustrate/animate the pick and place?

The Robot Interface/IDE is on an Android Tablet. I do not have access to the source of the App. The HMI is a simple Web Stack hosted on the Robot controller accessed through the app. I have to stick to vanilla JS because I will not be able to load 3rd party libraries on the Robot controller.

My first thought was to create an image sprite with 48 images. Every time the Robot Picks and place, just iterate through the images. Thoughts?

My second thought was to just use CSS and make boxes appear in a Grid. This approach is 2D and kind of boring. Thoughts?

For my information, if I didn’t have any limitations on libraries what is the most modern approach?

I haven’t started anything yet. I’m trying to get ideas for development. I am hoping to get feedback from the community.

Remove class of a div when clicking on another in vanilla JS

(Sorry for my English, it’s not my native language)

I created a function that widens a wrapper containing a visible small element and display an invisible element (map). If I click on another wrapper, the function works as well, but I would like to cancel the effect on the first wrapper.

Can you help me?

wrapper.forEach((wrapperElement)=> {
    let mapElement = wrapperElement.querySelector(".map");

    wrapperElement.addEventListener('click', function reset(){ 
        mapElement.classList.toggle('show');
        wrapperElement.classList.toggle('focus');

    });
});

I think I should attribute isWiden = true to the first wrapper, and the function would test it before targeting the second wrapper. But I’m struggling to do that.

Sharepoint API (Refused to connect because it violates the following content security policy…)

Good Day,

I am currently having issues connecting my SharePoint API.
There are no problems running the SharePoint API query on the browser.
However, when it comes to the function call this issue arises.
The API call is being processed on the front end using vanilla JavaScript only.

I tried adding the following code below to the HTML file, however it did not work.

<meta http-equiv="Content-Security-Policy" content="connect-src 'self'" />

Do I have to add any special request headers or meta tags? Please do let me know.
** I do not have access to the Sharepoint Server and do not have the rights to install external libraries for the current files.**

I am getting the an error:

"Refused to connect to "https://test.com/_api/search/query?querytext=%27civil%27" because it violates the following Content Security Policy directive "connect-src 'unsafe-inline' https://test.com wss://test.com https://localhost"

This is my implementation of the API call below

function sharePointAPITestCall(){
        $.ajax({
            url: "https://test.com/_api/search/query?querytext=%27civil%27", //Use for testing.
            type: "GET",
            contentType: "application/json; charset=utf-8",
            // headers: {"info1": sessionId},
            dataType: "json",
            success: async function (response) {
                const results = response.PrimaryQueryResult.RelevantResults.Table.Rows;

                for (const result of results) {
                    const extension = result.Cells.find(cell => cell.Key === 'FileExtension').Value;
                    if (extension && extension.toLowerCase() !== 'aspx') {
                        const title = result.Cells.find(cell => cell.Key === 'Title').Value;
                        const url = result.Cells.find(cell => cell.Key === 'Path').Value;
                        let hitHighlightedSummary = result.Cells.find(cell => cell.Key === 'HitHighlightedSummary').Value;
                        try {
                            const xmlContent = await readUrlContents(url);
                            if (xmlContent) {
                                console.log(xmlContent)
                            }
                        } catch (error) {
                            console.error(error);
                        }
                    }
                }
            },
            error: function (xhr, status, error) {
                if (xhr.status === 500 || xhr.status === 400) {
                    alert('Data Fetch Failed. Connect with System Administrator.');
                } else {
                    alert('Data Fetch Failed. Try again sometime.');
                }
            }
        });
    }

Babel ESLint parser difficulties

Hi I am quite new to ESLint and when I was gaining some headway I encountered issues with the assert when [importing a JSON file. I added the babel ESLint parser but on setting everything up I noticed all of my rules are no longer being read, I spent a good amount of time trying to figure out a solution but with no luck, could someone please assist me with this? This my .eslintrc.json file:

{
    "env": {
        "browser": true,
        "es2021": true,
        "mocha": true
    },
    "extends": [
        "eslint:recommended",
        "plugin:import/errors",
        "plugin:import/warnings"
    ],
    "parser": "@babel/eslint-parser",

    "parserOptions": {
        "requireConfigFile": false,
        "ecmaVersion": "latest",
        "sourceType": "module",
        "babelOptions": {
                "plugins": [
                  "@babel/plugin-syntax-import-assertions"
                ]
    },

    "rules": {

        "@babel/indent": ["error", 4],

        "linebreak-style": ["error", "windows"],

        "quotes": ["error", "single"],

        "semi": ["error", "always"],

        "prefer-template": ["error"], 

        "block-spacing": ["error", 
            "always"
        ],

        "spaced-comment": ["error", "always", {
            "line": {
                "markers": ["/"],
                "exceptions": ["-", "+"]
            },
            "block": {
                "markers": ["!"],
                "exceptions": ["*", "+", "-"],
                "balanced": true
            }
        }],

        "space-in-parens": ["error", "always", {
            "exceptions": ["()", "empty", "{}", "[]"]
        }],

        "object-curly-spacing": ["error", "always", { "arraysInObjects": false }], 

        "no-trailing-spaces": ["error", { "ignoreComments": true }]
    }
}
}

I tried to amend the rules even adding the @babel prefix but to no avail