问:
Django persistent conection with mysql
Tried to set different value for CONN_MAX_AGE as described in documentation.

I read about link and was trying to use this in my Django app. After setting this property i ran 10 concurrent requests using benchmarking tool (wrk)for a period of time. In MySQL I ran "show processlist" command it showed :

```<code>Id      User            Host            db                  Command Time    State   Info
5       event_scheduler localhost       NULL                Daemon  613647  Waiting on empty queue  NULL
8       root            localhost:62282 NULL                Sleep   134     NULL
9       root            localhost:62285 database1213        Query   0       init    SHOW PROCESSLIST
11      root            localhost:62288 NULL                Sleep   1       NULL
121088  root            localhost:52528 database1213        Sleep   193     NULL
121089  root            localhost:52530 database1213        Sleep   191     NULL
121090  root            localhost:52533 database1213        Sleep   191     NULL
121101  root            localhost:52885 database1213        Sleep   0       NULL
121102  root            localhost:52886 database1213        Sleep   0       NULL
121103  root            localhost:52887 database1213        Sleep   0       NULL
121104  root            localhost:52888 database1213        Sleep   0       NULL
121105  root            localhost:52889 database1213        Sleep   0       NULL
121106  root            localhost:52890 database1213        Sleep   0       NULL
121107  root            localhost:52891 database1213        Sleep   0       NULL
121108  root            localhost:52892 database1213        Sleep   0       NULL
121109  root            localhost:52893 database1213        Sleep   0       NULL
121110  root            localhost:52894 database1213        Sleep   0       NULL
</code>```

In the table Host and db entries are not changing for the period benchmarking is running, from which I am assuming that connections are being reused when setting CONN_MAX_AGE as non 0. While it was changing every moment when it was set as 0.

After benchmark was completed I ran same request just once and it showed one more entry in show processlist with other previous values.

But according to Django documentation it reuses the connection for time mentioned. Here although firing a new curl from terminal creating a new one.

Can somebody help in understanding if there is incomplete documentation or lack in understanding?

Title: Django persistent conection with mysql

Body:
Tried to set different value for CONN_MAX_AGE as described in documentation.

I read about link and was trying to use this in my Django app. After setting this property i ran 10 concurrent requests using benchmarking tool (wrk)for a period of time. In MySQL I ran "show processlist" command it showed :

Id      User            Host            db                  Command Time    State   Info
5       event_scheduler localhost       NULL                Daemon  613647  Waiting on empty queue  NULL
8       root            localhost:62282 NULL                Sleep   134     NULL
9       root            localhost:62285 database1213        Query   0       init    SHOW PROCESSLIST
11      root            localhost:62288 NULL                Sleep   1       NULL
121088  root            localhost:52528 database1213        Sleep   193     NULL
121089  root            localhost:52530 database1213        Sleep   191     NULL
121090  root            localhost:52533 database1213        Sleep   191     NULL
121101  root            localhost:52885 database1213        Sleep   0       NULL
121102  root            localhost:52886 database1213        Sleep   0       NULL
121103  root            localhost:52887 database1213        Sleep   0       NULL
121104  root            localhost:52888 database1213        Sleep   0       NULL
121105  root            localhost:52889 database1213        Sleep   0       NULL
121106  root            localhost:52890 database1213        Sleep   0       NULL
121107  root            localhost:52891 database1213        Sleep   0       NULL
121108  root            localhost:52892 database1213        Sleep   0       NULL
121109  root            localhost:52893 database1213        Sleep   0       NULL
121110  root            localhost:52894 database1213        Sleep   0       NULL

In the table Host and db entries are not changing for the period benchmarking is running, from which I am assuming that connections are being reused when setting CONN_MAX_AGE as non 0. While it was changing every moment when it was set as 0.

After benchmark was completed I ran same request just once and it showed one more entry in show processlist with other previous values.

But according to Django documentation it reuses the connection for time mentioned. Here although firing a new curl from terminal creating a new one.

Can somebody help in understanding if there is incomplete documentation or lack in understanding?


来源: stackexchange

问:
I try to store data to Firestore from my bare react native project, but it does not store and returns null
I'm using Firebase (web) in my React Native project for email authentication, which works perfectly. But when I try to save data to Firestore, it does not store and returns null. I have tried using the latest version of Firebase and also the old version 9.6.11, but there has been no change. Project link is ( https://drive.google.com/file/d/13zFyLa6LXiuOQot11ileYU_Lu6X01sPK/view?usp=sharing )</p>
```<code>import { StyleSheet, Text, View, TextInput, TouchableOpacity, ScrollView } from 'react-native'
import React, { useState } from 'react'
import Feather from 'react-native-vector-icons/Feather';
import Icon from 'react-native-vector-icons/FontAwesome';
import { createUserWithEmailAndPassword } from "firebase/auth";
import { auth, db } from '../Firebase/FirebaseConfig';
import { collection, addDoc } from "firebase/firestore";

const SignUp = ({ navigation }) => {

  const [emailColor, setEmailColor] = useState(false)
  const [passwordColor, setPasswordColor] = useState(false)
  const [fullNameColor, setFullNameColor] = useState(false)
  const [confirmPasswordColor, setConfirmPasswordColor] = useState(false)
  const [phoneColor, setPhoneColor] = useState(false)
  const [showPassword, setShowPassword] = useState(false)

  // taking form Data
  const [name, setName] = useState('')
  const [email, setEmail] = useState('')
  const [phone, setPhone] = useState('')
  const [password, setPassword] = useState('')
  const [confirmPassword, setconfirmPassword] = useState('')
  const [address, setAddress] = useState('')

  // console.log(name, email, phone, password, confirmPassword, address);

  const signup = () => {

    if (phone.length != 11) {
      alert("Phone number should be 11 digits")
      return;
    } else if (password != confirmPassword) {
      alert("Password doesn't match")
      // setCustomError("Password doesn't match")
      return;
    }

    createUserWithEmailAndPassword(auth, email, password)
      .then((userCredential) => {
        saveData()
        alert("User created successfully")
        navigation.replace("SignIn")
      })
      .catch((error) => {
        const errorCode = error.code;
        const errorMessage = error.message;
        alert(errorMessage)
        // ..
      });
  }

  const saveData = async () => {
    const docRef = await addDoc(collection(db, "UserData"), {
      Name: name,
      Email: email,
      Phone: phone,
      Password: password,
      Address: address
    });
    console.log(name, email, phone, password, confirmPassword, address);
    console.log("Document written with ID: ", docRef.id);
  }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm using Firebase (web) in my React Native project for email authentication, which works perfectly. But when I try to save data to Firestore, it does not store and returns null. I have tried using the latest version of Firebase and also the old version 9.6.11, but there has been no change. Project link is ( https://drive.google.com/file/d/13zFyLa6LXiuOQot11ileYU_Lu6X01sPK/view?usp=sharing )

import { StyleSheet, Text, View, TextInput, TouchableOpacity, ScrollView } from 'react-native'
import React, { useState } from 'react'
import Feather from 'react-native-vector-icons/Feather';
import Icon from 'react-native-vector-icons/FontAwesome';
import { createUserWithEmailAndPassword } from "firebase/auth";
import { auth, db } from '../Firebase/FirebaseConfig';
import { collection, addDoc } from "firebase/firestore";

const SignUp = ({ navigation }) => {

  const [emailColor, setEmailColor] = useState(false)
  const [passwordColor, setPasswordColor] = useState(false)
  const [fullNameColor, setFullNameColor] = useState(false)
  const [confirmPasswordColor, setConfirmPasswordColor] = useState(false)
  const [phoneColor, setPhoneColor] = useState(false)
  const [showPassword, setShowPassword] = useState(false)

  // taking form Data
  const [name, setName] = useState('')
  const [email, setEmail] = useState('')
  const [phone, setPhone] = useState('')
  const [password, setPassword] = useState('')
  const [confirmPassword, setconfirmPassword] = useState('')
  const [address, setAddress] = useState('')

  // console.log(name, email, phone, password, confirmPassword, address);

  const signup = () => {

    if (phone.length != 11) {
      alert("Phone number should be 11 digits")
      return;
    } else if (password != confirmPassword) {
      alert("Password doesn't match")
      // setCustomError("Password doesn't match")
      return;
    }

    createUserWithEmailAndPassword(auth, email, password)
      .then((userCredential) => {
        saveData()
        alert("User created successfully")
        navigation.replace("SignIn")
      })
      .catch((error) => {
        const errorCode = error.code;
        const errorMessage = error.message;
        alert(errorMessage)
        // ..
      });
  }

  const saveData = async () => {
    const docRef = await addDoc(collection(db, "UserData"), {
      Name: name,
      Email: email,
      Phone: phone,
      Password: password,
      Address: address
    });
    console.log(name, email, phone, password, confirmPassword, address);
    console.log("Document written with ID: ", docRef.id);
  }


问:
XGboost model variable transformation
I am working on an XGBoost model with a few input variables. There is one variable X that I am testing different ways of transformation.

option 1. I apply a group-by average of X, and use the deviation X - group_by_mean(X) as input

option 2. I apply a simple line regression y = aX + b on group-by X, and use y as input

I run two models, with otherwise identical input,
Result, I get better model prediction from option 1 then option 2 on XGboost model.

My question is, can anyone direct me to the potential theorical reason why opition 1 gives me better result as an input to XGboost model, than option 2?
I suspect it is due to option 2 a simple linear regression creates unobserved error, while option 1 a simple average has unobserved error 0, since I apply all known information in option 1. But I would appreciate more theorical reasoning and backing if possible.

Title: XGboost model variable transformation


问:
What are the best "session" variables to use with react and react router version 6.4?
Newbie just getting started with react & react router version 6.4. I am working with building a multi page solution and trying to understand the various variable storage to use such as local, session, global variables - also javascript Window localStorage & sessionStorage etc.

In previous PHP Solutions I extensively used session variables to store the user and invoice or project variables throughout the solution.

I am trying to learn about the various react hooks related to variable storage/usage and I am a bit confused between them such as: params, context, props etc.

Can someone help explain how these hooks compare to local - session - global variables?

As an example, let's say I have a user login and work with a shopping cart. Using "PHP session variables" concept - I could store the user login info and the various shopping cart variables such as an invoice ID and product id's etc. Then I could go to various separate pages and reference those variables easily. Is there a way to do this with react?

In react, I found myself working on a page and I was able to access a react hook: useParams in my main function but lower on the page I created a second function and it was unable to use the useParams variables. (Someone said now I needed to create custom hooks for this purpose?) Is there a way to create a "session" variable that can be used across multiple pages?

Q: thinking like what's possible in PHP, is there a way to declare some kind of react hook "session" variable or something else that can be used in a react project?

Thanks Dave

Update: Ex: let's say I was building a simple todo app that had various categories and the related child items. The general idea would be to click on a category - and then see a list of the available child items - and another list grandchild sub items.

So in this use case - it would be good to Store the category ID in some sort of "session variable" that could be reused when working with the various child items and possibly grandchild sub items.

For this very simple purpose what do you recommend to Store the category ID? Is this a good use for react context or is there a better "react place - hook" to Store the category ID?


问:
spring boot security rest service : allow requests from specific host name and port
i do a rest server with spring boot 2.7.1 then added spring security to control access to the service..
this is my SecurityConfiguration :

```<code>@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration {

  @Bean
  public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

    http.csrf().disable()
        .authorizeRequests()
        .mvcMatchers("/api/v1/svr40/info").permitAll()
        .mvcMatchers("/api/v1/svr40/initService").permitAll()
        .mvcMatchers("/api/v1/svr40/getServiceID").permitAll()
        //.anyRequest().permitAll()  // for testing
        .mvcMatchers("/api/v1/svr40/**").denyAll();

    return http.build();
  }

}
</code>```

now i want to limit requests only from a certain host:port ..
i tried with hasIpAddress(...) without success..

```<code>.mvcMatchers("/api/v1/svr40/info").hasIpAddress("127.0.0.1:8081")
</code>```

Body:
i do a rest server with spring boot 2.7.1 then added spring security to control access to the service..
this is my SecurityConfiguration :

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration {

  @Bean
  public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

    http.csrf().disable()
        .authorizeRequests()
        .mvcMatchers("/api/v1/svr40/info").permitAll()
        .mvcMatchers("/api/v1/svr40/initService").permitAll()
        .mvcMatchers("/api/v1/svr40/getServiceID").permitAll()
        //.anyRequest().permitAll()  // for testing
        .mvcMatchers("/api/v1/svr40/**").denyAll();

    return http.build();
  }

}

now i want to limit requests only from a certain host:port ..
i tried with hasIpAddress(...) without success..

.mvcMatchers("/api/v1/svr40/info").hasIpAddress("127.0.0.1:8081")


问:
Values of Array keeps changing
Because in C there is no Array List I wanted to try and code my own one. I came up with this Idea:

```<code>int* createArrayList(int size) {
    int arrayList[size];
    clearList(arrayList);
    int* returnVal = arrayList;
    return returnVal;
}
</code>```

This code makes an array with the given size, calls clearList() which sets all values in the array to 0 and than returns a refrences to that array.

```<code>int* arrayList = createArrayList(10);
outputArray(arrayList);
</code>```

This is the code in the main function, it gets the pointer from createArrayList() and then calls outputArray() which is just a for-loop that prints out the array using printf().

In the clearList() and outputArray() functions I use sizeof().

I am excpecting to have 10 rows of 0 but its only 8 rows and when I write for example arrayList[2] = 10; in beetween then the output is again 8 rows of 0 with a few random numbers in beetween and the 10. Also the random numbers only show up at the spots of 1 and 3.

Note: Please focus on the question and not my code for the array list, I know it can be better.

Title: Values of Array keeps changing

Body:
Because in C there is no Array List I wanted to try and code my own one. I came up with this Idea:

int* createArrayList(int size) {
    int arrayList[size];
    clearList(arrayList);
    int* returnVal = arrayList;
    return returnVal;
}

This code makes an array with the given size, calls clearList() which sets all values in the array to 0 and than returns a refrences to that array.

int* arrayList = createArrayList(10);
outputArray(arrayList);

This is the code in the main function, it gets the pointer from createArrayList() and then calls outputArray() which is just a for-loop that prints out the array using printf().

In the clearList() and outputArray() functions I use sizeof().

I am excpecting to have 10 rows of 0 but its only 8 rows and when I write for example arrayList[2] = 10; in beetween then the output is again 8 rows of 0 with a few random numbers in beetween and the 10. Also the random numbers only show up at the spots of 1 and 3.

Note: Please focus on the question and not my code for the array list, I know it can be better.


问:
downgrade java version on archlinux
I have just updated java on my archlinux server and now it mess up my tomcat projects.

I want to downgrade java from 11.0.17.u1 to 11.0.13.u8

I looked at my var/cache/pacman/pkg folder and it seems like my old package are still there

```<code>jre11-openjdk-11.0.13.u8-1-x86_64.pkg.tar.zst

jre11-openjdk-headless-11.0.13.u8-1-x86_64.pkg.tar.zst
</code>```

I am trying to run this command to force the installation of this java version :

```<code>sudo pacman -U jre11-openjdk-11.0.13.u8-1-x86_64.pkg.tar.zst
</code>```

But it does not let me and I get this message :

```<code>loading packages...
warning: downgrading package jre11-openjdk (11.0.17.u1-1 => 11.0.13.u8-1)
resolving dependencies...
warning: cannot resolve "jre11-openjdk-headless=11.0.13.u8-1", a dependency of "jre11-openjdk"
:: The following package cannot be upgraded due to unresolvable dependencies:
      jre11-openjdk
</code>```

What can I do to force the downgrade?

Further infos:

This is the error I am getting since I updated the JVM

```<code>09-Jan-2023 15:46:44.910 WARNING [main] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesObjectStreamClassCaches Failed to clear soft references from ObjectStreamClass$Caches for web application [docs]
    java.lang.ClassCastException: class java.io.ObjectStreamClass$Caches$1 cannot be cast to class java.util.Map (java.io.ObjectStreamClass$Caches$1 and java.util.Map are in module java.base of loader 'bootstrap')
</code>```

The tomcat servers I have not restarted yet (which are still running under the old jvm are doing just fine.

I found this topic here :

ClassCastException when stopping Tomcat 10 inside Eclipse

The solution that is brought is to upgrade the tomcat version. I am in an emergency situation where I don't have the time to update all my tomcat servers right now.

Title: downgrade java version on archlinux

Body:
I have just updated java on my archlinux server and now it mess up my tomcat projects.

I want to downgrade java from 11.0.17.u1 to 11.0.13.u8

I looked at my var/cache/pacman/pkg folder and it seems like my old package are still there

jre11-openjdk-11.0.13.u8-1-x86_64.pkg.tar.zst

jre11-openjdk-headless-11.0.13.u8-1-x86_64.pkg.tar.zst

I am trying to run this command to force the installation of this java version :

sudo pacman -U jre11-openjdk-11.0.13.u8-1-x86_64.pkg.tar.zst

But it does not let me and I get this message :

loading packages...
warning: downgrading package jre11-openjdk (11.0.17.u1-1 => 11.0.13.u8-1)
resolving dependencies...
warning: cannot resolve "jre11-openjdk-headless=11.0.13.u8-1", a dependency of "jre11-openjdk"
:: The following package cannot be upgraded due to unresolvable dependencies:
      jre11-openjdk

What can I do to force the downgrade?

Further infos:

This is the error I am getting since I updated the JVM

09-Jan-2023 15:46:44.910 WARNING [main] org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesObjectStreamClassCaches Failed to clear soft references from ObjectStreamClass$Caches for web application [docs]
    java.lang.ClassCastException: class java.io.ObjectStreamClass$Caches$1 cannot be cast to class java.util.Map (java.io.ObjectStreamClass$Caches$1 and java.util.Map are in module java.base of loader 'bootstrap')

The tomcat servers I have not restarted yet (which are still running under the old jvm are doing just fine.

I found this topic here :

ClassCastException when stopping Tomcat 10 inside Eclipse

The solution that is brought is to upgrade the tomcat version. I am in an emergency situation where I don't have the time to update all my tomcat servers right now.


问:
how to skip the unkownhost exception in unit test when i use a dummyUrl with restTemplate exchange metho
this is my code for the method

```<code>  public void sendFossInfoToMuninService(String productNumber, String rstate) throws Exception {
        var product = new FossInfo();
        product.setProductNumber(productNumber);
        product.setRstate(rstate);
        log.info(GENERIC_MSG_WHEN_SENDING, productNumber, rstate);
        try{
            RestTemplate restTemplate= new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> request = new HttpEntity<>(product.toString(), headers);
            var response = restTemplate.exchange(muninHost+"/product", HttpMethod.POST, request, String.class);
            if(response.getStatusCode().is2xxSuccessful()){
                log.info(INFO_MSG_SUCCESS_MUNIN, productNumber,rstate);
            }else{
                log.error(ERR_MSG_FAILED_MUNIN_REGISTRATION, productNumber,rstate);
            }
        } catch (Exception e) {
            log.info(ERR_MSG_UNSECCESSFUL_MUNIN_REGISTRATION, productNumber, rstate, e.getMessage());
        }
    }

</code>```

and this is the unit test class

```<code>
@RunWith(MockitoJUnitRunner.class)
@ExtendWith(OutputCaptureExtension.class)
@ExtendWith(MockitoExtension.class)
public class MuninServiceTest {

    String dummyUrl = "http://muninService/url/to/upload/product";

    @Mock
    private RestTemplate restTemplate;

    @InjectMocks
    MuninService muninService;

    @BeforeEach
    void setUp(){
        MockitoAnnotations.openMocks(this);
        muninService = new MuninService(dummyUrl);

    }

    @SneakyThrows
    @Test
    void sendFossInfosToMuninSuccess(CapturedOutput output)  {
            String productNumber = "2/CXD32EJ";
            String rState = "R12A";
            var product = new FossInfo(productNumber,productNumber);
            ResponseEntity<String> productEntity = new ResponseEntity<>(HttpStatus.ACCEPTED);
             Mockito.when(restTemplate.exchange(
                ArgumentMatchers.eq(dummyUrl),
                ArgumentMatchers.eq(HttpMethod.POST),
                ArgumentMatchers.<HttpEntity<String>>any(),
                ArgumentMatchers.<ParameterizedTypeReference<String>>any())
              ).thenReturn(productEntity);
            muninService.sendFossInfoToMuninService(productNumber,rState);
            assertThat(output).contains("Successfully sending FOSS with product number " + productNumber + " and Rstate " + rState + " to Munin");
    }

</code>```

and this is the exception
error message I/O error on POST request for "http://muninService/url/to/upload/product/product": muninService; nested exception is java.net.UnknownHostException: muninService

Body:
this is my code for the method

  public void sendFossInfoToMuninService(String productNumber, String rstate) throws Exception {
        var product = new FossInfo();
        product.setProductNumber(productNumber);
        product.setRstate(rstate);
        log.info(GENERIC_MSG_WHEN_SENDING, productNumber, rstate);
        try{
            RestTemplate restTemplate= new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> request = new HttpEntity<>(product.toString(), headers);
            var response = restTemplate.exchange(muninHost+"/product", HttpMethod.POST, request, String.class);
            if(response.getStatusCode().is2xxSuccessful()){
                log.info(INFO_MSG_SUCCESS_MUNIN, productNumber,rstate);
            }else{
                log.error(ERR_MSG_FAILED_MUNIN_REGISTRATION, productNumber,rstate);
            }
        } catch (Exception e) {
            log.info(ERR_MSG_UNSECCESSFUL_MUNIN_REGISTRATION, productNumber, rstate, e.getMessage());
        }
    }

and this is the unit test class

@RunWith(MockitoJUnitRunner.class)
@ExtendWith(OutputCaptureExtension.class)
@ExtendWith(MockitoExtension.class)
public class MuninServiceTest {

    String dummyUrl = "http://muninService/url/to/upload/product";

    @Mock
    private RestTemplate restTemplate;

    @InjectMocks
    MuninService muninService;

    @BeforeEach
    void setUp(){
        MockitoAnnotations.openMocks(this);
        muninService = new MuninService(dummyUrl);

    }

    @SneakyThrows
    @Test
    void sendFossInfosToMuninSuccess(CapturedOutput output)  {
            String productNumber = "2/CXD32EJ";
            String rState = "R12A";
            var product = new FossInfo(productNumber,productNumber);
            ResponseEntity<String> productEntity = new ResponseEntity<>(HttpStatus.ACCEPTED);
             Mockito.when(restTemplate.exchange(
                ArgumentMatchers.eq(dummyUrl),
                ArgumentMatchers.eq(HttpMethod.POST),
                ArgumentMatchers.<HttpEntity<String>>any(),
                ArgumentMatchers.<ParameterizedTypeReference<String>>any())
              ).thenReturn(productEntity);
            muninService.sendFossInfoToMuninService(productNumber,rState);
            assertThat(output).contains("Successfully sending FOSS with product number " + productNumber + " and Rstate " + rState + " to Munin");
    }

and this is the exception
error message I/O error on POST request for "http://muninService/url/to/upload/product/product": muninService; nested exception is java.net.UnknownHostException: muninService


问:
A unique Identifier for All Apps in device to identify a SSO session
I am working on a problem statement, where we are trying to create SSO system. For that SSO system, in order to create a SSO session for a user, we need to have a unqiue identifier which is same for all the apps in the device. So that, the server can identify that user has a existing SSO session for that device or not?

TLDR:
Looking for a unique identifier for all the apps in the device.d

I tried looking into ANDROID_ID, but got to know that it is combination of signing key, user and device. Hence, it will change for each app.


问:
How to get values of some form fields in react by clicking on a button?
I've created a form using antd-form-builder which contains 3 parts. In "Routines" part user can add several "Tasks" I need to collect each task information by clicking on the "Add Routine" button in an array like this:

```<code>"routinesList": [
    {
      "routinType": 1,
      "intervalDays": 20,
      "nextDueDate": "2023-01-08T15:46:33.185Z",
      "kindOfDate": 1,
      "serviceProvider": "string",
      "sop": "string",
      "displayBeforeDue": 1,
      "lastDate": "2023-01-08T15:46:33.185Z",
      "nextDate": "2023-01-08T15:46:33.185Z",
      "taskId": 1
    }
  ]
</code>```

and finally send all 3 parts data to the server by clicking on submit button.
how can I do it?

here is my code for Routine part of the form:

```<code>import React, { Fragment, useEffect, useState, useCallback } from "react"

import { Form, List, Select, Input, InputNumber, Row, Col, Button } from "antd"
import FormBuilder from "antd-form-builder"
import { MinusCircleOutlined, PlusOutlined } from "@ant-design/icons"
import axios from "axios"

const Option = Select.Option
const IntervalInput = ({ value, onChange }) => (
  <Row gutter={10}>
    <Col span={16}>
      <InputNumber min={1} style={{ width: "100%" }} value={value.number} onChange={(v) => onChange({ number: v, unit: value.unit })} />
    </Col>
    <Col span={8}>
      <Select value={value.unit} onChange={(v) => onChange({ number: value.number, unit: v })}>
        <Option value="1">Day(s)</Option>
        <Option value="2">Month(s)</Option>
      </Select>
    </Col>
  </Row>
)

function RoutineInfo(props) {
  const [form] = Form.useForm()
  const [routineData, setRoutineData] = useState([])
  const [opts, setOpts] = useState({ sop: [], service: [] })
  useEffect(() => {
    const fetchOpts = async () => {
      const serviceData = await axios("api?id=3")
      setOpts({ sop: [], service: serviceData.data })
    }
    fetchOpts()
  }, [])

  const optsService = opts.service
  const serviceOptions = optsService.map(({ typeValue }) => typeValue)

  const columns = 2
  const meta = {
    columns,
    fields: [
      {
        key: "routineType",
        label: "Routine Type",
        widget: "select",
        options: [
          { label: "Calibration", value: 1 },
          { label: "Maintenance", value: 2 },
        ],
        initialValue: 1,
        colSpan: 2,
      },
      {
        key: "interval",
        label: "Interval",
        forwardRef: true,
        widget: IntervalInput,
        initialValue: { number: 30, unit: "Days" },
      },
      {
        key: "lastDate",
        label: "Last Due Date",
        widget: "date-picker",
        widgetProps: { style: { width: "100%" } },
        colSpan: 2,
      },
      {
        key: "nextDate",
        label: "Next Due Date",
        widget: "date-picker",
        widgetProps: { style: { width: "100%" } },
        colSpan: 2,
      },
      {
        key: "displayBeforeDue",
        label: "Display Before Due",
        widget: "number",
        colSpan: 2,
      },
      {
        key: "sop",
        label: "SOP",
        widget: "select",
        colSpan: 2,
      },
      {
        key: "serviceProvider",
        label: "Service Provider",
        widget: "select",
        //onChange: (e) => setRoutineData(e.target.value),
        options: serviceOptions,
        widgetProps: { showSearch: true },
        colSpan: 2,
      },
      {
        key: "task",
        label: "Task",
        //forwardRef: true,
        widget: "select",
        widgetProps: { showSearch: true },
        options: [
          { label: "Pre-filter Replacement", value: 1 },
          { label: "Oil Change", value: 2 },
        ],
        colSpan: 2,
      },
    ],
  }

  const getData = () => {
    console.log(routineData)
  }

  return (
    <Fragment>
      <fieldset className="form-frame">
        <FormBuilder meta={meta} form={form} />
        <Form.Item className="ant-form-item--btn">
          <Button type="primary" onClick={getData}>
            Add Routine
          </Button>
        </Form.Item>
      </fieldset>
      <div
        id="scrollableDiv"
        style={{
          //height: 272,
          overflow: "auto",
          padding: "0 16px",
          border: "1px solid rgba(140, 140, 140, 0.35)",
        }}
      >

// here I want to display tasks in a list
            <List
              itemLayout="horizontal"
              //dataSource={data}
              renderItem={(item) => (
                <List.Item
                  actions={[
                    <a key="list-edit">edit</a>,
                    <a onClick={() => axios.delete(`api/${item.id}`, item)} key="list-delete">
                      delete
                    </a>,
                  ]}
                >
                  <List.Item.Meta title={item.typeValue} />
                </List.Item>
              )}
            />
          </div>
      <Form.Item className="ant-form-item--btn">
        <Button type="primary" htmlType="submit">
          Submit
        </Button>
      </Form.Item>
    </Fragment>
  )
}

export default RoutineInfo
</code>```

Body:
I've created a form using antd-form-builder which contains 3 parts. In "Routines" part user can add several "Tasks" I need to collect each task information by clicking on the "Add Routine" button in an array like this:

"routinesList": [
    {
      "routinType": 1,
      "intervalDays": 20,
      "nextDueDate": "2023-01-08T15:46:33.185Z",
      "kindOfDate": 1,
      "serviceProvider": "string",
      "sop": "string",
      "displayBeforeDue": 1,
      "lastDate": "2023-01-08T15:46:33.185Z",
      "nextDate": "2023-01-08T15:46:33.185Z",
      "taskId": 1
    }
  ]

and finally send all 3 parts data to the server by clicking on submit button.
how can I do it?

here is my code for Routine part of the form:

import React, { Fragment, useEffect, useState, useCallback } from "react"

import { Form, List, Select, Input, InputNumber, Row, Col, Button } from "antd"
import FormBuilder from "antd-form-builder"
import { MinusCircleOutlined, PlusOutlined } from "@ant-design/icons"
import axios from "axios"

const Option = Select.Option
const IntervalInput = ({ value, onChange }) => (
  <Row gutter={10}>
    <Col span={16}>
      <InputNumber min={1} style={{ width: "100%" }} value={value.number} onChange={(v) => onChange({ number: v, unit: value.unit })} />
    </Col>
    <Col span={8}>
      <Select value={value.unit} onChange={(v) => onChange({ number: value.number, unit: v })}>
        <Option value="1">Day(s)</Option>
        <Option value="2">Month(s)</Option>
      </Select>
    </Col>
  </Row>
)

function RoutineInfo(props) {
  const [form] = Form.useForm()
  const [routineData, setRoutineData] = useState([])
  const [opts, setOpts] = useState({ sop: [], service: [] })
  useEffect(() => {
    const fetchOpts = async () => {
      const serviceData = await axios("api?id=3")
      setOpts({ sop: [], service: serviceData.data })
    }
    fetchOpts()
  }, [])

  const optsService = opts.service
  const serviceOptions = optsService.map(({ typeValue }) => typeValue)

  const columns = 2
  const meta = {
    columns,
    fields: [
      {
        key: "routineType",
        label: "Routine Type",
        widget: "select",
        options: [
          { label: "Calibration", value: 1 },
          { label: "Maintenance", value: 2 },
        ],
        initialValue: 1,
        colSpan: 2,
      },
      {
        key: "interval",
        label: "Interval",
        forwardRef: true,
        widget: IntervalInput,
        initialValue: { number: 30, unit: "Days" },
      },
      {
        key: "lastDate",
        label: "Last Due Date",
        widget: "date-picker",
        widgetProps: { style: { width: "100%" } },
        colSpan: 2,
      },
      {
        key: "nextDate",
        label: "Next Due Date",
        widget: "date-picker",
        widgetProps: { style: { width: "100%" } },
        colSpan: 2,
      },
      {
        key: "displayBeforeDue",
        label: "Display Before Due",
        widget: "number",
        colSpan: 2,
      },
      {
        key: "sop",
        label: "SOP",
        widget: "select",
        colSpan: 2,
      },
      {
        key: "serviceProvider",
        label: "Service Provider",
        widget: "select",
        //onChange: (e) => setRoutineData(e.target.value),
        options: serviceOptions,
        widgetProps: { showSearch: true },
        colSpan: 2,
      },
      {
        key: "task",
        label: "Task",
        //forwardRef: true,
        widget: "select",
        widgetProps: { showSearch: true },
        options: [
          { label: "Pre-filter Replacement", value: 1 },
          { label: "Oil Change", value: 2 },
        ],
        colSpan: 2,
      },
    ],
  }

  const getData = () => {
    console.log(routineData)
  }

  return (
    <Fragment>
      <fieldset className="form-frame">
        <FormBuilder meta={meta} form={form} />
        <Form.Item className="ant-form-item--btn">
          <Button type="primary" onClick={getData}>
            Add Routine
          </Button>
        </Form.Item>
      </fieldset>

// here I want to display tasks in a list
            <List
              itemLayout="horizontal"
              //dataSource={data}
              renderItem={(item) => (
                <List.Item
                  actions={[
                    edit,
                     axios.delete(`api/${item.id}`, item)} key="list-delete">
                      delete
                    ,
                  ]}
                >
                  <List.Item.Meta title={item.typeValue} />
                </List.Item>
              )}
            />

      <Form.Item className="ant-form-item--btn">
        <Button type="primary" htmlType="submit">
          Submit
        </Button>
      </Form.Item>
    </Fragment>
  )
}

export default RoutineInfo


问:
how to pass data from string type to integer to make line chart using mpandroidchart
I am making an app in android studio with java in which I want to make a line graph with the mpchart android library. The data that I want to represent in my graph is obtained by reading a sqlite database. The idea is that the x axis shows the time and date while the axis and the amount of data. The problem is that the method to insert the values into the dataset with which it is graphed only accepts numeric values and the data that I read from my database are integers and strings, so My question is how to convert the date and time string to an integer so that the graph works for me?
my code:

lineGraphClass:

```<code>public class lineGraphClass {
    int count;
    String date;

    public String getDate() {

        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }
    public int getCount() {
        return count;
    }

    public void setCount(int count) {

        this.count = count;
    }
}

</code>```

conexionsqlitehelper.class:query database:

```<code>public List<lineGraphClass> dataDebatebyGroupDate(int id){
        SQLiteDatabase db = this.getReadableDatabase();
        String query = "SELECT count(arguments.id_arguments),arguments.date_arguments FROM arguments WHERE arguments.arguments_summary_debate_relation =? ";
        Cursor cursor = db.rawQuery(query, new String[]{String.valueOf(id)});
        List<lineGraphClass> data = new ArrayList<lineGraphClass>();
        if (cursor.moveToFirst()) {
            do {
                lineGraphClass fill_data = new lineGraphClass();
                fill_data.setCount(cursor.getInt(0));
                fill_data.setDate(cursor.getString(1));
                data.add(fill_data);
            } while (cursor.moveToNext());
        }
        db.close();
        return data;
    }
</code>```

lineChart.class:class that will draw the line graph

```<code>public class lineChart extends Fragment {
    public String name,title;
    List<lineGraphClass> data;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_line_chart, container, false);
        LineChart linechart = view.findViewById(R.id.linechart);
        LineDataSet linedataset = new LineDataSet(fillDataset(),"");
        ArrayList<ILineDataSet> dataSets = new ArrayList<>();
        dataSets.add(linedataset);
        LineData linedata = new LineData(dataSets);
        linechart.setData(linedata);
        linechart.invalidate();
        return view;
    }
    private ArrayList<Entry> fillDataset() {
        ConexionSQliteHelper conn = new ConexionSQliteHelper(getContext(), "lala", null, 40);
        name = getArguments().getString("name");
        title = getArguments().getString("title");
        int id = conn.requestId(name);
        int id_text_discuss = conn.requestIdDiscuss(id, title);
        data = conn.dataDebatebyGroupDate(id_text_discuss);
        ArrayList<Entry> datavalues = new ArrayList<Entry>();
        for (int i = 0; i < data.size(); i++) {
            datavalues.add(new Entry(data.get(i).getDate(), data.get(i).getCount()));
        }
        return datavalues;
    }
}
</code>```

Body:
I am making an app in android studio with java in which I want to make a line graph with the mpchart android library. The data that I want to represent in my graph is obtained by reading a sqlite database. The idea is that the x axis shows the time and date while the axis and the amount of data. The problem is that the method to insert the values into the dataset with which it is graphed only accepts numeric values and the data that I read from my database are integers and strings, so My question is how to convert the date and time string to an integer so that the graph works for me?
my code:

lineGraphClass:

public class lineGraphClass {
    int count;
    String date;

    public String getDate() {

        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }
    public int getCount() {
        return count;
    }

    public void setCount(int count) {

        this.count = count;
    }
}

conexionsqlitehelper.class:query database:

public List<lineGraphClass> dataDebatebyGroupDate(int id){
        SQLiteDatabase db = this.getReadableDatabase();
        String query = "SELECT count(arguments.id_arguments),arguments.date_arguments FROM arguments WHERE arguments.arguments_summary_debate_relation =? ";
        Cursor cursor = db.rawQuery(query, new String[]{String.valueOf(id)});
        List<lineGraphClass> data = new ArrayList<lineGraphClass>();
        if (cursor.moveToFirst()) {
            do {
                lineGraphClass fill_data = new lineGraphClass();
                fill_data.setCount(cursor.getInt(0));
                fill_data.setDate(cursor.getString(1));
                data.add(fill_data);
            } while (cursor.moveToNext());
        }
        db.close();
        return data;
    }

lineChart.class:class that will draw the line graph

public class lineChart extends Fragment {
    public String name,title;
    List<lineGraphClass> data;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_line_chart, container, false);
        LineChart linechart = view.findViewById(R.id.linechart);
        LineDataSet linedataset = new LineDataSet(fillDataset(),"");
        ArrayList<ILineDataSet> dataSets = new ArrayList<>();
        dataSets.add(linedataset);
        LineData linedata = new LineData(dataSets);
        linechart.setData(linedata);
        linechart.invalidate();
        return view;
    }
    private ArrayList<Entry> fillDataset() {
        ConexionSQliteHelper conn = new ConexionSQliteHelper(getContext(), "lala", null, 40);
        name = getArguments().getString("name");
        title = getArguments().getString("title");
        int id = conn.requestId(name);
        int id_text_discuss = conn.requestIdDiscuss(id, title);
        data = conn.dataDebatebyGroupDate(id_text_discuss);
        ArrayList<Entry> datavalues = new ArrayList<Entry>();
        for (int i = 0; i < data.size(); i++) {
            datavalues.add(new Entry(data.get(i).getDate(), data.get(i).getCount()));
        }
        return datavalues;
    }
}


问:
Why JSON.string is ommiting some values?
```<code>console.log(saveState) //IT RETURNS {user: {lat: -20.8213224, lng: -49.3581463}}
console.log(typeof saveState) //RETURNS "object"
console.log(JSON.stringify(saveState)) //RETURNS {"user":{}}
</code>```

Why is it happening, what i'm doing wrong? I'm using Javascript

This is the code of the error:
I'm trying to take states from localStorage, and send it to redux Storage.
I'm coding in Next.JS + Redux

Codes below

app.tsx

```<code>import type { AppProps } from 'next/app'
import { localStorageKeys, storeWrapper } from '../store'
import { Provider } from 'react-redux'
import { useEffect } from 'react'
import { userUpdate } from '../store/actions/users'
import GlobalStyle from '../styles/global'
import { Navbar } from '../components/Navbar'
import CategorySelector from '../components/CategorySelector'
import Head from 'next/head'

function App({ Component, pageProps }: AppProps) {
  const {store, props} = storeWrapper.useWrappedStore(pageProps)

  useEffect(()=>{
    let state: any = localStorage.getItem(process.env.NEXT_PUBLIC_STORAGE_KEY||"")

    if(state){
        try{
            state = JSON.parse(state)
            if(state.user){
              if(!state.user.lat || !state.user.lng){
                navigator.geolocation.getCurrentPosition((pos)=>{
                  state.user.lat = pos.coords.latitude;
                  state.user.lng = pos.coords.longitude;
                })
              }
            }
            else{
              navigator.geolocation.getCurrentPosition((pos)=>{
                state.user.lat = pos.coords.latitude;
                state.user.lng = pos.coords.longitude;
              })
            }

        }catch{
            state = {}
        }
    }else{
        state = {}

        state.user = {}

        navigator.geolocation.getCurrentPosition((pos)=>{
          state.user.lat = pos.coords.latitude,
          state.user.lng = pos.coords.longitude
        })
    }

    Object.entries(localStorageKeys).map((val, index)=>{
      const [ref, key] = val
      if(state[ref]){
        switch(ref){
          case 'user':
            store.dispatch(userUpdate(state[key]))
            break
          default:
            break
        }
      }
    })
  })

  return (
    <Provider store={store}>
      <GlobalStyle />
      <Navbar />
      <CategorySelector />
      <Component {...pageProps} />
    </Provider>
  )
}

export default App
</code>```

Here is the function that isn't working well, when I'm trying to convert the state to string to save, it returns nothing, but when it is in object type, it returns lat and lng properly
saveState.ts

```<code>export const saveState = (key: string, value: any) => {
    let state: any = localStorage.getItem(keyName)
    console.log("SAVE", key, value)
    if(state){
        try{
            state = JSON.parse(state)
        }catch{
            state = {}
        }
    }else{
        state = {}
    }

    state[key] = value

    const saveState = state

    console.log(saveState)
    console.log(typeof saveState)
    console.log(JSON.stringify({saveState}))

    localStorage.setItem(keyName, JSON.stringify(state))
}
</code>```

I really dont know what to do

Body:
console.log(saveState) //IT RETURNS {user: {lat: -20.8213224, lng: -49.3581463}}
console.log(typeof saveState) //RETURNS "object"
console.log(JSON.stringify(saveState)) //RETURNS {"user":{}}

Why is it happening, what i'm doing wrong? I'm using Javascript

This is the code of the error:
I'm trying to take states from localStorage, and send it to redux Storage.
I'm coding in Next.JS + Redux

Codes below

app.tsx

import type { AppProps } from 'next/app'
import { localStorageKeys, storeWrapper } from '../store'
import { Provider } from 'react-redux'
import { useEffect } from 'react'
import { userUpdate } from '../store/actions/users'
import GlobalStyle from '../styles/global'
import { Navbar } from '../components/Navbar'
import CategorySelector from '../components/CategorySelector'
import Head from 'next/head'

function App({ Component, pageProps }: AppProps) {
  const {store, props} = storeWrapper.useWrappedStore(pageProps)

  useEffect(()=>{
    let state: any = localStorage.getItem(process.env.NEXT_PUBLIC_STORAGE_KEY||"")

    if(state){
        try{
            state = JSON.parse(state)
            if(state.user){
              if(!state.user.lat || !state.user.lng){
                navigator.geolocation.getCurrentPosition((pos)=>{
                  state.user.lat = pos.coords.latitude;
                  state.user.lng = pos.coords.longitude;
                })
              }
            }
            else{
              navigator.geolocation.getCurrentPosition((pos)=>{
                state.user.lat = pos.coords.latitude;
                state.user.lng = pos.coords.longitude;
              })
            }

        }catch{
            state = {}
        }
    }else{
        state = {}

        state.user = {}

        navigator.geolocation.getCurrentPosition((pos)=>{
          state.user.lat = pos.coords.latitude,
          state.user.lng = pos.coords.longitude
        })
    }

    Object.entries(localStorageKeys).map((val, index)=>{
      const [ref, key] = val
      if(state[ref]){
        switch(ref){
          case 'user':
            store.dispatch(userUpdate(state[key]))
            break
          default:
            break
        }
      }
    })
  })

  return (
    <Provider store={store}>
      <GlobalStyle />
      <Navbar />
      <CategorySelector />
      <Component {...pageProps} />
    </Provider>
  )
}

export default App

Here is the function that isn't working well, when I'm trying to convert the state to string to save, it returns nothing, but when it is in object type, it returns lat and lng properly
saveState.ts

export const saveState = (key: string, value: any) => {
    let state: any = localStorage.getItem(keyName)
    console.log("SAVE", key, value)
    if(state){
        try{
            state = JSON.parse(state)
        }catch{
            state = {}
        }
    }else{
        state = {}
    }

    state[key] = value

    const saveState = state

    console.log(saveState)
    console.log(typeof saveState)
    console.log(JSON.stringify({saveState}))

    localStorage.setItem(keyName, JSON.stringify(state))
}

I really dont know what to do


问:
Cannot register user info to firebase database when creating a new user
I am working on a signup form and I can create a new user using firebase auth, but the part where I register informations like the name, email... in a database is not working.
On the firebase side, I created a firestore database and a realtime database, and I don't see anything on them.
I tried to use the firebase documentation but it's still not working so I am probably missing something.
Thanks for your help!

PS: I hidded my firebase config here but it's filled on my code

import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.15.0/firebase-app.js'
import { getAuth, createUserWithEmailAndPassword } from 'https://www.gstatic.com/firebasejs/9.15.0/firebase-auth.js'
import { getFirestore, doc, getDoc, getDocs, collection } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-firestore.js";
import { getDatabase, ref, set } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-database.js";

const firebaseConfig = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: ""
  };

const app = initializeApp(firebaseConfig);
//const db = getFirestore();
const auth = getAuth();
const db = getDatabase();

submitData.addEventListener('click', (e) => {
  e.preventDefault()
    var name = document.getElementById('full_name').value
    var email = document.getElementById('email').value;
    var password = document.getElementById('psw').value;
    // do verification

    // Move on with Auth
    createUserWithEmailAndPassword(auth, email, password)
    .then((userCredential) => {

      const user = userCredential.user
      alert("user created")

      //add to firebase database
      function writeUserData( name, email) {

        set(ref(db, 'users/' + userId), {
          username: name,
          email: email,
        });
      }
    })```


问:
NativeScript installation
After installing NativeScript Im getting this error when trying to run the following command
ns doctor

```<code>C:\Program Files\Eclipse Adoptium\jdk-11.0.17.8-hotspot\bin;
C:\Program Files\Common Files\Oracle\Java\javapath;
C:\Program Files\Python310\Scripts\;
C:\Program Files\Python310\;
C:\WINDOWS\system32;
C:\WINDOWS;
C:\WINDOWS\System32\Wbem;
C:\WINDOWS\System32\WindowsPowerShell\v1.0\;
C:\WINDOWS\System32\OpenSSH\;
C:\Program Files (x86)\dotnet\;
C:\Program Files\Java\jdk-19\bin;
C:\Program Files\Git\cmd;C:\WINDOWS\system32>ns doctor
√ Getting environment information

TIP: To avoid setting up the necessary environment variables, you can use the chocolatey package manager to install the Android SDK and its dependencies.

There seem to be issues with your configuration.
√ Getting NativeScript components versions information...
√ Component nativescript has 8.4.0 version and is up to date.
√ Your ANDROID_HOME environment variable is set and points to correct directory.
√ Your adb from the Android SDK is correctly installed.
√ The Android SDK is installed.
√ A compatible Android SDK for compilation is found.
√ Local builds for iOS can be executed only on a macOS system. To build for iOS on a different operating system, you can use the NativeScript cloud infrastructure.
× Error executing command 'javac'. Make sure you have installed The Java Development Kit (JDK) and set JAVA_HOME environment variable.
 You will not be able to build your projects for Android.
To be able to build for Android, verify that you have installed The Java Development Kit (JDK) and configured it according to system requirements as
 described in https://docs.nativescript.org/environment-setup.html

× WARNING: The Java Development Kit (JDK) is not installed or is not configured properly.
 You will not be able to work with the Android SDK and you might not be able
to perform some Android-related operations. To ensure that you can develop and
test your apps for Android, verify that you have installed the JDK as
described in http://docs.oracle.com/javase/8/docs/technotes/guides/install/install_overview.html (for JDK 8).

Your environment is not configured properly and you will not be able to execute local builds.
Verify that your environment is configured according to the system requirements described at
https://docs.nativescript.org/environment-setup.html.
C:\Users\Admin\AppData\Local\Android\Sdk\platform-tools;
C:\Program Files\Java\jdk-17.0.5\bin;
C:\ProgramData\chocolatey\bin;
C:\Program Files\nodejs\;
C:\Users\Admin\AppData\Local\Microsoft\WindowsApps;
C:\Users\Admin\AppData\Local\Programs\Microsoft VS Code\bin;
C:\Program Files (x86)\BrowserStackLocal\;
C:\Program Files\JetBrains\IntelliJ IDEA 2022.1.3\bin;
C:\Program Files\MongoDB\Server\5.0\bin;
C:\Users\Admin\AppData\Local\Programs\mongosh\;
C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2022.2.3\bin;
C:\Users\Admin\AppData\Roaming\npm

Also when I checked my Environment variables I can see this

```
C:\Program Files\Eclipse Adoptium\jdk-11.0.17.8-hotspot\bin;
C:\Program Files\Common Files\Oracle\Java\javapath;
C:\Program Files\Python310\Scripts\;
C:\Program Files\Python310\;
C:\WINDOWS\system32;
C:\WINDOWS;
C:\WINDOWS\System32\Wbem;
C:\WINDOWS\System32\WindowsPowerShell\v1.0\;
C:\WINDOWS\System32\OpenSSH\;
C:\Program Files (x86)\dotnet\;
**C:\Program Files\Java\jdk-19\bin;**
C:\Program Files\Git\cmd;
C:\Users\Admin\AppData\Local\Android\Sdk\platform-tools;
**C:\Program Files\Java\jdk-17.0.5\bin;**
C:\ProgramData\chocolatey\bin;
C:\Program Files\nodejs\;
C:\Users\Admin\AppData\Local\Microsoft\WindowsApps;
C:\Users\Admin\AppData\Local\Programs\Microsoft VS Code\bin;
C:\Program Files (x86)\BrowserStackLocal\;
C:\Program Files\JetBrains\IntelliJ IDEA 2022.1.3\bin;
C:\Program Files\MongoDB\Server\5.0\bin;
C:\Users\Admin\AppData\Local\Programs\mongosh\;
C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2022.2.3\bin;
C:\Users\Admin\AppData\Roaming\npm
```

Is the multiple jdks causing the issue, please guide me

Thanks in advance :)

I tried looking into the documentation marked as red in the command line error and also on google but nowhere it talks about multiple version issue

Title: NativeScript installation

Body:
After installing NativeScript Im getting this error when trying to run the following command
ns doctor

C:\Program Files\Eclipse Adoptium\jdk-11.0.17.8-hotspot\bin;
C:\Program Files\Common Files\Oracle\Java\javapath;
C:\Program Files\Python310\Scripts\;
C:\Program Files\Python310\;
C:\WINDOWS\system32;
C:\WINDOWS;
C:\WINDOWS\System32\Wbem;
C:\WINDOWS\System32\WindowsPowerShell\v1.0\;
C:\WINDOWS\System32\OpenSSH\;
C:\Program Files (x86)\dotnet\;
C:\Program Files\Java\jdk-19\bin;
C:\Program Files\Git\cmd;C:\WINDOWS\system32>ns doctor
√ Getting environment information

TIP: To avoid setting up the necessary environment variables, you can use the chocolatey package manager to install the Android SDK and its dependencies.

There seem to be issues with your configuration.
√ Getting NativeScript components versions information...
√ Component nativescript has 8.4.0 version and is up to date.
√ Your ANDROID_HOME environment variable is set and points to correct directory.
√ Your adb from the Android SDK is correctly installed.
√ The Android SDK is installed.
√ A compatible Android SDK for compilation is found.
√ Local builds for iOS can be executed only on a macOS system. To build for iOS on a different operating system, you can use the NativeScript cloud infrastructure.
× Error executing command 'javac'. Make sure you have installed The Java Development Kit (JDK) and set JAVA_HOME environment variable.
 You will not be able to build your projects for Android.
To be able to build for Android, verify that you have installed The Java Development Kit (JDK) and configured it according to system requirements as
 described in https://docs.nativescript.org/environment-setup.html

× WARNING: The Java Development Kit (JDK) is not installed or is not configured properly.
 You will not be able to work with the Android SDK and you might not be able
to perform some Android-related operations. To ensure that you can develop and
test your apps for Android, verify that you have installed the JDK as
described in http://docs.oracle.com/javase/8/docs/technotes/guides/install/install_overview.html (for JDK 8).

Your environment is not configured properly and you will not be able to execute local builds.
Verify that your environment is configured according to the system requirements described at
https://docs.nativescript.org/environment-setup.html.
C:\Users\Admin\AppData\Local\Android\Sdk\platform-tools;
C:\Program Files\Java\jdk-17.0.5\bin;
C:\ProgramData\chocolatey\bin;
C:\Program Files\nodejs\;
C:\Users\Admin\AppData\Local\Microsoft\WindowsApps;
C:\Users\Admin\AppData\Local\Programs\Microsoft VS Code\bin;
C:\Program Files (x86)\BrowserStackLocal\;
C:\Program Files\JetBrains\IntelliJ IDEA 2022.1.3\bin;
C:\Program Files\MongoDB\Server\5.0\bin;
C:\Users\Admin\AppData\Local\Programs\mongosh\;
C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2022.2.3\bin;
C:\Users\Admin\AppData\Roaming\npm

Also when I checked my Environment variables I can see this

```
C:\Program Files\Eclipse Adoptium\jdk-11.0.17.8-hotspot\bin;
C:\Program Files\Common Files\Oracle\Java\javapath;
C:\Program Files\Python310\Scripts\;
C:\Program Files\Python310\;
C:\WINDOWS\system32;
C:\WINDOWS;
C:\WINDOWS\System32\Wbem;
C:\WINDOWS\System32\WindowsPowerShell\v1.0\;
C:\WINDOWS\System32\OpenSSH\;
C:\Program Files (x86)\dotnet\;
**C:\Program Files\Java\jdk-19\bin;**
C:\Program Files\Git\cmd;
C:\Users\Admin\AppData\Local\Android\Sdk\platform-tools;
**C:\Program Files\Java\jdk-17.0.5\bin;**
C:\ProgramData\chocolatey\bin;
C:\Program Files\nodejs\;
C:\Users\Admin\AppData\Local\Microsoft\WindowsApps;
C:\Users\Admin\AppData\Local\Programs\Microsoft VS Code\bin;
C:\Program Files (x86)\BrowserStackLocal\;
C:\Program Files\JetBrains\IntelliJ IDEA 2022.1.3\bin;
C:\Program Files\MongoDB\Server\5.0\bin;
C:\Users\Admin\AppData\Local\Programs\mongosh\;
C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2022.2.3\bin;
C:\Users\Admin\AppData\Roaming\npm

Is the multiple jdks causing the issue, please guide me

Thanks in advance :)

I tried looking into the documentation marked as red in the command line error and also on google but nowhere it talks about multiple version issue


问:
VBA: XLfilterCopy not pasting data
I have a function using xlfiltercopy that takes a table, filters it by two values and then pastes the selected row to a separate page. This works...some of the time.

I've encountered an issue where some of the selections return no values and the result is that the xlfiltercopy ends up pasting blank cells.

The function is:

```<code>Sub Vehicle_Data_Copy()

    'takes the selected vehicle type and copies it's data to the tempoary data holding sheet
    Dim iRange As Range
    Dim iCriteria As Range

    'selects the manuever data, excluding top row
    Set iRange = Sheets("Vehicle_Data").Range("A10").CurrentRegion
    Set iRange = iRange.Offset(1).Resize(iRange.Rows.Count - 1)

    'MsgBox iRange.Address
    'selects the criteria
    Set iCriteria = Sheets("Config").Range("A2:B3")

    'copies the filtered data to the destination
    Sheets("Vehicle_Data").Range("A2:T15").AdvancedFilter Action:=xlFilterCopy, CriteriaRange:=iCriteria, CopyToRange:=Sheets("Temp_Data").Range("A3:T3")
End Sub
</code>```

I ran the code step by step and confirmed that it selected the full data set, I have also confirmed that are are no spelling mistakes in the conditions so that is not the issue either.

Does anyone know what else may be causing this issue?

Thanks in advance

Title: VBA: XLfilterCopy not pasting data

Body:
I have a function using xlfiltercopy that takes a table, filters it by two values and then pastes the selected row to a separate page. This works...some of the time.

I've encountered an issue where some of the selections return no values and the result is that the xlfiltercopy ends up pasting blank cells.

The function is:

Sub Vehicle_Data_Copy()

    'takes the selected vehicle type and copies it's data to the tempoary data holding sheet
    Dim iRange As Range
    Dim iCriteria As Range

    'selects the manuever data, excluding top row
    Set iRange = Sheets("Vehicle_Data").Range("A10").CurrentRegion
    Set iRange = iRange.Offset(1).Resize(iRange.Rows.Count - 1)

    'MsgBox iRange.Address
    'selects the criteria
    Set iCriteria = Sheets("Config").Range("A2:B3")

    'copies the filtered data to the destination
    Sheets("Vehicle_Data").Range("A2:T15").AdvancedFilter Action:=xlFilterCopy, CriteriaRange:=iCriteria, CopyToRange:=Sheets("Temp_Data").Range("A3:T3")
End Sub

I ran the code step by step and confirmed that it selected the full data set, I have also confirmed that are are no spelling mistakes in the conditions so that is not the issue either.

Does anyone know what else may be causing this issue?

Thanks in advance


问:
How to make a query to Firestore databse, wait the result and look for a url
I want to make a query to Firestore database to get a url stored. Then with that url I want to show the .txt that cointains the url.
My problem is that the code executes automatically and doesn't wait to end the query.
I want to:

Store the url in a variable.

With that variable take the .txt and read line by line in a texview.
I can do both, but separately, when I try to do it together I have the problem, I need to wait the result and then continue executing the code. How can I do it?
My code is:

```<code>String idioma, modo, cuento, url_cuento;
FirebaseFirestore db = FirebaseFirestore.getInstance();
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reproductor_cuento);

        //Hacemos llamada a clase para mostrar la pantalla completa
        PantallaCompleta pantallaCompleta = new PantallaCompleta();
        View decorView = getWindow().getDecorView();
        pantallaCompleta.pantallaCompleta(decorView);

        //Recogemos los parametros que se pasan por activities
        Bundle extra = this.getIntent().getExtras();
        idioma = extra.getString("idioma");
        modo = extra.getString("modo");
        cuento = extra.getString("cuento");

        url_cuento = consultaTxtCuento(cuento, idioma);
        new GetData().execute();
    }

public String consultaTxtCuento(String cuento, String idioma){
        final String[] urlTxt = new String[1];
        DocumentReference docRef = db.collection("cuentos").document(cuento);
        docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if (task.isSuccessful()) {
                    DocumentSnapshot document = task.getResult();
                    if (document.exists()) {
                        urlTxt[0] = document.get("txt_" + idioma).toString();
                        System.out.println("Se obtiene como URL -> " + urlTxt[0]);
                    }
                } else {
                    Log.d(TAG, "get failed with ", task.getException());
                }
            }
        });
        return urlTxt[0];
    }

    class GetData extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            HttpURLConnection urlConnection = null;
            String result = "";
            try {
                URL url = new URL(url_cuento);
                urlConnection = (HttpURLConnection) url.openConnection();
                int code = urlConnection.getResponseCode();
                if(code==200){
                    InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                    if (in != null) {
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
                        String line = "";
                        while ((line = bufferedReader.readLine()) != null)
                            result += line;
                    }
                    in.close();
                }
                return result;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            finally {
                urlConnection.disconnect();
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
        }
    }
</code>```

What can I do to execute waiting the results? Thanks

Body:
I want to make a query to Firestore database to get a url stored. Then with that url I want to show the .txt that cointains the url.
My problem is that the code executes automatically and doesn't wait to end the query.
I want to:

Store the url in a variable.

With that variable take the .txt and read line by line in a texview.
I can do both, but separately, when I try to do it together I have the problem, I need to wait the result and then continue executing the code. How can I do it?
My code is:

String idioma, modo, cuento, url_cuento;
FirebaseFirestore db = FirebaseFirestore.getInstance();
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reproductor_cuento);

        //Hacemos llamada a clase para mostrar la pantalla completa
        PantallaCompleta pantallaCompleta = new PantallaCompleta();
        View decorView = getWindow().getDecorView();
        pantallaCompleta.pantallaCompleta(decorView);

        //Recogemos los parametros que se pasan por activities
        Bundle extra = this.getIntent().getExtras();
        idioma = extra.getString("idioma");
        modo = extra.getString("modo");
        cuento = extra.getString("cuento");

        url_cuento = consultaTxtCuento(cuento, idioma);
        new GetData().execute();
    }

public String consultaTxtCuento(String cuento, String idioma){
        final String[] urlTxt = new String[1];
        DocumentReference docRef = db.collection("cuentos").document(cuento);
        docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if (task.isSuccessful()) {
                    DocumentSnapshot document = task.getResult();
                    if (document.exists()) {
                        urlTxt[0] = document.get("txt_" + idioma).toString();
                        System.out.println("Se obtiene como URL -> " + urlTxt[0]);
                    }
                } else {
                    Log.d(TAG, "get failed with ", task.getException());
                }
            }
        });
        return urlTxt[0];
    }

    class GetData extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            HttpURLConnection urlConnection = null;
            String result = "";
            try {
                URL url = new URL(url_cuento);
                urlConnection = (HttpURLConnection) url.openConnection();
                int code = urlConnection.getResponseCode();
                if(code==200){
                    InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                    if (in != null) {
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
                        String line = "";
                        while ((line = bufferedReader.readLine()) != null)
                            result += line;
                    }
                    in.close();
                }
                return result;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            finally {
                urlConnection.disconnect();
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
        }
    }

What can I do to execute waiting the results? Thanks


问:
Why is the val_acc of my model 4 classification always around 25%? My train_acc is increasing
I train my model in Colab. I want to use mobilenet_v2 model to classify picture to 4 categories, but the accuracy is always about 25%.

And the train_acc is increasing, but the val_acc is not.

Part of my code as follows:

base_model = tf.keras.applications.mobilenet_v2.MobileNetV2(input_shape=(224,224,3), weights=None, classes=4)

from tensorflow.keras.optimizers import RMSprop
base_model.compile(loss='categorical_crossentropy',
              optimizer=RMSprop(lr=0.001),
              metrics=['acc'])

from tensorflow.keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale=1/255)
train_generator = train_datagen.flow_from_directory(
    'GarbageForMaixHub',
    target_size=(224,224),
    batch_size=16,
    class_mode='categorical'
)

base_model.fit(
    train_generator,
    steps_per_epoch=64,
    epochs=5,
    verbose=1,
    validation_data=train_generator,  # same to train data
    validation_steps=16
)
```
<p>And part of the outputs as follows:</p>
```Epoch 1/5
64/64 [==============================] - 15s 226ms/step - loss: 1.1683 - acc: 0.4434 - val_loss: 1.4742 - val_acc: 0.2070
Epoch 2/5
64/64 [==============================] - 15s 228ms/step - loss: 1.2155 - acc: 0.4258 - val_loss: 1.4351 - val_acc: 0.2852
Epoch 3/5
64/64 [==============================] - 15s 228ms/step - loss: 1.1015 - acc: 0.5029 - val_loss: 1.4660 - val_acc: 0.2617
Epoch 4/5
64/64 [==============================] - 14s 223ms/step - loss: 1.0972 - acc: 0.5088 - val_loss: 1.5096 - val_acc: 0.2852
Epoch 5/5
64/64 [==============================] - 14s 222ms/step - loss: 1.0932 - acc: 0.5195 - val_loss: 1.6133 - val_acc: 0.2266
<keras.callbacks.History at 0x7ff01f7eeeb0>
```

The val_acc is so different from train_acc when I used my train_generator as my validation_generator.

What could I do to solve, or to avoid such problem?

I feel a little clueless. I tried some different model such as tf.keras.applications.EfficientNetB0, but it's no different. I have check the picture and labels, no problems found.

Body:
I train my model in Colab. I want to use mobilenet_v2 model to classify picture to 4 categories, but the accuracy is always about 25%.

And the train_acc is increasing, but the val_acc is not.

Part of my code as follows:

base_model = tf.keras.applications.mobilenet_v2.MobileNetV2(input_shape=(224,224,3), weights=None, classes=4)

from tensorflow.keras.optimizers import RMSprop
base_model.compile(loss='categorical_crossentropy',
              optimizer=RMSprop(lr=0.001),
              metrics=['acc'])

from tensorflow.keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale=1/255)
train_generator = train_datagen.flow_from_directory(
    'GarbageForMaixHub',
    target_size=(224,224),
    batch_size=16,
    class_mode='categorical'
)

base_model.fit(
    train_generator,
    steps_per_epoch=64,
    epochs=5,
    verbose=1,
    validation_data=train_generator,  # same to train data
    validation_steps=16
)

And part of the outputs as follows:

Epoch 1/5
64/64 [==============================] - 15s 226ms/step - loss: 1.1683 - acc: 0.4434 - val_loss: 1.4742 - val_acc: 0.2070
Epoch 2/5
64/64 [==============================] - 15s 228ms/step - loss: 1.2155 - acc: 0.4258 - val_loss: 1.4351 - val_acc: 0.2852
Epoch 3/5
64/64 [==============================] - 15s 228ms/step - loss: 1.1015 - acc: 0.5029 - val_loss: 1.4660 - val_acc: 0.2617
Epoch 4/5
64/64 [==============================] - 14s 223ms/step - loss: 1.0972 - acc: 0.5088 - val_loss: 1.5096 - val_acc: 0.2852
Epoch 5/5
64/64 [==============================] - 14s 222ms/step - loss: 1.0932 - acc: 0.5195 - val_loss: 1.6133 - val_acc: 0.2266
<keras.callbacks.History at 0x7ff01f7eeeb0>

The val_acc is so different from train_acc when I used my train_generator as my validation_generator.

What could I do to solve, or to avoid such problem?

I feel a little clueless. I tried some different model such as tf.keras.applications.EfficientNetB0, but it's no different. I have check the picture and labels, no problems found.


问:
Spring boot - $sample doesn't work on @Aggregation annotation
I have the following method in a MongoDB Repository interface

```<code>@org.springframework.stereotype.Repository
public interface AnecdoteRepository extends org.springframework.data.mongodb.repository.MongoRepository<Anecdote, Long> {

    @Aggregation(pipeline = { "{$sample:{size: 1}}" })
    Optional<Anecdote> findRandom();

}
</code>```

I have 20 records on Anecdote collection, but when I call directly this method, it returns me an empty Optional.

However, I have the same aggregation on MongoDB Compass and it returns me an only record, as I want.

Aggregation structure

Result

Should I add more records? Or what's wrong with the first pipeline in aggregation?

I'm using spring-boot-starter-data-mongodb library

Body:
I have the following method in a MongoDB Repository interface

@org.springframework.stereotype.Repository
public interface AnecdoteRepository extends org.springframework.data.mongodb.repository.MongoRepository<Anecdote, Long> {

    @Aggregation(pipeline = { "{$sample:{size: 1}}" })
    Optional<Anecdote> findRandom();

}

I have 20 records on Anecdote collection, but when I call directly this method, it returns me an empty Optional.

However, I have the same aggregation on MongoDB Compass and it returns me an only record, as I want.

Aggregation structure

Result

Should I add more records? Or what's wrong with the first pipeline in aggregation?

I'm using spring-boot-starter-data-mongodb library


问:
Issue with .CSV being inaccessible due to it being used by another process - VB.NET Application
We are having an issue with a .CSV file, it is being locked by another process on any shared folder location.

Before mid December this worked with no problem, but since then our guys keep getting this same error on the files. "The process cannot access the file "Filename.." because it is being used by another process" Once they are written into once and it appears that the shared file resource is keeping this file open, we have checked and we can see the close request coming through on the file server but it doesn't appear to be successfully closing said file.

Here is the code snippet which I have chopped down to get rid of the unnecessary information for our VB.Net application which creates and writes to the file in case it relates to it but it appears to be something with file sharing on Windows.

```<code>        Try
            Dim nowPathString As String = Now().ToString("yyyyMMdd-hhmmss")
            Dim nowString As String = Now().ToString() '
            Dim csvFilePath As String = $\\webserver\ExcelTest\Test-{nowPathString}.csv 'Path to create or existing file
            Dim outFile As IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(csvFilePath, False)
            outFile.WriteLine("Warehouse, StockItemCode, AllocationQuantity, Reference, SecondReference, ActivityDate")
            outFile.WriteLine($"Main, SHE060, 1, 123456, 123456-1, {nowString}")
            outFile.Close()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

</code>```

Any help or suggestions on this is greatly appreciated!

We thought this issue may be server related so we created a shared folder on our local C drive and the same issue occurred but if you save the file onto your local C drive normally it works.

The way to get around this being stored on our server is to go in and manually close the file down by using console root and the "Shared Folders" snap-in.

Body:
We are having an issue with a .CSV file, it is being locked by another process on any shared folder location.

Before mid December this worked with no problem, but since then our guys keep getting this same error on the files. "The process cannot access the file "Filename.." because it is being used by another process" Once they are written into once and it appears that the shared file resource is keeping this file open, we have checked and we can see the close request coming through on the file server but it doesn't appear to be successfully closing said file.

Here is the code snippet which I have chopped down to get rid of the unnecessary information for our VB.Net application which creates and writes to the file in case it relates to it but it appears to be something with file sharing on Windows.

        Try
            Dim nowPathString As String = Now().ToString("yyyyMMdd-hhmmss")
            Dim nowString As String = Now().ToString() '
            Dim csvFilePath As String = $\\webserver\ExcelTest\Test-{nowPathString}.csv 'Path to create or existing file
            Dim outFile As IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(csvFilePath, False)
            outFile.WriteLine("Warehouse, StockItemCode, AllocationQuantity, Reference, SecondReference, ActivityDate")
            outFile.WriteLine($"Main, SHE060, 1, 123456, 123456-1, {nowString}")
            outFile.Close()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

Any help or suggestions on this is greatly appreciated!

We thought this issue may be server related so we created a shared folder on our local C drive and the same issue occurred but if you save the file onto your local C drive normally it works.

The way to get around this being stored on our server is to go in and manually close the file down by using console root and the "Shared Folders" snap-in.


问:
What happens if parquet based external table is in loading process and the same table is used to load other table
What happens if parquet based external table is in loading process and the same table is used to load another table.

In SQL server, we had NOLOCK hint to avoid dirty reads. What to do here in Snowflake ?

Thank You.


问:
Open .xlsb with ExcelDataReader
ExcelDataReader documentation says that it can open .xlsb files.

```<code>using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
{
    // Auto-detect format, supports:
    //  - Binary Excel files (2.0-2003 format; *.xls)
    //  - OpenXml Excel files (2007 format; *.xlsx, *.xlsb)
    using (var reader = ExcelReaderFactory.CreateReader(stream))
    {
        // Choose one of either 1 or 2:

        // 1. Use the reader methods
        do
        {
            while (reader.Read())
            {
                // reader.GetDouble(0);
            }
        } while (reader.NextResult());

        // 2. Use the AsDataSet extension method
        var result = reader.AsDataSet();

        // The result of each spreadsheet is in result.Tables
    }
}
</code>```

But when I try to open a .xlsb stream, it gives an error saying that it can't open a zip file.

I have tried to see if any free third party lib that can convert xlsb to XLS, without any luck.

Title: Open .xlsb with ExcelDataReader

Body:
ExcelDataReader documentation says that it can open .xlsb files.

using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
{
    // Auto-detect format, supports:
    //  - Binary Excel files (2.0-2003 format; *.xls)
    //  - OpenXml Excel files (2007 format; *.xlsx, *.xlsb)
    using (var reader = ExcelReaderFactory.CreateReader(stream))
    {
        // Choose one of either 1 or 2:

        // 1. Use the reader methods
        do
        {
            while (reader.Read())
            {
                // reader.GetDouble(0);
            }
        } while (reader.NextResult());

        // 2. Use the AsDataSet extension method
        var result = reader.AsDataSet();

        // The result of each spreadsheet is in result.Tables
    }
}

But when I try to open a .xlsb stream, it gives an error saying that it can't open a zip file.

I have tried to see if any free third party lib that can convert xlsb to XLS, without any luck.


问:
Getting the session data from ASP classic isn't working
I am currently tasked with moving one of our older bits of software to a new server. The old server is running 2008 and the new server is on 2019. The code is a mixture of ASP and ASP.NET, both using VB. Unfortunately, I'm a C# developer and my VB knowledge is slight.

The main bit of the code is the older and is all in ASP and works fine on the new server. For a particular set of customers there is an add-on that is more recent and uses ASP.NET. For the new section of code to get the details of the logged in user it uses the code given in this answer. Unfortunately it seems like it is this bit of code that is failing.

We have this bit of code in our site.master.vb

```<code>ctx1 = ctx.Request.Url.Scheme
ctx2 = ctx.Request.Url.Host
dom = ctx1 + "://" + ctx2

Dim ASPRequest As HttpWebRequest = WebRequest.Create(New Uri(dom + "/arc/asp2netbridge.asp?sessVar=" + sessionValue))
ASPRequest.ContentType = "text/html"
ASPRequest.Credentials = CredentialCache.DefaultCredentials
If (ASPRequest.CookieContainer Is Nothing) Then
    ASPRequest.CookieContainer = New CookieContainer()
End If
</code>```

The asp2netbridge.asp file is stored in the directory one up from the directory that contains the code and the directory structure looks the same on both servers. The contents of the as2netbridge file are the the same as in the example code linked above with the addition of some extra comments.

It then calls a Stored Procedure on our database with the customer ID from session that should return the customer details as XML, but instead we get a 'Root Element is missing' Error. If I change the Stored Procedure to hard code the customer ID in it, rather than as a parameter then it works as expected.

Is there anything that I need to install on our server to get the system working correctly? Or is there anything else I need to do to get it to work?

Body:
I am currently tasked with moving one of our older bits of software to a new server. The old server is running 2008 and the new server is on 2019. The code is a mixture of ASP and ASP.NET, both using VB. Unfortunately, I'm a C# developer and my VB knowledge is slight.

The main bit of the code is the older and is all in ASP and works fine on the new server. For a particular set of customers there is an add-on that is more recent and uses ASP.NET. For the new section of code to get the details of the logged in user it uses the code given in this answer. Unfortunately it seems like it is this bit of code that is failing.

We have this bit of code in our site.master.vb

ctx1 = ctx.Request.Url.Scheme
ctx2 = ctx.Request.Url.Host
dom = ctx1 + "://" + ctx2

Dim ASPRequest As HttpWebRequest = WebRequest.Create(New Uri(dom + "/arc/asp2netbridge.asp?sessVar=" + sessionValue))
ASPRequest.ContentType = "text/html"
ASPRequest.Credentials = CredentialCache.DefaultCredentials
If (ASPRequest.CookieContainer Is Nothing) Then
    ASPRequest.CookieContainer = New CookieContainer()
End If

The asp2netbridge.asp file is stored in the directory one up from the directory that contains the code and the directory structure looks the same on both servers. The contents of the as2netbridge file are the the same as in the example code linked above with the addition of some extra comments.

It then calls a Stored Procedure on our database with the customer ID from session that should return the customer details as XML, but instead we get a 'Root Element is missing' Error. If I change the Stored Procedure to hard code the customer ID in it, rather than as a parameter then it works as expected.

Is there anything that I need to install on our server to get the system working correctly? Or is there anything else I need to do to get it to work?


问:
Generic implementation of backend crud actions - react typescript
I have a MERN project, using MongoDB, and I wish to turn it into a generic form, so for example it could also retrieve data from Monday's API for example.

I am a bit confused as for how would it be the correct, efficient way of doing so.

Right now, my backend consists mainly of the following folders and files:

server.ts: responsible for connecting my mongoose to MongoDB:

```<code>import express, { Express, Request, Response } from "express";
import dotenv from "dotenv";
import mongoose from "mongoose";
import cors from "cors";

const issueRoutes = require("./routes/issueRoutes");
const usersRoutes = require("./routes/usersRoutes");

dotenv.config();

mongoose.set("strictQuery", false);

const app: Express = express();
const port = process.env.PORT;

const uri: string = `mongodb+srv://${process.env.MONGO_USER}:${process.env.MONGO_PW}@cluster0.n2k7xvu.mongodb.net/${process.env.MONGO_DB}`;
app.use(cors());
app.use(express.json());
app.use(issueRoutes);
app.use(usersRoutes);

mongoose.connect(uri).then(() =>
  app.listen(process.env.PORT, () => {
    console.log(
      `[server]: Server is running at https://localhost:${process.env.PORT}`
    );
  })
);
</code>```

Three folders: Models/Routes/Controllers, which are implemented in a standard way, intended to use MongoDB

Example of my issueController, responsible of handling in the backend the api requests:

```<code>//@ts-nocheck
import { Response, Request } from "express";
import IssueInterface from "../types/IssueInterface";
import Issue from "../models/issueModel";
import { ref, uploadBytes, listAll } from "firebase/storage";

var ObjectID = require("mongodb").ObjectID;

export const getIssueById = async (
  req: Request,
  res: Response
) => {
  try {
    console.log("i'm in issue by id backend");
    const { id } = req.params;
    const body = req.body;
    const issue: IssueInterface | null = await Issue.findOne({ _id: id });
    res.status(200).json(issue);
  } catch (err) {
    res.status(404).json({ message: "error getIssueById" });
  }
};

export const getAllIssues = async (
  req: Request,
  res: Response
) => {
  try {
    const issues: IssueInterface[] = await Issue.find({});
    res.status(200).json({ issues, msg: "getAllIssues" });
  } catch (err) {
    res.status(500).json({ msg: "failed getting issues' images", error: err });
  }
};
//insert issue. retrieve the object id returned by mongodb. add image to firebase storage with id of the issue.
export const createIssue = async (
  req: Request,
  res: Response
) => {
  try {
    const answerDb = await Issue.collection.insertOne(req.body);
    res.json(answerDb.insertedId);
  } catch (err) {
    res.status(500).json({ message: "error createIssue" });
  }
};

export const updateIssueById = async (
  req: Request,
  res: Response
) => {
  try {
    const { id } = req.params;
    const body = req.body;
    console.log("in update issue by id: ", id);
    const updateIssue: IssueInterface | null = await Issue.findByIdAndUpdate(
      { _id: id },
      body
    );

    const allIssue: IssueInterface[] = await Issue.find();
    res.status(200).json({
      message: "User updated!",
      issue: updateIssue,
      issues: allIssue,
    });
  } catch (err) {
    res.status(500).json({ message: "error updateIssueById" });
  }
};

// getAllIssuesSortedByCompanyName
// getAllIssuesSortedByIssueDate
// getAllIssuesSortedBySeverity

export const getAllIssuesSortedBySeverity = async (
  req: Request,
  res: Response
) => {
  try {
    const allIssue: IssueInterface[] = await Issue.find().sort("severity");
    res.status(200).json({
      message: "Issues retrieved sorted by severity!",
      issues: allIssue,
    });
  } catch (err) {
    res.status(500).json({ message: "error getAllIssuesSortedBySeverity" });
  }
};

export const getAllIssuesSortedByCompanyName = async (
  req: Request,
  res: Response
) => {
  try {
    const allIssue: IssueInterface[] = await Issue.find().sort("company_name");
    res.status(200).json({
      message: "Issues retrieved sorted by company_name!",
      issues: allIssue,
    });
  } catch (err) {
    res.status(500).json({ message: "error getAllIssuesSortedByCompanyName" });
  }
};

export const getAllIssuesSortedByIssueDate = async (
  req: Request,
  res: Response
) => {
  try {
    const allIssue: IssueInterface[] = await Issue.find().sort(
      "start_issue_date"
    );
    res.status(200).json({
      message: "Issues retrieved sorted by start_issue_date!",
      issues: allIssue,
    });
  } catch (err) {
    res.status(500).json({ message: "error getAllIssuesSortedByIssueDate" });
  }
};

export const addNewIssueMessage = async (
  req: Request,
  res: Response
) => {
  try {
    const issue = await Issue.findByIdAndUpdate(
      req.body._id,
      {
        issue_messages: req.body.issue_messages,
      },
      { $currentDate: { lastModified: true } }
    );
    res
      .status(200)
      .json({ status: 200, data: issue, timeStamp: ObjectID.timeStamp });
  } catch (err) {
    console.log("error creating new issue: ", err);
  }
};
</code>```

Considering the fact that Controllers is made out of 'many' small functions, how would you make it generic?

I'm missing a piece in the puzzle.

Regards :_)

Body:
I have a MERN project, using MongoDB, and I wish to turn it into a generic form, so for example it could also retrieve data from Monday's API for example.

I am a bit confused as for how would it be the correct, efficient way of doing so.

Right now, my backend consists mainly of the following folders and files:

server.ts: responsible for connecting my mongoose to MongoDB:

import express, { Express, Request, Response } from "express";
import dotenv from "dotenv";
import mongoose from "mongoose";
import cors from "cors";

const issueRoutes = require("./routes/issueRoutes");
const usersRoutes = require("./routes/usersRoutes");

dotenv.config();

mongoose.set("strictQuery", false);

const app: Express = express();
const port = process.env.PORT;

const uri: string = `mongodb+srv://${process.env.MONGO_USER}:${process.env.MONGO_PW}@cluster0.n2k7xvu.mongodb.net/${process.env.MONGO_DB}`;
app.use(cors());
app.use(express.json());
app.use(issueRoutes);
app.use(usersRoutes);

mongoose.connect(uri).then(() =>
  app.listen(process.env.PORT, () => {
    console.log(
      `[server]: Server is running at https://localhost:${process.env.PORT}`
    );
  })
);

Three folders: Models/Routes/Controllers, which are implemented in a standard way, intended to use MongoDB

Example of my issueController, responsible of handling in the backend the api requests:

//@ts-nocheck
import { Response, Request } from "express";
import IssueInterface from "../types/IssueInterface";
import Issue from "../models/issueModel";
import { ref, uploadBytes, listAll } from "firebase/storage";

var ObjectID = require("mongodb").ObjectID;

export const getIssueById = async (
  req: Request,
  res: Response
) => {
  try {
    console.log("i'm in issue by id backend");
    const { id } = req.params;
    const body = req.body;
    const issue: IssueInterface | null = await Issue.findOne({ _id: id });
    res.status(200).json(issue);
  } catch (err) {
    res.status(404).json({ message: "error getIssueById" });
  }
};

export const getAllIssues = async (
  req: Request,
  res: Response
) => {
  try {
    const issues: IssueInterface[] = await Issue.find({});
    res.status(200).json({ issues, msg: "getAllIssues" });
  } catch (err) {
    res.status(500).json({ msg: "failed getting issues' images", error: err });
  }
};
//insert issue. retrieve the object id returned by mongodb. add image to firebase storage with id of the issue.
export const createIssue = async (
  req: Request,
  res: Response
) => {
  try {
    const answerDb = await Issue.collection.insertOne(req.body);
    res.json(answerDb.insertedId);
  } catch (err) {
    res.status(500).json({ message: "error createIssue" });
  }
};

export const updateIssueById = async (
  req: Request,
  res: Response
) => {
  try {
    const { id } = req.params;
    const body = req.body;
    console.log("in update issue by id: ", id);
    const updateIssue: IssueInterface | null = await Issue.findByIdAndUpdate(
      { _id: id },
      body
    );

    const allIssue: IssueInterface[] = await Issue.find();
    res.status(200).json({
      message: "User updated!",
      issue: updateIssue,
      issues: allIssue,
    });
  } catch (err) {
    res.status(500).json({ message: "error updateIssueById" });
  }
};

// getAllIssuesSortedByCompanyName
// getAllIssuesSortedByIssueDate
// getAllIssuesSortedBySeverity

export const getAllIssuesSortedBySeverity = async (
  req: Request,
  res: Response
) => {
  try {
    const allIssue: IssueInterface[] = await Issue.find().sort("severity");
    res.status(200).json({
      message: "Issues retrieved sorted by severity!",
      issues: allIssue,
    });
  } catch (err) {
    res.status(500).json({ message: "error getAllIssuesSortedBySeverity" });
  }
};

export const getAllIssuesSortedByCompanyName = async (
  req: Request,
  res: Response
) => {
  try {
    const allIssue: IssueInterface[] = await Issue.find().sort("company_name");
    res.status(200).json({
      message: "Issues retrieved sorted by company_name!",
      issues: allIssue,
    });
  } catch (err) {
    res.status(500).json({ message: "error getAllIssuesSortedByCompanyName" });
  }
};

export const getAllIssuesSortedByIssueDate = async (
  req: Request,
  res: Response
) => {
  try {
    const allIssue: IssueInterface[] = await Issue.find().sort(
      "start_issue_date"
    );
    res.status(200).json({
      message: "Issues retrieved sorted by start_issue_date!",
      issues: allIssue,
    });
  } catch (err) {
    res.status(500).json({ message: "error getAllIssuesSortedByIssueDate" });
  }
};

export const addNewIssueMessage = async (
  req: Request,
  res: Response
) => {
  try {
    const issue = await Issue.findByIdAndUpdate(
      req.body._id,
      {
        issue_messages: req.body.issue_messages,
      },
      { $currentDate: { lastModified: true } }
    );
    res
      .status(200)
      .json({ status: 200, data: issue, timeStamp: ObjectID.timeStamp });
  } catch (err) {
    console.log("error creating new issue: ", err);
  }
};

Considering the fact that Controllers is made out of 'many' small functions, how would you make it generic?

I'm missing a piece in the puzzle.

Regards :_)


问:
What is the easiest way to get the loss history from a .tfevents file?
I'm training a Tensorflow model making use of the TF ODA, object_detection.model_lib_v2.train_loop. This function creates a .tfevents file that can be red with Tensorboard.

Tensorboard prints graphs regarding the evolution of the loss/mAP of a training by reading this file. I want to be able to read it so that I can make a graph of the evolution of the loss with another library (MLFlow in this case).

Which is the simplest way to output the evolution of the loss as a list from this file? I'm using Python 3.9.

Thanks!