Is it possible to extend Joi schema using a existent rule?

I have a schema like this (the real one is doble the size):

const optionalIfPatch = { patch: (schema: AnySchema) => schema.optional() };

const personValidator = Joi.object({
  username: Joi.string().token().lowercase().min(5).required().alter(optionalIfPatch),
  password: Joi.string().min(6).required().alter(optionalIfPatch),
  fullName: Joi.string().min(5).required().alter(optionalIfPatch),
  email: Joi.string().email().required().alter(optionalIfPatch),
  userProfile: Joi.string().valid(...Object.keys(UserProfile)).default(UserProfile.default),
  address: Joi.object({
    streetAddress: Joi.string().min(5),
    city: Joi.string().min(3),
    state: Joi.string().min(3),
    zipCode: Joi.string().min(3),
  }),
}).options({ abortEarly: false });

Basically I want make required fields optional with the personValidator.tailor() function at validation time. It works this way, but I was trying to make this behavior into an extension:

const joiExtensions: Joi.ExtensionFactory[] = [
  (joi: Joi.Root) => ({
    type: /.*/,
    rules: {
      requiredButPatchable: {
        alias: 'reqOrPatch',
        method() {
          return this.required().alter(optionalIfPatch); // GOT STUCK HERE
        }
      },
    },
  }),
];

To be used like this:

Joi.string().token().lowercase().min(5).requiredButPatchable()

But to be honest, I’ve been researching for three days and couldn’t find a proper explanation of how to build an extension like this (using Joi itself).

(Also, when I extend the Joi model, I loose the autocompletion for VSCode… is there a way arround it?)

I’ve tried the Joi docs, git issues, stack overflow questions… couldn’t find a proper answer.
I want to use the alter()and tailor() functionalities as an extension so I can reduce the repeated code…

Use WebSocket wrapper for all iframe, ws requests

I’m trying to experiment if I can force all elements within an iframe (of dask-labextension to be precise) to use a custom web socket wrapper following answers to this question with the following snippet:

const iframe = document.getElementsByTagName("iframe")[0];
const originalSocket = iframe.contentWindow.WebSocket;
iframe.contentWindow.WebSocket = function(...args) {
    const socket = originalSocket(...args);
    console.log("Creating new socket: ", socket);
    return socket;
};

iframe.contentWindow.WebSocket.prototype = originalSocket.prototype;
iframe.contentWindow.WebSocket.prototype.constructor = iframe.contentWindow.WebSocket;

JupyterLab’s Dask Extension loads a bunch of dashboards as iframes, each of which includes the following bokeh js files:

<head>
    <meta charset="utf-8">
    <title>Bokeh Application</title>
    <script type="text/javascript" src="static/js/bokeh.min.js?v=3c61e952b808bb7e346ce828a565a5f23aaf7708d034fa9d0906403813355d45bb4e8d8b0b23a93f032c76831d4f0221846f28699c7f5147caa62e0d31668314"></script>
    <script type="text/javascript" src="static/js/bokeh-gl.min.js?v=e5df31fd9010eacff0aa72d315264604b5e34972ba445acea6fce98080eecf33acf2d2986126360faaa5852813cffa16f6f6f4889923318300f062497c02da4e"></script>
    <script type="text/javascript" src="static/js/bokeh-widgets.min.js?v=8a1ff6f5aa0d967f4998d275803bbb111d928fd9f605ef9e1f30cfd021df0e77224ee3d13f83edb3a942f6e4ccc569ee5dd8951a8aa6cb600602463b90c65a87"></script>
    <script type="text/javascript" src="static/js/bokeh-tables.min.js?v=ae2903e57cf57f52819fdf4d938c648982b51c34f73b6e653a0f3bb3c8ab44f338505931ace43eafc1636e215492e2314acf54c54baffb47813b86b4923a7fe0"></script>
    <script type="text/javascript" src="static/js/bokeh-mathjax.min.js?v=176c36fdbcd8fc1019fc828101a2804081a35baf4018d7f2633cd263156b593aa73112f400112b662daa0590138b74851bc91f1f2a5fbf5416ee8c876c3e0d0c"></script>
    <script type="text/javascript">
        Bokeh.set_log_level("info");
    </script>
  </head>

But it looks like all of Bokeh’s websocket requests goes through a separate WebSocket object, instead of my custom wrapper. The following are console logs coming from Bokeh:

[bokeh] setting log level to: 'info'
bokeh.min.js?v=3c61e952b808bb7e346ce828a565a5f23aaf7708d034fa9d0906403813355d45bb4e8d8b0b23a93f032c76831d4f0221846f28699c7f5147caa62e0d31668314:587 [bokeh] Websocket connection 0 is now open
bokeh.min.js?v=3c61e952b808bb7e346ce828a565a5f23aaf7708d034fa9d0906403813355d45bb4e8d8b0b23a93f032c76831d4f0221846f28699c7f5147caa62e0d31668314:165 [bokeh] document idle at 94 ms
bokeh.min.js?v=3c61e952b808bb7e346ce828a565a5f23aaf7708d034fa9d0906403813355d45bb4e8d8b0b23a93f032c76831d4f0221846f28699c7f5147caa62e0d31668314:163 Bokeh items were rendered successfully

Is there a way to force Bokeh (or any other included script’s) websockets to use my custom wrapper?

How do i pass my data come from json file from one page to another in React Native? [duplicate]

PHOTO OF MY CODES

I’m trying to develop a mobile application that has book categories, books, and their details. I have successfully placed the categories from the json file on the homepage. But when I click on any category, I cannot send the books belonging to that category to the other page. I can print the category id on the books page, but I cannot import other data in it. (In addition, I have a json file with 100 books in it, and there are many categories in it. Can I print only the books with the same category from this file on one page?)

While transferring data to the other page, I was able to send information such as book name and author alone instead of id. But since I want to create a card, I need to send all of this information. I failed to do so.

MIME Error when using Vue-Router and Express

Everytime I want to access a specific route in Express I get the followwing error in my browser while also having a default and blank Vue HTML without content. Everything works in Vue debug mode but after building everything, only the Home page works.

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.

In Express I have the following code:

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);


this.app.use(express.static(`${__dirname}/html`));
this.app.get('/*', (req, res) => res.sendFile(`${__dirname}/html/index.html`));

In my router.ts in vue I have the following code:

import { defineAsyncComponent } from "vue";
import { createRouter, createWebHistory } from "vue-router";

import Natives from '../views/Natives.vue';

const router = createRouter({
  routes: [
    {
      path: "/",
      name: "Home",
      component: defineAsyncComponent(() => import('../views/Home.vue')),
      meta: {
        name: "Home",
      },
    },
    {
      path: "/gta",
      name: "GTA V",
      component: defineAsyncComponent(() =>  import("../views/GTA.vue")),
      meta: {
        name: "GTA"
      }
    },
    {
      path: "/gta/natives",
      name: "Natives",
      component: Natives,
      meta: {
        name: "GTANatives",
      },
    },
    {
      path: '/gta/natives/:hash',
      name: 'Native',
      component: defineAsyncComponent(() =>  import("../views/DetailedNative.vue")),
      meta: {
        name: "DetailedNative"
      }
    },
    {
      path: "/:pathMatch(.*)*",
      name: "Page not found!",
      component: defineAsyncComponent(() =>  import("../views/NotFound.vue")),
      meta: {
        name: "NotFound",
      },
    },
  ],
  history: createWebHistory(),
});

I appreciate any help.

How do I make the text appear and disappear again

I want the text appears when I click the button then disappear again when I click the same button again by javascript:

const firstclick = document.querySelector('.btn-story');
const hidecontenttwo = document.querySelector('.hide-content-two');

function revealcontentTwo(){
    if(firstclick.classList.contains('hidecontenttwo')){
        hidecontenttwo.style.display='none';
        
    }
    else{
        hidecontenttwo.style.display='block';

    }

}

firstclick.addEventListener("click",revealcontentTwo);

Does new version of Gatsby not work with Material UI?

I am running into this error

portfolio % npm install gatsby-theme-material-ui
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR! 
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/gatsby
npm ERR!   gatsby@"^5.3.3" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer gatsby@"^3.0.0 || ^4.0.0" from [email protected]
npm ERR! node_modules/gatsby-theme-material-ui
npm ERR!   gatsby-theme-material-ui@"*" from the root project
npm ERR! 

Within my gatsby config I have the plugin but am noticing some weird styling for production. I assumed it was because it is missing something like gatsby-theme-material-ui for it to work.

Any ideas?

Converting objects to numbers – how it’s being implemented under the hood?

I’m trying to figure out how the conversion from Object to Number is being implemented under the hood. The abstract definition from the ES doc for converting objects into numbers and strings:

7.1.1.1 OrdinaryToPrimitive ( O, hint ) The abstract operation OrdinaryToPrimitive takes arguments O (an Object) and hint (string or
number) and returns either a normal completion containing an
ECMAScript language value or an abrupt completion. It performs the
following steps when called:

  1. If hint is string, then:
  • Let methodNames be « “toString”, “valueOf” ».
  1. Else:
  • Let methodNames be « “valueOf”, “toString” ».
  1. For each element name of methodNames, do
  • Let method be ? Get(O, name).
  • If IsCallable(method) is true, then:
    • Let result be ? Call(method, O)
    • If Type(result) is not Object, return result.
  1. Throw a TypeError exception.

So, I tried to implement it in JavaScript:

function OrdinaryToPrimitive(O, hint) {
  let methodNames;
  if (typeof hint === "string") {
    methodNames = ["toString", "valueOf"];
  } else {
    methodNames = ["valueOf", "toString"];
  }
  for (let name of methodNames) {
    let method = O[name];
    if (typeof method === "function") {
      let result = method.call(O);
      if (typeof result !== "object") {
        return result;
      }
    }
  }
  throw new TypeError();
}

console.log(OrdinaryToPrimitive({}, "string")); //[object Object]
console.log(String({})); //[object Object]
console.log(OrdinaryToPrimitive({}, "number")); //[object Object]
console.log(Number({})); //NaN

The problem is that the implementation doesn’t work like the built-in conversion. Can someone tell me what did I do wrong? I even have no idea why it should work on theory since we first get the value of the object which is the object itself and then convert it to string so the result is “[object Object]”. Did I misunderstand the docs?

How do I append a ‘%’ symbol at the end of any value that was put into an input textbox in HTML/JavaScript? [duplicate]

I have an input textbox like this but I want to append % at the end of any value that was input into it at the end

<input type="text" digitsOnly/>

So if 50 was put in 50% would display

I tried adding a ::after with content: "%" in the styles but nothing appears at the end of the input. I also tried adding % at the end of my input but it is displaying outside the textbox when I want it to be inside right after the value.

I tried:

<input type="text" digitsOnly/> %

Js app runs locally but Heroku Throws and error

I built an app that runs well on locally. But when I deploy on heroku it crashes and shows me this.

Error: Cannot find module './dist'
2023-01-06T22:40:19.130104+00:00 app[web.1]: Require stack:
2023-01-06T22:40:19.130104+00:00 app[web.1]: - /app/node_modules/optional-require/index.js
2023-01-06T22:40:19.130120+00:00 app[web.1]: - /app/node_modules/mongoose/node_modules/mongodb/lib/core/index.js
2023-01-06T22:40:19.130120+00:00 app[web.1]: - /app/node_modules/mongoose/node_modules/mongodb/index.js
2023-01-06T22:40:19.130121+00:00 app[web.1]: - /app/node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js
2023-01-06T22:40:19.130121+00:00 app[web.1]: - /app/node_modules/mongoose/lib/drivers/node-mongodb-native/index.js
2023-01-06T22:40:19.130121+00:00 app[web.1]: - /app/node_modules/mongoose/lib/index.js
2023-01-06T22:40:19.130121+00:00 app[web.1]: - /app/node_modules/mongoose/index.js
2023-01-06T22:40:19.130122+00:00 app[web.1]: - /app/index.js

My code is in this repo: https://github.com/Franttisekpetruv/Carelooker
Website is:https://dashboard.heroku.com/apps/calm-crag-33682

I understand that some modules. I re-install npm and it did nothing…
I am expecting my app to run, connect to atlas etc… since it runs locally I even paid $5 to heroku, was that also necessary?

Unexpected clicking of button when typing in v-text-field after button event @click or form event @submit

I encountered this strange scenario in Vue and Vuetify.

This happens after clicking the button and executes a certain function using @click or @submit event and calls a specific vuex-mutations (this.$store.commit(<mutation_name>, <specific_value>)

Then after that, when I am now typing within v-text-field, it actually triggers the @click or @submit event which is very strange (I figure this out when I was console.log() within the function called at @click or @submit event)

I can’t post the actual code here for some reasons. Hope that someone also encountered this very strange scenario and thank you in advance on all your answers under this question.

Convert js objects to array [closed]

how to convert js object to array

[{"name":"bill","age":43,"count":5},{"name":"john","age":32,"count":1},{"name":"andy","age":25,"count":1}]

to

[ [ "name" => "bill", "age" => 43, "count" => 5 ], [ "name" => "john", "age" => 32, "count" => 1 ], [ "name" => "andy", "age" => 25, "count" => 1 ] ];

Drag and drop rotated images javascript

so i have a code that allows me to drag and drop an img tag. The drag and drop works fine but when i added a rotation function, the drag and drop started acting weird (the coordinates changed and when i drag the element the rotation reset). Also when i try dragging again, it goes back to its initial position, do you please have any idea on how i can fix this?
Image before rotation
Image after rotation
while dragging after changing rotation

This is my code and thank you in advance:

let rotate=0

function rot_plus() {
 
  rotate=rotate+10
  $("#test").css('transform',"rotate("+rotate+"deg)")
 

}

function rot_minus() {
 
  rotate=rotate-10
  $("#test").css('transform',"rotate("+rotate+"deg)")
 

}

var active = false;
var currentX;
var currentY;
var initialX;
var initialY;
var xOffset = 0;
var yOffset = 0;
let current_elem
var container = document.querySelector("#boite");
container.addEventListener("mousedown", dragStart, false);
container.addEventListener("mouseup", dragEnd, false);
container.addEventListener("mousemove", drag, false);

function dragStart(e) {
if(e.target.id=="test"){
dragItem1=e.target.id
    dragItem = document.querySelector("#"+e.target.id);
          initialX=e.clientX-xOffset
          initialY=e.clientY-yOffset

    active = true;
}
  }



function drag(e) {

  if (active) {

    e.preventDefault();
   currentX = e.clientX - initialX;
          currentY = e.clientY - initialY;

    xOffset = currentX;
    yOffset = currentY;
    setTranslate(currentX, currentY, dragItem);
  }

}

function dragEnd(e) {
        active = false;
        initialX=currentX
       initialY=currentY

  selectedElement = null;
   }


function setTranslate(xPos, yPos, el) {

  el.style.transform = "translate3d(" + xPos + "px, " + yPos + "px, 0)";

}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js" integrity="sha512-STof4xm1wgkfm7heWqFJVn58Hm3EtS31XFaagaa8VMReCXAkQnJZ+jEy8PCC/iT18dFy95WcExNHFTqLyp72eQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>
<body>
    <div id="boite">
 <img src="https://static.vecteezy.com/system/resources/previews/009/342/282/original/cartoon-eyes-clipart-design-illustration-free-png.png" id="test" class="remove" style="position: absolute; width:150px; height:auto" >
  <svg xmlns="http://www.w3.org/2000/svg" width="46" height="46" fill="currentColor" class="bi bi-plus-circle" id="rotplus" style="margin-top:120px" onclick="rot_plus()" viewBox="0 0 16 16">
    <path fill-rule="evenodd" d="M8 3a5 5 0 1 0 4.546 2.914.5.5 0 0 1 .908-.417A6 6 0 1 1 8 2v1z"/>
    <path d="M8 4.466V.534a.25.25 0 0 1 .41-.192l2.36 1.966c.12.1.12.284 0 .384L8.41 4.658A.25.25 0 0 1 8 4.466z"/>
  </svg>

  <svg xmlns="http://www.w3.org/2000/svg"width="46" height="46" fill="currentColor" class="bi bi-dash-circle" id="rotminus"
style="margin-top:120px" onclick="rot_minus()" viewBox="0 0 16 16">
    <path fill-rule="evenodd" d="M8 3a5 5 0 1 1-4.546 2.914.5.5 0 0 0-.908-.417A6 6 0 1 0 8 2v1z"/>
    <path d="M8 4.466V.534a.25.25 0 0 0-.41-.192L5.23 2.308a.25.25 0 0 0 0 .384l2.36 1.966A.25.25 0 0 0 8 4.466z"/>
  </svg>
</div>
</body>
</html>

nodejs Jest testing exec.stdout.on(‘data’,data)

Trying to to test a function the incorporates the exec of child_process library.

const { exec } = require('child_process')

const randomFunc = () => { 
  const newSync = exec('some command to execute')
  newSync.stdout.on('data', data => {
   console.log(data.toString())
  })
}

testfile:

const {randomFunc} = require(randomFuncFile)
const { exec } = require('child_process')
jest.mock('child_process')

it('test', () => {
    const readStreamObject = {
      on: jest.fn().mockImplementation(function (event, handler) {
        handler('streaming ')
      })
    }
   exec.mockImplementation(data => ({stdout: readStreamObject})
   randomFunc()
   expect(exec.stdout.on).toHaveBeenCalled()
}

I’m getting ‘TypeError: Cannot read properties of undefined (reading ‘on’)’
some tips would be great thanks!

Attempting to mock child method, fails if parent module imports it using object destructuring

I was doing some basic jest unit testing in attempt to learn it more.

I have this issue I do not know how to explain

This file has the child function add

// FileB.js 

const add = (a, b) => {
  return a + b;
}

module.exports = {
  add,
};

This file has the parent function addTen

// FileA.js

const { add } = require('./FileB');

const addTen = num => {
  return add(10, num);
}

module.exports = {
  addTen,
};

this is my test file, where I am trying to either check <mockedFunction/spy>.mock.calls or do toHaveBeenCalledWith to see if the inner child method, add, is being passed in 10,10 when i call addTen(10);

This file is not used in any real env, its simply me trying to learn jest + unit testing more.

// randomTest.js

const { addTen } = require('../src/FileA');
const fileB = require('../src/FileB'); 

describe('temp', () => {
  it('temp', () => {
    const addSpy = jest.spyOn(fileB, 'add');

    addTen(10);
    console.log(addSpy.mock.calls);

    expect(addSpy).toHaveBeenCalledWith(10,10)
  });
});

Now for the issue, the test fails, saying add was never called, or nothing passed in. I logged the add function within FileB

However, if I modify FileA in this way, by importing entore module instead of destructuring, the test passes and I cna log out the functions and everything and see it works

This is what works

// FileA.js

const fileB = require('./FileB');

const addTen = num => {
  return fileB.add(10, num);
}

module.exports = {
  addTen,
};

Why does this slight change work?