问:
Uncaught (in promise) TypeError: n.indexOf is not a function at rt.fromString (index.esm2017.js:1032:1)
I was learning react and firebase but my app keeps showing this error and can't continue

Uncaught (in promise) TypeError: n.indexOf is not a function
at rt.fromString (index.esm2017.js:1032:1)

this is my code

```<code>import React, { useRef, useState } from 'react'
import styled from 'styled-components'
import { Button } from '@mui/material'
import { collection, doc,addDoc,serverTimestamp } from "firebase/firestore";
import { db } from '../firebase'

function ChatInput(chatName,channelId) {
    const [input,setInput] = useState('')
    console.log(channelId);
    const sendMessage = async e =>{
        e.preventDefault()
        if(!channelId){
            return false
        }

        const messageRef = doc(db, "rooms", channelId);
        await addDoc(collection( messageRef,"messages"), {
            message: input,
            timestamp: serverTimestamp(),
            user:'Abd',
            userImage:'img'
          });
          setInput('')
    }
  return (
    <ChatInputContainer>
        <form>
            <input value={input} onChange={e=>setInput(e.target.value)} placeholder={`Message #ROM`} />
            <Button hidden type='submit' onClick={sendMessage}>
                send
            </Button>
        </form>
    </ChatInputContainer>
  )
}

export default ChatInput

const ChatInputContainer = styled.div`
border-radius: 20px;
>form{
    position: relative;
    display: flex;
    justify-content: center;

}
>form>input{
    position: fixed;
    bottom: 30px;
    width: 60%;
    border: 1px solid gray;
    border-radius: 3px;
    padding: 20px;
    outline: none;
}
>form>button{
    display: none !important;
}
`
</code>```

if you need anything ask me

I tried updateDoc() setDoc() and many other answers from stack overflow

Body:
I was learning react and firebase but my app keeps showing this error and can't continue

Uncaught (in promise) TypeError: n.indexOf is not a function
at rt.fromString (index.esm2017.js:1032:1)

this is my code

import React, { useRef, useState } from 'react'
import styled from 'styled-components'
import { Button } from '@mui/material'
import { collection, doc,addDoc,serverTimestamp } from "firebase/firestore";
import { db } from '../firebase'

function ChatInput(chatName,channelId) {
    const [input,setInput] = useState('')
    console.log(channelId);
    const sendMessage = async e =>{
        e.preventDefault()
        if(!channelId){
            return false
        }

        const messageRef = doc(db, "rooms", channelId);
        await addDoc(collection( messageRef,"messages"), {
            message: input,
            timestamp: serverTimestamp(),
            user:'Abd',
            userImage:'img'
          });
          setInput('')
    }
  return (
    <ChatInputContainer>
        <form>
            <input value={input} onChange={e=>setInput(e.target.value)} placeholder={`Message #ROM`} />
            <Button hidden type='submit' onClick={sendMessage}>
                send
            </Button>
        </form>
    </ChatInputContainer>
  )
}

export default ChatInput

const ChatInputContainer = styled.div`
border-radius: 20px;
>form{
    position: relative;
    display: flex;
    justify-content: center;

}
>form>input{
    position: fixed;
    bottom: 30px;
    width: 60%;
    border: 1px solid gray;
    border-radius: 3px;
    padding: 20px;
    outline: none;
}
>form>button{
    display: none !important;
}
`

if you need anything ask me

I tried updateDoc() setDoc() and many other answers from stack overflow


来源: stackexchange

问:
How do I highlight words starting with a dollar sign in Draft.js
I'm trying to change the font colour for words starting with a dollar sign ($). I believe this should be possible in Draft.js as both stocktwits and twitter appear to use this library and changing of font colour for tickers (stocktwits) and hashtags (twitter) is done on these sites. After playing around with Draft.js and lots of googling I can't figure out a way to do it. Has anyone done anything similar?</p>

ContentLicense: CC BY-SA 4.0


问:
facing an issue while trying to logout an user , using local storage in Reactjs
while using navlinks in the component having logout logic, while running the app its functioning except the thing is that on click logout it is not redirecting the login page and on checking console i am getting the issue that  cannot read the properties null (reading length, how can i resolve it ?

Trying to logout the user instead its showing balnk page and on checking the console it says cannot read properties null in index.js .
on checking index.js from console i am unable to find the error it is mentioned that in array length the problem arises but i couldn't understand how to rectify it , kindly post a solution for this, thanks

```<code>import React from "react";
import { Redirect } from "react-router-dom";
import {Nav,Navbar,Container} from 'react-bootstrap'
import SweetAlert from "react-bootstrap-sweetalert";
import logo from'./Images/logo.jpeg'

const _ = require("lodash");

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      username: this.props.name,
      board: [],
      boardItem: "",
      toggle: false,
      submit: true,
      logout: false,
      loggedInUserObj: "",
    };
  }

  onLogoutYes = () => {
    this.setState({ submit: false });
    this.setState({ toggle: true });
    const userObj = JSON.parse(
      localStorage.getItem(_.get(this.state.loggedInUserObj, "userName", ""))
    );
    userObj.isUserLoggedIn = false;
    localStorage.setItem(
      _.get(this.state.loggedInUserObj, "userName", ""),
      JSON.stringify(userObj)
    );
  };

  onLogout = () => {
    this.setState({
      logout: !this.state.logout,
    });
  };

  componentDidMount() {
    const loggedInUserName = _.get(this.props.location, "state.userName", {});
    this.setState({
      loggedInUserObj: JSON.parse(localStorage.getItem(loggedInUserName)),
    });
  }

  render() {
    const localUname = `${_.get(
      this.state.loggedInUserObj,
      "firstName",
      ""
    )} ${_.get(this.state.loggedInUserObj, "lastName", "")}`;

    return (
      <div>
          <h1 style={{textAlign:"center"}}>ONLINE ART GALLERY</h1>
          <Navbar collapseOnSelect expand="lg" bg="dark" variant="dark">
      <Container>
      <img src={logo} style={{height:"40px"}}/>
        <Navbar.Brand href="" style={{fontWeight:"bold",fontFamily:"cursive"}}></Navbar.Brand>
            <Navbar.Toggle aria-controls="responsive-navbar-nav" />
        <Navbar.Collapse id="responsive-navbar-nav">
            <Nav.Link href="/home" style={{color:"gray",fontWeight:"bold",fontSize:"120%"}}>Home</Nav.Link>
            <Nav.Link href="/about"style={{color:"gray",fontWeight:"bold",fontSize:"120%"}}>About</Nav.Link>
            <Nav.Link href="/product"style={{color:"gray",fontWeight:"bold",fontSize:"120%"}}>Products</Nav.Link>
            <Nav.Link href="/profile"style={{color:"gray",fontWeight:"bold",fontSize:"120%"}}>Profile</Nav.Link>
            <Nav.Link href="/feedback"style={{color:"gray",fontWeight:"bold",fontSize:"120%"}}>Feedback</Nav.Link>
            <Nav.Link href="/cart"style={{color:"gray",fontWeight:"bold",fontSize:"120%"}}>Cart</Nav.Link>

            {/* <button
              // className="navbar-toggler"
              // type="button"
              // data-toggle="collapse"
              // data-target="#navbarResponsive"
              // aria-controls="navbarResponsive"
              // aria-expanded="false"
              // aria-label="Toggle navigation"
            >
              <span className="navbar-toggler-icon"></span>
            </button> */}
            {/* <div className="collapse navbar-collapse" id="navbarResponsive"> */}
              <ul className="navbar-nav ml-auto">
                <li
                  className="nav-item active text-left"
                  onClick={this.onLogout}
                >
                  <button
                    type="button"
                    className="btn btn-danger"
                    onClick={this.onLogout}
                  >
                    LOGOUT
                  </button>
                </li>
              </ul>
            {/* </div> */}
            </Navbar.Collapse>
         </Container>
         </Navbar>
        {/* <div className="container">
          <h1 className="mt-4">HELLO {localUname}</h1>
          <p>Welcome to ART GALLERY</p>
        </div> */}
        {!this.state.submit ? <Redirect to={`/`} /> : null}
        {this.state.logout ? (
          <SweetAlert
            warning
            showCancel
            confirmBtnText="Yes"
            confirmBtnBsStyle="danger"
            title="Are you sure?"
            onConfirm={this.onLogoutYes}
            onCancel={this.onLogout}
            focusCancelBtn
          ></SweetAlert>
        ) : (
          ""
        )}

    </div>
    );
}
}
export default Header;
</code>```
```<code>Error displayed in console:-
react-dom.development.js:11102

       Uncaught TypeError: Cannot set properties of null (setting 'isUserLoggedIn')
    at Header.onLogoutYes [as onConfirm] (Header.js:32:1)

Could not get the stack frames of error: TypeError: Cannot read properties of null (reading 'length')
    at G (index.js:1:1)
    at index.js:1:1
    at Array.map (<anonymous>)
    at index.js:1:1
    at c (index.js:1:1)
    at Generator._invoke (index.js:1:1)
    at Generator.next (index.js:1:1)
    at D (index.js:1:1)
    at i (index.js:1:1)
</code>```

Body:
while using navlinks in the component having logout logic, while running the app its functioning except the thing is that on click logout it is not redirecting the login page and on checking console i am getting the issue that  cannot read the properties null (reading length, how can i resolve it ?

Trying to logout the user instead its showing balnk page and on checking the console it says cannot read properties null in index.js .
on checking index.js from console i am unable to find the error it is mentioned that in array length the problem arises but i couldn't understand how to rectify it , kindly post a solution for this, thanks

import React from "react";
import { Redirect } from "react-router-dom";
import {Nav,Navbar,Container} from 'react-bootstrap'
import SweetAlert from "react-bootstrap-sweetalert";
import logo from'./Images/logo.jpeg'

const _ = require("lodash");

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      username: this.props.name,
      board: [],
      boardItem: "",
      toggle: false,
      submit: true,
      logout: false,
      loggedInUserObj: "",
    };
  }

  onLogoutYes = () => {
    this.setState({ submit: false });
    this.setState({ toggle: true });
    const userObj = JSON.parse(
      localStorage.getItem(_.get(this.state.loggedInUserObj, "userName", ""))
    );
    userObj.isUserLoggedIn = false;
    localStorage.setItem(
      _.get(this.state.loggedInUserObj, "userName", ""),
      JSON.stringify(userObj)
    );
  };

  onLogout = () => {
    this.setState({
      logout: !this.state.logout,
    });
  };

  componentDidMount() {
    const loggedInUserName = _.get(this.props.location, "state.userName", {});
    this.setState({
      loggedInUserObj: JSON.parse(localStorage.getItem(loggedInUserName)),
    });
  }

  render() {
    const localUname = `${_.get(
      this.state.loggedInUserObj,
      "firstName",
      ""
    )} ${_.get(this.state.loggedInUserObj, "lastName", "")}`;

    return (

ONLINE ART GALLERY

          <Navbar collapseOnSelect expand="lg" bg="dark" variant="dark">
      <Container>

        <Navbar.Brand href="" style={{fontWeight:"bold",fontFamily:"cursive"}}></Navbar.Brand>
            <Navbar.Toggle aria-controls="responsive-navbar-nav" />
        <Navbar.Collapse id="responsive-navbar-nav">
            Home
            About
            Products
            Profile
            Feedback
            Cart

            {/* <button
              // className="navbar-toggler"
              // type="button"
              // data-toggle="collapse"
              // data-target="#navbarResponsive"
              // aria-controls="navbarResponsive"
              // aria-expanded="false"
              // aria-label="Toggle navigation"
            >

            </button> */}
            {/*
 */}

                  <button
                    type="button"
                    className="btn btn-danger"
                    onClick={this.onLogout}
                  >
                    LOGOUT
                  </button>

            {/*
 */}
            </Navbar.Collapse>
         </Container>
         </Navbar>
        {/*

HELLO {localUname}

Welcome to ART GALLERY

 */}
        {!this.state.submit ? <Redirect to={`/`} /> : null}
        {this.state.logout ? (
          <SweetAlert
            warning
            showCancel
            confirmBtnText="Yes"
            confirmBtnBsStyle="danger"
            title="Are you sure?"
            onConfirm={this.onLogoutYes}
            onCancel={this.onLogout}
            focusCancelBtn
          ></SweetAlert>
        ) : (
          ""
        )}

    );
}
}
export default Header;

Error displayed in console:-
react-dom.development.js:11102

       Uncaught TypeError: Cannot set properties of null (setting 'isUserLoggedIn')
    at Header.onLogoutYes [as onConfirm] (Header.js:32:1)

Could not get the stack frames of error: TypeError: Cannot read properties of null (reading 'length')
    at G (index.js:1:1)
    at index.js:1:1
    at Array.map (<anonymous>)
    at index.js:1:1
    at c (index.js:1:1)
    at Generator._invoke (index.js:1:1)
    at Generator.next (index.js:1:1)
    at D (index.js:1:1)
    at i (index.js:1:1)


问:
ngx-bootstrap@0.0.1 being installed on angular version 14.2 project
To reproduce create a new angular project using Angular version 14.2, ng new ngxbootstrap. Then in project folder, ngxbootstrap, run ng add ngx-bootstrap.

When I perform the steps above, this is what I get.

Using package manager: npm
Found compatible package version: ngx-bootstrap@0.0.1.
Package information loaded.

The package ngx-bootstrap@0.0.1 will be installed and executed.
Would you like to proceed? (Y/n)

On the ngx-bootstrap compatibility page, it states that ngx-bootstrap 10.2 is compatible with Angular 14.x

Anyone know the best way to resolve?

I tried the steps mentioned above on a new Angular project. I expected ngx-bootstrap version 10 would be installed.

Below is my package.json.

```<code>{
  "name": "ngxbootstrap",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^14.2.0",
    "@angular/common": "^14.2.0",
    "@angular/compiler": "^14.2.0",
    "@angular/core": "^14.2.0",
    "@angular/forms": "^14.2.0",
    "@angular/platform-browser": "^14.2.0",
    "@angular/platform-browser-dynamic": "^14.2.0",
    "@angular/router": "^14.2.0",
    "rxjs": "~7.5.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^14.2.10",
    "@angular/cli": "~14.2.10",
    "@angular/compiler-cli": "^14.2.0",
    "@types/jasmine": "~4.0.0",
    "jasmine-core": "~4.3.0",
    "karma": "~6.4.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.2.0",
    "karma-jasmine": "~5.1.0",
    "karma-jasmine-html-reporter": "~2.0.0",
    "typescript": "~4.7.2"
  }
}
</code>```

Body:
To reproduce create a new angular project using Angular version 14.2, ng new ngxbootstrap. Then in project folder, ngxbootstrap, run ng add ngx-bootstrap.

When I perform the steps above, this is what I get.

Using package manager: npm
Found compatible package version: ngx-bootstrap@0.0.1.
Package information loaded.

The package ngx-bootstrap@0.0.1 will be installed and executed.
Would you like to proceed? (Y/n)

On the ngx-bootstrap compatibility page, it states that ngx-bootstrap 10.2 is compatible with Angular 14.x

Anyone know the best way to resolve?

I tried the steps mentioned above on a new Angular project. I expected ngx-bootstrap version 10 would be installed.

Below is my package.json.

{
  "name": "ngxbootstrap",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^14.2.0",
    "@angular/common": "^14.2.0",
    "@angular/compiler": "^14.2.0",
    "@angular/core": "^14.2.0",
    "@angular/forms": "^14.2.0",
    "@angular/platform-browser": "^14.2.0",
    "@angular/platform-browser-dynamic": "^14.2.0",
    "@angular/router": "^14.2.0",
    "rxjs": "~7.5.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^14.2.10",
    "@angular/cli": "~14.2.10",
    "@angular/compiler-cli": "^14.2.0",
    "@types/jasmine": "~4.0.0",
    "jasmine-core": "~4.3.0",
    "karma": "~6.4.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.2.0",
    "karma-jasmine": "~5.1.0",
    "karma-jasmine-html-reporter": "~2.0.0",
    "typescript": "~4.7.2"
  }
}


问:
Variable-base column bar graph
I am trying to get a variable-base column bar graph in Excel. Basically, with reference to the figure below, I have a number of periods. Each period can range from 1 to 5 months. So the various periods do not have the same length. Each period, however, has only one value associated with it that is representative of the entire period.

What I wish to achieve can be seen in the first figure (A), where two characteristics that the graph must have are also highlighted, namely, to consist of columns of varying width, as well as height, and to have the final month of the period placed in the center of the column and not at the bottom right.

I have tried several ways to get this graph with Excel, but all I have been able to get is visible in the second figure (B). Basically, I had to create a second, auxiliary, table by hand from the first, and then generate a normal column chart.

Clearly the result is different from what I wanted, although I came close.

Do you think it is possible, with Excel, to get exactly the chart I need without having to use a second table? Or, alternatively, do you think there are other programs, e.g., Holoviews (Python) to get the expected result?

Title: Variable-base column bar graph


问:
Can't store user_id into another table in flutter
I need to create a table that will add the user_id as another data in the table. But somehow my solution does not work.

The table user looks like this:

```<code>CREATE TABLE user(
      user_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
      username TEXT NOT NULL,
      password TEXT NOT NULL,
      f_name TEXT NOT NULL,
      l_name TEXT NOT NULL,
      email TEXT NOT NULL,
      phone INTEGER NOT NULL
    )
</code>```

After the login, the user have to fill in a form, the data goes to the table, flowerbook:

```<code>CREATE TABLE flowerbook(
      book_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
      deliver_date TEXT NOT NULL,
      arrangement TEXT NOT NULL,
      flower_type TEXT NOT NULL,
      user_id INTEGER NOT NULL
    )
</code>```

I tried doing this, on the submit button of the form:

```<code>onPressed: () {
                            Flowerbook flowerbook = Flowerbook(
                              deliver_date: dateController.text,
                              flower_type: checkboxController.text,
                              arrangement: dropdownController.text,
                              user_id: widget.user.user_id,
                            );

                            Flowerbook.register(flowerbook);

                          },
</code>```

But I still get this error:

[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: DatabaseException(NOT NULL constraint failed: flowerbook.user_id (code 1299 SQLITE_CONSTRAINT_NOTNULL)) sql 'INSERT OR REPLACE INTO flowerbook (book_id, deliver_date, arrangement, flower_type, user_id) VALUES (NULL, ?, ?, ?, NULL)' args [1/1/2023 12:00:00, Box, Carnation]

As you can see, the delivery_date, flower_type, and arrangement is successfully added as an argument. But user_id is NULL.

What seems to be the problem here?

I did log the widget.user.user_id, and it is indeed NULL.

Maybe there's something wrong at my menu page? Here's my code:

```<code>final List<Widget> _widgetOptions = <Widget>[
      FormPage(user: widget.user),
      OrderPage(user: widget.user),
      AccountPage(user: widget.user),
    ];
</code>```

Body:
I need to create a table that will add the user_id as another data in the table. But somehow my solution does not work.

The table user looks like this:

CREATE TABLE user(
      user_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
      username TEXT NOT NULL,
      password TEXT NOT NULL,
      f_name TEXT NOT NULL,
      l_name TEXT NOT NULL,
      email TEXT NOT NULL,
      phone INTEGER NOT NULL
    )

After the login, the user have to fill in a form, the data goes to the table, flowerbook:

CREATE TABLE flowerbook(
      book_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
      deliver_date TEXT NOT NULL,
      arrangement TEXT NOT NULL,
      flower_type TEXT NOT NULL,
      user_id INTEGER NOT NULL
    )

I tried doing this, on the submit button of the form:

onPressed: () {
                            Flowerbook flowerbook = Flowerbook(
                              deliver_date: dateController.text,
                              flower_type: checkboxController.text,
                              arrangement: dropdownController.text,
                              user_id: widget.user.user_id,
                            );

                            Flowerbook.register(flowerbook);

                          },

But I still get this error:

[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: DatabaseException(NOT NULL constraint failed: flowerbook.user_id (code 1299 SQLITE_CONSTRAINT_NOTNULL)) sql 'INSERT OR REPLACE INTO flowerbook (book_id, deliver_date, arrangement, flower_type, user_id) VALUES (NULL, ?, ?, ?, NULL)' args [1/1/2023 12:00:00, Box, Carnation]

As you can see, the delivery_date, flower_type, and arrangement is successfully added as an argument. But user_id is NULL.

What seems to be the problem here?

I did log the widget.user.user_id, and it is indeed NULL.

Maybe there's something wrong at my menu page? Here's my code:

final List<Widget> _widgetOptions = <Widget>[
      FormPage(user: widget.user),
      OrderPage(user: widget.user),
      AccountPage(user: widget.user),
    ];


问:
How to convert reddit posts to list in dart?
I want to get posts from Reddit API. Posts are in "children" node but each object has another object inside.

Can somebody help me write a function that convert this JSON to a list of dart objects?

Here is JSON string.

```<code>
{
    "kind": "Listing",
    "data": {
        "after": "t3_zzzhq4",
        "dist": 2,
        "children": [
            {
                "kind": "t3",
                "data": {

                    "selftext": "blablabla",
                    "author_fullname": "3xblabla",
                    "title": "moreblabla",
                    "created": 1672515982,
                    "id": "10020p0"
                }
            },
            {
                "kind": "t3",
                "data": {
                    "selftext": "blablabla",
                    "author_fullname": "3xblabla",
                    "title": "moreblabla",
                    "created": 1672515982,
                    "id": "10020p0"
                }
            }
        ],
        "before": null
    }
}

</code>```

I tried all the tutorials on the topic of complex json parsing, but none of them met my needs. I would know how to parse simple json, but here it is deeply nested JSON, which bothers me a lot, and i cant quite grasp it. Appreciete any help.

Solution:

First go to json to dart and paste JSON string, this generator will make you all classes needed for your JSON.

Then you will need to decode string:

final jsonResponse = json.decode(jsonString);

And then deserialize your JSON like this:

List postslist = list.map((i) => Post.fromJson(i['data'])).toList();

For me, it was crucial i['data']. After adding that, i could deserialize all objects that were living inside that node. Thanks everyone! Hope that someone else this will be helpful! Cheers.

Body:
I want to get posts from Reddit API. Posts are in "children" node but each object has another object inside.

Can somebody help me write a function that convert this JSON to a list of dart objects?

Here is JSON string.

{
    "kind": "Listing",
    "data": {
        "after": "t3_zzzhq4",
        "dist": 2,
        "children": [
            {
                "kind": "t3",
                "data": {

                    "selftext": "blablabla",
                    "author_fullname": "3xblabla",
                    "title": "moreblabla",
                    "created": 1672515982,
                    "id": "10020p0"
                }
            },
            {
                "kind": "t3",
                "data": {
                    "selftext": "blablabla",
                    "author_fullname": "3xblabla",
                    "title": "moreblabla",
                    "created": 1672515982,
                    "id": "10020p0"
                }
            }
        ],
        "before": null
    }
}

I tried all the tutorials on the topic of complex json parsing, but none of them met my needs. I would know how to parse simple json, but here it is deeply nested JSON, which bothers me a lot, and i cant quite grasp it. Appreciete any help.

Solution:

First go to json to dart and paste JSON string, this generator will make you all classes needed for your JSON.

Then you will need to decode string:

final jsonResponse = json.decode(jsonString);

And then deserialize your JSON like this:

List postslist = list.map((i) => Post.fromJson(i['data'])).toList();

For me, it was crucial i['data']. After adding that, i could deserialize all objects that were living inside that node. Thanks everyone! Hope that someone else this will be helpful! Cheers.


问:
Sphinx Results Take Huge Time To Show (Slow Index)
I'm new to Sphinx, i have simple table tbl_urls with two columns (domain_id,url)
i created my index as below to get domain id and number of urls for any giving keyword

```<code>source src2
{
  type                  = mysql
  sql_host              = 0.0.0.0
  sql_user              = spnx
  sql_pass              = 123
  sql_db                = db_spnx
  sql_port              = 3306 # optional, default is 3306
  sql_query             = select id,domain_id,url from tbl_domain_urls
  sql_attr_uint         = domain_id
  sql_field_string      = url
}
index url_tbl
{
    source   = src2
    path     =/var/lib/sphinx/data/url_tbl
}
indexer
{
    mem_limit               = 2047M
}
searchd
{
    listen                  = 0.0.0.0:9312
    listen                  = 0.0.0.0:9306:mysql41
    listen                  = /home/charlie/sphinx-3.4.1/bin/searchd.sock:sphinx
    log                     = /var/log/sphinx/sphinx.log
    query_log               = /var/log/sphinx/query.log
    read_timeout            = 5
    max_children            = 30
    pid_file                = /var/run/sphinx/sphinx.pid
    max_filter_values       = 20000
    seamless_rotate         = 1
    preopen_indexes         = 0
    unlink_old              = 1
    workers                 = threads # for RT indexes to work
    binlog_path             = /var/lib/sphinx/data
    max_batch_queries       = 128
}
</code>```

problem is the time taken to show results is over one min

```<code>
SELECT domain_id,count(*) as url_counter
FROM ul_tbl WHERE MATCH('games')
group by domain_id limit 1000000 OPTION max_matches=1000000;show meta;

+-----------+-------+
| domain_id | url   |
+-----------+-------+
|      9900 |   444 |
|     41309 |    48 |
|     62308 |   491 |
|     85798 |   401 |
|       595 |  4851 |

13545 rows in set (3 min 22.56 sec)

+---------------+--------+
| Variable_name | Value  |
+---------------+--------+
| total         | 13545  |
| total_found   | 13545  |
| time          | 1.406  |
| keyword[0]    | games  |
| docs[0]       | 456667 |
| hits[0]       | 514718 |
+---------------+--------+
</code>```

table tbl_domain_urls 100,821,614 rows

dedicated server HP Proliant 2xL5420 16GB RAM 2x1TB HDD

I need your support to optimize my QUERY or config settings, i need the results in the lowest time possible, i really appreciate any new idea to test

Note:
I tried distributed index to use multiple core for processing without any noticable results

Body:
I'm new to Sphinx, i have simple table tbl_urls with two columns (domain_id,url)
i created my index as below to get domain id and number of urls for any giving keyword

source src2
{
  type                  = mysql
  sql_host              = 0.0.0.0
  sql_user              = spnx
  sql_pass              = 123
  sql_db                = db_spnx
  sql_port              = 3306 # optional, default is 3306
  sql_query             = select id,domain_id,url from tbl_domain_urls
  sql_attr_uint         = domain_id
  sql_field_string      = url
}
index url_tbl
{
    source   = src2
    path     =/var/lib/sphinx/data/url_tbl
}
indexer
{
    mem_limit               = 2047M
}
searchd
{
    listen                  = 0.0.0.0:9312
    listen                  = 0.0.0.0:9306:mysql41
    listen                  = /home/charlie/sphinx-3.4.1/bin/searchd.sock:sphinx
    log                     = /var/log/sphinx/sphinx.log
    query_log               = /var/log/sphinx/query.log
    read_timeout            = 5
    max_children            = 30
    pid_file                = /var/run/sphinx/sphinx.pid
    max_filter_values       = 20000
    seamless_rotate         = 1
    preopen_indexes         = 0
    unlink_old              = 1
    workers                 = threads # for RT indexes to work
    binlog_path             = /var/lib/sphinx/data
    max_batch_queries       = 128
}

problem is the time taken to show results is over one min

SELECT domain_id,count(*) as url_counter
FROM ul_tbl WHERE MATCH('games')
group by domain_id limit 1000000 OPTION max_matches=1000000;show meta;

+-----------+-------+
| domain_id | url   |
+-----------+-------+
|      9900 |   444 |
|     41309 |    48 |
|     62308 |   491 |
|     85798 |   401 |
|       595 |  4851 |

13545 rows in set (3 min 22.56 sec)

+---------------+--------+
| Variable_name | Value  |
+---------------+--------+
| total         | 13545  |
| total_found   | 13545  |
| time          | 1.406  |
| keyword[0]    | games  |
| docs[0]       | 456667 |
| hits[0]       | 514718 |
+---------------+--------+

table tbl_domain_urls 100,821,614 rows

dedicated server HP Proliant 2xL5420 16GB RAM 2x1TB HDD

I need your support to optimize my QUERY or config settings, i need the results in the lowest time possible, i really appreciate any new idea to test

Note:
I tried distributed index to use multiple core for processing without any noticable results


问:
Trigonometry Functions in GBDK?
There is probably a rather elegant solution to this, but for the life of me I am unable to find any form of trig functions in gbdk – with the "math.h" library not included (probably missing something). Any help would be greatly appreciated.

I've tried including the standard "math.h" library (not included) and wasn't able to find any documentation from their website

Title: Trigonometry Functions in GBDK?


问:
How to replace an LSTM with BERT in a PyTorch classification model

Context

I have an LSTM model with pre-trained word embeddings for a multiclass classification problem with 10 output classes.

```<code># LSTM model
hidden_dim = 64
n_layers=1
embed_len = 100

class LSTMClassifier(nn.Module):
    def __init__(self, embeddings, n_layers):
        super(LSTMClassifier, self).__init__()

        #self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

        self.n_layers = n_layers
        self.weights = torch.FloatTensor(embeddings)
        self.embedding_layer = nn.Embedding.from_pretrained(self.weights)
        self.lstm = nn.LSTM(input_size=embed_len, hidden_size=hidden_dim,
                            num_layers=self.n_layers, batch_first=True)
        self.linear = nn.Linear(hidden_dim, 10)

        self.activation = nn.Tanh()
        self.dropout = nn.Dropout(0.4)

    def forward(self, X_batch):
        embeddings = self.embedding_layer(X_batch)
        embeddings = self.dropout(embeddings)

        output, (hidden, cell) = self.lstm(embeddings, (torch.randn(self.n_layers, len(X_batch), hidden_dim),
                                                        torch.randn(self.n_layers, len(X_batch), hidden_dim)))

        output = self.activation(output)
        output = self.dropout(output)

        return self.linear(output[:,-1])

</code>```

Problem

Now I would like to change the LSTM layer to BERT. I tried it the following way, but when I try to train the BERT model, I get a value error ValueError: too many values to unpack (expected 2). This probably means that the input shape of the embeddings for self.bert(embeddings) pass is not of the right shape. The embeddings that are passed to self.bert() have the shape torch.Size([256, 64, 100]). What do I need to change so that my BERT model works?

```<code>class BERTClassifier(nn.Module):
    def __init__(self, embeddings):
        super(BERTClassifier, self).__init__()

        # Load the BERT model
        self.bert = BertModel.from_pretrained('bert-base-uncased')

        # Embeddings
        self.weights = torch.FloatTensor(embeddings)
        self.embedding_layer = nn.Embedding.from_pretrained(self.weights)

        # Final layer for classifcation
        self.linear = nn.Linear(self.bert.config.hidden_size, 10)

        self.dropout = nn.Dropout(0.4)

    def forward(self, X_batch):
      device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
      X_batch = X_batch.to(device)

      embeddings = self.embedding_layer(X_batch)

      output, (hidden, cell) = self.bert(embeddings)

      hidden = self.dropout(hidden[:, 0, :])

      logits = self.linear(hidden)

      return logits
</code>```

Training lines

```<code>epochs = 50
learning_rate = 1e-4

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
bert_classifier = BERTClassifier(word_embeddings_with_stopwords)
bert_classifier = bert_classifier.to(device)

# Freeze the BERT layer
for param in bert_classifier.bert.parameters():
    param.requires_grad = False

# Freeze the embedding layer
for param in bert_classifier.embedding_layer.parameters():
    param.requires_grad = False

loss_fn = nn.CrossEntropyLoss()
optimizer = Adam(bert_classifier.parameters(), lr=learning_rate, weight_decay=1e-5)

results_bert_classifier = train_model(bert_classifier, loss_fn, optimizer, train_loader_with_stopwords, val_loader_with_stopwords, epochs)
</code>```

Training functions

```<code># Create validation evaluation function
def calc_val_loss_accuracy(model, loss_fn, val_loader, val_losses_list, val_accuracy_list):
  """
  Calculates the validation loss and accuracy during training.
  Adds the calculated validation loss and accuracy to a predefined list.
  """

  model.eval()

  with torch.no_grad():

      Y_shuffled = []
      Y_preds = []
      losses = []

      for X, Y in val_loader:

          preds = model(X)
          loss = loss_fn(preds, Y)
          losses.append(loss.item())

          Y_shuffled.append(Y)
          Y_preds.append(preds.argmax(dim=-1))

      Y_shuffled = torch.cat(Y_shuffled)
      Y_preds = torch.cat(Y_preds)
      val_accuracy = accuracy_score(Y_shuffled.detach().numpy(), Y_preds.detach().numpy())

      print("Valid Loss : {:.3f}".format(torch.tensor(losses).mean()))
      print("Valid Acc  : {:.3f}".format(val_accuracy))

      val_losses_list.append(np.array(losses).mean())
      val_accuracy_list.append(val_accuracy)

# Create training function
def train_model(model, loss_fn, optimizer, train_loader, val_loader, epochs=10):
  """
  Trains a model for a given set of epochs, with a given loss function and optimizer.
  Returns a dictionary consisting of the train loss and accuracy per epoch
  and val loss and accuracy per epoch.
  """

  model.train()

  train_losses = []
  train_accuracy = []
  val_losses = []
  val_accuracy = []
  Y_shuffled_list = []
  Y_preds_list = []

  for i in range(1, epochs+1):
    print(f"EPOCH {i}")
    losses = []
    for X, Y in tqdm(train_loader):

      preds = model(X)

      loss = loss_fn(preds, Y)
      losses.append(loss.item())

      Y_shuffled_list.append(Y)
      Y_preds_list.append(preds.argmax(dim=-1))

      optimizer.zero_grad()
      loss.backward()
      optimizer.step()

    Y_shuffled = torch.cat(Y_shuffled_list)
    Y_preds = torch.cat(Y_preds_list)
    train_accuracy_score = accuracy_score(Y_shuffled.detach().numpy(), Y_preds.detach().numpy())

    print("Train Loss : {:.3f}".format(torch.tensor(losses).mean()))
    print("Train Acc  : {:.3f}".format(train_accuracy_score))
    calc_val_loss_accuracy(model, loss_fn, val_loader, val_losses, val_accuracy)

    # Save training history
    train_losses.append(np.array(losses).mean())
    train_accuracy.append(train_accuracy_score)

  # Create results
  results = {'train_loss': train_losses,
              'train_acc': train_accuracy,
              'val_loss': val_losses,
              'val_acc': val_accuracy}

  return results
</code>```

Full Traceback

```<code>---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-113-c162e15ac6eb> in <module>
     17 optimizer = Adam(bert_classifier.parameters(), lr=learning_rate, weight_decay=1e-5)
     18
---> 19 results_bert_classifier = train_model(bert_classifier, loss_fn, optimizer, train_loader_with_stopwords, val_loader_with_stopwords, epochs)

4 frames
<ipython-input-76-af9148b7ec20> in train_model(model, loss_fn, optimizer, train_loader, val_loader, epochs)
     21     for X, Y in tqdm(train_loader):
     22
---> 23       preds = model(X)
     24
     25       loss = loss_fn(preds, Y)

/usr/local/lib/python3.8/dist-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
   1188         if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
   1189                 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1190             return forward_call(*input, **kwargs)
   1191         # Do not call functions when jit is used
   1192         full_backward_hooks, non_full_backward_hooks = [], []

<ipython-input-112-cbe2b66bfaf1> in forward(self, X_batch)
     25       embeddings = embeddings.reshape(batch_size, sequence_length, hidden_size)
     26
---> 27       output, hidden = self.bert(embeddings)
     28
     29       hidden = self.dropout(hidden[:, 0, :])

/usr/local/lib/python3.8/dist-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
   1188         if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
   1189                 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1190             return forward_call(*input, **kwargs)
   1191         # Do not call functions when jit is used
   1192         full_backward_hooks, non_full_backward_hooks = [], []

/usr/local/lib/python3.8/dist-packages/transformers/models/bert/modeling_bert.py in forward(self, input_ids, attention_mask, token_type_ids, position_ids, head_mask, inputs_embeds, encoder_hidden_states, encoder_attention_mask, past_key_values, use_cache, output_attentions, output_hidden_states, return_dict)
    973             raise ValueError("You have to specify either input_ids or inputs_embeds")
    974
--> 975         batch_size, seq_length = input_shape
    976         device = input_ids.device if input_ids is not None else inputs_embeds.device
    977

ValueError: too many values to unpack (expected 2)
</code>```

Body:
Context

I have an LSTM model with pre-trained word embeddings for a multiclass classification problem with 10 output classes.

# LSTM model
hidden_dim = 64
n_layers=1
embed_len = 100

class LSTMClassifier(nn.Module):
    def __init__(self, embeddings, n_layers):
        super(LSTMClassifier, self).__init__()

        #self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

        self.n_layers = n_layers
        self.weights = torch.FloatTensor(embeddings)
        self.embedding_layer = nn.Embedding.from_pretrained(self.weights)
        self.lstm = nn.LSTM(input_size=embed_len, hidden_size=hidden_dim,
                            num_layers=self.n_layers, batch_first=True)
        self.linear = nn.Linear(hidden_dim, 10)

        self.activation = nn.Tanh()
        self.dropout = nn.Dropout(0.4)

    def forward(self, X_batch):
        embeddings = self.embedding_layer(X_batch)
        embeddings = self.dropout(embeddings)

        output, (hidden, cell) = self.lstm(embeddings, (torch.randn(self.n_layers, len(X_batch), hidden_dim),
                                                        torch.randn(self.n_layers, len(X_batch), hidden_dim)))

        output = self.activation(output)
        output = self.dropout(output)

        return self.linear(output[:,-1])

Problem

Now I would like to change the LSTM layer to BERT. I tried it the following way, but when I try to train the BERT model, I get a value error ValueError: too many values to unpack (expected 2). This probably means that the input shape of the embeddings for self.bert(embeddings) pass is not of the right shape. The embeddings that are passed to self.bert() have the shape torch.Size([256, 64, 100]). What do I need to change so that my BERT model works?

class BERTClassifier(nn.Module):
    def __init__(self, embeddings):
        super(BERTClassifier, self).__init__()

        # Load the BERT model
        self.bert = BertModel.from_pretrained('bert-base-uncased')

        # Embeddings
        self.weights = torch.FloatTensor(embeddings)
        self.embedding_layer = nn.Embedding.from_pretrained(self.weights)

        # Final layer for classifcation
        self.linear = nn.Linear(self.bert.config.hidden_size, 10)

        self.dropout = nn.Dropout(0.4)

    def forward(self, X_batch):
      device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
      X_batch = X_batch.to(device)

      embeddings = self.embedding_layer(X_batch)

      output, (hidden, cell) = self.bert(embeddings)

      hidden = self.dropout(hidden[:, 0, :])

      logits = self.linear(hidden)

      return logits

Training lines

epochs = 50
learning_rate = 1e-4

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
bert_classifier = BERTClassifier(word_embeddings_with_stopwords)
bert_classifier = bert_classifier.to(device)

# Freeze the BERT layer
for param in bert_classifier.bert.parameters():
    param.requires_grad = False

# Freeze the embedding layer
for param in bert_classifier.embedding_layer.parameters():
    param.requires_grad = False

loss_fn = nn.CrossEntropyLoss()
optimizer = Adam(bert_classifier.parameters(), lr=learning_rate, weight_decay=1e-5)

results_bert_classifier = train_model(bert_classifier, loss_fn, optimizer, train_loader_with_stopwords, val_loader_with_stopwords, epochs)

Training functions

# Create validation evaluation function
def calc_val_loss_accuracy(model, loss_fn, val_loader, val_losses_list, val_accuracy_list):
  """
  Calculates the validation loss and accuracy during training.
  Adds the calculated validation loss and accuracy to a predefined list.
  """

  model.eval()

  with torch.no_grad():

      Y_shuffled = []
      Y_preds = []
      losses = []

      for X, Y in val_loader:

          preds = model(X)
          loss = loss_fn(preds, Y)
          losses.append(loss.item())

          Y_shuffled.append(Y)
          Y_preds.append(preds.argmax(dim=-1))

      Y_shuffled = torch.cat(Y_shuffled)
      Y_preds = torch.cat(Y_preds)
      val_accuracy = accuracy_score(Y_shuffled.detach().numpy(), Y_preds.detach().numpy())

      print("Valid Loss : {:.3f}".format(torch.tensor(losses).mean()))
      print("Valid Acc  : {:.3f}".format(val_accuracy))

      val_losses_list.append(np.array(losses).mean())
      val_accuracy_list.append(val_accuracy)

# Create training function
def train_model(model, loss_fn, optimizer, train_loader, val_loader, epochs=10):
  """
  Trains a model for a given set of epochs, with a given loss function and optimizer.
  Returns a dictionary consisting of the train loss and accuracy per epoch
  and val loss and accuracy per epoch.
  """

  model.train()

  train_losses = []
  train_accuracy = []
  val_losses = []
  val_accuracy = []
  Y_shuffled_list = []
  Y_preds_list = []

  for i in range(1, epochs+1):
    print(f"EPOCH {i}")
    losses = []
    for X, Y in tqdm(train_loader):

      preds = model(X)

      loss = loss_fn(preds, Y)
      losses.append(loss.item())

      Y_shuffled_list.append(Y)
      Y_preds_list.append(preds.argmax(dim=-1))

      optimizer.zero_grad()
      loss.backward()
      optimizer.step()

    Y_shuffled = torch.cat(Y_shuffled_list)
    Y_preds = torch.cat(Y_preds_list)
    train_accuracy_score = accuracy_score(Y_shuffled.detach().numpy(), Y_preds.detach().numpy())

    print("Train Loss : {:.3f}".format(torch.tensor(losses).mean()))
    print("Train Acc  : {:.3f}".format(train_accuracy_score))
    calc_val_loss_accuracy(model, loss_fn, val_loader, val_losses, val_accuracy)

    # Save training history
    train_losses.append(np.array(losses).mean())
    train_accuracy.append(train_accuracy_score)

  # Create results
  results = {'train_loss': train_losses,
              'train_acc': train_accuracy,
              'val_loss': val_losses,
              'val_acc': val_accuracy}

  return results

Full Traceback

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-113-c162e15ac6eb> in <module>
     17 optimizer = Adam(bert_classifier.parameters(), lr=learning_rate, weight_decay=1e-5)
     18
---> 19 results_bert_classifier = train_model(bert_classifier, loss_fn, optimizer, train_loader_with_stopwords, val_loader_with_stopwords, epochs)

4 frames
<ipython-input-76-af9148b7ec20> in train_model(model, loss_fn, optimizer, train_loader, val_loader, epochs)
     21     for X, Y in tqdm(train_loader):
     22
---> 23       preds = model(X)
     24
     25       loss = loss_fn(preds, Y)

/usr/local/lib/python3.8/dist-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
   1188         if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
   1189                 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1190             return forward_call(*input, **kwargs)
   1191         # Do not call functions when jit is used
   1192         full_backward_hooks, non_full_backward_hooks = [], []

<ipython-input-112-cbe2b66bfaf1> in forward(self, X_batch)
     25       embeddings = embeddings.reshape(batch_size, sequence_length, hidden_size)
     26
---> 27       output, hidden = self.bert(embeddings)
     28
     29       hidden = self.dropout(hidden[:, 0, :])

/usr/local/lib/python3.8/dist-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
   1188         if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
   1189                 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1190             return forward_call(*input, **kwargs)
   1191         # Do not call functions when jit is used
   1192         full_backward_hooks, non_full_backward_hooks = [], []

/usr/local/lib/python3.8/dist-packages/transformers/models/bert/modeling_bert.py in forward(self, input_ids, attention_mask, token_type_ids, position_ids, head_mask, inputs_embeds, encoder_hidden_states, encoder_attention_mask, past_key_values, use_cache, output_attentions, output_hidden_states, return_dict)
    973             raise ValueError("You have to specify either input_ids or inputs_embeds")
    974
--> 975         batch_size, seq_length = input_shape
    976         device = input_ids.device if input_ids is not None else inputs_embeds.device
    977

ValueError: too many values to unpack (expected 2)


问:
How do I serach in laravel Eloquent relationships?
I have a function that returns data as required. When I add a search string so that I can filter the results, no filtering is done.
Function

```<code>  public function getComboSubItemRequirements(Request $request, $comboId){

$search_string = $request->query('search_string');
$search_string = empty($search_string)
  ? null
  : trim(urldecode($search_string));

$combo = ComboSellable::where('id', $comboId)
  ->with('sellable')
  ->with('items')
  ->first();
$sellable_id = $combo->sellable->sellable_id;
$sellables = Sellable::thisMerchant()
  ->with('sellable')
  ->where('sellable_type', '<>', Sellable::COMBO)
  ->when(!empty($sellable_id) && !is_numeric($sellable_id), function ($q) use($search_string){
    $q->whereHasMorph(
      'sellable',
      [Sellable::SERVICE, Sellable::PRODUCT],
      function ($qq) use ($search_string){
        return $qq->where('sellable.name', 'like', "%{$search_string}%");
      }
    );
  })
  ->whereNotIn('id', $combo->items->pluck('sellable_id')->toArray())
  ->limit(10)
  ->get();
return response()->json($sellables);
 }
}
</code>```

Result structure

```<code>[
{
    "id": 3,
    "merchant_id": 2,
    "sellable_id": 3,
    "sellable_type": "App\\Product",
    "created_at": null,
    "updated_at": null,
    "deleted_at": null,
    "sellable": {
        "id": 3,
        "merchant_id": "2",
        "name": "Wash and set weave",
        "description": "",
        "cost": "1000",
        "image": null,
        "duration": "60",
        "remainder_days": null,
        "created_at": "2020-12-02T06:59:24.000000Z",
        "updated_at": "2021-06-19T16:03:30.000000Z",
        "commission": null,
        "deleted_at": null,
        "can_be_sold": 1,
        "tax_id": null,
        "tax_method": null
    }
},
{
    "id": 4,
    "merchant_id": 2,
    "sellable_id": 4,
    "sellable_type": "App\\Product",
    "created_at": null,
    "updated_at": null,
    "deleted_at": null,
    "sellable": {
        "id": 4,
        "merchant_id": "2",
        "name": "Wash andset tracks",
        "description": "",
        "cost": "800",
        "image": null,
        "duration": "75",
        "remainder_days": null,
        "created_at": "2020-12-02T06:59:53.000000Z",
        "updated_at": "2021-08-21T02:47:18.000000Z",
        "commission": null,
        "deleted_at": null,
        "can_be_sold": 1,
        "tax_id": null,
        "tax_method": null
    }
}
]
</code>```

I want to search items based on sellable->name. I have added the sellable table to the query but the results are still the same. No search or filtering is done.
How do I filter in such a case?

Body:
I have a function that returns data as required. When I add a search string so that I can filter the results, no filtering is done.
Function

  public function getComboSubItemRequirements(Request $request, $comboId){

$search_string = $request->query('search_string');
$search_string = empty($search_string)
  ? null
  : trim(urldecode($search_string));

$combo = ComboSellable::where('id', $comboId)
  ->with('sellable')
  ->with('items')
  ->first();
$sellable_id = $combo->sellable->sellable_id;
$sellables = Sellable::thisMerchant()
  ->with('sellable')
  ->where('sellable_type', '<>', Sellable::COMBO)
  ->when(!empty($sellable_id) && !is_numeric($sellable_id), function ($q) use($search_string){
    $q->whereHasMorph(
      'sellable',
      [Sellable::SERVICE, Sellable::PRODUCT],
      function ($qq) use ($search_string){
        return $qq->where('sellable.name', 'like', "%{$search_string}%");
      }
    );
  })
  ->whereNotIn('id', $combo->items->pluck('sellable_id')->toArray())
  ->limit(10)
  ->get();
return response()->json($sellables);
 }
}

Result structure

[
{
    "id": 3,
    "merchant_id": 2,
    "sellable_id": 3,
    "sellable_type": "App\\Product",
    "created_at": null,
    "updated_at": null,
    "deleted_at": null,
    "sellable": {
        "id": 3,
        "merchant_id": "2",
        "name": "Wash and set weave",
        "description": "",
        "cost": "1000",
        "image": null,
        "duration": "60",
        "remainder_days": null,
        "created_at": "2020-12-02T06:59:24.000000Z",
        "updated_at": "2021-06-19T16:03:30.000000Z",
        "commission": null,
        "deleted_at": null,
        "can_be_sold": 1,
        "tax_id": null,
        "tax_method": null
    }
},
{
    "id": 4,
    "merchant_id": 2,
    "sellable_id": 4,
    "sellable_type": "App\\Product",
    "created_at": null,
    "updated_at": null,
    "deleted_at": null,
    "sellable": {
        "id": 4,
        "merchant_id": "2",
        "name": "Wash andset tracks",
        "description": "",
        "cost": "800",
        "image": null,
        "duration": "75",
        "remainder_days": null,
        "created_at": "2020-12-02T06:59:53.000000Z",
        "updated_at": "2021-08-21T02:47:18.000000Z",
        "commission": null,
        "deleted_at": null,
        "can_be_sold": 1,
        "tax_id": null,
        "tax_method": null
    }
}
]

I want to search items based on sellable->name. I have added the sellable table to the query but the results are still the same. No search or filtering is done.
How do I filter in such a case?


问:
Change in data type from bigint to double while renaming in pandas
I am new to Python Pandas. I am having data input in the below form.

```<code>Name,Empid,2020_salary,2021_salary,2022_salary
Adam,21223,58000,60000,62000
John,21534,67465,70985,90857
Terry,35463,76000,86765,97886
</code>```

As you observe in the year I am getting an underscore salary(ex 2020_salary) along with the year. But I want the data in the below form

```<code>    Name,Empid,2020,2021,2022
    Adam,21223,58000,60000,62000
    John,21534,67465,70985,90857
    Terry,35463,76000,86765,97886
</code>```

Since the table structure is not consistent(New Year will add in the future). That's why I cannot manually rename each column. I used pandas to rename all columns having salary text in the column.

```<code>df.rename(columns= lambda x: x.replace('_salary',''),inplace=True)
</code>```

Now I got the column structure the way I wanted. But now my data type has been changed from int to
double for some columns.

```<code>        Name,Empid,2020,2021,2022
        Adam,21223,58000.0,60000,62000
        John,21534,67465.0,70985,90857
        Terry,35463,76000.0,86765,97886
</code>```

I am getting output similar to the above. Can you please help me how to convert the above double data type to int without manually changing anything or some better way to rename the year's column?  Thanks in advance

Body:
I am new to Python Pandas. I am having data input in the below form.

Name,Empid,2020_salary,2021_salary,2022_salary
Adam,21223,58000,60000,62000
John,21534,67465,70985,90857
Terry,35463,76000,86765,97886

As you observe in the year I am getting an underscore salary(ex 2020_salary) along with the year. But I want the data in the below form

    Name,Empid,2020,2021,2022
    Adam,21223,58000,60000,62000
    John,21534,67465,70985,90857
    Terry,35463,76000,86765,97886

Since the table structure is not consistent(New Year will add in the future). That's why I cannot manually rename each column. I used pandas to rename all columns having salary text in the column.

df.rename(columns= lambda x: x.replace('_salary',''),inplace=True)

Now I got the column structure the way I wanted. But now my data type has been changed from int to
double for some columns.

        Name,Empid,2020,2021,2022
        Adam,21223,58000.0,60000,62000
        John,21534,67465.0,70985,90857
        Terry,35463,76000.0,86765,97886

I am getting output similar to the above. Can you please help me how to convert the above double data type to int without manually changing anything or some better way to rename the year's column?  Thanks in advance


问:
Android: difference between import my library from github, or directly as dependency
I have a library, for other users, I also have an app, that use this library.
I have two options to use the library on my code:

on my build.gradle add it as dependency - implementation(project(":..."))

download it from github as library - the same way other user will use it. for example:   implementation 'androidx.appcompat:appcompat:1.5.1'

The only different that i'm thinking about is that on the first options, my development will be against my dev code and on the second option production code.

I'm trying to figure out if there is any more consequences


问:
Is there a programm accessible relation between click-, mousedown- and pointerdown-events in Javascript?
Using pointer-events rather then mouse, touch or click events more often, I run into a situation where I would like to tell the browser, "hey, I am using pointer-events on this HTMLElement, forget about mouse, click or touch events (in particular any device defaults)".

In particular stopPropagation() or preventDefault() called from a pointer-event handler have no influence on the other types of events that may be generated from the same user action.

Is there anything similar to, say, stopPropagation() to tell the browser not to derive further events from a user interaction that was handled already in my pointer-down event?

There are a few specific questions in this direction like this one, but I couldn't find a definitive answer like "there is no relation" (what I am afraid will be the answer finally :-/ ).


问:
Google Cloud Database third-party connection with Python
I have created a database on Google Cloud with a google account A and am trying to access this database from another google account B using the Python API.

First, I have created a user (DB_USER/DB_PASSWORD) that has access to the database.

Then I wrote this code:

```<code>INSTANCE_CONNECTION_NAME = "xxxxxxx:us-central1:xxxxxx"
DB_USER ="thirdpartyuser"
DB_PASS ="xxxxxxxxxx"
DB_NAME ="postgres"

connector = Connector()

def getconn():
    conn = connector.connect(
        INSTANCE_CONNECTION_NAME,
        "pg8000",
        user = DB_USER,
        password = DB_PASS,
        db = DB_NAME
    )
    return conn

pool = sqlalchemy.create_engine(
    "postgresql+pg8000://",
    creator=getconn,
)

# connect to connection pool
with pool.connect() as db_conn:
  results = db_conn.execute("SELECT * FROM ratings").fetchall()
  for row in results:
    print(row)
</code>```

But I keep getting the same error:

```<code>raise exceptions.DefaultCredentialsError(_HELP_MESSAGE)
google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see https://cloud.google.com/docs/authentication/getting-started
</code>```

I understand that I need to authentificate before sending a request but I do not understand how ? How can I authentificate my google account B ? Where can I have the required json credentials file ? What is the best way to do it ?

Altought it sounds like an easy problem, I could not find a solution since 5 days. Any help is welcome!

Body:
I have created a database on Google Cloud with a google account A and am trying to access this database from another google account B using the Python API.

First, I have created a user (DB_USER/DB_PASSWORD) that has access to the database.

Then I wrote this code:

INSTANCE_CONNECTION_NAME = "xxxxxxx:us-central1:xxxxxx"
DB_USER ="thirdpartyuser"
DB_PASS ="xxxxxxxxxx"
DB_NAME ="postgres"

connector = Connector()

def getconn():
    conn = connector.connect(
        INSTANCE_CONNECTION_NAME,
        "pg8000",
        user = DB_USER,
        password = DB_PASS,
        db = DB_NAME
    )
    return conn

pool = sqlalchemy.create_engine(
    "postgresql+pg8000://",
    creator=getconn,
)

# connect to connection pool
with pool.connect() as db_conn:
  results = db_conn.execute("SELECT * FROM ratings").fetchall()
  for row in results:
    print(row)

But I keep getting the same error:

raise exceptions.DefaultCredentialsError(_HELP_MESSAGE)
google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application. For more information, please see https://cloud.google.com/docs/authentication/getting-started

I understand that I need to authentificate before sending a request but I do not understand how ? How can I authentificate my google account B ? Where can I have the required json credentials file ? What is the best way to do it ?

Altought it sounds like an easy problem, I could not find a solution since 5 days. Any help is welcome!


问:
Failed to install any R packages in my conda virtual environment
I got my new computer (Mac Pro M1) lately but I am not quite familiar with the MacOS system...

I enjoy using VSCode so I configured it with R language. I created an virtual environment with commands:

```<code>conda create -n R python=3.8
conda activate R
conda install -c conda-forge r-base=4.1.2
conda install -c conda-forge r-languageserver
</code>```

and configured everything following this website. Everything goes fine when I run R language except for installing R packages. Here is a screenshot of my problem.

I can only install packages on R.app:

Can anyone help me? Thanks so much in advance!!!

I really want to get everything ready for coding in R language with VSCode!!! How to solve it? It seems not a problem of permission?

Updated infomation here:

Below are some screenshots showing what are in my R conda environment:

Also, the paths of R and Radian are added to settings of VSCode:

Body:
I got my new computer (Mac Pro M1) lately but I am not quite familiar with the MacOS system...

I enjoy using VSCode so I configured it with R language. I created an virtual environment with commands:

conda create -n R python=3.8
conda activate R
conda install -c conda-forge r-base=4.1.2
conda install -c conda-forge r-languageserver

and configured everything following this website. Everything goes fine when I run R language except for installing R packages. Here is a screenshot of my problem.

I can only install packages on R.app:

Can anyone help me? Thanks so much in advance!!!

I really want to get everything ready for coding in R language with VSCode!!! How to solve it? It seems not a problem of permission?

Updated infomation here:

Below are some screenshots showing what are in my R conda environment:

Also, the paths of R and Radian are added to settings of VSCode:


问:
Next JS: SSG Pageprops not change in production but work in dev
So i had Container Component that pass props to the meta

export default function Container({ children, ...customMeta }) {
  const [mounted, setMounted] = useState(false);
  const { resolvedTheme, setTheme } = useTheme();

  // After mounting, we have access to the theme
  useEffect(() => setMounted(true), []);

  // const { children, ...customMeta } = props;
  const router = useRouter();
  const meta = {
    title: 'title',
    description: `description`,
    image: '',
    type: 'website',
    ...customMeta
  };

  return (

        <title>{meta.title}</title>
        <meta name="robots" content="follow, index" />
        <meta content={meta.description} name="description" />

.....
```

On development, the title showed up, but on production it didn't. It just showed the url.

I had tried to remove all fetch error but it still not work. Any help?

Body:
So i had Container Component that pass props to the meta

export default function Container({ children, ...customMeta }) {
  const [mounted, setMounted] = useState(false);
  const { resolvedTheme, setTheme } = useTheme();

  // After mounting, we have access to the theme
  useEffect(() => setMounted(true), []);

  // const { children, ...customMeta } = props;
  const router = useRouter();
  const meta = {
    title: 'title',
    description: `description`,
    image: '',
    type: 'website',
    ...customMeta
  };

  return (

        <title>{meta.title}</title>
        <meta name="robots" content="follow, index" />
        <meta content={meta.description} name="description" />

.....

On development, the title showed up, but on production it didn't. It just showed the url.

I had tried to remove all fetch error but it still not work. Any help?


问:
words hyperlink in a wordcloud
i am trying to develop a hyperlink worcloud. MWE is given below, any hint please.

```<code>link = {'Python':'https://www.python.org/',
        'R':'https://cran.r-project.org/bin/windows/base/',
        'php':'https://www.php.net/downloads.php',
        'java':'https://www.java.com/download/ie_manual.jsp',
        'C++':'https://sourceforge.net/projects/orwelldevcpp/'
        }
freq = {'Python':30,
       'R': 17,
       'php':15,
       'java':13,
       'C++':10
       }

wordcloud = WordCloud(colormap='tab10').generate_from_frequencies(freq)
#display
plt.figure(figsize=(8,8))
plt.imshow(wordcloud)
plt.axis('off')
</code>```

Title: words hyperlink in a wordcloud

Body:
i am trying to develop a hyperlink worcloud. MWE is given below, any hint please.

link = {'Python':'https://www.python.org/',
        'R':'https://cran.r-project.org/bin/windows/base/',
        'php':'https://www.php.net/downloads.php',
        'java':'https://www.java.com/download/ie_manual.jsp',
        'C++':'https://sourceforge.net/projects/orwelldevcpp/'
        }
freq = {'Python':30,
       'R': 17,
       'php':15,
       'java':13,
       'C++':10
       }

wordcloud = WordCloud(colormap='tab10').generate_from_frequencies(freq)
#display
plt.figure(figsize=(8,8))
plt.imshow(wordcloud)
plt.axis('off')


问:
Making a comments system in rarebit
I recently started a webcomic using rarebit. However, I want to add a comments system. The problem with this is that each strip does not have its own page, but the data from that strip is pulled using a js script on index.html. (works out what comic it is supposed to be showing, gets the data for it and then displays it using more functions. I guess the way to do it would be to store the comments in the pages data, which looks like this:

```<code>`{

pgNum: 2,

title: "title",

date: writeDate([YEAR],[MONTH],[DAY]),

altText: "alt text",

imageFiles: "no. of image files in that strip",

authorNotes: \`
    <p>notes go here>/p>
    `

},`
</code>```

I guess I would store comments here, but have no idea how to do it(don't know js). Thank you for any help!

Link to webcomic for reference: https://ahumanibelieve.github.io/

I thought having normal comment code would work, but then I realised that since every strip is in one html file, it wouldn't work

Title: Making a comments system in rarebit

Body:
I recently started a webcomic using rarebit. However, I want to add a comments system. The problem with this is that each strip does not have its own page, but the data from that strip is pulled using a js script on index.html. (works out what comic it is supposed to be showing, gets the data for it and then displays it using more functions. I guess the way to do it would be to store the comments in the pages data, which looks like this:

`{

pgNum: 2,

title: "title",

date: writeDate([YEAR],[MONTH],[DAY]),

altText: "alt text",

imageFiles: "no. of image files in that strip",

authorNotes: \`

notes go here>/p>
    `

},`

I guess I would store comments here, but have no idea how to do it(don't know js). Thank you for any help!

Link to webcomic for reference: https://ahumanibelieve.github.io/

I thought having normal comment code would work, but then I realised that since every strip is in one html file, it wouldn't work


问:
_veriff_js_sdk__WEBPACK_IMPORTED_MODULE_0__ is not a function
I get the following error thrown in the browser. What should I do to prevent this error from popping ?

veriff_js_sdk__WEBPACK_IMPORTED_MODULE_0_ is not a function

```<code>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import * as Veriff from '@veriff/js-sdk';

@Component({
  selector: 'hp',
  templateUrl: './hp-page.component.html',
  styleUrls: ['./hp-page.component.css']
})
export class HomePageComponent implements OnInit {

  constructor(private route: ActivatedRoute, private router : Router) { }

  ngOnInit(): void {
  }

  hpclicked(){

    const veriff = Veriff({
      apiKey: 'API_KEY',
      parentId: 'veriff-root',
      onSession: function(err : Error, response : Response) {
        console.log("executed");
      }
    });
    veriff.setParams({
      person: {
        givenName: 'Foo',
        lastName: 'Bar'
      },
      vendorData: '7eb19312-79d6-11ec-90d6-0242ac120003'
    });
    veriff.mount({
      submitBtnText: 'Get verified'
    });

   }
}
</code>```

Note:

Package                         Version

@angular/cli                    11.2.19

typescript                      4.1.6

Body:
I get the following error thrown in the browser. What should I do to prevent this error from popping ?

veriff_js_sdk__WEBPACK_IMPORTED_MODULE_0_ is not a function

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import * as Veriff from '@veriff/js-sdk';

@Component({
  selector: 'hp',
  templateUrl: './hp-page.component.html',
  styleUrls: ['./hp-page.component.css']
})
export class HomePageComponent implements OnInit {

  constructor(private route: ActivatedRoute, private router : Router) { }

  ngOnInit(): void {
  }

  hpclicked(){

    const veriff = Veriff({
      apiKey: 'API_KEY',
      parentId: 'veriff-root',
      onSession: function(err : Error, response : Response) {
        console.log("executed");
      }
    });
    veriff.setParams({
      person: {
        givenName: 'Foo',
        lastName: 'Bar'
      },
      vendorData: '7eb19312-79d6-11ec-90d6-0242ac120003'
    });
    veriff.mount({
      submitBtnText: 'Get verified'
    });

   }
}

Note:

Package                         Version

@angular/cli                    11.2.19

typescript                      4.1.6


问:
How do I make VSCode have permissions to edit my apache2 directory
I can't seem to find a way to make visual studio code have root access on my azure server

I tried to change the index.html file on var/www/html/index.html on vscode but instead I got this error Failed to save 'index.html': Unable to write file 'vscode-remote://ssh-remote+"serverip"/var/www/html/index.html' (NoPermissions (FileSystemError): Error: EACCES: permission denied, open '/var/www/html/index.html')
the error:


问:
Log in firebase real-time database Activity
How can I make a Login activity to connect firebase?

I want to make an app that could login to firebase database project.

I want that someone that have project in firebase could connect his project. That why the login activity need to be dynamic and changeable, that anyone could login to his account without connecting the app to just one project.

For example - I built a desktop application in C# (on visual studio WinForm with FireSharp package), that has a login form to an exist real-time database project using the BasePath (the link of the ptoject), and the Secret in the setting.

Is this possible to do something like that on Android Studio?


问:
Optical Character Recognition with Python Tesseract on a series of symbols

Hello, i am looking for guidance. I have been using pytesseract to do OCR but it seems like i can't get the OCR to recognise a series of equal signs put together in an image. any guidance on how to address this issue ? i tested the image with AWS Rekognition, Google Vision and same results. I tried to select ROI with Open CV and focus the OCR on that, and yet it still came out empty, i.e. no character recognised. appreciate for any guidance.

thank you


问:
Drawing issues using SwiftUI view as a PrimaryView in uisplitviewcontroller
I am trying to use SwiftUI View as a primary view in a UISplitViewController.
I have setup and added my PrimaryViewController to the NavigationController in my SplitviewController, in Storyboard.

mySwiftUI view code is as follows:

```<code>struct Tile_SwiftUI: View {
    var body: some View {
        RoundedRectangle(cornerRadius: 15)
            .fill( Color.red )
            .frame(height: 100)
            .padding()
     }
}
</code>```

And my PrimaryViewController setup is as follows:

```<code>import UIKit
import SwiftUI

class PrimaryViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let testVC = UIHostingController(rootView: Tile_SwiftUI() )
        self.view.backgroundColor = UIColor.white
        testVC.view.backgroundColor = UIColor.blue
        addChild(testVC)

        view.addSubview(testVC.view)
        testVC.view.translatesAutoresizingMaskIntoConstraints = false

            NSLayoutConstraint.activate([
                testVC.view.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor ),
                testVC.view.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor ),
                testVC.view.topAnchor.constraint(equalTo: view.topAnchor ),
                testVC.view.bottomAnchor.constraint(equalTo: view.bottomAnchor ),
            ])
        testVC.didMove(toParent: self)

    }
 }
</code>```

It all works as expected on the iPhone and iPad landscape orientation, but on portrait orientation the primaryViewController gets an odd overlay. Please see attached images.

Here is also a link to the full project:

https://www.sticklets.co/code/SplitViewController_SwiftUI_bug.zip

Any ideas what is causing this?

Body:
I am trying to use SwiftUI View as a primary view in a UISplitViewController.
I have setup and added my PrimaryViewController to the NavigationController in my SplitviewController, in Storyboard.

mySwiftUI view code is as follows:

struct Tile_SwiftUI: View {
    var body: some View {
        RoundedRectangle(cornerRadius: 15)
            .fill( Color.red )
            .frame(height: 100)
            .padding()
     }
}

And my PrimaryViewController setup is as follows:

import UIKit
import SwiftUI

class PrimaryViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let testVC = UIHostingController(rootView: Tile_SwiftUI() )
        self.view.backgroundColor = UIColor.white
        testVC.view.backgroundColor = UIColor.blue
        addChild(testVC)

        view.addSubview(testVC.view)
        testVC.view.translatesAutoresizingMaskIntoConstraints = false

            NSLayoutConstraint.activate([
                testVC.view.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor ),
                testVC.view.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor ),
                testVC.view.topAnchor.constraint(equalTo: view.topAnchor ),
                testVC.view.bottomAnchor.constraint(equalTo: view.bottomAnchor ),
            ])
        testVC.didMove(toParent: self)

    }
 }

It all works as expected on the iPhone and iPad landscape orientation, but on portrait orientation the primaryViewController gets an odd overlay. Please see attached images.

Here is also a link to the full project:

https://www.sticklets.co/code/SplitViewController_SwiftUI_bug.zip

Any ideas what is causing this?


问:
How to run Julia codes with a windows10 machine in Jenkins?
I want to run some codes with the help of Jenkins. OS is win10
Are there any tutorials on this issue? I searched around and couldn't find it.

I tried this command but failed.

```<code>cd E:\\sim_1\scripts
set JULIA_NUM_THREADS=8
julia E:\\sim_1\scripts\main.jl
</code>```

told me julia is not a command. but it works on CMD.

Body:
I want to run some codes with the help of Jenkins. OS is win10
Are there any tutorials on this issue? I searched around and couldn't find it.

I tried this command but failed.

cd E:\\sim_1\scripts
set JULIA_NUM_THREADS=8
julia E:\\sim_1\scripts\main.jl

told me julia is not a command. but it works on CMD.


问:
Error on Starting MySQL Cluster 8.0 Data Node on Ubuntu 22.04 LTS
When I start the data nodeid 1 (10.1.1.103) of MySQL Cluster 8.0 on Ubuntu 22.04 LTS I am getting the following error:

```<code># ndbd
Failed to open /sys/devices/system/cpu/cpu0/cache/index3/shared_cpu_list: No such file or directory
2023-01-02 17:16:55 [ndbd] INFO     -- Angel connected to '10.1.1.102:1186'
2023-01-02 17:16:55 [ndbd] INFO     -- Angel allocated nodeid: 2
</code>```

When I start data nodeid 2 (10.1.1.105) I get the following error:

```<code># ndbd
Failed to open /sys/devices/system/cpu/cpu0/cache/index3/shared_cpu_list: No such file or directory
2023-01-02 11:10:04 [ndbd] INFO     -- Angel connected to '10.1.1.102:1186'
2023-01-02 11:10:04 [ndbd] ERROR    -- Failed to allocate nodeid, error: 'Error: Could not alloc node id at 10.1.1.102:1186: Connection done from wrong host ip 10.1.1.105.'
</code>```

The management node log file reports (on /var/lib/mysql-cluster/ndb_1_cluster.log):

```<code>2023-01-02 11:28:47 [MgmtSrvr] INFO     -- Node 2: Initial start, waiting for 3 to connect,  nodes [ all: 2 and 3 connected: 2 no-wait:  ]
</code>```

What is the relevance of failing to open: /sys/devices/system/cpu/cpu0/cache/index3/shared_cpu_list: No such file or directory?

Why is data node on 10.1.1.105 unable to allocate a nodeid?

I initially installed a single Management Node on 10.1.1.102:

```<code>wget https://dev.mysql.com/get/Downloads/MySQL-Cluster-8.0/mysql-cluster_8.0.31-1ubuntu22.04_amd64.deb-bundle.tar

tar -xf mysql-cluster_8.0.31-1ubuntu22.04_amd64.deb-bundle.tar

dpkg -i mysql-cluster-community-management-server_8.0.31-1ubuntu22.04_amd64.deb

mkdir /var/lib/mysql-cluster
vi /var/lib/mysql-cluster/config.ini
</code>```

The configuration set up on config.ini:

```<code>[ndbd default]
# Options affecting ndbd processes on all data nodes:
NoOfReplicas=2  # Number of replicas

[ndb_mgmd]
# Management process options:
hostname=10.1.1.102 # Hostname of the manager
datadir=/var/lib/mysql-cluster  # Directory for the log files

[ndbd]
hostname=10.1.1.103 # Hostname/IP of the first data node
NodeId=2      # Node ID for this data node
datadir=/usr/local/mysql/data # Remote directory for the data files

[ndbd]
hostname=10.1.1.105 # Hostname/IP of the second data node
NodeId=3      # Node ID for this data node
datadir=/usr/local/mysql/data # Remote directory for the data files

[mysqld]
# SQL node options:
hostname=10.1.1.102 # In our case the MySQL server/client is on the same Droplet as the cluster manager
</code>```

I then started and killed the running server and created a systemd file for Cluster manager:

```<code>ndb_mgmd -f /var/lib/mysql-cluster/config.ini

pkill -f ndb_mgmd

vi /etc/systemd/system/ndb_mgmd.service
</code>```

Adding the following configuration:

```<code>[Unit]
Description=MySQL NDB Cluster Management Server
After=network.target auditd.service

[Service]
Type=forking
ExecStart=/usr/sbin/ndb_mgmd -f /var/lib/mysql-cluster/config.ini
ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
Restart=on-failure

[Install]
WantedBy=multi-user.target
</code>```

I then reloaded the systemd daemon to apply the changes, started and enabled the Cluster Manager and checked its active status:

```<code>systemctl daemon-reload

systemctl start ndb_mgmd
systemctl enable ndb_mgmd
</code>```

Here is the status of the Cluster Manager:

```<code># systemctl status ndb_mgmd
● ndb_mgmd.service - MySQL NDB Cluster Management Server
     Loaded: loaded (/etc/systemd/system/ndb_mgmd.service; enabled; vendor preset: enabled)
     Active: active (running) since Sun 2023-01-01 08:25:07 CST; 27min ago
   Main PID: 320972 (ndb_mgmd)
      Tasks: 12 (limit: 9273)
     Memory: 2.5M
        CPU: 35.467s
     CGroup: /system.slice/ndb_mgmd.service
             └─320972 /usr/sbin/ndb_mgmd -f /var/lib/mysql-cluster/config.ini

Jan 01 08:25:07 nuc systemd[1]: Starting MySQL NDB Cluster Management Server...
Jan 01 08:25:07 nuc ndb_mgmd[320971]: MySQL Cluster Management Server mysql-8.0.31 ndb-8.0.31
Jan 01 08:25:07 nuc systemd[1]: Started MySQL NDB Cluster Management Server.
</code>```

I then set up a data node on 10.1.1.103, installing dependencies, downloading the data node and setting up its config:

```<code>apt update && apt -y install libclass-methodmaker-perl

wget https://dev.mysql.com/get/Downloads/MySQL-Cluster-8.0/mysql-cluster_8.0.31-1ubuntu22.04_amd64.deb-bundle.tar

tar -xf mysql-cluster_8.0.31-1ubuntu22.04_amd64.deb-bundle.tar

dpkg -i mysql-cluster-community-data-node_8.0.31-1ubuntu22.04_amd64.deb

vi /etc/my.cnf
</code>```

I entered the address of the Cluster Management Node in the configuration:

```<code># ndbd
Failed to open /sys/devices/system/cpu/cpu0/cache/index3/shared_cpu_list: No such file or directory
2023-01-02 11:10:04 [ndbd] INFO     -- Angel connected to '10.1.1.102:1186'
2023-01-02 11:10:04 [ndbd] ERROR    -- Failed to allocate nodeid, error: 'Error: Could not alloc node id at 10.1.1.102:1186: Connection done from wrong host ip 10.1.1.105.'
</code>```0

I then created a data directory and started the node:

```<code># ndbd
Failed to open /sys/devices/system/cpu/cpu0/cache/index3/shared_cpu_list: No such file or directory
2023-01-02 11:10:04 [ndbd] INFO     -- Angel connected to '10.1.1.102:1186'
2023-01-02 11:10:04 [ndbd] ERROR    -- Failed to allocate nodeid, error: 'Error: Could not alloc node id at 10.1.1.102:1186: Connection done from wrong host ip 10.1.1.105.'
</code>```1

This is when I got the "Failed to open" error result on data nodeid 1 (102.1.1.103):

```<code># ndbd
Failed to open /sys/devices/system/cpu/cpu0/cache/index3/shared_cpu_list: No such file or directory
2023-01-02 11:10:04 [ndbd] INFO     -- Angel connected to '10.1.1.102:1186'
2023-01-02 11:10:04 [ndbd] ERROR    -- Failed to allocate nodeid, error: 'Error: Could not alloc node id at 10.1.1.102:1186: Connection done from wrong host ip 10.1.1.105.'
</code>```2

UPDATED (2023-01-02)

Thank you @MauritzSundell.  I corrected the (private) IP addresses above and no longer got:

```<code># ndbd
Failed to open /sys/devices/system/cpu/cpu0/cache/index3/shared_cpu_list: No such file or directory
ERROR: Unable to connect with connect string: nodeid=0,10.1.1.2:1186
Retrying every 5 seconds. Attempts left: 12 11 10 9 8 7 6 5 4 3 2 1, failed.
2023-01-01 14:41:57 [ndbd] ERROR    -- Could not connect to management server, error: ''
</code>```

Also @MauritzSundell, in order to use the ndbmtd process rather than the ndbd process, does any alteration need to be made to any of the configuration files (e.g. /etc/systemd/system/ndb_mgmd.service)?

What is the appropriate reference/tutorial documentation for MySQL Cluster 8.0?  Is it MySQL Cluster "MySQL NDB Cluster 8.0" on:
https://downloads.mysql.com/docs/mysql-cluster-excerpt-8.0-en.pdf

Or is it "MySQL InnoDB Cluster" on:
https://dev.mysql.com/doc/refman/8.0/en/mysql-innodb-cluster-introduction.html

Not sure I understand the difference.

Body:
When I start the data nodeid 1 (10.1.1.103) of MySQL Cluster 8.0 on Ubuntu 22.04 LTS I am getting the following error:

# ndbd
Failed to open /sys/devices/system/cpu/cpu0/cache/index3/shared_cpu_list: No such file or directory
2023-01-02 17:16:55 [ndbd] INFO     -- Angel connected to '10.1.1.102:1186'
2023-01-02 17:16:55 [ndbd] INFO     -- Angel allocated nodeid: 2

When I start data nodeid 2 (10.1.1.105) I get the following error:

# ndbd
Failed to open /sys/devices/system/cpu/cpu0/cache/index3/shared_cpu_list: No such file or directory
2023-01-02 11:10:04 [ndbd] INFO     -- Angel connected to '10.1.1.102:1186'
2023-01-02 11:10:04 [ndbd] ERROR    -- Failed to allocate nodeid, error: 'Error: Could not alloc node id at 10.1.1.102:1186: Connection done from wrong host ip 10.1.1.105.'

The management node log file reports (on /var/lib/mysql-cluster/ndb_1_cluster.log):

2023-01-02 11:28:47 [MgmtSrvr] INFO     -- Node 2: Initial start, waiting for 3 to connect,  nodes [ all: 2 and 3 connected: 2 no-wait:  ]

What is the relevance of failing to open: /sys/devices/system/cpu/cpu0/cache/index3/shared_cpu_list: No such file or directory?

Why is data node on 10.1.1.105 unable to allocate a nodeid?

I initially installed a single Management Node on 10.1.1.102:

wget https://dev.mysql.com/get/Downloads/MySQL-Cluster-8.0/mysql-cluster_8.0.31-1ubuntu22.04_amd64.deb-bundle.tar

tar -xf mysql-cluster_8.0.31-1ubuntu22.04_amd64.deb-bundle.tar

dpkg -i mysql-cluster-community-management-server_8.0.31-1ubuntu22.04_amd64.deb

mkdir /var/lib/mysql-cluster
vi /var/lib/mysql-cluster/config.ini

The configuration set up on config.ini:

[ndbd default]
# Options affecting ndbd processes on all data nodes:
NoOfReplicas=2  # Number of replicas

[ndb_mgmd]
# Management process options:
hostname=10.1.1.102 # Hostname of the manager
datadir=/var/lib/mysql-cluster  # Directory for the log files

[ndbd]
hostname=10.1.1.103 # Hostname/IP of the first data node
NodeId=2      # Node ID for this data node
datadir=/usr/local/mysql/data # Remote directory for the data files

[ndbd]
hostname=10.1.1.105 # Hostname/IP of the second data node
NodeId=3      # Node ID for this data node
datadir=/usr/local/mysql/data # Remote directory for the data files

[mysqld]
# SQL node options:
hostname=10.1.1.102 # In our case the MySQL server/client is on the same Droplet as the cluster manager

I then started and killed the running server and created a systemd file for Cluster manager:

ndb_mgmd -f /var/lib/mysql-cluster/config.ini

pkill -f ndb_mgmd

vi /etc/systemd/system/ndb_mgmd.service

Adding the following configuration:

[Unit]
Description=MySQL NDB Cluster Management Server
After=network.target auditd.service

[Service]
Type=forking
ExecStart=/usr/sbin/ndb_mgmd -f /var/lib/mysql-cluster/config.ini
ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
Restart=on-failure

[Install]
WantedBy=multi-user.target

I then reloaded the systemd daemon to apply the changes, started and enabled the Cluster Manager and checked its active status:

systemctl daemon-reload

systemctl start ndb_mgmd
systemctl enable ndb_mgmd

Here is the status of the Cluster Manager:

# systemctl status ndb_mgmd
● ndb_mgmd.service - MySQL NDB Cluster Management Server
     Loaded: loaded (/etc/systemd/system/ndb_mgmd.service; enabled; vendor preset: enabled)
     Active: active (running) since Sun 2023-01-01 08:25:07 CST; 27min ago
   Main PID: 320972 (ndb_mgmd)
      Tasks: 12 (limit: 9273)
     Memory: 2.5M
        CPU: 35.467s
     CGroup: /system.slice/ndb_mgmd.service
             └─320972 /usr/sbin/ndb_mgmd -f /var/lib/mysql-cluster/config.ini

Jan 01 08:25:07 nuc systemd[1]: Starting MySQL NDB Cluster Management Server...
Jan 01 08:25:07 nuc ndb_mgmd[320971]: MySQL Cluster Management Server mysql-8.0.31 ndb-8.0.31
Jan 01 08:25:07 nuc systemd[1]: Started MySQL NDB Cluster Management Server.

I then set up a data node on 10.1.1.103, installing dependencies, downloading the data node and setting up its config:

apt update && apt -y install libclass-methodmaker-perl

wget https://dev.mysql.com/get/Downloads/MySQL-Cluster-8.0/mysql-cluster_8.0.31-1ubuntu22.04_amd64.deb-bundle.tar

tar -xf mysql-cluster_8.0.31-1ubuntu22.04_amd64.deb-bundle.tar

dpkg -i mysql-cluster-community-data-node_8.0.31-1ubuntu22.04_amd64.deb

vi /etc/my.cnf

I entered the address of the Cluster Management Node in the configuration:

[mysql_cluster]
# Options for NDB Cluster processes:
ndb-connectstring=10.1.1.102  # location of cluster manager

I then created a data directory and started the node:

mkdir -p /usr/local/mysql/data

ndbd

This is when I got the "Failed to open" error result on data nodeid 1 (102.1.1.103):

# ndbd
Failed to open /sys/devices/system/cpu/cpu0/cache/index3/shared_cpu_list: No such file or directory
2023-01-02 17:16:55 [ndbd] INFO     -- Angel connected to '10.1.1.102:1186'
2023-01-02 17:16:55 [ndbd] INFO     -- Angel allocated nodeid: 2

UPDATED (2023-01-02)

Thank you @MauritzSundell.  I corrected the (private) IP addresses above and no longer got:

# ndbd
Failed to open /sys/devices/system/cpu/cpu0/cache/index3/shared_cpu_list: No such file or directory
ERROR: Unable to connect with connect string: nodeid=0,10.1.1.2:1186
Retrying every 5 seconds. Attempts left: 12 11 10 9 8 7 6 5 4 3 2 1, failed.
2023-01-01 14:41:57 [ndbd] ERROR    -- Could not connect to management server, error: ''

Also @MauritzSundell, in order to use the ndbmtd process rather than the ndbd process, does any alteration need to be made to any of the configuration files (e.g. /etc/systemd/system/ndb_mgmd.service)?

What is the appropriate reference/tutorial documentation for MySQL Cluster 8.0?  Is it MySQL Cluster "MySQL NDB Cluster 8.0" on:
https://downloads.mysql.com/docs/mysql-cluster-excerpt-8.0-en.pdf

Or is it "MySQL InnoDB Cluster" on:
https://dev.mysql.com/doc/refman/8.0/en/mysql-innodb-cluster-introduction.html

Not sure I understand the difference.


问:
how to get rid of (Time Limit Exceeded) in below question
You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]

my code in vs:

```<code>#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main (){

vector<vector<int>> matrix ={{1,2,3},{4,5,6},{7,8,9}};

        int m = matrix.size();
        int n = matrix[0].size();

        int start= 0 ,last = n-1;

        for( int i=0;i<n;i++){
            for(int j=i;j<n;j++){
                swap(matrix[i][j],matrix[j][i]);
            }
        }

        while(start<last){
            for(int i=0;i<n;i++){
        swap(matrix[i][start],matrix[i][last]);
        }

        start++;
        last--;}

   for( int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                cout<<matrix[i][j];
            }
        }

return 0;}
</code>```

my code in leet code

```<code>class Solution {
public:
    void rotate(vector<vector<int>>& matrix) {

        int m = matrix.size();
        int n = matrix[0].size();

        int start = 0 , last = n-1;

        for( int i=0;i<n;i++){
            for(int j=i;j<n;j++){
                swap(matrix[i][j],matrix[j][i]);
            }
        }

        while(start<last){
            for(int i=0;i<n;i++){
        swap(matrix[i][start],matrix[i][last]);}
        }
        start++;
        last--;
    }
};
</code>```

it is a leed code question (48. Rotate Image) my code is working fine in vs code but in leetcode it shows tle.

Body:
You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]

my code in vs:

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main (){

vector<vector<int>> matrix ={{1,2,3},{4,5,6},{7,8,9}};

        int m = matrix.size();
        int n = matrix[0].size();

        int start= 0 ,last = n-1;

        for( int i=0;i<n;i++){
            for(int j=i;j<n;j++){
                swap(matrix[i][j],matrix[j][i]);
            }
        }

        while(start<last){
            for(int i=0;i<n;i++){
        swap(matrix[i][start],matrix[i][last]);
        }

        start++;
        last--;}

   for( int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                cout<<matrix[i][j];
            }
        }

return 0;}

my code in leet code

class Solution {
public:
    void rotate(vector<vector<int>>& matrix) {

        int m = matrix.size();
        int n = matrix[0].size();

        int start = 0 , last = n-1;

        for( int i=0;i<n;i++){
            for(int j=i;j<n;j++){
                swap(matrix[i][j],matrix[j][i]);
            }
        }

        while(start<last){
            for(int i=0;i<n;i++){
        swap(matrix[i][start],matrix[i][last]);}
        }
        start++;
        last--;
    }
};

it is a leed code question (48. Rotate Image) my code is working fine in vs code but in leetcode it shows tle.


问:
Need help understanding why I cannot decode a jpg file properly from an AJAX call to an API
I am working with a private API that via HTTP returns a JPEG. I am having issues decoding the returned data in javascript.

if I use fetch and decode the data like this:

```<code>    .then((data) => {
    var reader = new FileReader();
    reader.onload = function() {
        var b64 = reader.result
        console.log("This is base64", b64)
        document.getElementById("camerapreview2").src = b64
    }
    reader.readAsDataURL(data)
})
</code>```

Then I get data that displays as a JPG. If however I use jquery AJAX method and encode the result like this:

```<code>document.getElementById("camerapreview").src = "data:image/jpeg;base64," + $.base64.encode(result, true)
</code>```

Using the jquery base64 library (or a million other code samples I have found that do the same thing).

The issue seems to be the base64 both create

Working starts with:  /9j/4AAQSkZJRgABAQEAYABgAAD//gA8Q1JFQVR which I believe shows the right header for a jpeg

Not working starts with: v7/wAQSkZJRgABAQEAYABgAA/wA8Q1JFQVRPUjogZ2Qta

So I dont understand why its not working both ways, lots of code samples seem to be doing this fine for jpegs using ajax

Also if I look at the network tab in chrome for the call (created by either code approach) chrome seems to be able to decode the response as a jpeg both times

Body:
I am working with a private API that via HTTP returns a JPEG. I am having issues decoding the returned data in javascript.

if I use fetch and decode the data like this:

    .then((data) => {
    var reader = new FileReader();
    reader.onload = function() {
        var b64 = reader.result
        console.log("This is base64", b64)
        document.getElementById("camerapreview2").src = b64
    }
    reader.readAsDataURL(data)
})

Then I get data that displays as a JPG. If however I use jquery AJAX method and encode the result like this:

document.getElementById("camerapreview").src = "data:image/jpeg;base64," + $.base64.encode(result, true)

Using the jquery base64 library (or a million other code samples I have found that do the same thing).

The issue seems to be the base64 both create

Working starts with:  /9j/4AAQSkZJRgABAQEAYABgAAD//gA8Q1JFQVR which I believe shows the right header for a jpeg

Not working starts with: v7/wAQSkZJRgABAQEAYABgAA/wA8Q1JFQVRPUjogZ2Qta

So I dont understand why its not working both ways, lots of code samples seem to be doing this fine for jpegs using ajax

Also if I look at the network tab in chrome for the call (created by either code approach) chrome seems to be able to decode the response as a jpeg both times


问:
can not export object from js module with webpack
I want to build javascript library with webpack. i want to use require statements to import my library and my library should export default an object with specific properties.
but when I bundle it with webpack as a "lib" type , webpack generate an empty file.
what is the problem?

mylib.js

export default {plugin:"my-plugin"}

application

const object = require('my-library')

i already done it by rollup.how can i config webpack to export a object from entry point to be importable from any application?


问:
Upload Files to mediafire using python
i have a porblem when i run my script of uploading a file everything it's ok and the file is uploaded but in the console an error appears: this is the error:
and i check about the path and everything .. and

here's the code

and when this error appears everything stop working, like the script is ending here but there's some few lines after this and they don't work... and thank you !

Title: Upload Files to mediafire using python


问:
Display Version in ESP32 Web-Tools
I am currently writing on an ESP32 project in PlatformIO.
To distribute my firmware to other users, I want to use ESP-web-tools.
https://esphome.github.io/esp-web-tools/

Picture of demo firmware

So fare, it works as intended, but I want to display the version of my code that is on my ESP, like displayed in the demo.
Do you know how to implement this? I guess that it might be connected to improv, but I can't verify that.
Do you have some example code for me?

Title: Display Version in ESP32 Web-Tools