random forest – Error in eval(predvars, data, env) : object ‘Clay’ not found

I’m trying to find the root mean square error between my training and testing data. I use the code
rmse_reg(rf.mehgdata, testdat, "MeHg")

but I keep getting Error in eval(predvars, data, env) : object ‘Clay’ not found

I tried : names(mehgdata) <- make.names(names(mehgdata))
but got Error in eval(predvars, data, env) : object ‘Clay’ not found

object oriented – My Javascript events countdown OOP app

I wrote a javascript app with allows the user to add events and get countdown for every event. Also the events and there dates are stored in localStorage.
I want a general review and I think that every second the browser makes a lot of operations like here:

 let interval = setInterval(() => {
      let timerValue = this.__timer.tick(values);
      if (timerValue === "Timed out") {
        alert(`${values.title} is out now !`);
        this.__adapter.removeEvent(values.title);
        clearInterval(interval);
      } else {
        this.__adapter.createEventOrUpdateIfExisted(values, timerValue);
      }
    }, 1000);

What’s the best approach to follow?

Source code: https://github.com/dvmhmdsd/Events-countdown

cpu – What subfields in computer sciences may one study without learning Object Oriented Programming?

Object Oriented Programming is a type of programming paradigm.

A Computer Science degree is mostly theoretical (not only machine learning and applied statistics! Believe me there is so much more), so you wont see any of this in most courses, however, in a Software Engineering degree I suppose you do learn more about OOP.

Anyways, OOP is always good to know. Its not as complicated as you would think from its fancy name, and it gives a nice way to write organized code, and most programming languages support that kind of programming.

However, there are some programming languages that use a different type of programming paradigm called “functional programming”. I recommend you to take a look at it too.

If you are wondering about what kinds of things there are in a CS degree, feel free to ask me!

BTW: This Stack Exchange site is for theoretical computer science, so questions about theoretical computer science problems are seen here all of the time.

calculations – What is the relationship between size of object with distance?

Inversely linear is a good approximation.
Imagine a 1,7m tall girl at 1 m distance b. Her head is at point B.
triangle that name corners and sides. Source: Wikipedia Article "Arctangent". This file is licensed under the Creative Commons Attribution-Share Alike 3.0 Unported license.

How does the size/length of an object vary with distance?

Let the girl walk away from you. Her size a stays the same. She appears smaller, because she is appearing under a smaller angle. Her angular size changes. Try to imagine it with the picture attached.
Using arctangent to calculate her angular size is the correct way. For small angles you can simplify:

Angular size is inversely proportional to its object distance, without using optical devices.

An object on full-field with focal length of 12 mm would be measured incorrectly. An error 2-5% in length measurement may be made. For fish-eye lenses this may be even worse. Hands-on rule: Use the inverse relationship if angular size is smaller than 10°.

Finding lower boundary of a 3D object in list format

I have the following point list and would like to find the points located in the lower boundary of the 3D object (It is part of a body torso).

https://pastebin.com/L12n0Gfr

I am using the following script. However, in the end it shows just one point which is not correct. I think the reason is that the lower boundary points are not aligned with a straight line. Any help is really appreciated.

B3 = Select(data3D, MemberQ(#, Min( data3D((All, 2)))) &);

javascript – Jasmine spyOn not finding object

Im trying to make a test with spyon from jasmine. The error is telling the it could not find an object to spy upon for GetGame(). The test looks like this:

describe("get the game info", function () {
    const responseJSON = ({"status":"ok","description":"test","data":"{"GameId":1013,"Name":"Testing","GameToken":"QKqiZtaHLUySQots1EUzzA==","PlayerWhiteToken":"enzv7d6GZEicAOn07NCVow==","PlayerBlackToken":"w5dnLkhS506PVlaxzyWMuw==","OnSet":2,"Winner":null,"GameStatus":"inprogress","Board":"((0,0,0,0,0,0,0,0),(0,1,0,0,0,0,0,0),(0,2,1,2,2,2,0,0),(0,0,0,1,2,2,0,0),(0,2,2,2,2,2,0,0),(0,0,1,1,1,1,0,0),(0,0,0,2,0,0,0,0),(0,0,0,0,0,0,0,0))"}"});
let promiseHelper;

beforeEach(function () {
    let fetchPromise = new Promise(function (resolve, reject) {
        promiseHelper = {
            resolve: resolve,
            reject: reject
        };
    });

    promiseHelper.resolve(new Response(JSON.stringify(responseJSON)));

    spyOn(Spa.data, "GetGame").and.returnValue(fetchPromise);
});

it("fetches game data", function () {
    Spa.Data.GetGame().then(function (data) {
            expect(data.description).toBe("test");
    });
});

Then we have the Spa.data which has a few functions, one of them is GetGame. which looks like this:

Spa.Data = (() => {
    let configmap = {
        gametoken: null,
        env: "production"
    };
   
   ....

   function GetGame() {
        //check if the board exist
        return new Promise(function (resolve, reject) {
            $.ajax({
                url: "https://localhost:44375/api/game/" + configmap.gametoken,
                method: "GET",
                success: function success(response) {
                    resolve({
                        name: "prep_board",
                        response: response
                    });
                },
                error: function error(xhr, _error2) {
                    var widget = new Widget(xhr.responseText, "body", 'warning');
                    widget.Load();
                    reject({
                        name: _error2,
                        response: _error2
                    });
                }
            });
        });
    };
    
    ...

    return {
        init: init,
        GetPlayers: players,
        getWhoIs: getWhoIs,
        GetGame: GetGame,
        move: passMove
    };
})();

I removed the other classes to make it more understandable.

python – TypeError: cannot use a string pattern on a bytes-like object

I am doing HackTheBox Web Challenge & I have to write a Python Script in order to solve it.
I am writing a python script to fetch the HTML code of the website & remove the unnecessary HTML tags.

This is the script:


import requests
import hashlib
import re

req = requests.session()
url = "http://docker.hackthebox.eu:30596/"


rget = req.get(url)
html = rget.content


def html_tags(html):
    clean = re.compile('<.*?>')
    return re.sub(clean, '', html)

print(html_tags(html))

Unfortunately, I am getting an error.

Traceback (most recent call last):
  File "1.py", line 19, in <module>
    print(html_tags(html))
  File "1.py", line 17, in html_tags
    return re.sub(clean, '', html)
  File "/usr/lib/python3.8/re.py", line 210, in sub
    return _compile(pattern, flags).sub(repl, string, count)
TypeError: cannot use a string pattern on a bytes-like object

A guy did the same script, but mine is giving error. What could be the cause. Please help me with this.

How to flatten a specific key in a nested JSON object with C#

Is there an efficient way to flatten a specific key in a JSON structure using a slash?

This is what my JSON file looks like:

{
  "BookMax": 0,
  "BookMin": 0,
  "Books": [
    {
      "BookPackage": {
        "BookType": "Fictional",
        "PackageNumber": 2
      },
      "BookPrequelList": [
        {
          "BookPrequelList": "ABookPrequel"
        }
      ],
      "BookSequelList": null,
      "BookBio": null,
      "BookBack": null,
      "Author": "Alice",
      "AuthorPsuedoName": "AuthorX",
      "BookISBN": "ISBN_6312"
    },
    {
      "BookPackage": {
        "BookType": "Fictional",
        "PackageNumber": 3
      },
      "BookPrequelList": [
        {
          "BookPrequelList": "ABookPrequel"
        }
      ],
      "BookSequelList": null,
      "BookBio": null,
      "BookBack": null,
      "Author": "Bob",
      "AuthorPseudoName": "NotBob",
      "Book_ISBN": "ISBN_533"
    }
  ],
  "Library": null,
  "LibraryNumber": 5,
  "Author": {
    "Year": null,
    "Address": null,
    "LastName": null,
    "AllBooks": [],
    "WonNYBestSeller": false,
    "NumberofBooks": 0,
    "SelfPublished": false,
    "AuthorFunFacts": {
      "NumberofPets": 0,
      "NumberofCars": 0,
      "PlaceofBirth": null,
      "WrittenChildrenBook": false
    },
    "Biography": null,
    "Age": 32,
    "NumberBestSellers": 0,
    "NumberMovies": 1
  },
  "AuthorLuckyNumber": 24,
  "SearchKeys": [
    "Alice",
    "AuthorX"
  ],
  "Website": null,
  "BookPublications": {
    "FirstPublication": 1,
    "LastPublication": 1
  },
  "FavoriteQuote": "FavoriteQuote1"
  "NumberPoems": 1,
}

Normally, flattening should be straightforward with the slash. But with the Books key, because each object looks like this:

    {
      "BookPackage": {
        "BookType": "Fictional",
        "PackageNumber": 2
      },
      "BookPrequelList": [
        {
          "BookPrequelList": "ABookPrequel"
        }
      ],
      "BookSequelList": null,
      "BookBio": null,
      "BookBack": null,
      "Author": "Alice",
      "AuthorPsuedoName": "AuthorX",
      "BookISBN": "ISBN_6312"
    }

Is there a way to flatten this Book key specifically according to the BookPackage/PackageNumber? The BookPackage inner object is simply used to differentiate the different BookPackage objects. Right now I can’t figure out how to use BookPackage as an identifier that will be able to differentiate the different Books objects into something like this:

Books / Fictional_2 / BookPrequelList / BookPrequelList | ABookPrequel

Books / Fictional_2 / BookSequelList |

Books / Fictional_2 / BookBio |

Books / Fictional_2 / BookBack |

Books / Fictional_2 / Author | Alice

Books / Fictional_2 / AuthorPsuedoName | AuthorX

Books / Fictional_2 / BookISBN | ISBN_6312

Books / Fictional_3 / BookPrequelList / BookPrequelList | ABookPrequel

Books / Fictional_3 / BookSequelList |

Books / Fictional_3 / BookBio |

Books / Fictional_3 / BookBack |

Books / Fictional_3 / Author | Bob

Books / Fictional_3 / AuthorPseudoName | NotBob

Books / Fictional_3 / Book_ISBN | ISBN_533

Every other key will be flattened in the order it appears. Thanks

How to replace the particular value in array object of nested object with another array object in javascript

I have two objects obj1 and obj2, if obj1 property info has keys id and code,

If the array object info of obj1 keys code and id matches with obj2, then replace the nos of obj2 with obj1. if not matches, change it to 0

How to replace the value in array object of nested array object if id and code matched with another array object in javscript.

function newArray (obj1,obj2){
 return obj2.map(e=>{
   nos = obj1.filter(i=>i.info.some(x=>x.id === e.id && x.code === i.code)
   return nos ? {...e, nos} : e;
 })
}

var obj1 =(
 {tot: 4, info: ({id:1, code:"x1",nos:2},{id:2, code:"x2",nos:2}) }
 {tot: 2, info: ({id:3, code:"x3",nos:2},{id:5, code:"x5",nos:3}})}
)

var obj2 = (
 {id:1, code: "x1", nos:1, name:"sample1"},
 {id:2, code: "x2", nos:2, name:"sample2"},
 {id:3, code:"x3",nos:3, name:"sample3"},
 {id:4, code: "x1", nos:0},
 {id:5, code: "x5", nos:3, name:"sample5"},
)

Expected Output:

(
{id:1, code: "x1", nos:2, name:"sample1"},
{id:2, code: "x2", nos:2, name:"sample2"},
{id:3, code:"x3",nos:2, name:"sample3"},
{id:4, code: "x1", nos:0},
{id:5, code:"x5",nos:3, name"sample5"}
)

javascript – How to change state of object correctly?

I have an object that I would like to change the values when button is clicked. Whatever I do, I am only able to change the state on second click. First click is always returning the initial values for me. Can somebody guide me on what is the problem here ?

initial state:

const (currencyResult, setCurrencyResult) = useState({
        amount: "1",
        currencyFrom: "EUR",
        currencyTo: "USD",
        multipliedAmount: "",
        date: ""
    });

onclick :

setCurrencyResult({
                amount: currencyResult.amount,
                currencyFrom: currencyResult.currencyFrom,
                currencyTo: currencyResult.currencyTo,
                multipliedAmount: currencyRate * currencyResult.amount,
                date: Date.now()
            })

whole code is:

import React, { useState, useEffect } from 'react';
import { Form, Icon } from 'semantic-ui-react';
import { Link } from 'react-router-dom';
import ShowResult from './ShowResult';
import "../styles/HomePage.css"


const HomePage = (props) => {
    const options = (
        { key: 'EUR', value: 'EUR', text: 'EUR' },
        { key: 'USD', value: 'USD', text: 'USD' },
        { key: 'CHF', value: 'CHF', text: 'CHF' },
    );
    const baseUrl = `https://api.exchangeratesapi.io/latest?base=`
    const (currencyResult, setCurrencyResult) = useState({
        amount: "1",
        currencyFrom: "EUR",
        currencyTo: "USD",
        multipliedAmount: "",
        date: ""
    });
    const (currencyDatabase, setCurrencyDatabase) = useState(());
    const (hasError, setHasError) = useState(false);
    const (errorMessage, setErrorMessage) = useState("");
    const { amount, currencyFrom, currencyTo, multipliedAmount, date } = currencyResult;
    const (currencyRate, setCurrencyRate) = useState("");
    const (clicked, setClicked) = useState(false);
    const formValidation = () => {

        if (currencyResult.currencyFrom === currencyResult.currencyTo) setErrorMessage("Equal currencies")
        if (!currencyResult.amount) setErrorMessage("no number given")
        if (currencyResult.amount.charAt(0) === "-") setErrorMessage("no minus numbers")
        if (currencyResult.amount === "0") setErrorMessage("can't convert 0")
        if (errorMessage) setHasError(true)
    }

    const calculationHandler = async () => {
        formValidation()

        if (hasError) {
            return
        } else {
            setClicked(!false)
            const fetchData = await fetch(`${baseUrl}${currencyResult.currencyFrom}&symbols=${currencyResult.currencyTo}`);
            const response = await fetchData.json();
            setCurrencyRate(await Object.values(response.rates)(0))
            setCurrencyDatabase((...currencyDatabase, currencyResult))
            setCurrencyResult({
                amount: currencyResult.amount,
                currencyFrom: currencyResult.currencyFrom,
                currencyTo: currencyResult.currencyTo,
                multipliedAmount: currencyRate * currencyResult.amount,
                date: Date.now()
            })
        }
    }





    if (currencyDatabase) props.getCalculations(currencyDatabase);


    const changeCurrency = () => {
        setCurrencyResult({
            ...currencyResult,
            currencyTo: currencyResult.currencyTo
        })
        setCurrencyResult({
            ...currencyResult,
            currencyFrom: currencyResult.currencyFrom
        })
    }

    return (
        <div className="app">
            <div className="header">
                <h1 className="headline">Convert currencies in real-time.</h1>
            </div>
            <div className="form-content">

                <Form className="box-background">
                    <Form.Group style={{ margin: "auto" }} >
                        <Form.Input
                            required
                            label='Amount'
                            placeholder='Amount'
                            value={currencyResult.amount}
                            onChange={(e, { value }) => setCurrencyResult({
                                ...currencyResult,
                                amount: value
                            })}
                            type="number"
                        />
                        <Form.Select
                            required
                            placeholder="From"
                            label="From"
                            value={currencyResult.currencyFrom}
                            onChange={(e, { value }) => setCurrencyResult({
                                ...currencyResult,
                                currencyFrom: value
                            })}
                            options={options}
                        />
                        <Icon name="exchange" onClick={changeCurrency} size="large" />
                        <Form.Select
                            required
                            placeholder="To"
                            label="To"
                            value={currencyResult.currencyTo}
                            onChange={(e, { value }) => setCurrencyResult({
                                ...currencyResult,
                                currencyTo: value
                            })}
                            options={options}
                        />
                        <Form.Button
                            className="btn-div"
                            onClick={calculationHandler}>
                            Convert
                            </Form.Button>
                    </Form.Group>
                    <Form.Field className="error-msg">
                        {hasError ? <p>{errorMessage}</p> : null}
                    </Form.Field>
                </Form>
                <Link to="/result" className="conversion-history">
                    <span>View conversion history {">"}</span>
                </Link>
            </div>
            {currencyResult && <ShowResult currencyResult={currencyResult} />}
        </div>
    );
}

export default HomePage;