net::ERR_ABORTED 404 (Not Found) After moving the library files

I was trying to use p5js library, if I put my library into a library folder, the error occurs. But if I put it right next to my script2.js file(where the main program is), it works fine.

This gives error:

<script src="../library/p5.js"></script>
<script src="../library/p5.collide2d.js"></script>
<script src="js/script2.js"></script>

This works fine :(Aftering moving p5.js and p5.collide2d.js to js folder(same as script2.js))

<script src="js/p5.js"></script>
<script src="js/p5.collide2d.js"></script>
<script src="js/script2.js"></script>

I have checked the path for both cases, both should be correct(I ctrl+Left clicked on the paths in VS code and successfully opened the library files)
Why is this happening? Any help would be greatly appreciated.

Error while deploying contract with “solc”: Transaction has been reverted by the EVM

I’m trying to deploy a smart contract to Ropsten Testnet using node module “solc”.

WHEN I DEPLOY IT IN REMIX IT WORKS JUST FINE, BUT NODE MODULE “SOLC” RETURNS ERROR LIKE THIS.

Error: Transaction has been reverted by the EVM:
{
“blockHash”: “0xbbe98bb8fbb9eae6de17277fcbc23012111d5b738ccd528211db48bdea872926”,
“blockNumber”: 12183688,
“contractAddress”: “0x22DA0b8D52a3A2E19Dd5d92c43b8048013326893”,
“cumulativeGasUsed”: 2236891,
“effectiveGasPrice”: 1499999077,
“from”: “0xc240181d20d4b4124db6bea1344d2c1fa0574979”,
“gasUsed”: 774706,
“logs”: [],
“logsBloom”: “0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000”,
“status”: false,
“to”: null,
“transactionHash”: “0xfc40f32301ef022a5d046ab949edbe2e721e76d667d2f4df1a8eef8d48352682”,
“transactionIndex”: 14,
“type”: “0x0”
}
at Object.TransactionError (D:4_Work2_Ongoing_ProjectsLaunchpad DAppDeploynode_modulesweb3-core-helpersliberrors.js:87:21)
at Object.TransactionRevertedWithoutReasonError (D:4_Work2_Ongoing_ProjectsLaunchpad DAppDeploynode_modulesweb3-core-helpersliberrors.js:98:21)
at D:4_Work2_Ongoing_ProjectsLaunchpad DAppDeploynode_modulesweb3-core-methodlibindex.js:396:57
at processTicksAndRejections (internal/process/task_queues.js:93:5) {
receipt: {
blockHash: ‘0xbbe98bb8fbb9eae6de17277fcbc23012111d5b738ccd528211db48bdea872926’,
blockNumber: 12183688,
contractAddress: ‘0x22DA0b8D52a3A2E19Dd5d92c43b8048013326893’,
cumulativeGasUsed: 2236891,
effectiveGasPrice: 1499999077,
from: ‘0xc240181d20d4b4124db6bea1344d2c1fa0574979’,
gasUsed: 774706,
logs: [],
logsBloom: ‘0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000’,
status: false,
to: null,
transactionHash: ‘0xfc40f32301ef022a5d046ab949edbe2e721e76d667d2f4df1a8eef8d48352682’,
transactionIndex: 14,
type: ‘0x0’
}
}

First I thought it’s because the compile size exceeds EIP-170 limit. But it doesn’t make sense, since the same code deploys in Remix.

Here is the structure of solidity file.

pragma solidity ^0.8.4;
abstract contract Context {...}
interface IERC20 {...}
library SafeMath {...}
library Address {...}
contract Ownable is Context  {...}
interface IUniswapV2Factory {...}
interface IUniswapV2Pair {...}
interface IUniswapV2Router01 {...}
interface IUniswapV2Router02 is IUniswapV2Router01  {...}
contract MyToken is Context, IERC20, Ownable {...}

Here are the compile.js and deploy.js files.

const path = require('path');
const fs = require('fs');
const solc = require('solc');

const contractPath = path.resolve(__dirname, 'test.sol');
const source = fs.readFileSync(contractPath, 'utf8');
const input = {
   language: 'Solidity',
   sources: {
    'test.sol': {
        content: source,
    },
},
settings: {
    // optimizer: {
    //     enabled: true,
    //     // Optimize for how many times you intend to run the code.
    //     // Lower values will optimize more for initial deployment cost, higher values will optimize more for high-frequency usage.
    //     runs: 1
    // },
    outputSelection: {
        '*': {
            '*': ['*'],
        },
    },
},
};
const tempFile = JSON.parse(solc.compile(JSON.stringify(input)));
const contractFile = tempFile.contracts['test.sol']['MyToken'];
module.exports = contractFile;

deploy.js file

const Web3 = require('web3');
const contractFile = require('./compile');
const bytecode = contractFile.evm.bytecode.object;
const abi = contractFile.abi;
const privKey = "#################";
const address = "#################";
const ropstenUrl = 'https://ropsten.infura.io/v3/#################';
const web3 = new Web3(ropstenUrl);
const deploy = async() => {
console.log('Attempting to deploy from account:', address);
const tokenContract = new web3.eth.Contract(abi);

const tokenTx = tokenContract.deploy({
    data: bytecode,
    arguments: []
});

const signedTransaction = await web3.eth.accounts.signTransaction({
        from: address,
        data: tokenTx.encodeABI(),
        gas: 4000000 //'4294967295',
    },
    privKey
);

const createReceipt = await web3.eth.sendSignedTransaction(
    signedTransaction.rawTransaction
);

console.log('Contract deployed at address', createReceipt.contractAddress);
};
deploy();

I hope somebody would tell me WHY THE SMART CONTRACT DOESN’T DEPLOY WITH “SOLC” BUT WITH REMIX.

Read text file in Javascript Rhino

I am writing a code to read a local text file into my No Magic Cameo Systems Modeler. I am using Javascript Rhino for the same. But not getting any viable solution to read the text file.

enter image description here

I used Java’s bufferedReader class but then I am getting the following error :

“org.mozilla.javascript.EvaluatorException: missing ; before statement (#25)”

Can anyone assist me in what I am doing wrong. I am fairly new to javascript .

Sequelize searching and sorting not working

I’m searching as such:

var options = {
  where: {
    text: {
      [Op.like]: '%' + query + '%'
    }
  }
};

Post.findAll(options).then((r)=>{

Then sort the results based on when they were created:

if(sort == 'new'){
  r=r.sort(function (a, b) {
    return a.created.getTime() - b.created.getTime();
  });
}

What comes out:

Wrong

This is entirely out of order.

A few things:

  • The sort function IS called
  • I’ve tried just doing r.sort not r=r.sort
  • The .created is always valid and is set with DataTypes.Now
  • This is the same for doing any sort with it

What the search outputs before filtering:

[
  Post {
    dataValues: {
      id: 1,
      text: 'Cheese is great! You should totally eat it.',
      creator: 1,
      created: 2022-04-05T09:15:39.102Z,
      likes: '[1]',
      repliesLastID: 1,
      replies: '[{"id":1,"author":1,"text":"cheese","likes":[]}]',
      createdAt: 2022-04-05T09:15:39.103Z,
      updatedAt: 2022-04-06T06:23:18.355Z
    },
    _previousDataValues: {
      id: 1,
      text: 'Cheese is great! You should totally eat it.',
      creator: 1,
      created: 2022-04-05T09:15:39.102Z,
      likes: '[1]',
      repliesLastID: 1,
      replies: '[{"id":1,"author":1,"text":"cheese","likes":[]}]',
      createdAt: 2022-04-05T09:15:39.103Z,
      updatedAt: 2022-04-06T06:23:18.355Z
    },
    uniqno: 1,
    _changed: Set(0) {},
    _options: {
      isNewRecord: false,
      _schema: null,
      _schemaDelimiter: '',
      raw: true,
      attributes: [Array]
    },
    isNewRecord: false
  },
  Post {
    dataValues: {
      id: 2,
      text: "Access granted. No longer stuck on cheese.social's weird /welcome.n" +
        'This is a historic day for all.',
      creator: 1,
      created: 2022-04-08T06:29:22.226Z,
      likes: '[1,2]',
      repliesLastID: 1,
      replies: '[]',
      createdAt: 2022-04-08T06:29:22.227Z,
      updatedAt: 2022-04-09T04:27:43.171Z
    },
    _previousDataValues: {
      id: 2,
      text: "Access granted. No longer stuck on cheese.social's weird /welcome.n" +
        'This is a historic day for all.',
      creator: 1,
      created: 2022-04-08T06:29:22.226Z,
      likes: '[1,2]',
      repliesLastID: 1,
      replies: '[]',
      createdAt: 2022-04-08T06:29:22.227Z,
      updatedAt: 2022-04-09T04:27:43.171Z
    },
    uniqno: 1,
    _changed: Set(0) {},
    _options: {
      isNewRecord: false,
      _schema: null,
      _schemaDelimiter: '',
      raw: true,
      attributes: [Array]
    },
    isNewRecord: false
  },
  Post {
    dataValues: {
      id: 3,
      text: 'Welcome to Cheese.social!',
      creator: 0,
      created: 2022-04-09T01:57:51.059Z,
      likes: '[1,2]',
      repliesLastID: 3,
      replies: `[{"id":1,"author":1,"text":"Yeah ik right cheese","likes":[1,2]},{"id":2,"author":1,"text":"cheese; SELECT * FROM Users;","likes":[]},{"id":3,"author":2,"text":"Yo dude! Cheese.social is greeeeeeeeeeeeeeeeeat. btw bro don't try sneaky sqli pleasesae","likes":[2]}]`,
      createdAt: 2022-04-09T01:57:51.061Z,
      updatedAt: 2022-04-09T04:28:41.572Z
    },
    _previousDataValues: {
      id: 3,
      text: 'Welcome to Cheese.social!',
      creator: 0,
      created: 2022-04-09T01:57:51.059Z,
      likes: '[1,2]',
      repliesLastID: 3,
      replies: `[{"id":1,"author":1,"text":"Yeah ik right cheese","likes":[1,2]},{"id":2,"author":1,"text":"cheese; SELECT * FROM Users;","likes":[]},{"id":3,"author":2,"text":"Yo dude! Cheese.social is greeeeeeeeeeeeeeeeeat. btw bro don't try sneaky sqli pleasesae","likes":[2]}]`,
      createdAt: 2022-04-09T01:57:51.061Z,
      updatedAt: 2022-04-09T04:28:41.572Z
    },
    uniqno: 1,
    _changed: Set(0) {},
    _options: {
      isNewRecord: false,
      _schema: null,
      _schemaDelimiter: '',
      raw: true,
      attributes: [Array]
    },
    isNewRecord: false
  },
  Post {
    dataValues: {
      id: 4,
      text: 'Cheese, bro!',
      creator: 2,
      created: 2022-04-09T04:23:42.014Z,
      likes: '[2]',
      repliesLastID: 0,
      replies: '[]',
      createdAt: 2022-04-09T04:23:42.014Z,
      updatedAt: 2022-04-09T04:28:49.259Z
    },
    _previousDataValues: {
      id: 4,
      text: 'Cheese, bro!',
      creator: 2,
      created: 2022-04-09T04:23:42.014Z,
      likes: '[2]',
      repliesLastID: 0,
      replies: '[]',
      createdAt: 2022-04-09T04:23:42.014Z,
      updatedAt: 2022-04-09T04:28:49.259Z
    },
    uniqno: 1,
    _changed: Set(0) {},
    _options: {
      isNewRecord: false,
      _schema: null,
      _schemaDelimiter: '',
      raw: true,
      attributes: [Array]
    },
    isNewRecord: false
  },
  Post {
    dataValues: {
      id: 5,
      text: 'Cheese is great! You should totally eat it.n' +
        "Btw, I'm testing https://example.com/#LINKS",
      creator: 1,
      created: 2022-04-10T09:56:15.243Z,
      likes: '[]',
      repliesLastID: 3,
      replies: `[{"id":1,"author":1,"text":"Links didn't work correctly with cheese.social. They may return in a future update.","likes":[1]},{"id":2,"author":4,"text":"cheese the frick out ofh ere","likes":[]}]`,
      createdAt: 2022-04-10T09:56:15.244Z,
      updatedAt: 2022-04-11T02:27:12.827Z
    },
    _previousDataValues: {
      id: 5,
      text: 'Cheese is great! You should totally eat it.n' +
        "Btw, I'm testing https://example.com/#LINKS",
      creator: 1,
      created: 2022-04-10T09:56:15.243Z,
      likes: '[]',
      repliesLastID: 3,
      replies: `[{"id":1,"author":1,"text":"Links didn't work correctly with cheese.social. They may return in a future update.","likes":[1]},{"id":2,"author":4,"text":"cheese the frick out ofh ere","likes":[]}]`,
      createdAt: 2022-04-10T09:56:15.244Z,
      updatedAt: 2022-04-11T02:27:12.827Z
    },
    uniqno: 1,
    _changed: Set(0) {},
    _options: {
      isNewRecord: false,
      _schema: null,
      _schemaDelimiter: '',
      raw: true,
      attributes: [Array]
    },
    isNewRecord: false
  },
  Post {
    dataValues: {
      id: 6,
      text: 'I love me some cheese',
      creator: 3,
      created: 2022-04-11T01:36:09.758Z,
      likes: '[1,3]',
      repliesLastID: 2,
      replies: '[{"id":1,"author":3,"text":" ikr I love cheese <3","likes":[1]},{"id":2,"author":1,"text":"Yeah cheese is amazing","likes":[1]}]',
      createdAt: 2022-04-11T01:36:09.758Z,
      updatedAt: 2022-04-11T02:21:21.753Z
    },
    _previousDataValues: {
      id: 6,
      text: 'I love me some cheese',
      creator: 3,
      created: 2022-04-11T01:36:09.758Z,
      likes: '[1,3]',
      repliesLastID: 2,
      replies: '[{"id":1,"author":3,"text":" ikr I love cheese <3","likes":[1]},{"id":2,"author":1,"text":"Yeah cheese is amazing","likes":[1]}]',
      createdAt: 2022-04-11T01:36:09.758Z,
      updatedAt: 2022-04-11T02:21:21.753Z
    },
    uniqno: 1,
    _changed: Set(0) {},
    _options: {
      isNewRecord: false,
      _schema: null,
      _schemaDelimiter: '',
      raw: true,
      attributes: [Array]
    },
    isNewRecord: false
  },
  Post {
    dataValues: {
      id: 7,
      text: 'i cheesed ur mother',
      creator: 4,
      created: 2022-04-11T01:38:23.013Z,
      likes: '[4]',
      repliesLastID: 0,
      replies: '[]',
      createdAt: 2022-04-11T01:38:23.013Z,
      updatedAt: 2022-04-11T02:29:07.661Z
    },
    _previousDataValues: {
      id: 7,
      text: 'i cheesed ur mother',
      creator: 4,
      created: 2022-04-11T01:38:23.013Z,
      likes: '[4]',
      repliesLastID: 0,
      replies: '[]',
      createdAt: 2022-04-11T01:38:23.013Z,
      updatedAt: 2022-04-11T02:29:07.661Z
    },
    uniqno: 1,
    _changed: Set(0) {},
    _options: {
      isNewRecord: false,
      _schema: null,
      _schemaDelimiter: '',
      raw: true,
      attributes: [Array]
    },
    isNewRecord: false
  },
  Post {
    dataValues: {
      id: 8,
      text: 'stilton or camembert cheese?',
      creator: 5,
      created: 2022-04-11T02:26:59.488Z,
      likes: '[5,1]',
      repliesLastID: 1,
      replies: `[{"id":1,"author":1,"text":"I say Camembert, it's a good cheese.","likes":[]}]`,
      createdAt: 2022-04-11T02:26:59.489Z,
      updatedAt: 2022-04-11T02:28:58.565Z
    },
    _previousDataValues: {
      id: 8,
      text: 'stilton or camembert cheese?',
      creator: 5,
      created: 2022-04-11T02:26:59.488Z,
      likes: '[5,1]',
      repliesLastID: 1,
      replies: `[{"id":1,"author":1,"text":"I say Camembert, it's a good cheese.","likes":[]}]`,
      createdAt: 2022-04-11T02:26:59.489Z,
      updatedAt: 2022-04-11T02:28:58.565Z
    },
    uniqno: 1,
    _changed: Set(0) {},
    _options: {
      isNewRecord: false,
      _schema: null,
      _schemaDelimiter: '',
      raw: true,
      attributes: [Array]
    },
    isNewRecord: false
  },
  Post {
    dataValues: {
      id: 9,
      text: 'I like cheese',
      creator: 6,
      created: 2022-04-11T02:30:29.244Z,
      likes: '[6]',
      repliesLastID: 0,
      replies: '[]',
      createdAt: 2022-04-11T02:30:29.245Z,
      updatedAt: 2022-04-11T02:31:33.682Z
    },
    _previousDataValues: {
      id: 9,
      text: 'I like cheese',
      creator: 6,
      created: 2022-04-11T02:30:29.244Z,
      likes: '[6]',
      repliesLastID: 0,
      replies: '[]',
      createdAt: 2022-04-11T02:30:29.245Z,
      updatedAt: 2022-04-11T02:31:33.682Z
    },
    uniqno: 1,
    _changed: Set(0) {},
    _options: {
      isNewRecord: false,
      _schema: null,
      _schemaDelimiter: '',
      raw: true,
      attributes: [Array]
    },
    isNewRecord: false
  },
  Post {
    dataValues: {
      id: 10,
      text: 'Cheese and pasta!!',
      creator: 6,
      created: 2022-04-11T02:32:39.524Z,
      likes: '[6,1]',
      repliesLastID: 0,
      replies: '[]',
      createdAt: 2022-04-11T02:32:39.525Z,
      updatedAt: 2022-04-11T02:33:23.727Z
    },
    _previousDataValues: {
      id: 10,
      text: 'Cheese and pasta!!',
      creator: 6,
      created: 2022-04-11T02:32:39.524Z,
      likes: '[6,1]',
      repliesLastID: 0,
      replies: '[]',
      createdAt: 2022-04-11T02:32:39.525Z,
      updatedAt: 2022-04-11T02:33:23.727Z
    },
    uniqno: 1,
    _changed: Set(0) {},
    _options: {
      isNewRecord: false,
      _schema: null,
      _schemaDelimiter: '',
      raw: true,
      attributes: [Array]
    },
    isNewRecord: false
  },
  Post {
    dataValues: {
      id: 11,
      text: 'Cheese is yum uwu',
      creator: 7,
      created: 2022-04-11T02:40:40.170Z,
      likes: '[]',
      repliesLastID: 0,
      replies: '[]',
      createdAt: 2022-04-11T02:40:40.170Z,
      updatedAt: 2022-04-11T02:48:26.315Z
    },
    _previousDataValues: {
      id: 11,
      text: 'Cheese is yum uwu',
      creator: 7,
      created: 2022-04-11T02:40:40.170Z,
      likes: '[]',
      repliesLastID: 0,
      replies: '[]',
      createdAt: 2022-04-11T02:40:40.170Z,
      updatedAt: 2022-04-11T02:48:26.315Z
    },
    uniqno: 1,
    _changed: Set(0) {},
    _options: {
      isNewRecord: false,
      _schema: null,
      _schemaDelimiter: '',
      raw: true,
      attributes: [Array]
    },
    isNewRecord: false
  },
  Post {
    dataValues: {
      id: 12,
      text: 'Cheese is great! You should totally eat it.n<marquee>Cheese</marquee>',
      creator: 7,
      created: 2022-04-11T02:44:03.630Z,
      likes: '[]',
      repliesLastID: 0,
      replies: '[]',
      createdAt: 2022-04-11T02:44:03.631Z,
      updatedAt: 2022-04-11T02:44:03.631Z
    },
    _previousDataValues: {
      id: 12,
      text: 'Cheese is great! You should totally eat it.n<marquee>Cheese</marquee>',
      creator: 7,
      created: 2022-04-11T02:44:03.630Z,
      likes: '[]',
      repliesLastID: 0,
      replies: '[]',
      createdAt: 2022-04-11T02:44:03.631Z,
      updatedAt: 2022-04-11T02:44:03.631Z
    },
    uniqno: 1,
    _changed: Set(0) {},
    _options: {
      isNewRecord: false,
      _schema: null,
      _schemaDelimiter: '',
      raw: true,
      attributes: [Array]
    },
    isNewRecord: false
  }
]

how to make user input on screen to reflect on click event (js, html)

I am trying to write html and js codes to make user input to change according to which button user clicks. For example, user enters find/replace values respectively and when they hit the replace button, the user input they initially typed in will change. below is my code which is not working at all..

var str = document.getElementById('text').value;
var f = document.getElementById('find').value;
var r = document.getElementById('replace').value;

let rep = str.replace(f, r);
document.getElementById('text'),innerHTML = rep;

//

<button onclick="funcname()">Replace</button><br>

How to count item based on specific property in array of object in Javascript? [duplicate]

I have below sample javascript array of object in which I have to maintain count based on category property. And I need to stored the category and count property in seperate of array of object.

const data = [
  {
    _id: "61f5487cd6cb076cf4556d74",
    title: "Test Data 123",
    description:
      "Contrary to popular belief, Lorem Ipsum is not simply random text.",
    name: "Harry",
    category: "Education",
  },
  {
    _id: "61f5487cd6cb076cf4556d74",
    title: "Test Data 234",
    description:
      "Contrary to popular belief, Lorem Ipsum is not simply random text.",
    name: "Jerry",
    category: "Sports",
  },
  {
    _id: "61f5487cd6cb076cf4556d74",
    title: "Test Data 767",
    description:
      "Contrary to popular belief, Lorem Ipsum is not simply random text.",
    name: "Paul",
    category: "Fashion",
  },
  {
    _id: "61f5487cd6cb076cf4556d74",
    title: "Test Data 664",
    description:
      "Contrary to popular belief, Lorem Ipsum is not simply random text.",
    name: "Jenny",
    category: "Fashion",
  },
];

I need to show the category count of the above data in below format.

const category = [ {category: "Education", count: 1},  {category: "Sports", count: 1},  {category: "Fashion", count: 2}]

Cannot pass error from controller to view in MVC

I am trying to pass an error from the controller to view to javascript. However, I am not able to capture the error that I am passing from the controller.
Below is the code. When if(signInValid) is false, I am adding error in the model and passing it to the view. But the model is not receiving that error.

[HttpGet]
        public IActionResult SignIn(string returnUrl)
        {
            SignInModel model = new SignInModel();
            if (returnUrl != null)
                model.RedirectUrl = returnUrl;
            else
                model.RedirectUrl = "/Home/Index";

            model.AvailableAccounts = _da.GetSystemAccounts();
            return View(model);
        }

 [HttpPost]
 public async Task<IActionResult> SignIn(SignInModel model)
 {
            if (ModelState.IsValid)
            {
                if (model.ForgotPassword)
                {
                }
                else
                {
                    bool signInValid = true; //todo: authenticate

                    Guid userID = _da.VerifyLoginUsername(model.Email);
                    signInValid = _da.VerifyLoginPassword(userID, model.Password);

                    if (signInValid)
                    {
                        return Ok();
                    }
                    else
                    {
                        model.Error = "Your e-mail address and password do not match, or the account may have been deactivated";
                    }
                }

            }
            return View(model);
        }

Below is the view

@model VeoScheduling.Models.SignInModel
@{
    ViewData["Title"] = "SignIn";
}
<div class="login">
    <h2>Sign In</h2>
    <div>
        <form method="post" asp-action="SignIn" asp-controller="Account">

            <input type="hidden" asp-for="RedirectUrl" />
            <div class="form-group">
                <label asp-for="Email" class="control-label"></label>
                <input type="email"
                       data-bind="value: email" asp-for="Email"
                       class="form-control" id="email-input" />
                <span asp-validation-for="Email" class="text-danger" id="email-validate"></span>
            </div>

            <div class="form-group">
                <label asp-for="Password"
                       class="control-label"></label>
                <input type="password" asp-for="Password"
                       data-bind="value: password"
                       class="form-control" id="password-input" />
                <span asp-validation-for="Password" class="text-danger" id="password-validate"></span>
            </div>
            <span asp-validation-for="Error" class="text-danger" id="login-error"></span>

            <div class="form-group">
                <label class="control-label">Account</label>
                <select name="accountSelected" style="margin:5px;width:200px"
                        data-bind='options: availableAccounts, optionsText: "value", optionsValue: "key", value: selectedAccount,event:{change: accountSelected()}'></select>

            </div>

            <br />

            <!--ko if: availableAccounts().length > 0 -->
            <div class="form-group">
                @*<input type="submit" value="Sign In" class="dialogButton" />*@
                <input type="button"
                       data-bind="click: signOn"
                       value="Sign In"
                       class="dialogButton" />
            </div>
            <br />
            <!--/ko-->
            <!--ko if: availableAccounts().length == 0 -->
            <span class="text-danger">Your account does not exist.</span>
            <!--/ko-->

        </form>
    </div>

</div>

@section Scripts{
  
    <script>
            var vModel = @Html.Raw(Json.Serialize(Model));
    </script>
    <script src="~/js/signIn.js" asp-append-version="true"></script>
}

Below is a javascript code. I am expecting an error in self.error that I am passing from the controller but it is always empty.

var viewModel = function (model) {
    var self = this;


    //properties
    self.email = ko.observable('');
    self.error = ko.observable(model.error);
    self.password = ko.observable('');
    self.redirectUrl = model.redirectUrl;

    self.availableAccounts = ko.observableArray(model.availableAccounts);
    self.selectedAccount = ko.observable(null);

    //events
    self.signOn = function () {
        console.log("Email : ", self.email());
        console.log("Password : ", self.password());
        console.log("Error : ", self.error());
        if (self.email() == null || self.email() == "") {
            $('#email-validate').html("*Email is required");
            return false;
        }
        if (self.password() == null || self.password() == "") {
            $('#password-validate').html("*Password is required");
            return false;
        }
        if (self.email() != null && self.password != null) {
            var payloadData = {
                'email': self.email(),
                'password': self.password(),
                'accountSelected': self.selectedAccount()
            };

            var url = window.location.origin + '/account/SignIn';

            CallService("Post", url, payloadData)
                .done(function (data) {
                    console.log(self);
                    if (self.error() != null || self.error() != "") {
                        var url = window.location.origin + self.redirectUrl;
                        //window.location.replace(url);
                    }
                    else {
                        $("#login-error").html("*Your e-mail address and password do not match, or the account may have been deactivated");
                    }

                });
        }


    };


    $(document).ready(function () {
        self.vm = new viewModel(self.vModel);
        ko.applyBindings(self.vm);
    });
}

How to fetch and update data from an API in react with hook

Question regarding fetching nested data in react.

functionality:
Albums load from https://jsonplaceholder.typicode.com/albums and are displayed on the page.
The page displays the title property from the album.
When an album’s title is clicked, the album’s photos are fetched from https://jsonplaceholder.typicode.com/albums/${albumId}/photos.
The page displays the title, and the thumbnails of up to 10 of the photos for an album on the page after the album is clicked.

codes:

App.js

import React, { useEffect, useState } from "react";
import AlbumDetail from "./AlbumDetail";

function App() {
const [albums, setAlbums] = useState([]);

 useEffect(() => {
 const loadalbums = async() => {
    const response = await
      fetch("https://jsonplaceholder.typicode.com/albums?userId=1")
  const data = await response.json()
  setAlbums(data)

   };
  loadalbums
   }, []);

   return <div className="App">
    {albums.map((id) => (
      <li key={album.id}>
        <AlbumDetail
          albumId={albums.id}
          title={albums.title}
        />
       </li>
    ))}
  </div>;
  }

  export default App;

AlbumDetail.js

 import React, { useEffect, useState } from "react";

 function AlbumDetail(albumId, id, title) {
  const [photos, setPhotos] = useState([]);

  useEffect(() => {
  fetch(`https://jsonplaceholder.typicode.com/albums/${albumId}/photos`)
  .then((response) => response.json())
  .then(setPhotos)
  .catch((error) => {
    console.log(error);
    });
  }, []);

  const clickHandler =() => {
  setPhotos({albumId})
  }
  return <div className="AlbumDetail">
  <h1>{photos.title}</h1>
  {photos.map(({title}) => ( 
    <li key={albumId}>
      <dl>{title}</dl>
    </li>
  ))}
  </div>;
 }

export default AlbumDetail;

With this, it giving a Test Failed:
Failure:
TestingLibraryElementError:

Apply affine transformation to value in TensorFlow

I use TF.js to run a key-point prediction model for an input image in browser. And I’d like to apply affine transformation to the value of every keypoint using TF.js and webgl backend.

For the value of every key-point I’d like to do translate, scale and rotation.


Input

As a result of model prediction, I have a tensor with the shape [coord, n], where coord is [x, y] position of the keypoint in pixels.

My tensor

inputTensor.print();

> Tensor
    [[103.9713821, 128.1083069], // <- [x, y]
     [103.7512436, 107.0477371],
     [103.3587036, 115.1293793],
     [99.65448   , 92.0794601 ],
     [103.9862061, 101.7136688],
     [104.2239304, 95.8158569 ],
     [104.6783295, 82.7580566 ]]

Formula

I see tf.image.transform uses the following formula to compute the pixel position.

(x', y') = ((a0 x + a1 y + a2) / k, (b0 x + b1 y + b2) / k)
where k = c0 x + c1 y + 1.

I have values for [a0, a1, a2, b0 b1, b2, c0, c1], so seems like I only need a way to apply this formula to every (x, y) pair in my tensor.


CPU Example (I need it on TF.js)

I’ve tried to do the transformation on the CPU using THREE.js. It works but is too slow.
Hope it will give you some ideas of what I expect.

const landmarks: Float32Array = inputTensor.dataSync();

const output: Point3D[] = [];

for (let i = 0; i < landmarks.length - 1; i += 2) {
    const x = landmarks[i];
    const y = landmarks[i + 1];


    const mat4 = new Matrix4();
    mat4.identity();
    
    // Fill in with the basic values
    mat4.multiply(new Matrix4().makeTranslation(x, y, 0));

    // Scale 
    mat4.multiply(
        new Matrix4().makeScale(
            1 / scaleX,
            1 / scaleY,
            1,
        ),
    );
    // Rotate
    mat4.multiply(new Matrix4().makeRotationZ(rotate));
    // Translate
    mat4.multiply(
        new Matrix4().makeTranslation(
            translateX,
            translateY,
            0,
        ),
    );

    const p = new Vector3(x, y, 0).applyMatrix4(mat4);
    output.push(new Point3D(p.x, p.y, p.z));
}


Note

As far as I see tf.image.transform doesn’t work for me since it operates with the position of the element, but I need to operate with the value.

React Native FontFamily Bold and color globally not working

I have an issue which the font-family not working on my app, especially when applying bold text, I’ve already placed all of my font in my android/app/src/main/assets/fonts and doing react-native link command

./constants/theme.js

import { Dimensions } from "react-native";
const { width, height } = Dimensions.get("window");
export const FONTS = {
        h1: { fontFamily: "Roboto-Black", fontSize: SIZES.h1, lineHeight: 36 },
        h2: { fontFamily: "Roboto-Bold", fontSize: SIZES.h2, lineHeight: 30 },
        h3: { fontFamily: "Roboto-Bold", fontSize: SIZES.h3, lineHeight: 22 },
        h4: { fontFamily: "Roboto-Bold", fontSize: SIZES.h4, lineHeight: 22 },
        body1: { fontFamily: "Roboto-Regular", fontSize: SIZES.body1, lineHeight: 36 },
        body2: { fontFamily: "Roboto-Regular", fontSize: SIZES.body2, lineHeight: 30 },
        body3: { fontFamily: "Roboto-Regular", fontSize: SIZES.body3, lineHeight: 22 },
        body4: { fontFamily: "Roboto-Regular", fontSize: SIZES.body4, lineHeight: 22 },
        body5: { fontFamily: "Roboto-Regular", fontSize: SIZES.body5, lineHeight: 22 },
    };

export const COLORS = {
    primary: "#7F5DF0",     // Light purple
    secondary: "#5D2DFD",   // Dark purple
    white: "#fff",
    black: "#000000",
    green: "#37E39F",
    red: "#F9A8BA",
    gray: "#6A6A6A",
    lightGray: "#dbdbdb",
    lightGray1: "#f5f6fa"
};  
export const SIZES = {
    // global sizes
    base: 8,
    font: 14,
    radius: 12,
    padding: 24,
    // font sizes
    h1: 30,
    h2: 22,
    h3: 16,
    h4: 14,
    body1: 30,
    body2: 22,
    body3: 16,
    body4: 14,
    body5: 12,
    // app dimensions
    width,
    height
};

const appTheme = { COLORS, SIZES, FONTS };
export default appTheme;

And when I return it when I use ...FONTS.h3 the text was not bold even though I declared bold text

 import {COLORS, FONTS} from '../constants';
 <View>
    <Text style={{...FONTS.h3, ...COLORS.green}}>Text with bold and green color</Text>
 </View>

./contants/index.js

import icons from "./icons";
import images from "./images";
import theme, { COLORS, SIZES, FONTS } from "./theme";

export { icons, images, theme, COLORS, SIZES, FONTS };

The best way to resize canvas with its objects

I have a Fabric.js canvas inside in a responsive design with boostrap.
To resize the canvas, I use canvas.setDimensions({width:w, height:h});
From the width and the height of the current window clientWidth and clientHeight. Here is my canvas and his container :

<div style="width: 100%;" class="canvas-container">
   <canvas id="canvas" class='img-fluid'></canvas>
</div>

When the canvas is resized, for each object in the canvas I change proportionally their size and location. I calculate a factor to apply to each object’s top/left/width/height using the original and new canvas sizes. This code runs every time the canvas is resized:

 function resizeCanvas() {
    const outerCanvasContainer = $('.canvas-container')[0];
    const ratio = canvas.getWidth() / canvas.getHeight();
    const containerWidth   = outerCanvasContainer.clientWidth;
    const containerHeight  = outerCanvasContainer.clientHeight;
    const scale = containerWidth / canvas.getWidth();
    const zoom  = canvas.getZoom() * scale;

    canvas.setDimensions({width: containerWidth, height: containerWidth / ratio});
    canvas.setViewportTransform([zoom, 0, 0, zoom, 0, 0]);

        if (canvas.width != containerWidth) {
          var scaleMultiplier = newWidth / canvas.width;
          var objects = canvas.getObjects();
          var factorX = newWidth / canvas.getWidth();
          var factorY = newWidth / canvas.getHeight();
          for (var i in objects) {
              objects[i].scaleX = objects[i].scaleX *factorX;
              objects[i].scaleY = objects[i].scaleY *factorX;
              objects[i].left = factorX * objects[i].left;
              objects[i].top = factorX * objects[i].top ;
              objects[i].setCoords();
          };

          canvas.setWidth(canvas.getWidth() * factorX);
          canvas.setHeight(canvas.getHeight() * factorY);
          canvas.renderAll();
          canvas.calcOffset();
        }
}

$(window).resize(resizeCanvas);

Resizing works fine, all the objects change their dimensions correctly.
The problem is that most objects cannot be selected after the canvas is resized.
Also, clicking on empty areas of the canvas sometimes selects objects…

I have done a lot of research on the internet and tried a lot of things and I would like to know if anyone knows the best way to make a responsive design while keeping the correct values of the canvas objects in order to avoid this problem happening.

Thank you

What is the easiest way to check adjacent elements in a 2d array?

I am making a chess Game using JS/HTML/CSS and I want to check for squares next to my king. Using a 2d array, what is the easiest way to check adjacent elements?

If my index is [5][5], the top left element is [4][4] and the bottom right one is [6][6].
Is there a way to somehow slice all elements from start (44) to end (66) and add them to another array?

Eps.jsx:28 Uncaught TypeError: anime.quality.map is not a function [duplicate]

why every time I use .map() at the 2nd value of the object is always an error.

sorry if my explanation is not clear

My code is like this.

import React from "react";
import { useParams } from "react-router-dom";

export default function Eps() {
  const [anime, setAnime] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const param = useParams();
  const slug = param.slug;
  async function getEpisodeAnime() {
    const reqAnime = await fetch(
      `https://****api.herokuapp.com/api/eps/${slug}`
    );
    const data = await reqAnime.json();
    setAnime(data);
    setLoading(false);
  }
  React.useEffect(() => {
    getEpisodeAnime();
  }, []);
  return (
    <>
            <h1>{anime.title}</h1>
            {anime.quality.map((res) => {
              return (
                <>
                  <p>....</p>
                </>
              );
            })}
    </>
  );
}