问:
Run code or set environment variable before meson cross-compile setup is run
I'm cross compiling to WASM using emscripten using meson and the cross file I have currently looks like this:

```<code>[binaries]
c = 'emcc'
cpp = 'em++'
ar = 'emar'
ranlib = 'emranlib'
pkgconfig = 'pkg-config'
strip = 'strip'

[project options]
sharedlib = false

[host_machine]
cpu = 'wasm'
cpu_family = 'wasm'
endian = 'little'
system = 'emscripten'

[properties]
sys_root = '$EM_CACHE/sysroot'
</code>```

What bothers me is that last line - I'm setting the EM_CACHE variable manually but it can be derived with em-config CACHE. I'm not sure what order meson runs the build configuration but it seems that when you specify --cross-file it pre-empts anything in meson.build, so I'm unable to pre-set that variable.

Is there a way to set this, or set a variable that can be used in the cross file, or is there just a better/more graceful way to do this that I've missed?

Body:
I'm cross compiling to WASM using emscripten using meson and the cross file I have currently looks like this:

[binaries]
c = 'emcc'
cpp = 'em++'
ar = 'emar'
ranlib = 'emranlib'
pkgconfig = 'pkg-config'
strip = 'strip'

[project options]
sharedlib = false

[host_machine]
cpu = 'wasm'
cpu_family = 'wasm'
endian = 'little'
system = 'emscripten'

[properties]
sys_root = '$EM_CACHE/sysroot'

What bothers me is that last line - I'm setting the EM_CACHE variable manually but it can be derived with em-config CACHE. I'm not sure what order meson runs the build configuration but it seems that when you specify --cross-file it pre-empts anything in meson.build, so I'm unable to pre-set that variable.

Is there a way to set this, or set a variable that can be used in the cross file, or is there just a better/more graceful way to do this that I've missed?


来源: stackexchange

问:
How to drag and drop element in placeholder in React?
i have a few pictures in my React.Component, they come with axios from server

```<code>class GalleryReady extends React.Component {
  state = {
    images: []
  }
  componentDidMount() {
    const url = 'http://work.eniso.ru/galleryready.php'
    axios.get(url).then(response => response.data)
    .then((data) => {
      this.setState({ images: data })
      console.log(this.state.images)
     })
  }
  doSomething() {
    console.log(this)
  }
  eventControl = (e) => {
    console.log(e.target)
    e.target.classList.add('hold')
  }
  drop(event){
    let item = document.querySelector('.item')
    event.target.classList.remove('hovered')
    event.target.append(item)
    console.log(event.target)
  }
  render(){
    return(
      <div className='gallery'>
        <ul>
          {this.state.images.map((response, i) => (
                <div key={i}>
                    <img draggable="true" onDrag={this.eventControl} className='item' src={response.images} />
                </div>
            ))}
            <div onDragOverCapture={this.drop} className='placeholder'></div>
            <div onDragOverCapture={this.drop} className='placeholder'></div>
            <div onDragOverCapture={this.drop} className='placeholder'></div>
            <div onDragOverCapture={this.drop} className='placeholder'></div>
        </ul>
      </div>
    )
  }
}
</code>```

I need to drag any one picture and drop in any placeholder. I don't understand for i can to take information in "Drop" which picture i take in drag

i try to call drop in drag with argument e like this

```<code>  eventControl = (e) => {
    console.log(e.target)
    e.target.classList.add('hold')
    this.drop(e)
  }
</code>```

And it's work but have many mistakes in console and delete all pictures in array images

ContentLicense: CC BY-SA 4.0

Body:
i have a few pictures in my React.Component, they come with axios from server

class GalleryReady extends React.Component {
  state = {
    images: []
  }
  componentDidMount() {
    const url = 'http://work.eniso.ru/galleryready.php'
    axios.get(url).then(response => response.data)
    .then((data) => {
      this.setState({ images: data })
      console.log(this.state.images)
     })
  }
  doSomething() {
    console.log(this)
  }
  eventControl = (e) => {
    console.log(e.target)
    e.target.classList.add('hold')
  }
  drop(event){
    let item = document.querySelector('.item')
    event.target.classList.remove('hovered')
    event.target.append(item)
    console.log(event.target)
  }
  render(){
    return(

          {this.state.images.map((response, i) => (

            ))}

    )
  }
}

I need to drag any one picture and drop in any placeholder. I don't understand for i can to take information in "Drop" which picture i take in drag

i try to call drop in drag with argument e like this

  eventControl = (e) => {
    console.log(e.target)
    e.target.classList.add('hold')
    this.drop(e)
  }

And it's work but have many mistakes in console and delete all pictures in array images


问:
How to detect and terminate infinte loop from user's code in Node.js?
I have a simple coding problem evaluation feature in my project, where a user can submit his JavaScript code. Then I am sending this code as string to my Express.js server, creating a temporary file with the code, importing that file and calling it with previously set test cases, matching the result and sending the result to the user.
Here is a sample of the code:

```<code>const code = "
${req.body.code}

module.exports = ${functionName};
";

const filePath = await generateFile(language, code);

const fn = require(`../data/codes/${filePath.fileName}`);

testCases.forEach(testCase => {
  let output = fn(...testCase.input);
  if (!_.isEqual(output, testCase.output)) {
    isValid = false;
  }
});
</code>```

Everything is working fine here. But the problem is, if the user submits a code with an infinite loop, I'm unable to detect it and terminate it.

I want to detect, terminate and send the user a response that there is an infinite loop in his code. How can I do that?

Also, if you have any better way to evaluate the user's code, you can also suggest me that.

Body:
I have a simple coding problem evaluation feature in my project, where a user can submit his JavaScript code. Then I am sending this code as string to my Express.js server, creating a temporary file with the code, importing that file and calling it with previously set test cases, matching the result and sending the result to the user.
Here is a sample of the code:

const code = "
${req.body.code}

module.exports = ${functionName};
";

const filePath = await generateFile(language, code);

const fn = require(`../data/codes/${filePath.fileName}`);

testCases.forEach(testCase => {
  let output = fn(...testCase.input);
  if (!_.isEqual(output, testCase.output)) {
    isValid = false;
  }
});

Everything is working fine here. But the problem is, if the user submits a code with an infinite loop, I'm unable to detect it and terminate it.

I want to detect, terminate and send the user a response that there is an infinite loop in his code. How can I do that?

Also, if you have any better way to evaluate the user's code, you can also suggest me that.


问:
The context api resets and re-evaluates from start when I go to another profile route/ next page
AuthContext.js

```<code>import { createContext, useEffect, useState } from "react";
import { axiosInstance } from "../../axiosConfig";
import { useCustomToast } from "../../customHooks/useToast";

const initialState = {
  user: null,
  isLoggedIn: false,
  login: () => null,
  logOut: () => null,
};

export const AuthContext = createContext(initialState);

export const AuthContextProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const { showToast } = useCustomToast();

  console.log("i am rinning agaon here");

  const checkLogin = async () => {
    try {
      const res = await axiosInstance.get("/auth/refresh");
      setIsLoggedIn(true);
      console.log("the user is", res?.data);
      setUser(res?.data?.user);
    } catch (e) {
      console.log(e);
      setIsLoggedIn(false);
    }
  };

  const logOutHandler = async () => {
    try {
      const res = await axiosInstance.get("/auth/logout");
      showToast(res?.data?.message);
    } catch (e) {
      showToast("Something went wrong.Please try again");
    }
  };

  useEffect(() => {
    checkLogin();
  }, []);

  const login = (userData) => {
    setUser(userData);
    setIsLoggedIn(true);
  };

  const logOut = () => {
    setUser(null);
    logOutHandler();
    setIsLoggedIn(false);
  };

  return (
    <AuthContext.Provider
      value={{
        user,
        isLoggedIn,
        login,
        logOut,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};
</code>```

ProtectedRoute.js

```<code>import React, { useEffect, useContext } from "react";
import { useRouter } from "next/router";
import { AuthContext } from "../context/authContext";

const ProtectedRoute = ({ children }) => {
  const { isLoggedIn } = useContext(AuthContext);
  const router = useRouter();

  useEffect(() => {
    if (!isLoggedIn) {
      router.push("/login");
    }
  }, [isLoggedIn]);

  return <>{isLoggedIn && children}</>;
};
export default ProtectedRoute;

</code>```

I am using NextJS and context api for managing user state. Here at first I will check for tokens and if it is valid I will set loggedIn state to true. But suppose I want to go to profile page which is wrapped by protected route, what is happening is AuthContext is resetting and evaluating itself from beginning, the isLoggedIn state is false when I go to /profile route. If I console log isLoggedIn state inside protectedRoute.js, it is false at start and before it becomes true, that router.push("/login) already runs before isLoggedIn becomes true. It feels like all AuthContext is executing again and again on each route change. Is there any code problem? How can I fix it? The one solution I have found is wrapping that wrapping that if(!loggedIn) statement with setTimeOut() of 1 secs so that until that time loggedIn becomes true from context API

Body:
AuthContext.js

import { createContext, useEffect, useState } from "react";
import { axiosInstance } from "../../axiosConfig";
import { useCustomToast } from "../../customHooks/useToast";

const initialState = {
  user: null,
  isLoggedIn: false,
  login: () => null,
  logOut: () => null,
};

export const AuthContext = createContext(initialState);

export const AuthContextProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const { showToast } = useCustomToast();

  console.log("i am rinning agaon here");

  const checkLogin = async () => {
    try {
      const res = await axiosInstance.get("/auth/refresh");
      setIsLoggedIn(true);
      console.log("the user is", res?.data);
      setUser(res?.data?.user);
    } catch (e) {
      console.log(e);
      setIsLoggedIn(false);
    }
  };

  const logOutHandler = async () => {
    try {
      const res = await axiosInstance.get("/auth/logout");
      showToast(res?.data?.message);
    } catch (e) {
      showToast("Something went wrong.Please try again");
    }
  };

  useEffect(() => {
    checkLogin();
  }, []);

  const login = (userData) => {
    setUser(userData);
    setIsLoggedIn(true);
  };

  const logOut = () => {
    setUser(null);
    logOutHandler();
    setIsLoggedIn(false);
  };

  return (
    <AuthContext.Provider
      value={{
        user,
        isLoggedIn,
        login,
        logOut,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};

ProtectedRoute.js

import React, { useEffect, useContext } from "react";
import { useRouter } from "next/router";
import { AuthContext } from "../context/authContext";

const ProtectedRoute = ({ children }) => {
  const { isLoggedIn } = useContext(AuthContext);
  const router = useRouter();

  useEffect(() => {
    if (!isLoggedIn) {
      router.push("/login");
    }
  }, [isLoggedIn]);

  return <>{isLoggedIn && children}</>;
};
export default ProtectedRoute;

I am using NextJS and context api for managing user state. Here at first I will check for tokens and if it is valid I will set loggedIn state to true. But suppose I want to go to profile page which is wrapped by protected route, what is happening is AuthContext is resetting and evaluating itself from beginning, the isLoggedIn state is false when I go to /profile route. If I console log isLoggedIn state inside protectedRoute.js, it is false at start and before it becomes true, that router.push("/login) already runs before isLoggedIn becomes true. It feels like all AuthContext is executing again and again on each route change. Is there any code problem? How can I fix it? The one solution I have found is wrapping that wrapping that if(!loggedIn) statement with setTimeOut() of 1 secs so that until that time loggedIn becomes true from context API


问:
If I use weight_col with flow_from_dataframe and a custom loss function do I have to take it into account in the loss function or is it automatic?
In my problem I have to account for an imbalance between the samples and I also made a custom loss function and so I was wondering if I should take those weights into account in the loss function or was it automatic?

I use flow_from_dataframe to pass the data with the parameter weight_col.

So I have to do something like this?

```<code>def my_loss(y_true,y_pred):
    mae_func = tf.keras.losses.MeanAbsoluteError()
    mae = mae_func(y_true,y_pred)
    return mae
</code>```

Or like this?

```<code>def my_loss(y_true,y_pred,weight):
    mae_func = tf.keras.losses.MeanAbsoluteError()
    # Do some operations with weights
    mae = mae_func(y_true,y_pred)
    return mae

</code>```

Body:
In my problem I have to account for an imbalance between the samples and I also made a custom loss function and so I was wondering if I should take those weights into account in the loss function or was it automatic?

I use flow_from_dataframe to pass the data with the parameter weight_col.

So I have to do something like this?

def my_loss(y_true,y_pred):
    mae_func = tf.keras.losses.MeanAbsoluteError()
    mae = mae_func(y_true,y_pred)
    return mae

Or like this?

def my_loss(y_true,y_pred,weight):
    mae_func = tf.keras.losses.MeanAbsoluteError()
    # Do some operations with weights
    mae = mae_func(y_true,y_pred)
    return mae


问:
AttributeError: module 'numpy.core' has no attribute '_set_promotion_state'
Snip of ouput console in spyder

The image embedded above shows the error msg occured in the spyder console

This is happens  everytime while trying to execute a python module which use numpy class.
Tried to uninstall and re-install the package but still facing the same issue.


问:
run(): incompatible function arguments in onnxruntime
In doing inference on mobilenet 0.25 model-In face detection task-, I prefer to convert model to ONNX. Then, I used a simple code to do inference like this one:

```<code>import onnx
import onnxruntime
import cv2
import numpy as np
import time
import sys
import onnx

from onnxruntime import InferenceSession, RunOptions

def input_output_layer(model_path):
    model = onnx.load(model_path)
    output =[node.name for node in model.graph.output]

    input_all = [node.name for node in model.graph.input]
    input_initializer =  [node.name for node in model.graph.initializer]
    net_feed_input = list(set(input_all)  - set(input_initializer))

    print('Inputs: ', net_feed_input)
    print('Outputs: ', output)
    return net_feed_input, output

model_path = "mnet.25.onnx"
model = onnx.load(model_path)
print(onnx.checker.check_model(model))

sess = InferenceSession(model_path)

for t in sess.get_inputs():
    print("input:", t.name, t.type, t.shape)
for t in sess.get_outputs():
    print("input:", t.name, t.type, t.shape)

img_path = "Face.jpg"

image = cv2.imread(img_path, cv2.IMREAD_COLOR)
img_data = cv2.resize(image, (640, 640)).astype(np.float32)
img_data = np.expand_dims(img_data, 0)
print(f" onnx  shapeee: {np.shape(img_data)}")
img_data = np.transpose(img_data, [0, 3, 1, 2])

print(f" onnx  shapeee: {np.shape(img_data)}, {type(img_data)}")

session_option = onnxruntime.SessionOptions()
session_option.log_severity_level = 4

model = onnxruntime.InferenceSession(model_path, sess_options=session_option,  providers=['CPUExecutionProvider'])

ort_inputs_name, ort_ouputs_names = input_output_layer(model_path)

print(ort_inputs_name, ort_ouputs_names)

start = time.time()
ort_outs = model.run(ort_ouputs_names[0], {ort_inputs_name[0]: img_data.astype('float32')})
outputs = np.array(ort_outs[0]).astype("float32")
print(outputs)
</code>```

But after running that, I get this error message:

```<code>Traceback (most recent call last):
  File "onnx_test_1.py", line 56, in <module>
    ort_outs = model.run(output_x, {ort_inputs_name[0]: img_data.astype('float32')}, None)
  File "/home/mohammad/Documents/insightface/insightface.onnx.env/lib/python3.8/site-packages/onnxruntime/capi/onnxruntime_inference_collection.py", line 200, in run
    return self._sess.run(output_names, input_feed, run_options)
TypeError: run(): incompatible function arguments. The following argument types are supported:
    1. (self: onnxruntime.capi.onnxruntime_pybind11_state.InferenceSession, arg0: List[str], arg1: Dict[str, object], arg2: onnxruntime.capi.onnxruntime_pybind11_state.RunOptions) -> List[object]

Invoked with: <onnxruntime.capi.onnxruntime_pybind11_state.InferenceSession object at 0x7f5e26b0d670>, 'output', {'data': array([[[[184., 184., 184., ..., 167., 167., 167.],
         [184., 184., 184., ..., 167., 167., 167.],
         [183., 183., 184., ..., 169., 169., 169.],
         ...,
         [243., 243., 243., ..., 254., 254., 254.],
         [243., 243., 243., ..., 255., 255., 255.],
         [243., 243., 243., ..., 255., 255., 255.]],

        [[196., 196., 196., ..., 178., 178., 178.],
         [196., 196., 196., ..., 178., 178., 178.],
         [196., 196., 196., ..., 179., 179., 179.],
         ...,
         [251., 251., 251., ..., 254., 255., 255.],
         [251., 251., 251., ..., 255., 255., 255.],
         [251., 251., 251., ..., 255., 255., 255.]],

        [[176., 176., 176., ..., 174., 175., 175.],
         [176., 176., 176., ..., 174., 175., 175.],
         [176., 176., 176., ..., 174., 175., 175.],
         ...,
         [249., 249., 249., ..., 254., 255., 255.],
         [250., 250., 250., ..., 255., 255., 255.],
         [250., 250., 250., ..., 255., 255., 255.]]]], dtype=float32)}, None
</code>```

It seems that I missed a argument for model.run. But how I set it?

I did inference on Image Quality Assessment models and got proper output. So the main part of code is correct.

Thanks in advance.

Body:
In doing inference on mobilenet 0.25 model-In face detection task-, I prefer to convert model to ONNX. Then, I used a simple code to do inference like this one:

import onnx
import onnxruntime
import cv2
import numpy as np
import time
import sys
import onnx

from onnxruntime import InferenceSession, RunOptions

def input_output_layer(model_path):
    model = onnx.load(model_path)
    output =[node.name for node in model.graph.output]

    input_all = [node.name for node in model.graph.input]
    input_initializer =  [node.name for node in model.graph.initializer]
    net_feed_input = list(set(input_all)  - set(input_initializer))

    print('Inputs: ', net_feed_input)
    print('Outputs: ', output)
    return net_feed_input, output

model_path = "mnet.25.onnx"
model = onnx.load(model_path)
print(onnx.checker.check_model(model))

sess = InferenceSession(model_path)

for t in sess.get_inputs():
    print("input:", t.name, t.type, t.shape)
for t in sess.get_outputs():
    print("input:", t.name, t.type, t.shape)

img_path = "Face.jpg"

image = cv2.imread(img_path, cv2.IMREAD_COLOR)
img_data = cv2.resize(image, (640, 640)).astype(np.float32)
img_data = np.expand_dims(img_data, 0)
print(f" onnx  shapeee: {np.shape(img_data)}")
img_data = np.transpose(img_data, [0, 3, 1, 2])

print(f" onnx  shapeee: {np.shape(img_data)}, {type(img_data)}")

session_option = onnxruntime.SessionOptions()
session_option.log_severity_level = 4

model = onnxruntime.InferenceSession(model_path, sess_options=session_option,  providers=['CPUExecutionProvider'])

ort_inputs_name, ort_ouputs_names = input_output_layer(model_path)

print(ort_inputs_name, ort_ouputs_names)

start = time.time()
ort_outs = model.run(ort_ouputs_names[0], {ort_inputs_name[0]: img_data.astype('float32')})
outputs = np.array(ort_outs[0]).astype("float32")
print(outputs)

But after running that, I get this error message:

Traceback (most recent call last):
  File "onnx_test_1.py", line 56, in <module>
    ort_outs = model.run(output_x, {ort_inputs_name[0]: img_data.astype('float32')}, None)
  File "/home/mohammad/Documents/insightface/insightface.onnx.env/lib/python3.8/site-packages/onnxruntime/capi/onnxruntime_inference_collection.py", line 200, in run
    return self._sess.run(output_names, input_feed, run_options)
TypeError: run(): incompatible function arguments. The following argument types are supported:
    1. (self: onnxruntime.capi.onnxruntime_pybind11_state.InferenceSession, arg0: List[str], arg1: Dict[str, object], arg2: onnxruntime.capi.onnxruntime_pybind11_state.RunOptions) -> List[object]

Invoked with: <onnxruntime.capi.onnxruntime_pybind11_state.InferenceSession object at 0x7f5e26b0d670>, 'output', {'data': array([[[[184., 184., 184., ..., 167., 167., 167.],
         [184., 184., 184., ..., 167., 167., 167.],
         [183., 183., 184., ..., 169., 169., 169.],
         ...,
         [243., 243., 243., ..., 254., 254., 254.],
         [243., 243., 243., ..., 255., 255., 255.],
         [243., 243., 243., ..., 255., 255., 255.]],

        [[196., 196., 196., ..., 178., 178., 178.],
         [196., 196., 196., ..., 178., 178., 178.],
         [196., 196., 196., ..., 179., 179., 179.],
         ...,
         [251., 251., 251., ..., 254., 255., 255.],
         [251., 251., 251., ..., 255., 255., 255.],
         [251., 251., 251., ..., 255., 255., 255.]],

        [[176., 176., 176., ..., 174., 175., 175.],
         [176., 176., 176., ..., 174., 175., 175.],
         [176., 176., 176., ..., 174., 175., 175.],
         ...,
         [249., 249., 249., ..., 254., 255., 255.],
         [250., 250., 250., ..., 255., 255., 255.],
         [250., 250., 250., ..., 255., 255., 255.]]]], dtype=float32)}, None

It seems that I missed a argument for model.run. But how I set it?

I did inference on Image Quality Assessment models and got proper output. So the main part of code is correct.

Thanks in advance.


问:
get location from center in snake sort
I made a game that can buy a house per user.

if user buy a house, save user index in db.

For example, It's db.

Index
PlayerUUID

1
UUID_1

2
UUID_2

3
UUID_3

n
UUID_n

so, I need the distance between (0, 0) and user index.

For Example, User Index is 1, the output is (0, 0)

```<code>[
  [1]
]
</code>```

For Example, User Index is 10, the output is (-1, -2)

because index of 10 is [3][0], index of 1(center) is [1, 1] ==> index of 1 - index of 10 ==> (1, 1) - (3, 0) ==> (-3, -1)

```<code>[
  [7, 6, 5, 16]
  [8, 1, 4, 15]
  [9, 2, 3, 14]
  [10, 11, 12, 13]
]
</code>```

For Example, User Index is 17, the output is (2, 2)

because index of 17 is [0][4], index of 1(center) is [2, 2] ==> index of 1 - index of 17 ==> (2, 2) - (0, 4) ==> (2, 2)

```<code>[
  [21, 20, 19, 18, 17, 36]
  [22, 7, 6, 5, 16, 35]
  [23, 8, 1, 4, 15, 34]
  [24, 9, 2, 3, 14, 33]
  [25, 10, 11, 12, 13, 32]
  [26, 27, 28, 29, 30, 31]
]
</code>```

I tried . :

int n = (int) Math.ceil(Math.sqrt(index));

int[][] arr = new int[n][n];

int a = 0, b = 0, c = n-1, d = n-1;
int num = (int) Math.pow(n, 2);

while (num > 0) {
  for (int i = b; num > 0 && i <= d; i++)
    arr[i][c] = num--;
  c--;

  for (int i = c; num > 0 && i >= a; i--)
    arr[d][i] = num--;
  d--;

  for (int i = d; num > 0 && i >= b; i--)
    arr[i][a] = num--;
  a++;

  for (int i = a; num > 0 && i <= c; i++)
    arr[b][i] = num--;
  b++;
}

int center = Math.max(n / 2 - (n % 2 == 1 ? 0 : 1), 0);
```

Title: get location from center in snake sort

Body:
I made a game that can buy a house per user.

if user buy a house, save user index in db.

For example, It's db.

Index
PlayerUUID

1
UUID_1

2
UUID_2

3
UUID_3

n
UUID_n

so, I need the distance between (0, 0) and user index.

For Example, User Index is 1, the output is (0, 0)

[
  [1]
]

For Example, User Index is 10, the output is (-1, -2)

because index of 10 is [3][0], index of 1(center) is [1, 1] ==> index of 1 - index of 10 ==> (1, 1) - (3, 0) ==> (-3, -1)

[
  [7, 6, 5, 16]
  [8, 1, 4, 15]
  [9, 2, 3, 14]
  [10, 11, 12, 13]
]

For Example, User Index is 17, the output is (2, 2)

because index of 17 is [0][4], index of 1(center) is [2, 2] ==> index of 1 - index of 17 ==> (2, 2) - (0, 4) ==> (2, 2)

[
  [21, 20, 19, 18, 17, 36]
  [22, 7, 6, 5, 16, 35]
  [23, 8, 1, 4, 15, 34]
  [24, 9, 2, 3, 14, 33]
  [25, 10, 11, 12, 13, 32]
  [26, 27, 28, 29, 30, 31]
]

I tried . :

int n = (int) Math.ceil(Math.sqrt(index));

int[][] arr = new int[n][n];

int a = 0, b = 0, c = n-1, d = n-1;
int num = (int) Math.pow(n, 2);

while (num > 0) {
  for (int i = b; num > 0 && i <= d; i++)
    arr[i][c] = num--;
  c--;

  for (int i = c; num > 0 && i >= a; i--)
    arr[d][i] = num--;
  d--;

  for (int i = d; num > 0 && i >= b; i--)
    arr[i][a] = num--;
  a++;

  for (int i = a; num > 0 && i <= c; i++)
    arr[b][i] = num--;
  b++;
}

int center = Math.max(n / 2 - (n % 2 == 1 ? 0 : 1), 0);


问:
Clion show wrong inferred type in Quick Documentation popup

The type of variable C should be int, but CLion infers the type as short in Quick Documentation popup.

Is there a way to change this setting?


问:
Incompatibile Input Size Tensorflow and
I cannot train my model properly. I have created dataset:

```<code>INPUT_SHAPE: Tuple[int] = (128, 128, 3)

def decode_img(path: str, filename: str) -> tf.Tensor:
    full_path: str = os.path.join(IMAGES_PATH, filename)
    img = tf.io.decode_jpeg(tf.io.read_file(full_path), channels=3)
    return tf.image.resize(img, INPUT_SHAPE[:2])

images: List[tf.Tensor] = [decode_img(IMAGES_PATH, filename) for filename in os.listdir(IMAGES_PATH)]
means: List[float] = ...
weights: List[float] = ...

ds: tf.data.Dataset = tf.data.Dataset.from_tensor_slices((images, means, weights)).shuffle(SEED)

train_dataset = ds.skip(int(IMAGE_COUNT*VAL_SPLIT))

model: keras.models = keras.models.Sequential([
    tf.keras.layers.InputLayer(input_shape=INPUT_SHAPE),
    tf.keras.layers.Conv2D(filters=16, kernel_size=(5, 5), activation='relu'),
...)

model.compile(...)

history = model.fit(
    train_dataset,
    batch_size=BATCH_SIZE,
    epochs=10,
    validation_data=val_dataset,
    )
</code>```

but still getting error like that:

```<code>ValueError: Input 0 of layer "sequential_2" is incompatible with the layer: expected shape=(None, 128, 128, 3), found shape=(128, 128, 3)
</code>```

while I try to set BATCH_SIZE inside dataset constructor:

```<code>ds: tf.data.Dataset = tf.data.Dataset.from_tensor_slices((images, means, weights)).shuffle(SEED).batch(BATCH_SIZE)
</code>```

I got error:

```<code>ValueError: Unexpected result of `train_function` (Empty logs). Please use `Model.compile(..., run_eagerly=True)`, or `tf.config.run_functions_eagerly(True)` for more information of where went wrong, or file a issue/bug to `tf.keras`.
</code>```

Both cases: with BATCH_SIZE set inside .fit() function and without the error is the same.

How can I solve this problem?

Title: Incompatibile Input Size Tensorflow and

Body:
I cannot train my model properly. I have created dataset:

INPUT_SHAPE: Tuple[int] = (128, 128, 3)

def decode_img(path: str, filename: str) -> tf.Tensor:
    full_path: str = os.path.join(IMAGES_PATH, filename)
    img = tf.io.decode_jpeg(tf.io.read_file(full_path), channels=3)
    return tf.image.resize(img, INPUT_SHAPE[:2])

images: List[tf.Tensor] = [decode_img(IMAGES_PATH, filename) for filename in os.listdir(IMAGES_PATH)]
means: List[float] = ...
weights: List[float] = ...

ds: tf.data.Dataset = tf.data.Dataset.from_tensor_slices((images, means, weights)).shuffle(SEED)

train_dataset = ds.skip(int(IMAGE_COUNT*VAL_SPLIT))

model: keras.models = keras.models.Sequential([
    tf.keras.layers.InputLayer(input_shape=INPUT_SHAPE),
    tf.keras.layers.Conv2D(filters=16, kernel_size=(5, 5), activation='relu'),
...)

model.compile(...)

history = model.fit(
    train_dataset,
    batch_size=BATCH_SIZE,
    epochs=10,
    validation_data=val_dataset,
    )

but still getting error like that:

ValueError: Input 0 of layer "sequential_2" is incompatible with the layer: expected shape=(None, 128, 128, 3), found shape=(128, 128, 3)

while I try to set BATCH_SIZE inside dataset constructor:

ds: tf.data.Dataset = tf.data.Dataset.from_tensor_slices((images, means, weights)).shuffle(SEED).batch(BATCH_SIZE)

I got error:

ValueError: Unexpected result of `train_function` (Empty logs). Please use `Model.compile(..., run_eagerly=True)`, or `tf.config.run_functions_eagerly(True)` for more information of where went wrong, or file a issue/bug to `tf.keras`.

Both cases: with BATCH_SIZE set inside .fit() function and without the error is the same.

How can I solve this problem?


问:
POST JSON over CURL with basic authentication(windows os)
I tried to use below command to call api data.
It would be successful on linux os.
But in windows os,it showed 400 Bad Request.

your textcmd:
your textcurl --basic -u CDPdashboard:J_p2LdUs5ipLkaJ3prum -X POST -H "Content-Type: application/json" -d '{"showYear":"2022","showID":"QE"}' http://uatapiw.mytts.tw/service/api/v1/visitor

your textwindows os outcome:
your text
your text400 Bad Request
your text
Bad Request

your text
The browser (or proxy) sent a request that this server could not understand.

what's the problem that I didn't notice?


问:
How do I write a complex type safe composer function in typescript, and returns a Component with composed props and a hook
I have some simple logic here, however i can't wrap my head around typescript.

I have the following interfaces

```<code>interface Data<RecordType extends {}> {
  records: RecordType[];
}

enum DefaultActions {
  READ = "READ",
  WRITE = "WRITE",
}

type DefaultActionType =
  | {
      type: DefaultActions.READ;
    }
  | {
      type: DefaultActions.WRITE;
      payload: Record<string, any>;
    };

interface DataSourceObject<
  RecordType extends {},
  ActionType extends DefaultActionType,
  ReturnType,
  StateType extends Data<RecordType>,
  PropsType
> {
  props: PropsType;
  reducer?: (state: StateType, action: ActionType) => StateType;
  actionCreator: ActionCreatorType<
    RecordType,
    ActionType,
    ReturnType,
    StateType,
    PropsType
  >;
}

type ActionCreatorType<
  RecordType extends {},
  ActionType extends DefaultActionType,
  ReturnType,
  StateType extends Data<RecordType>,
  PropsType
> = (
  props: PropsType,
  state: StateType,
  dispatch: (action: ActionType) => void
) => ReturnType;

type FooActions = { type: "SET_FOOLISH"; payload: { isFoolish: true } };

type FooProps = {
  isFoo: boolean;
  foo: boolean;
  fooTable: string[];
  food: string;
  fooLish: boolean;
};

type FooReturns = {
  isFoo: boolean,
  hasFood: boolean,
  setFoolish: (isFoolish: boolean) => void;
};

const foo = {
  props: {
    isFoo: true,
    foo: true,
    fooTable: [],
    food: "string",
    fooLish: false,
  } as FooProps,
  reducer: <RecordType extends {}>(
    state: FooProps & Data<RecordType>,
    action: FooActions
  ) => {
    // DO SOME JAVASCRIPT MAGIC...
    return state;
  },
  actionCreator: <RecordType extends {},>(
    props: FooProps,
    state: FooProps & Data<RecordType>,
    dispatch
  ) => {
    return {
      isFoo: props.isFoo,

      hasFood: false,
      setFoolish: (isFoolish) => {
        dispatch({ type: "SET_FOOLISH", payload: { isFoolish } });
      },
    } as FooReturns;
  },
};

type BarProps = {
  isBar: boolean;
  barTable: number[];
  barPress: number;
  barTender: string;
  barStool: boolean;
};

type BarReturns = {
  isBar: boolean;
  setBarPress: (isBar: boolean) => void;
  getBarTender: (barTender: string) => void;
  setBarStool: (barStool: boolean) => void;
};

const bar = {
  props: {
    isBar: true,
    barTable: [],
    barPress: 10,
    barTender: "",
    barStool: false,
  } as BarProps,
  actionCreator: <RecordType extends {}>(
    props: BarProps,
    state: BarProps & Data<RecordType>,
    dispatch
  ) => {
    return {
      isBar: props.isBar,
      setBarPress(isBar) {
        dispatch({ type: "SET_FOOLISH", payload: { isBar } });
      },
      getBarTender(barTender) {
        dispatch({ type: "SET_BAR_TENDER", payload: { barTender } });
      },
      setBarStool(barStool) {
        dispatch({ type: "SET_BAR_STOOL", payload: { barStool } });
      },
    } as BarReturns;
  },
};
</code>```

As you can see, the interfaces for props, reducers and actionCreators are all different.

I have a composer function that takes an array of DataSources and returns a Component and a hook.

```<code>const createDataSource = <
  RecordType extends {},
  DS extends DataSourceObject<RecordType, {}, {}, {}, {}>
>(
  dataSources: DS[]
) => {
  return {

    // expect props to be BarProps && FooProps
    Component: (props) => null,
    Hook: () => {},
  };
};
</code>```

And here's how I want to use it.

```<code>const {Component} = createDataSource([foo, bar]);

const App = () => {
  return <Component isBar isFoo isFoolish />
}

</code>```

Now, coming to the question;
How do I create my types/interfaces such that

The props for the component is an intersection of PropTypes.

The return value of the Hook is an intersection of the ReturnTypes.

How do I make all of this a proper generic such that I can declare foo to be of a particular type, and createDataSource accepts it in the array.

The problem I face at the moment is.

While the code works like a charm, type-safety is entirely broken.

I want this to be a part of a project I would like to open source, but once it is ready.

Any help with advanced typescript would be really welcome

I have tried looking at inferring the type of props, and extracting the argument types etc.

I keep getting stuck with Generics.

Body:
I have some simple logic here, however i can't wrap my head around typescript.

I have the following interfaces

interface Data<RecordType extends {}> {
  records: RecordType[];
}

enum DefaultActions {
  READ = "READ",
  WRITE = "WRITE",
}

type DefaultActionType =
  | {
      type: DefaultActions.READ;
    }
  | {
      type: DefaultActions.WRITE;
      payload: Record<string, any>;
    };

interface DataSourceObject<
  RecordType extends {},
  ActionType extends DefaultActionType,
  ReturnType,
  StateType extends Data<RecordType>,
  PropsType
> {
  props: PropsType;
  reducer?: (state: StateType, action: ActionType) => StateType;
  actionCreator: ActionCreatorType<
    RecordType,
    ActionType,
    ReturnType,
    StateType,
    PropsType
  >;
}

type ActionCreatorType<
  RecordType extends {},
  ActionType extends DefaultActionType,
  ReturnType,
  StateType extends Data<RecordType>,
  PropsType
> = (
  props: PropsType,
  state: StateType,
  dispatch: (action: ActionType) => void
) => ReturnType;

type FooActions = { type: "SET_FOOLISH"; payload: { isFoolish: true } };

type FooProps = {
  isFoo: boolean;
  foo: boolean;
  fooTable: string[];
  food: string;
  fooLish: boolean;
};

type FooReturns = {
  isFoo: boolean,
  hasFood: boolean,
  setFoolish: (isFoolish: boolean) => void;
};

const foo = {
  props: {
    isFoo: true,
    foo: true,
    fooTable: [],
    food: "string",
    fooLish: false,
  } as FooProps,
  reducer: <RecordType extends {}>(
    state: FooProps & Data<RecordType>,
    action: FooActions
  ) => {
    // DO SOME JAVASCRIPT MAGIC...
    return state;
  },
  actionCreator: <RecordType extends {},>(
    props: FooProps,
    state: FooProps & Data<RecordType>,
    dispatch
  ) => {
    return {
      isFoo: props.isFoo,

      hasFood: false,
      setFoolish: (isFoolish) => {
        dispatch({ type: "SET_FOOLISH", payload: { isFoolish } });
      },
    } as FooReturns;
  },
};

type BarProps = {
  isBar: boolean;
  barTable: number[];
  barPress: number;
  barTender: string;
  barStool: boolean;
};

type BarReturns = {
  isBar: boolean;
  setBarPress: (isBar: boolean) => void;
  getBarTender: (barTender: string) => void;
  setBarStool: (barStool: boolean) => void;
};

const bar = {
  props: {
    isBar: true,
    barTable: [],
    barPress: 10,
    barTender: "",
    barStool: false,
  } as BarProps,
  actionCreator: <RecordType extends {}>(
    props: BarProps,
    state: BarProps & Data<RecordType>,
    dispatch
  ) => {
    return {
      isBar: props.isBar,
      setBarPress(isBar) {
        dispatch({ type: "SET_FOOLISH", payload: { isBar } });
      },
      getBarTender(barTender) {
        dispatch({ type: "SET_BAR_TENDER", payload: { barTender } });
      },
      setBarStool(barStool) {
        dispatch({ type: "SET_BAR_STOOL", payload: { barStool } });
      },
    } as BarReturns;
  },
};

As you can see, the interfaces for props, reducers and actionCreators are all different.

I have a composer function that takes an array of DataSources and returns a Component and a hook.

const createDataSource = <
  RecordType extends {},
  DS extends DataSourceObject<RecordType, {}, {}, {}, {}>
>(
  dataSources: DS[]
) => {
  return {

    // expect props to be BarProps && FooProps
    Component: (props) => null,
    Hook: () => {},
  };
};

And here's how I want to use it.

const {Component} = createDataSource([foo, bar]);

const App = () => {
  return <Component isBar isFoo isFoolish />
}

Now, coming to the question;
How do I create my types/interfaces such that

The props for the component is an intersection of PropTypes.

The return value of the Hook is an intersection of the ReturnTypes.

How do I make all of this a proper generic such that I can declare foo to be of a particular type, and createDataSource accepts it in the array.

The problem I face at the moment is.

While the code works like a charm, type-safety is entirely broken.

I want this to be a part of a project I would like to open source, but once it is ready.

Any help with advanced typescript would be really welcome

I have tried looking at inferring the type of props, and extracting the argument types etc.

I keep getting stuck with Generics.


问:
How to handle a overlapped data in node.js
When I was running this code I have some problems with data overlapped and it only displayed the last data in multiple outputs

```<code>      const options = {
        host: 'jsonplaceholder.typicode.com',
        path: '/users?_limit=2',
        method: 'Get',
        headers: {
          'Accept': 'application/json'
        }
      };
      let request = https.request(options, (res) => {
        statusCodeMessages = [res.statusCode, res.statusMessage];
        codes = res.statusCode;
        messages = res.statusMessage;
        statusCode = codes;
        statusCodeMessage = codes + ' ' +messages;
        console.log('Result 1:', statusCode);
        if (res.statusCode !== 200) {
          console.error(`Did not get an OK from the server. Code: ${res.statusCode}`);
          res.resume();
          return;
        }
        let data = '';
        res.on('data', (chunk) => {
          data += chunk;
          httpDataRecevied = data;
          console.log('Data Recevied:', httpDataRecevied);
          console.log('Result 2:', statusCode);
        });
        res.on('close', () => {
          console.log('Retrieved all data');
          console.log(JSON.parse(data));
        });
        console.log('Result 3:', statusCode);
      });
      request.end();
      request.on('error', (err) => {
        console.error(`Encountered an error trying to make a request: ${err.message}`);
      });
    }
 setTimeout(() => {
   if(statusCode > 199 && statusCode < 209){
        pfeDatas = 'Pass';
        testCasePass++;
        console.log('TestCase Is Pass:', pfeDatas)
      }
      else if(statusCode > 399 && statusCode < 600){
        pfeDatas = 'Failed';
        testCaseFail++;
        console.log('TestCase Is Failed:', pfeDatas)
      }
      else{
        pfeDatas = 'Error';
        testCaseError++;
        console.log('TestCase Is Error:', pfeDatas)
      }

      httpDataRequire = {statusCodeMessage, pfeDatas};
      console.log(httpDataRequire);
},"2000")
</code>```

enter image description here
HTTP communication with node.js
displayed the last data in multiple output one data one results....

Body:
When I was running this code I have some problems with data overlapped and it only displayed the last data in multiple outputs

      const options = {
        host: 'jsonplaceholder.typicode.com',
        path: '/users?_limit=2',
        method: 'Get',
        headers: {
          'Accept': 'application/json'
        }
      };
      let request = https.request(options, (res) => {
        statusCodeMessages = [res.statusCode, res.statusMessage];
        codes = res.statusCode;
        messages = res.statusMessage;
        statusCode = codes;
        statusCodeMessage = codes + ' ' +messages;
        console.log('Result 1:', statusCode);
        if (res.statusCode !== 200) {
          console.error(`Did not get an OK from the server. Code: ${res.statusCode}`);
          res.resume();
          return;
        }
        let data = '';
        res.on('data', (chunk) => {
          data += chunk;
          httpDataRecevied = data;
          console.log('Data Recevied:', httpDataRecevied);
          console.log('Result 2:', statusCode);
        });
        res.on('close', () => {
          console.log('Retrieved all data');
          console.log(JSON.parse(data));
        });
        console.log('Result 3:', statusCode);
      });
      request.end();
      request.on('error', (err) => {
        console.error(`Encountered an error trying to make a request: ${err.message}`);
      });
    }
 setTimeout(() => {
   if(statusCode > 199 && statusCode < 209){
        pfeDatas = 'Pass';
        testCasePass++;
        console.log('TestCase Is Pass:', pfeDatas)
      }
      else if(statusCode > 399 && statusCode < 600){
        pfeDatas = 'Failed';
        testCaseFail++;
        console.log('TestCase Is Failed:', pfeDatas)
      }
      else{
        pfeDatas = 'Error';
        testCaseError++;
        console.log('TestCase Is Error:', pfeDatas)
      }

      httpDataRequire = {statusCodeMessage, pfeDatas};
      console.log(httpDataRequire);
},"2000")

enter image description here
HTTP communication with node.js
displayed the last data in multiple output one data one results....


问:
I have an image file of fractures in the subsurface. How do I create higher order fractal images from the starting image
I have an image of subsurface fractures. How do I classify it as a fractal and how to create higher order fractal image from this image

I tyried meg noah's code to see if it is a fractal. I am getting fractal dimension of 3. I want to create higher order fractals


问:
HDFS partition data reading in most optimal way
I have this 2 cases one with 4 partitons and another with 5 partition each partition is size of 10 GB. I just wanted to understand which case would be most optimal way to reading dat and what will the reason behind it?

I belive the smaller partion is the optimal to read it as it will scan the data more efficiently. therefore case 2 is most optimal way. however, i am looking forward to your input.

**Case-1:** A HDFS file of 10 TB with 4 partitions each with 2.5 TB

**Case-2:** A HDFS file of 10 TB with 5 partitions having splits of 3 TB , 3 TB, 2 TB, 1 TB & 1 TB

Out of the above 2 cases, which one would be more optimal reading data in spark/pyspark and why ?


问:
unable to extract very large zip files in elfinder
Extracting 2gb+ zip file gives error:
Unable to extract files from "user/file.zip".
Archive files exceeds maximum allowed size.

This is not happening with smaller zip files. I tried extracting 666mb zip file and did not face it.

This is happening only with very large zip files. What can be a proper solution for this?


问:
Tensorflow Keras does not learn properly when a data generator is used
I am trying to get Keras to classify pcitures into 2 catagories. When I use a generator, Keras gives very unexpected results. I wonder if I am doing something wrong with my generator.

Here is my generator code.

```<code>def generator(training, labels, batch_size):
     # Create empty arrays to contain batch of features and labels#
     batch_training = np.empty((batch_size, 472,696)) #(472,696) is my image's dimension
     batch_labels = np.zeros((batch_size,1))
     while True:
       for i in range(batch_size):
         # choose random index in the training set
         ID= np.random.choice(training,1)
         index= training.index(ID)

         batch_training[i] = np.load('data/' + ID[0] + '.npy')
         batch_labels[i] = labels[index]
       yield batch_training, batch_labels
</code>```

Here is how I set up my model

```<code>model = tf.keras.Sequential([
    tf.keras.layers.Flatten(input_shape=(472,696)),#flatten the data
    tf.keras.layers.Dense(128, activation='relu'),#decide how many neurons to use
    #tf.keras.layers.Dense(1, activation='sigmoid'),
    tf.keras.layers.Dense(2)])#how many classes you have

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])
model.fit_generator(generator(train, label, 900), steps_per_epoch=3, epochs=3)
</code>```

My total sample is about 3000 images.
After training I get this:

Epoch 1/3
3/3 [==============================] - 9s 4s/step - loss: 128101.8516 - accuracy: 0.6667

Epoch 2/3
3/3 [==============================] - 10s 3s/step - loss: 62697.7500 - accuracy: 0.3333

Epoch 3/3
3/3 [==============================] - 10s 3s/step - loss: 43824.9883 - accuracy: 0.0000e+00

I have tried different a batchsize as well
model.fit_generator(generator(train, label, 200), steps_per_epoch=12, epochs=6)

Epoch 1/6
12/12 [==============================] - 10s 831ms/step - loss: 56976.1016 - accuracy: 0.3333

Epoch 2/6
12/12 [==============================] - 10s 816ms/step - loss: 562.3458 - accuracy: 0.9162

Epoch 3/6
12/12 [==============================] - 10s 818ms/step - loss: 0.6935 - accuracy: 1.0000

Epoch 4/6
12/12 [==============================] - 10s 806ms/step - loss: 0.6933 - accuracy: 1.0000

Epoch 5/6
12/12 [==============================] - 10s 844ms/step - loss: 0.6933 - accuracy: 1.0000

Epoch 6/6
12/12 [==============================] - 10s 817ms/step - loss: 0.6935 - accuracy: 1.0000

Then the problem becomes the model saying accuracy is 1. Even though it was clearly not the case when I use the model on some of the images.

If I load 3000 images altogether without using a generator, I would get something much more sensible.

Am I doing something wrong with the generator?

Body:
I am trying to get Keras to classify pcitures into 2 catagories. When I use a generator, Keras gives very unexpected results. I wonder if I am doing something wrong with my generator.

Here is my generator code.

def generator(training, labels, batch_size):
     # Create empty arrays to contain batch of features and labels#
     batch_training = np.empty((batch_size, 472,696)) #(472,696) is my image's dimension
     batch_labels = np.zeros((batch_size,1))
     while True:
       for i in range(batch_size):
         # choose random index in the training set
         ID= np.random.choice(training,1)
         index= training.index(ID)

         batch_training[i] = np.load('data/' + ID[0] + '.npy')
         batch_labels[i] = labels[index]
       yield batch_training, batch_labels

Here is how I set up my model

model = tf.keras.Sequential([
    tf.keras.layers.Flatten(input_shape=(472,696)),#flatten the data
    tf.keras.layers.Dense(128, activation='relu'),#decide how many neurons to use
    #tf.keras.layers.Dense(1, activation='sigmoid'),
    tf.keras.layers.Dense(2)])#how many classes you have

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])
model.fit_generator(generator(train, label, 900), steps_per_epoch=3, epochs=3)

My total sample is about 3000 images.
After training I get this:

Epoch 1/3
3/3 [==============================] - 9s 4s/step - loss: 128101.8516 - accuracy: 0.6667

Epoch 2/3
3/3 [==============================] - 10s 3s/step - loss: 62697.7500 - accuracy: 0.3333

Epoch 3/3
3/3 [==============================] - 10s 3s/step - loss: 43824.9883 - accuracy: 0.0000e+00

I have tried different a batchsize as well
model.fit_generator(generator(train, label, 200), steps_per_epoch=12, epochs=6)

Epoch 1/6
12/12 [==============================] - 10s 831ms/step - loss: 56976.1016 - accuracy: 0.3333

Epoch 2/6
12/12 [==============================] - 10s 816ms/step - loss: 562.3458 - accuracy: 0.9162

Epoch 3/6
12/12 [==============================] - 10s 818ms/step - loss: 0.6935 - accuracy: 1.0000

Epoch 4/6
12/12 [==============================] - 10s 806ms/step - loss: 0.6933 - accuracy: 1.0000

Epoch 5/6
12/12 [==============================] - 10s 844ms/step - loss: 0.6933 - accuracy: 1.0000

Epoch 6/6
12/12 [==============================] - 10s 817ms/step - loss: 0.6935 - accuracy: 1.0000

Then the problem becomes the model saying accuracy is 1. Even though it was clearly not the case when I use the model on some of the images.

If I load 3000 images altogether without using a generator, I would get something much more sensible.

Am I doing something wrong with the generator?


问:
languages, pumping-lemma and myhill-nerode-equivalence-classes
Is it possible that a context-free-language has infinite myhill-nerode-classes or is there a way to narrow down (in terms of chomsky hierachy) which kind of classes can or can't have infinite myhill-nerode-classes?

I have a problem where I should show via the pumping-lemma for context-free languages that the language a^(3n+2)$b^(3n+2) with the alphabet {a,b,$} has infinite myhill-nerode-equivalence-classes.


问:
Is there any endpoint of NSE API which gives Technical Indicators as JSON output?
I have been using https://www.nseindia.com/api/quote-equity?symbol=ABB endpoint for getting basic details of a stock symbol.

I have requirement of Technical Indicators such as RSI, MACD etc. Any help would be appreciated..


问:
Django For Loop messing with Javascript ID
I am trying to make a page that shows multiple social media posts on 1 page. Through using a for loop using the Django template tag, I was able to cycle through the posts and they all showed up on the page. However, I have an image slideshow through each post. While the for loop runs, it keeps the same Javascript names for each post. Thus, only the first post is identified and the left and right arrows only work on the first post. I am new to programming and this is my first time. Any help is appreciated. I found a very similar problem here but I am struggling to apply it to my own code.</p>
```<code>

{% for e in social_info %}

<div class="testimonial-box"
style=" display: block; margin-left: auto; margin-right: auto; width: 530px; height: 655px; margin-top: 60px; box-shadow: 1px 1px 5px; border-radius: 10px; ">

<!-- <div style="margin-top: -20px;"> -->
                        <div class="profile-img">
                            <img src="static/images/profile.png" />
                        </div>

<div>

<h3 style="font-weight: bold; float: left; margin-left: 60px; margin-top:-45px; max-width: 50px; text-transform: none; letter-spacing: 1px;"> @{{e.username}} </h3>

<h5 style="float: left; margin-left: 65px; margin-top: -20px; color: black;"> {{e.created_at}} </h5>

</div>

    <!-- start of partial -->

<script>
function Slider() {
    const carouselSlides = document.querySelectorAll('.slide');
    const btnPrev = document.querySelector('.prev');
    const btnNext = document.querySelector('.next');
    const dotsSlide = document.querySelector('.dots-container');
    let currentSlide = 0;

    const activeDot = function (slide) {
        document.querySelectorAll('.dot').forEach(dot => dot.classList.remove('active'));
        document.querySelector(`.dot[data-slide="${slide}"]`).classList.add('active');
    };
    activeDot(currentSlide);

    const changeSlide = function (slides) {
        carouselSlides.forEach((slide, index) => (slide.style.transform = `translateX(${100 * (index - slides)}%)`));
    };
    changeSlide(currentSlide);

    btnNext.addEventListener('click', function () {
        currentSlide++;
        if (carouselSlides.length - 1 < currentSlide) {
            currentSlide = 0;
        };
        changeSlide(currentSlide);
        activeDot(currentSlide);
});
    btnPrev.addEventListener('click', function () {
        currentSlide--;
        if (0 >= currentSlide) {
            currentSlide = 0;
        };
        changeSlide(currentSlide);
        activeDot(currentSlide);
    });

    dotsSlide.addEventListener('click', function (e) {
        if (e.target.classList.contains('dot')) {
            const slide = e.target.dataset.slide;
            changeSlide(slide);
            activeDot(slide);
        }
    });
  };
Slider();

</script>

    <div class="slider" style="width: 450px; height: 430px; margin-top: 15px; border-radius:20px;">

{%if e.image1 %}
      <div class="slide">
            <img src="{{e.image1}}" alt="Photo1"/>
        </div>
{% endif %}

{%if e.image2 %}
      <div class="slide">
            <img src="{{e.image2}}" alt="Photo2"/>
        </div>
{% endif %}

{%if e.image3 %}
      <div class="slide">
            <img src="{{e.image3}}" alt="Photo3"/>
        </div>
{% endif %}

{%if e.image4 %}
      <div class="slide">
            <img src="{{e.image4}}" alt="Photo4"/>
        </div>
{% endif %}

{%if e.image5 %}
      <div class="slide">
            <img src="{{e.image5}}" alt="Photo5"/>
        </div>
{% endif %}

{%if e.image2 %} <!-- If there is more than 1 image  -->

        <!-- Left and Right buttons -->

        <button class="btn-slide prev"><i class="fas fa-3x fa-chevron-circle-left"></i></button>
        <button class="btn-slide next"><i class="fas fa-3x fa-chevron-circle-right"></i></button>
{% endif %}
    </div>

  <!-- Slider dots -->
    <div class="dots-container">

{%if e.image1 %}
            <span class="dot active" data-slide="0"></span>
{% endif %}

{%if e.image2 %}
            <span class="dot" data-slide="1"></span>
{% endif %}

{%if e.image3 %}
            <span class="dot" data-slide="2"></span>
{% endif %}

{%if e.image4 %}
            <span class="dot" data-slide="3"></span>
{% endif %}

{%if e.image5 %}
            <span class="dot" data-slide="4"></span>
{% endif %}

    </div>

<!-- end of partial -->

<!-- Caption  -->
<h4 style="margin-top: 15px;  text-transform: none; text-align: center; font-size: 18.12px; letter-spacing: 1px;"> {{e.caption}} </h4>

<h5 style="margin-top: 25px;  text-transform: none; text-align: left; word-spacing: auto;">View all 53 comments</h5>

<h5 style="margin-top: -25px;  text-transform: none; text-align: right; word-spacing: auto; margin-right: 30px">{{e.likes}} Likes </h5>

<button type="button" class="favorite-button" style="margin-top: -30px; float:right; margin-right:20px">
  <i class="fas fa-heart favorite__icon favorite--enable"></i>
  <i class="far fa-heart favorite__icon favorite--not"></i></button>

</div>

  {% endfor %}
</code>```

Body:
I am trying to make a page that shows multiple social media posts on 1 page. Through using a for loop using the Django template tag, I was able to cycle through the posts and they all showed up on the page. However, I have an image slideshow through each post. While the for loop runs, it keeps the same Javascript names for each post. Thus, only the first post is identified and the left and right arrows only work on the first post. I am new to programming and this is my first time. Any help is appreciated. I found a very similar problem here but I am struggling to apply it to my own code.

{% for e in social_info %}

 @{{e.username}}

 {{e.created_at}}

{%if e.image1 %}

{% endif %}

{%if e.image2 %}

{% endif %}

{%if e.image3 %}

{% endif %}

{%if e.image4 %}

{% endif %}

{%if e.image5 %}

{% endif %}

{%if e.image2 %}

        <button class="btn-slide prev"></button>
        <button class="btn-slide next"></button>
{% endif %}

{%if e.image1 %}

{% endif %}

{%if e.image2 %}

{% endif %}

{%if e.image3 %}

{% endif %}

{%if e.image4 %}

{% endif %}

{%if e.image5 %}

{% endif %}

 {{e.caption}}

View all 53 comments

{{e.likes}} Likes

<button type="button" class="favorite-button" style="margin-top: -30px; float:right; margin-right:20px">

  </button>

  {% endfor %}


问:
How do I convert VueJS to static HTML file?
I want to convert a simple VueJS file to static HTML and host it on an S3 bucket.

How can I make this conversion?


问:
Group by in PostgreSQL with Sequelize
I am using Sequelize.js and PostgreSQL in a Node.js app, and I have a problem with grouping my result after joining several tables. As you probably know in Postgres I have to set all my fields in "Group By" or "Aggregate function" but after joining tables I have more than 50 attributes.

I found this solution to set an empty array for attributes but my joins did not work.
Is there any solution?

Title: Group by in PostgreSQL with Sequelize


问:
Starting kiosk application without any navigation bar or status bar while booting
I have an application for unattended use to develop on android device which needs to start when the device boots, now i have already created my app as an launcher but before my app starts i still can see navigation bar. In that moment when the nav bar is present user can still click on nav bar or pull the status bar down and make mess on the device.

Is there any programtical or configurational way to prevent any use until the launcher app starts ?

What i am trying to achieve is that ALL user interaction is disabled until the app is started, meaning not malicius intent from user is possible.

Are there any good aproaches for solving this?

With kind regards!


问:
What is the best way to put back all entries in rte_mempool in one go
I am using a mempool in my dpdk app to store values that are periodically emitted to an external server. Everytime the values are emitted I want to replenish the complete mempool. What is the best wat to put back all elements as available to the mempool?</p>


问:
navigator.getBattery() not working on S3 static website
Normally in Chrome I can get the battery level by doing something like

```<code>navigator.getBattery().then((battery) => {
    console.log(battery.level)
})
</code>```

This works fine when testing with a local file and on other websites, however, when I try to do this on an S3 static website it gives me this error: Uncaught TypeError: navigator.getBattery is not a function. This is in Chrome which supports the getBattery method. The only difference is that it is on an S3 static website. Why is this method not found when hosting on S3?

Body:
Normally in Chrome I can get the battery level by doing something like

navigator.getBattery().then((battery) => {
    console.log(battery.level)
})

This works fine when testing with a local file and on other websites, however, when I try to do this on an S3 static website it gives me this error: Uncaught TypeError: navigator.getBattery is not a function. This is in Chrome which supports the getBattery method. The only difference is that it is on an S3 static website. Why is this method not found when hosting on S3?


问:
flutter nodejs post api
i wanna connect my backend and frontend. but i dont understand flutter code to POST api code. so i dont know what is the problem backend and frontend. i need your help.

```<code>import "./db";
import "./models/Todo";
import express from "express";

const app = express();
const PORT = 3000;

const handleHome = (req, res) => {
  return res.send("Welcome to my Home");
};

const postTodo = async (req, res) => {
  const { title, description } = req.body;
  await Todo.create({
    title,
    description,
  });
  return res.end();
};

app.post("/todo", postTodo);

app.get("/", handleHome);

const handleListening = () => {
  console.log(`✅Server listening on port : http://localhost:${PORT} `);
};

app.listen(PORT, handleListening);
</code>```

that is nodeJS code for server. i wanna get todo by '/todo' that is correct? i use mongodb for database

```<code>import mongoose from "mongoose";

const todoSchema = new mongoose.Schema({
  title: String,
  description: String,
});

const Todo = mongoose.model("Todo", todoSchema);
export default Todo;
</code>```

this is todo model. for mongodb

```<code>import 'dart:convert';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

Future<Todo> createTodo(String title,String description) async{
  final response = await http.post(
    Uri.parse('http://localhost:3000/todo'),
    headers: <String, String>{
    'Content-Type': 'application/json; charset=UTF-8',
  },
    body: jsonEncode(<String, String>{
      'title':title,
      'description' :description,
    }),
  );
  print(response.body);
  if(response.statusCode == 201){
    return Todo.fromJson(jsonDecode(response.body));
  }else{
    throw Exception('Failed to create user');
  }
}

class Todo{
  final String title,description;

  Todo.fromJson(Map<String, dynamic> json):
    title= json['title'],
    description= json['description'];
}

class HomeScreen extends StatelessWidget {
  HomeScreen({super.key});
  TextEditingController _todoController = TextEditingController();
  TextEditingController _desController = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: SafeArea(
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal:20),
            child: Column(
              children: [
                SizedBox(height:60),
                TextFormField(
                  controller:_todoController,
                  decoration:InputDecoration(
                    hintText:'todo',
                    border: OutlineInputBorder(
                      borderSide: BorderSide(
                        color: Colors.black,
                        width: 3
                      )
                    )
                  ),
                ),
                TextFormField(
                  controller:_desController,
                  decoration:InputDecoration(
                    hintText:'todo',
                    border: OutlineInputBorder(
                      borderSide: BorderSide(
                        color: Colors.black,
                        width: 3
                      )
                    )
                  ),
                ),
                ElevatedButton(
                  child: Icon(Icons.arrow_right),
                  onPressed: () {
                    var newTodo = createTodo(_todoController.text,_desController.text);
                    print(newTodo);
                  },
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}

</code>```

this is flutter code. how can i post data in flutter?? that code is correct?

how can i connect this code? i need your help please helpme

error is

```<code>flutter: Instance of 'Future<Todo>'
[VERBOSE-2:dart_vm_initializer.cc(41)] Unhandled Exception: Connection refused
#0      IOClient.send (package:http/src/io_client.dart:88:7)
<asynchronous suspension>
#1      BaseClient._sendUnstreamed (package:http/src/base_client.dart:93:32)
<asynchronous suspension>
#2      _withClient (package:http/http.dart:164:12)
<asynchronous suspension>
#3      createTodo (package:login_app/home_screen.dart:7:20)
<asynchronous suspension>
</code>```

Title: flutter nodejs post api

Body:
i wanna connect my backend and frontend. but i dont understand flutter code to POST api code. so i dont know what is the problem backend and frontend. i need your help.

import "./db";
import "./models/Todo";
import express from "express";

const app = express();
const PORT = 3000;

const handleHome = (req, res) => {
  return res.send("Welcome to my Home");
};

const postTodo = async (req, res) => {
  const { title, description } = req.body;
  await Todo.create({
    title,
    description,
  });
  return res.end();
};

app.post("/todo", postTodo);

app.get("/", handleHome);

const handleListening = () => {
  console.log(`✅Server listening on port : http://localhost:${PORT} `);
};

app.listen(PORT, handleListening);

that is nodeJS code for server. i wanna get todo by '/todo' that is correct? i use mongodb for database

import mongoose from "mongoose";

const todoSchema = new mongoose.Schema({
  title: String,
  description: String,
});

const Todo = mongoose.model("Todo", todoSchema);
export default Todo;

this is todo model. for mongodb

import 'dart:convert';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

Future<Todo> createTodo(String title,String description) async{
  final response = await http.post(
    Uri.parse('http://localhost:3000/todo'),
    headers: <String, String>{
    'Content-Type': 'application/json; charset=UTF-8',
  },
    body: jsonEncode(<String, String>{
      'title':title,
      'description' :description,
    }),
  );
  print(response.body);
  if(response.statusCode == 201){
    return Todo.fromJson(jsonDecode(response.body));
  }else{
    throw Exception('Failed to create user');
  }
}

class Todo{
  final String title,description;

  Todo.fromJson(Map<String, dynamic> json):
    title= json['title'],
    description= json['description'];
}

class HomeScreen extends StatelessWidget {
  HomeScreen({super.key});
  TextEditingController _todoController = TextEditingController();
  TextEditingController _desController = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: SafeArea(
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal:20),
            child: Column(
              children: [
                SizedBox(height:60),
                TextFormField(
                  controller:_todoController,
                  decoration:InputDecoration(
                    hintText:'todo',
                    border: OutlineInputBorder(
                      borderSide: BorderSide(
                        color: Colors.black,
                        width: 3
                      )
                    )
                  ),
                ),
                TextFormField(
                  controller:_desController,
                  decoration:InputDecoration(
                    hintText:'todo',
                    border: OutlineInputBorder(
                      borderSide: BorderSide(
                        color: Colors.black,
                        width: 3
                      )
                    )
                  ),
                ),
                ElevatedButton(
                  child: Icon(Icons.arrow_right),
                  onPressed: () {
                    var newTodo = createTodo(_todoController.text,_desController.text);
                    print(newTodo);
                  },
                )
              ],
            ),
          ),
        ),
      ),
    );
  }
}

this is flutter code. how can i post data in flutter?? that code is correct?

how can i connect this code? i need your help please helpme

error is

flutter: Instance of 'Future<Todo>'
[VERBOSE-2:dart_vm_initializer.cc(41)] Unhandled Exception: Connection refused
#0      IOClient.send (package:http/src/io_client.dart:88:7)
<asynchronous suspension>
#1      BaseClient._sendUnstreamed (package:http/src/base_client.dart:93:32)
<asynchronous suspension>
#2      _withClient (package:http/http.dart:164:12)
<asynchronous suspension>
#3      createTodo (package:login_app/home_screen.dart:7:20)
<asynchronous suspension>


问:
what is this error in NVM jenkins build : ERROR: Failed to fork bash?
I installed nvm-wrapper plugin and set it in my build steps.when I trying to build my angular project the build phase encounter failure and below is console output .what is the problem?</p>
```<code>NVM is already installed
[admin] $ bash -c "export > env.txt"
[admin] $ bash -c "NVM_DIR=$HOME/.nvm && source $NVM_DIR/nvm.sh --no-use &&
NVM_NODEJS_ORG_MIRROR=https://nodejs.org/dist nvm install 14.20.0 && nvm use 14.20.0 &&
export > env.txt"
Version '14.20.0' not found - try `nvm ls-remote` to browse available versions.
ERROR: Failed to fork bash
Finished: FAILURE
</code>```

Body:
I installed nvm-wrapper plugin and set it in my build steps.when I trying to build my angular project the build phase encounter failure and below is console output .what is the problem?

NVM is already installed
[admin] $ bash -c "export > env.txt"
[admin] $ bash -c "NVM_DIR=$HOME/.nvm && source $NVM_DIR/nvm.sh --no-use &&
NVM_NODEJS_ORG_MIRROR=https://nodejs.org/dist nvm install 14.20.0 && nvm use 14.20.0 &&
export > env.txt"
Version '14.20.0' not found - try `nvm ls-remote` to browse available versions.
ERROR: Failed to fork bash
Finished: FAILURE


问:
React Redux Useselector Hook Not re-render after store state update
I want to remove an item from an array in redux store, which served as a history array. But the state change does not always trigger re-render. I have to click 4 times delete button, or change tab in order to see state change to trigger re-render.

I have tried the following:

using shallowEqual as comparison function

using Object.assign for a new array object, to trigger state change

But, still no luck. Anyone please guide me on this. My codes are below:

Action:

```<code>export function removeHistoryPlaces(index) {
  return {
    type: type.REMOVE_HISTORY_PLACES,
    payload: index,
  }
}
</code>```

store configure

```<code>import { createStore, applyMiddleware, compose } from "redux";
import rootReducer from "./reducers/index.js";
import createSagaMiddleware from "redux-saga";
import rootSaga from "./sagas/index";

const sagaMiddleware = createSagaMiddleware();

// TO TEST WITH DEV TOOL
// const store = compose(
//   applyMiddleware(sagaMiddleware),
//   window.devToolsExtension && window.devToolsExtension(),
// )(createStore)(rootReducer);

const store = createStore(rootReducer,applyMiddleware(sagaMiddleware))

sagaMiddleware.run(rootSaga);

export default store;
</code>```

reducer

```<code>const initialState = {
  historyPlaces: [],
}

export default function historyPlaces(state = initialState, action) {
  switch (action.type) {
      case type.REMOVE_HISTORY_PLACES:
        // const newList = Object.assign([],[...state.historyPlaces].filter((place,index)=>index != action.payload))
        // const isSame = newList === state.historyPlaces
        // console.log("new place list " , newList)
        return {
          ...state,
          historyPlaces: state.historyPlaces.filter((place,index)=>index != action.payload),
        }

    default:
      return state
  }
}
</code>```

HistoryList component where user can view, click and delete history

```<code>import Chip from "@mui/material/Chip";
import Stack from "@mui/material/Stack";
import { useDispatch } from "react-redux";
import { removeHistoryPlaces } from "../redux/actions/historyPlaces";

export default function HistoryList({ data, onItemClick }) {
  const dispatch = useDispatch();
  const maxDisplay = 5;

  const handleDelete = (index) => {
    dispatch(removeHistoryPlaces(index));
  };

  return (
    <Stack direction="row" spacing={1}>
      {data.slice(0, maxDisplay).map((item, index) => (
        <Chip
        style={{maxWidth:'200px'}}
          key={new Date().getTime()}
          label={item.description}
          onClick={()=>onItemClick(item)}
          onDelete={()=>handleDelete(index)}
        />
      ))}
    </Stack>
  );
}
</code>```

Home page where HistoryList component is used

```<code>import HistoryList from "../components/HistoryList";
import React, { useEffect, useState } from 'react';
import { useSelector, useDispatch, shallowEqual } from 'react-redux';

const libraries = ['places'];
export default function Home() {
  const [currentFocusLocation,setCurrentFocusLocation] = useState('')
  const places = useSelector(state => state.historyPlaces.historyPlaces,shallowEqual);
  const onItemClick = (item) =>{
     ...
  }

  useEffect(()=>{
    console.log('places update detected')
    setCurrentFocusLocation(...)
  },[places])

  if (!isLoaded) return <div>Loading...</div>;
  return (
    <>
      <div className="home-container">
        <HistoryList data={places} onItemClick={onItemClick}/>
      </div>
    </>
  );
}
</code>```

For complete codes, can check this github link

Body:
I want to remove an item from an array in redux store, which served as a history array. But the state change does not always trigger re-render. I have to click 4 times delete button, or change tab in order to see state change to trigger re-render.

I have tried the following:

using shallowEqual as comparison function

using Object.assign for a new array object, to trigger state change

But, still no luck. Anyone please guide me on this. My codes are below:

Action:

export function removeHistoryPlaces(index) {
  return {
    type: type.REMOVE_HISTORY_PLACES,
    payload: index,
  }
}

store configure

import { createStore, applyMiddleware, compose } from "redux";
import rootReducer from "./reducers/index.js";
import createSagaMiddleware from "redux-saga";
import rootSaga from "./sagas/index";

const sagaMiddleware = createSagaMiddleware();

// TO TEST WITH DEV TOOL
// const store = compose(
//   applyMiddleware(sagaMiddleware),
//   window.devToolsExtension && window.devToolsExtension(),
// )(createStore)(rootReducer);

const store = createStore(rootReducer,applyMiddleware(sagaMiddleware))

sagaMiddleware.run(rootSaga);

export default store;

reducer

const initialState = {
  historyPlaces: [],
}

export default function historyPlaces(state = initialState, action) {
  switch (action.type) {
      case type.REMOVE_HISTORY_PLACES:
        // const newList = Object.assign([],[...state.historyPlaces].filter((place,index)=>index != action.payload))
        // const isSame = newList === state.historyPlaces
        // console.log("new place list " , newList)
        return {
          ...state,
          historyPlaces: state.historyPlaces.filter((place,index)=>index != action.payload),
        }

    default:
      return state
  }
}

HistoryList component where user can view, click and delete history

import Chip from "@mui/material/Chip";
import Stack from "@mui/material/Stack";
import { useDispatch } from "react-redux";
import { removeHistoryPlaces } from "../redux/actions/historyPlaces";

export default function HistoryList({ data, onItemClick }) {
  const dispatch = useDispatch();
  const maxDisplay = 5;

  const handleDelete = (index) => {
    dispatch(removeHistoryPlaces(index));
  };

  return (
    <Stack direction="row" spacing={1}>
      {data.slice(0, maxDisplay).map((item, index) => (
        <Chip
        style={{maxWidth:'200px'}}
          key={new Date().getTime()}
          label={item.description}
          onClick={()=>onItemClick(item)}
          onDelete={()=>handleDelete(index)}
        />
      ))}
    </Stack>
  );
}

Home page where HistoryList component is used

import HistoryList from "../components/HistoryList";
import React, { useEffect, useState } from 'react';
import { useSelector, useDispatch, shallowEqual } from 'react-redux';

const libraries = ['places'];
export default function Home() {
  const [currentFocusLocation,setCurrentFocusLocation] = useState('')
  const places = useSelector(state => state.historyPlaces.historyPlaces,shallowEqual);
  const onItemClick = (item) =>{
     ...
  }

  useEffect(()=>{
    console.log('places update detected')
    setCurrentFocusLocation(...)
  },[places])

  if (!isLoaded) return
Loading...
;
  return (
    <>

        <HistoryList data={places} onItemClick={onItemClick}/>

    </>
  );
}

For complete codes, can check this github link


问:
Golang struct with different types and JSON marshalling
I am new to Go and I feel as though I grappling with something fundamental around typing whilst trying to build a JSON payload.

My http web app (a kubernetes mutating webhook) is returning a JSON []byte(string) in a field admissionResponse.Patch

The JSON returned is an array of JSONPatch and looks something like this:

```<code>[{
  "op": "add",
  "path":  "/spec/containers",
  "value": <SPEC-JSON>
}]
</code>```

The problem I have is trying to build the different JSONPatch objects in a generic way.

I am Unmarshalling my <SPEC-JSON> from yaml files using various k8s v1 types (E.g. v1.Volume, v1.Container) which is ok, but then because each <SPEC-JSON> is of different type for different JSONPatch objects, I am having to create different struct{} types like so;

```<code>type ContainerPatch struct {
    Op      string `json:"op"`
    Path    string `json:"path"`
    Value   []v1.Container `json:"value"`
}

type VolumePatch struct {
    Op      string `json:"op"`
    Path    string `json:"path"`
    Value   []v1.Volume `json:"value"`
}
</code>```

Now, when I want to put these into an array ready to Marshal back to a JSON string, they are of different types so I am ending up doing:

```<code>    myPatch := []interface{}{
        VolumePatch(PatchVolumes(pod)),
        ContainerPatch(PatchContainers(pod)),
        ContainerPatch(PatchInitContainers(pod)),
    }
    data, _ := json.Marshal(myPatch)
</code>```

which works, but seems wrong?  Essentially these are all of type JSONPatch where the json:"value" can be different k8s objects.

How should we do these things in Go?

---update--- (thanks to mkopriva)

Thank you.  Reading around a bit, it seems that any is essentially an (empty) interface{}(?).  So I tried with both;

```<code>type Patch struct {
    Op      string `json:"op"`
    Path    string `json:"path"`
    Value   interface{} `json:"value"`
}
</code>```

and

```<code>type Patch struct {
    Op      string `json:"op"`
    Path    string `json:"path"`
    Value   any `json:"value"`
}
</code>```

... and both work ok.  I like this way as it allows me to have a single patching func() that returns a common type.

Body:
I am new to Go and I feel as though I grappling with something fundamental around typing whilst trying to build a JSON payload.

My http web app (a kubernetes mutating webhook) is returning a JSON []byte(string) in a field admissionResponse.Patch

The JSON returned is an array of JSONPatch and looks something like this:

[{
  "op": "add",
  "path":  "/spec/containers",
  "value": <SPEC-JSON>
}]

The problem I have is trying to build the different JSONPatch objects in a generic way.

I am Unmarshalling my <SPEC-JSON> from yaml files using various k8s v1 types (E.g. v1.Volume, v1.Container) which is ok, but then because each <SPEC-JSON> is of different type for different JSONPatch objects, I am having to create different struct{} types like so;

type ContainerPatch struct {
    Op      string `json:"op"`
    Path    string `json:"path"`
    Value   []v1.Container `json:"value"`
}

type VolumePatch struct {
    Op      string `json:"op"`
    Path    string `json:"path"`
    Value   []v1.Volume `json:"value"`
}

Now, when I want to put these into an array ready to Marshal back to a JSON string, they are of different types so I am ending up doing:

    myPatch := []interface{}{
        VolumePatch(PatchVolumes(pod)),
        ContainerPatch(PatchContainers(pod)),
        ContainerPatch(PatchInitContainers(pod)),
    }
    data, _ := json.Marshal(myPatch)

which works, but seems wrong?  Essentially these are all of type JSONPatch where the json:"value" can be different k8s objects.

How should we do these things in Go?

---update--- (thanks to mkopriva)

Thank you.  Reading around a bit, it seems that any is essentially an (empty) interface{}(?).  So I tried with both;

type Patch struct {
    Op      string `json:"op"`
    Path    string `json:"path"`
    Value   interface{} `json:"value"`
}

and

type Patch struct {
    Op      string `json:"op"`
    Path    string `json:"path"`
    Value   any `json:"value"`
}

... and both work ok.  I like this way as it allows me to have a single patching func() that returns a common type.


问:
Inserting data from csv too slow Django
My problem is that inserting data into the database is too slow. I have written a correct algorithm that loads the data properly however with this method it will take 700 hours to load the database. There are almost 30 million records in the csv file.

Here is my models.py

```<code>from django.db import models

class Region(models.Model):

    region = models.CharField(max_length=20)

class Rank(models.Model):

    rank = models.IntegerField()

class Chart(models.Model):

    chart = models.CharField(max_length=8)

class Artist(models.Model):

    artist = models.CharField(max_length=60)

class Title(models.Model):

    title = models.CharField(max_length=60)

class ArtistTitle(models.Model):

    artist = models.ForeignKey(Artist, on_delete=models.CASCADE)
    title = models.ForeignKey(Title, on_delete=models.CASCADE)

class SpotifyData(models.Model):

    title = models.ForeignKey(ArtistTitle, related_name='re_title', on_delete=models.CASCADE)
    rank = models.ForeignKey(Rank, on_delete=models.CASCADE)
    date = models.DateField()
    artist = models.ForeignKey(ArtistTitle, related_name='re_artist', on_delete=models.CASCADE)
    region = models.ForeignKey(Region, on_delete=models.CASCADE)
    chart = models.ForeignKey(Chart, on_delete=models.CASCADE)
    streams = models.IntegerField()

</code>```

My upload script looks like this:

```<code>def load_to_db(self, df):
        bad = 0
        good = 0
        start = datetime.datetime.now
        for _, row in df.iterrows():
            try:
                region_obj, _ = Region.objects.get_or_create(
                    region=row["region"],
                )
                rank_obj, _ = Rank.objects.get_or_create(
                    rank=row["rank"],
                )
                chart_obj, _ = Chart.objects.get_or_create(
                    chart=row["chart"],
                )
                artist_obj, _ = Artist.objects.get_or_create(
                    artist=row["artist"],
                )
                title_obj, _ = Title.objects.get_or_create(
                    title=row["title"],
                )
                arttit_obj, _ = ArtistTitle.objects.update_or_create(
                    artist=artist_obj,
                    title=title_obj,
                )
                spotifydata_obj, _ = SpotifyData.objects.update_or_create(
                    title=arttit_obj,
                    rank=rank_obj,
                    date=row["date"],
                    artist=arttit_obj,
                    region=region_obj,
                    chart=chart_obj,
                    streams=row["streams"],
                )
                good += 1
                now = datetime.datetime.now
                print(f"goods: {good}, loading time: {start-now}", )
            except Exception as e:
                bad += 1
                current_time = datetime.datetime.now()
                with open("data_load_logging.txt", "w") as bad_row:
                    bad_row.write(
                        f"Error message: {e} \n"
                        + f"time: {current_time}, \n"
                        + f"title: {row['title']}, type: {row['title']} \n"
                        + f"rank: {int(row['rank'])}, type: {int(row['rank'])} \n"
                        + f"date: {row['date']}, type: {row['date']} \n"
                        + f"artist: {row['artist']}, type: {row['artist']} \n"
                        + f"region: {row['region']}, type: {row['region']} \n"
                        + f"chart: {row['chart']}, type: {row['chart']} \n"
                        + f"streams: {int(row['streams'])}, type: {int(row['streams'])} \n"
                        + "-" * 30
                        + "\n"
                    )
</code>```

I know it could probably help to use bulk/bulk_create/bulk_update but I can't figure out how to write the correct script....

```<code>def load_to_db(self, path):
        start_time = timezone.now()
        try:
            with open(path, "r") as csv_file:
                data = csv.reader(csv_file)
                next(data)
                packet_region = []
                packet_rank = []
                packet_chart = []
                packet_artist = []
                packet_title = []
                packet_artist_title = []
                packet_spotify_data = []
                bad = -1  # first row is a header
                for row in data:

                    region = Region(
                        region = row[4]
                    )

                    rank = Rank(
                        rank = row[1]
                    )

                    chart = Chart(
                        chart = row[5]
                    )

                    artist = Artist(
                        artist = row[3]
                    )

                    title = Title(
                        title = row[0]
                    )

                    artist_title = ArtistTitle(
                        artist = artist,
                        title = title
                    )

                    spotify_data = SpotifyData(
                        title = artist_title,
                        rank = rank,
                        date = row[3],
                        artist = artist_title,
                        region = region,
                        chart = chart,
                        streams = int(row[6])
                    )

                    packet_region.append(region)
                    packet_rank.append(rank)
                    packet_chart.append(chart)
                    packet_artist.append(artist)
                    packet_title.append(title)
                    packet_artist_title.append(artist_title)
                    packet_spotify_data.append(spotify_data)
                    if len(packet_spotify_data) > 1000:
                        print(datetime.datetime.now())
                        Region.objects.bulk_create(packet_region)
                        Rank.objects.bulk_create(packet_rank)
                        Chart.objects.bulk_create(packet_chart)
                        Artist.objects.bulk_create(packet_artist)
                        Title.objects.bulk_create(packet_title)
                        ArtistTitle.objects.bulk_update(packet_artist_title)
                        SpotifyData.objects.bulk_update(packet_spotify_data)
                        packet_region = []
                        packet_rank = []
                        packet_chart = []
                        packet_artist = []
                        packet_title = []
                        packet_artist_title = []
                        packet_spotify_data = []

                logging.info(f"Failure numbers: {bad}")
                if packet_spotify_data:
                    Region.objects.bulk_create(packet_region)
                    Rank.objects.bulk_create(packet_rank)
                    Chart.objects.bulk_create(packet_chart)
                    Artist.objects.bulk_create(packet_artist)
                    Title.objects.bulk_create(packet_title)
                    ArtistTitle.objects.bulk_update(packet_artist_title)
                    SpotifyData.objects.bulk_update(packet_spotify_data)
        except FileNotFoundError as e:
            raise NoFilesException("No such file or directory") from e

        end_time = timezone.now()
        self.stdout.write(
            self.style.SUCCESS(
                f"Loading CSV took: {(end_time-start_time).total_seconds()} seconds."
            )
        )
</code>```

I tried to use bulk this way but unfortunately it doesn't work

Title: Inserting data from csv too slow Django

Body:
My problem is that inserting data into the database is too slow. I have written a correct algorithm that loads the data properly however with this method it will take 700 hours to load the database. There are almost 30 million records in the csv file.

Here is my models.py

from django.db import models

class Region(models.Model):

    region = models.CharField(max_length=20)

class Rank(models.Model):

    rank = models.IntegerField()

class Chart(models.Model):

    chart = models.CharField(max_length=8)

class Artist(models.Model):

    artist = models.CharField(max_length=60)

class Title(models.Model):

    title = models.CharField(max_length=60)

class ArtistTitle(models.Model):

    artist = models.ForeignKey(Artist, on_delete=models.CASCADE)
    title = models.ForeignKey(Title, on_delete=models.CASCADE)

class SpotifyData(models.Model):

    title = models.ForeignKey(ArtistTitle, related_name='re_title', on_delete=models.CASCADE)
    rank = models.ForeignKey(Rank, on_delete=models.CASCADE)
    date = models.DateField()
    artist = models.ForeignKey(ArtistTitle, related_name='re_artist', on_delete=models.CASCADE)
    region = models.ForeignKey(Region, on_delete=models.CASCADE)
    chart = models.ForeignKey(Chart, on_delete=models.CASCADE)
    streams = models.IntegerField()

My upload script looks like this:

def load_to_db(self, df):
        bad = 0
        good = 0
        start = datetime.datetime.now
        for _, row in df.iterrows():
            try:
                region_obj, _ = Region.objects.get_or_create(
                    region=row["region"],
                )
                rank_obj, _ = Rank.objects.get_or_create(
                    rank=row["rank"],
                )
                chart_obj, _ = Chart.objects.get_or_create(
                    chart=row["chart"],
                )
                artist_obj, _ = Artist.objects.get_or_create(
                    artist=row["artist"],
                )
                title_obj, _ = Title.objects.get_or_create(
                    title=row["title"],
                )
                arttit_obj, _ = ArtistTitle.objects.update_or_create(
                    artist=artist_obj,
                    title=title_obj,
                )
                spotifydata_obj, _ = SpotifyData.objects.update_or_create(
                    title=arttit_obj,
                    rank=rank_obj,
                    date=row["date"],
                    artist=arttit_obj,
                    region=region_obj,
                    chart=chart_obj,
                    streams=row["streams"],
                )
                good += 1
                now = datetime.datetime.now
                print(f"goods: {good}, loading time: {start-now}", )
            except Exception as e:
                bad += 1
                current_time = datetime.datetime.now()
                with open("data_load_logging.txt", "w") as bad_row:
                    bad_row.write(
                        f"Error message: {e} \n"
                        + f"time: {current_time}, \n"
                        + f"title: {row['title']}, type: {row['title']} \n"
                        + f"rank: {int(row['rank'])}, type: {int(row['rank'])} \n"
                        + f"date: {row['date']}, type: {row['date']} \n"
                        + f"artist: {row['artist']}, type: {row['artist']} \n"
                        + f"region: {row['region']}, type: {row['region']} \n"
                        + f"chart: {row['chart']}, type: {row['chart']} \n"
                        + f"streams: {int(row['streams'])}, type: {int(row['streams'])} \n"
                        + "-" * 30
                        + "\n"
                    )

I know it could probably help to use bulk/bulk_create/bulk_update but I can't figure out how to write the correct script....

def load_to_db(self, path):
        start_time = timezone.now()
        try:
            with open(path, "r") as csv_file:
                data = csv.reader(csv_file)
                next(data)
                packet_region = []
                packet_rank = []
                packet_chart = []
                packet_artist = []
                packet_title = []
                packet_artist_title = []
                packet_spotify_data = []
                bad = -1  # first row is a header
                for row in data:

                    region = Region(
                        region = row[4]
                    )

                    rank = Rank(
                        rank = row[1]
                    )

                    chart = Chart(
                        chart = row[5]
                    )

                    artist = Artist(
                        artist = row[3]
                    )

                    title = Title(
                        title = row[0]
                    )

                    artist_title = ArtistTitle(
                        artist = artist,
                        title = title
                    )

                    spotify_data = SpotifyData(
                        title = artist_title,
                        rank = rank,
                        date = row[3],
                        artist = artist_title,
                        region = region,
                        chart = chart,
                        streams = int(row[6])
                    )

                    packet_region.append(region)
                    packet_rank.append(rank)
                    packet_chart.append(chart)
                    packet_artist.append(artist)
                    packet_title.append(title)
                    packet_artist_title.append(artist_title)
                    packet_spotify_data.append(spotify_data)
                    if len(packet_spotify_data) > 1000:
                        print(datetime.datetime.now())
                        Region.objects.bulk_create(packet_region)
                        Rank.objects.bulk_create(packet_rank)
                        Chart.objects.bulk_create(packet_chart)
                        Artist.objects.bulk_create(packet_artist)
                        Title.objects.bulk_create(packet_title)
                        ArtistTitle.objects.bulk_update(packet_artist_title)
                        SpotifyData.objects.bulk_update(packet_spotify_data)
                        packet_region = []
                        packet_rank = []
                        packet_chart = []
                        packet_artist = []
                        packet_title = []
                        packet_artist_title = []
                        packet_spotify_data = []

                logging.info(f"Failure numbers: {bad}")
                if packet_spotify_data:
                    Region.objects.bulk_create(packet_region)
                    Rank.objects.bulk_create(packet_rank)
                    Chart.objects.bulk_create(packet_chart)
                    Artist.objects.bulk_create(packet_artist)
                    Title.objects.bulk_create(packet_title)
                    ArtistTitle.objects.bulk_update(packet_artist_title)
                    SpotifyData.objects.bulk_update(packet_spotify_data)
        except FileNotFoundError as e:
            raise NoFilesException("No such file or directory") from e

        end_time = timezone.now()
        self.stdout.write(
            self.style.SUCCESS(
                f"Loading CSV took: {(end_time-start_time).total_seconds()} seconds."
            )
        )

I tried to use bulk this way but unfortunately it doesn't work