问:
How to rename a directory/folder on GitHub website?
I was able to find a way on GitHub Website to rename a single file and did so with success.

I was also able to find a way to rename a whole repository and did that with success.

Does anyone know how to do this to a single directory without using command line? For reference, I am trying to change a directory named InterviewTesting (that contains source files, etc) to something else. I tried doing it the single file way.
 But this didn't allow me to change the name of the directory (InterviewTesting), only the actual file name.

答: Go into your directory and click on 'Settings' next to the little cog. There is a field to rename your directory.</p>


来源: stackexchange

问:
BAPI for getting material and order BOM?
Is there a BAPI for getting material and order BOM?

Function modules won't help as those can't be called remotely.

答:
You can use CSAP_MAT_BOM_READ module like this

```<code>DATA:
  lt_stpo         TYPE TABLE OF stpo_api02,
  lt_stko         TYPE TABLE OF stko_api02,
  lt_dep_data     TYPE TABLE OF csdep_dat,
  lt_dep_descr    TYPE TABLE OF csdep_desc,
  lt_dep_order    TYPE TABLE OF csdep_ord,
  lt_dep_source   TYPE TABLE OF csdep_sorc,
  lt_dep_doc      TYPE TABLE OF csdep_doc,
  lt_doc_link     TYPE TABLE OF csdoc_link,
  lt_dmu_tmx      TYPE TABLE OF csdmu_tmx,
  lt_ltx_line     TYPE TABLE OF csltx_line,
  lt_stpu         TYPE TABLE OF stpu_api01.

CALL FUNCTION 'CSAP_MAT_BOM_READ'
  EXPORTING
    material     = 'P-501'
    plant        = '1000'
    bom_usage    = '1'
  TABLES
    t_stpo       = lt_stpo
    t_stko       = lt_stko
    t_dep_data   = lt_dep_data
    t_dep_descr  = lt_dep_descr
    t_dep_order  = lt_dep_order
    t_dep_source = lt_dep_source
    t_dep_doc    = lt_dep_doc
    t_doc_link   = lt_doc_link
    t_dmu_tmx    = lt_dmu_tmx
    t_ltx_line   = lt_ltx_line
    t_stpu       = lt_stpu
  EXCEPTIONS
    error        = 1
    OTHERS       = 2.
</code>```

It is remote-enabled so can be perfectly called outside

ContentLicense: CC BY-SA 4.0

Body:
You can use CSAP_MAT_BOM_READ module like this

DATA:
  lt_stpo         TYPE TABLE OF stpo_api02,
  lt_stko         TYPE TABLE OF stko_api02,
  lt_dep_data     TYPE TABLE OF csdep_dat,
  lt_dep_descr    TYPE TABLE OF csdep_desc,
  lt_dep_order    TYPE TABLE OF csdep_ord,
  lt_dep_source   TYPE TABLE OF csdep_sorc,
  lt_dep_doc      TYPE TABLE OF csdep_doc,
  lt_doc_link     TYPE TABLE OF csdoc_link,
  lt_dmu_tmx      TYPE TABLE OF csdmu_tmx,
  lt_ltx_line     TYPE TABLE OF csltx_line,
  lt_stpu         TYPE TABLE OF stpu_api01.

CALL FUNCTION 'CSAP_MAT_BOM_READ'
  EXPORTING
    material     = 'P-501'
    plant        = '1000'
    bom_usage    = '1'
  TABLES
    t_stpo       = lt_stpo
    t_stko       = lt_stko
    t_dep_data   = lt_dep_data
    t_dep_descr  = lt_dep_descr
    t_dep_order  = lt_dep_order
    t_dep_source = lt_dep_source
    t_dep_doc    = lt_dep_doc
    t_doc_link   = lt_doc_link
    t_dmu_tmx    = lt_dmu_tmx
    t_ltx_line   = lt_ltx_line
    t_stpu       = lt_stpu
  EXCEPTIONS
    error        = 1
    OTHERS       = 2.

It is remote-enabled so can be perfectly called outside


问:
Function returning object type
When I define an object in Typescript, it can not have properties not specified in its types:

However, when I define a function which returns an object, this object can have more properties than the ones specified in its types:

type Style = { color: string };
type IFunction = () => Style

const foo: Style = {
    color: "red",
    toto:"blue" // error yeah :)
}

const bar: IFunction = () => ({
    color: "red",
    toto:"blue"
})
```

<p>How can I do to specify that I only want to return the properties specified in my object type, and I want to raise an error whenever some extra property is added ?</p>

<p>Typescript example here</p>

<p>EDIT: I should have specified that I would prefer not to tell explicitly the returning type like that:</p>

<pre class="lang-js prettyprint-override"><code>const bar: IFunction = ():Style => ({
    color: "red",
    toto:"blue"
})
</code>```

Indeed, I want to use this code for every React component in my App and it's going to be really cumbersome to specify this type every single time

答:
Try like below, say explicitly about the function return type

```<code>type Style = { color: string };
type IFunction = () => Style;

const foo: Style = {
    color: "red",
    toto: "blue" // error yeah :)
};

const bar: IFunction = (): Style => ({
    color: "red",
    toto: "blue" // no error ??????
});
</code>```

Property excessive checks won't work until explicitly say the type in below scenario as well(as of TypeScript 3.4), In Typescript 3.5 improved excess Property checks in union types

```<code>function checkStyle(style: Style) {}

checkStyle({
    color: "red",
    toto: "blue" // cast to Style, no error yeah :(
} as Style);

let foo3 = {
    color: "red",
    toto: "blue" // no type annotation and no error yeah :(
};

checkStyle(foo3);
</code>```

The reason for not throwing an error is type widening when TypeScript checks whether or not one object type is assignable to another object type. As long as color property exists on object TypeScript will be happy.

Title: Function returning object type

Body:
When I define an object in Typescript, it can not have properties not specified in its types:

However, when I define a function which returns an object, this object can have more properties than the ones specified in its types:

type Style = { color: string };
type IFunction = () => Style

const foo: Style = {
    color: "red",
    toto:"blue" // error yeah :)
}

const bar: IFunction = () => ({
    color: "red",
    toto:"blue"
})

How can I do to specify that I only want to return the properties specified in my object type, and I want to raise an error whenever some extra property is added ?

<a href="https://www.typescriptlang.org/play/#src=type%20Style%20%3D%20%7B%20color%3A%20string%20%7D%3B%0D%0Atype%20IFunction%20%3D%20()%20%3D%3E%20Style%0D%0A%0D%0Aconst%20foo%3A%20Style%20%3D%20%7B%0D%0A%20%20%20%20color%3A%20%22red%22%2C%0D%0A%20%20%20%20toto%3A%22blue%22%20%2F%2F%20error%20yeah%20%3A)%0D%0A%7D%0D%0A%0D%0Aconst%20bar%3A%20IFunction%20%3D%20()%20%3D%3E%20(%7B%0D%0A%20%20%20%20color%3A%20%22red%22%2C%0D%0A%20%20%20%20toto%3A%22blue%22%20%2F%2F%20no%20error%20%3F%3F%3F%3F%3F%3F%0D%0A%7D)" rel="nofollow noreferrer">Typescript example here

EDIT: I should have specified that I would prefer not to tell explicitly the returning type like that:

const bar: IFunction = ():Style => ({
    color: "red",
    toto:"blue"
})

Indeed, I want to use this code for every React component in my App and it's going to be really cumbersome to specify this type every single time

Body:
Try like below, say explicitly about the function return type

type Style = { color: string };
type IFunction = () => Style;

const foo: Style = {
    color: "red",
    toto: "blue" // error yeah :)
};

const bar: IFunction = (): Style => ({
    color: "red",
    toto: "blue" // no error ??????
});

Property excessive checks won't work until explicitly say the type in below scenario as well(as of TypeScript 3.4), In Typescript 3.5 improved excess Property checks in union types

function checkStyle(style: Style) {}

checkStyle({
    color: "red",
    toto: "blue" // cast to Style, no error yeah :(
} as Style);

let foo3 = {
    color: "red",
    toto: "blue" // no type annotation and no error yeah :(
};

checkStyle(foo3);

The reason for not throwing an error is type widening when TypeScript checks whether or not one object type is assignable to another object type. As long as color property exists on object TypeScript will be happy.


问:
How to parse string fragment between two others using "sed" or other linux terminal utilities?
I need to parse the passphrase using ssid like trigger from android file (data/misc/wifi/wpa_supplicant.conf)(need root)  using android terminal utilities, which will calling in java function. fragment of file  looks like the next:

```<code>network={
    ssid="12345678"
    psk="87654321"
    key_mgmt=WPA-PSK
</code>```

I need to parse psk phrase. I am trying to use this:

```<code>sed -n '/ssid=""+ssid+""psk"/,/"key_mgmt/p'
</code>```

but it can't work, please help.

Body:
I need to parse the passphrase using ssid like trigger from android file (data/misc/wifi/wpa_supplicant.conf)(need root)  using android terminal utilities, which will calling in java function. fragment of file  looks like the next:

network={
    ssid="12345678"
    psk="87654321"
    key_mgmt=WPA-PSK

I need to parse psk phrase. I am trying to use this:

sed -n '/ssid=""+ssid+""psk"/,/"key_mgmt/p'

but it can't work, please help.

Body:
Try the following sed:

ssid=12345678
sed -n '/ssid="'$ssid'"/{N;s/.*psk="\([^"]*\).*/\1/p}'

It will extract 87654321.


问:
Upload image to Firebase from UIImagePicker
I would like to upload a profile picture to Firebase when my UIImage picker has been chosen. But I don't know how to do it and
I can not understand the documentation, because I'm new in coding). Please, help me. I need to upload picture to Firebase. It will be user picture, so reference to picture should save to Database.

```<code>extension ProfileViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

    let image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
    profileImage.image = image
   picker.dismiss(animated: true, completion: nil)
}
</code>```

I don't how to upload and dowload profile image.

答:
Create a storage reference and add folder name and image names.

```<code>Storage.storage().reference().child("id").child("profile.png")
</code>```

and use putData:metadata:completion: method to upload the image. Once image has been uploaded get the image url and update it in user details.

Upload profile image

```<code>import FirebaseStorage
import FirebaseAuth

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    if let image = info[.originalImage] as? UIImage, let imageData = image.pngData() {
        profileImage.image = image
        let storageRef = Storage.storage().reference().child("id").child("profile.png")
        let metaData = StorageMetadata()
        metaData.contentType = "image/png"
        storageRef.putData(imageData, metadata: metaData) { (metaData, error) in
            if error == nil, metaData != nil {
                storageRef.downloadURL { url, error in
                    if let url = url {
                        print(url)//URL of the profile image
                        self.saveProfileImageUrlInUserDetails(url: url)
                    }
                }
            } else {
                print(error?.localizedDescription)//upload failed
            }
        }
    }
    picker.dismiss(animated: true, completion: nil)
}
</code>```

Save uploaded photo reference in user detail Update the user's profile

```<code>func saveProfileImageUrlInUserDetails(url: URL) {
    let changeRequest = Auth.auth().currentUser?.createProfileChangeRequest()
    changeRequest?.photoURL = url
    changeRequest?.commitChanges(completion: { error in
        if error == nil {
            //saved
        } else {
            print(error?.localizedDescription)//failed to udpate
        }
    })
}
</code>```

Download profile image

```<code>if let profileImgUrl = Auth.auth().currentUser?.photoURL?.absoluteString {
    let ref = Storage.storage().reference(forURL: profileImgUrl)
    ref.getData(maxSize: 1 * 1024 * 1024) { data, error in
        if let error = error {
            print(error.localizedDescription)
        } else if let data = data, let image = UIImage(data: data) {
                self.profileImage.image = image
        }
    }
}
</code>```

Body:
I would like to upload a profile picture to Firebase when my UIImage picker has been chosen. But I don't know how to do it and
I can not understand the documentation, because I'm new in coding). Please, help me. I need to upload picture to Firebase. It will be user picture, so reference to picture should save to Database.

extension ProfileViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

    let image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
    profileImage.image = image
   picker.dismiss(animated: true, completion: nil)
}

I don't how to upload and dowload profile image.

Body:
Create a storage reference and add folder name and image names.

Storage.storage().reference().child("id").child("profile.png")

and use putData:metadata:completion: method to upload the image. Once image has been uploaded get the image url and update it in user details.

Upload profile image

import FirebaseStorage
import FirebaseAuth

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    if let image = info[.originalImage] as? UIImage, let imageData = image.pngData() {
        profileImage.image = image
        let storageRef = Storage.storage().reference().child("id").child("profile.png")
        let metaData = StorageMetadata()
        metaData.contentType = "image/png"
        storageRef.putData(imageData, metadata: metaData) { (metaData, error) in
            if error == nil, metaData != nil {
                storageRef.downloadURL { url, error in
                    if let url = url {
                        print(url)//URL of the profile image
                        self.saveProfileImageUrlInUserDetails(url: url)
                    }
                }
            } else {
                print(error?.localizedDescription)//upload failed
            }
        }
    }
    picker.dismiss(animated: true, completion: nil)
}

Save uploaded photo reference in user detail Update the user's profile

func saveProfileImageUrlInUserDetails(url: URL) {
    let changeRequest = Auth.auth().currentUser?.createProfileChangeRequest()
    changeRequest?.photoURL = url
    changeRequest?.commitChanges(completion: { error in
        if error == nil {
            //saved
        } else {
            print(error?.localizedDescription)//failed to udpate
        }
    })
}

Download profile image

if let profileImgUrl = Auth.auth().currentUser?.photoURL?.absoluteString {
    let ref = Storage.storage().reference(forURL: profileImgUrl)
    ref.getData(maxSize: 1 * 1024 * 1024) { data, error in
        if let error = error {
            print(error.localizedDescription)
        } else if let data = data, let image = UIImage(data: data) {
                self.profileImage.image = image
        }
    }
}


问:
Remove first element of JSON object array
I'm struggling to find a way to cut down this JSON array so I can use the values remaining. Below is what's returned to me from the API I'm fetching and I'm looking to remove the excess so I just have an array with the LGA results. Really unsure where to even start.</p>

```<code>{
  "query": {
    "offence": "Dangerous Operation of a Vehicle",
    "area": "",
    "age": "",
    "year": "",
    "gender": ""
  },
  "result": [
    {
      "LGA": "Aurukun Shire Council",
      "total": 156,
      "lat": -13.354875,
      "lng": 141.729058
    },
    {
      "LGA": "Balonne Shire Council",
      "total": 99,
      "lat": -28.464607,
      "lng": 148.189292
    },
    {
      "LGA": "Yarrabah Shire Council",
      "total": 28,
      "lat": -16.910135,
      "lng": 145.868659
    }
  ]
}
</code>```

答:
I'm not sure how you get the response from API, but you can try:</p>

```<code>console.log(response.data.result);
</code>```

Body:
I'm struggling to find a way to cut down this JSON array so I can use the values remaining. Below is what's returned to me from the API I'm fetching and I'm looking to remove the excess so I just have an array with the LGA results. Really unsure where to even start.

{
  "query": {
    "offence": "Dangerous Operation of a Vehicle",
    "area": "",
    "age": "",
    "year": "",
    "gender": ""
  },
  "result": [
    {
      "LGA": "Aurukun Shire Council",
      "total": 156,
      "lat": -13.354875,
      "lng": 141.729058
    },
    {
      "LGA": "Balonne Shire Council",
      "total": 99,
      "lat": -28.464607,
      "lng": 148.189292
    },
    {
      "LGA": "Yarrabah Shire Council",
      "total": 28,
      "lat": -16.910135,
      "lng": 145.868659
    }
  ]
}

Body:
I'm not sure how you get the response from API, but you can try:

console.log(response.data.result);


问:
css - targeting styles when overflow causing scrollbars
I have a div like this:

```<code><div id="test"></div>

#test {
  width:100px;
  overflow-y:auto;
}
</code>```

What I want to do is apply styles only when the overflow-y:auto has actually caused a scrollbar to appear.  Is there a way to do this via CSS/CSS3?

Thank you.

答:
No, you will have to manually calculate the available height of the containing div and the actual height of the element in question.

```<code>var containerHeight = $(container).height();
var elemHeight = $(elem).height();

var elemTop = $(elem).offset().top;
var elemBottom = elemTop + elemHeight;

the two case you need to check are
1. elemHeight > containerHeight
2. elemBottom > containerHeight
</code>```

If either of these is true, a vertical scrollbar should have appeared if the overflow property for the container has been set correctly.

Do excuse me if the above code is not exact since I cannot test it right now.

ContentLicense: CC BY-SA 3.0

Body:
I have a div like this:

#test {
  width:100px;
  overflow-y:auto;
}

What I want to do is apply styles only when the overflow-y:auto has actually caused a scrollbar to appear.  Is there a way to do this via CSS/CSS3?

Thank you.

Body:
No, you will have to manually calculate the available height of the containing div and the actual height of the element in question.

var containerHeight = $(container).height();
var elemHeight = $(elem).height();

var elemTop = $(elem).offset().top;
var elemBottom = elemTop + elemHeight;

the two case you need to check are
1. elemHeight > containerHeight
2. elemBottom > containerHeight

If either of these is true, a vertical scrollbar should have appeared if the overflow property for the container has been set correctly.

Do excuse me if the above code is not exact since I cannot test it right now.


问:
How to use gather() function for multiple value arguments in R
I am new in the tidyverse data manipulation and I am using gather() function from the tidyr package for changing from wide to long form on my data.

I have the following data dataframe:

```<code>id <- 1:10
stim_1_ACC <- 0.5:10
stim_2_ACC <- 10:19
stim_1_RT <- 0.4:10
stim_2_RT <- 15:24
data <- data.frame(id,stim_1_ACC,stim_2_ACC,stim_1_RT,stim_2_RT)
</code>```

I would have one column for stim in which I have stim1 and stim2 as values, and two columns ACC and RT as numeric variables.

With gather() function I can select only one value argument and so having doing what I want only for one variable.

```<code>data %>%
  gather(key = "Stimuli", value = "ACC", 2:5)
</code>```

I reach my goal with multiple steps, splitting and then binding dataframe columns, but I'm looking for a more tidy approach. Final results would be like this:

```<code>   id   stim  ACC  RT
1   1 stim_1  1.5 900
2   2 stim_1  2.5 901
3   3 stim_1  3.5 902
4   4 stim_1  4.5 903
5   5 stim_1  5.5 904
6   6 stim_2  6.5 905
7   7 stim_2  7.5 906
8   8 stim_2  8.5 907
9   9 stim_2  9.5 908
10 10 stim_2 10.5 909
</code>```

Thanks!

答:
Here is an option with separate to split the 'key' column into 'stim' and 'temp' by splitting at the '_' before the character element

```<code>library(tidyverse)
data %>%
   gather(key, value, -id) %>%
   separate(key, into = c("stim", "temp"), sep="(_)(?=[A-Z])") %>%
   spread(temp, value)
</code>```

Body:
I am new in the tidyverse data manipulation and I am using gather() function from the tidyr package for changing from wide to long form on my data.

I have the following data dataframe:

id <- 1:10
stim_1_ACC <- 0.5:10
stim_2_ACC <- 10:19
stim_1_RT <- 0.4:10
stim_2_RT <- 15:24
data <- data.frame(id,stim_1_ACC,stim_2_ACC,stim_1_RT,stim_2_RT)

I would have one column for stim in which I have stim1 and stim2 as values, and two columns ACC and RT as numeric variables.

With gather() function I can select only one value argument and so having doing what I want only for one variable.

data %>%
  gather(key = "Stimuli", value = "ACC", 2:5)

I reach my goal with multiple steps, splitting and then binding dataframe columns, but I'm looking for a more tidy approach. Final results would be like this:

   id   stim  ACC  RT
1   1 stim_1  1.5 900
2   2 stim_1  2.5 901
3   3 stim_1  3.5 902
4   4 stim_1  4.5 903
5   5 stim_1  5.5 904
6   6 stim_2  6.5 905
7   7 stim_2  7.5 906
8   8 stim_2  8.5 907
9   9 stim_2  9.5 908
10 10 stim_2 10.5 909

Thanks!

Body:
Here is an option with separate to split the 'key' column into 'stim' and 'temp' by splitting at the '_' before the character element

library(tidyverse)
data %>%
   gather(key, value, -id) %>%
   separate(key, into = c("stim", "temp"), sep="(_)(?=[A-Z])") %>%
   spread(temp, value)


问:
Converting Input data to dictionary (no single delimiter)
I am trying to convert an file.txt into dictionary. I know if the delimiter is only used one time, Then the code is as follows:

```<code>dict = {}
with open('file.txt') as input_file:
for line in input_file:
    entry = line.split(":")
    dict[entry[0].strip()] = entry[1].strip()
</code>```

However, how do you turn a input file into a dictionary with no clear delimiter?

file.txt:

```<code>cats****5
doggie**6
ox******7
</code>```

output:

```<code>dict = {'cats':5,  'doggie':6, 'ox':7}
</code>```

Thank you for your help :)

答:
You can simply split on your delimeter as before, but take the first and last field:

```<code>for line in input_file:
    entry = line.split("*")
    dict[entry[0].strip()] = entry[-1].strip()
</code>```

Negative indices fetch elements from the back of the list - the index -1 is the last element, -2 is the second-to-last element, and so on.

You can also use unpacking, which allows for self-documenting variable naming:

```<code>for line in input_file:
    key, *_, value = line.split("*")
    dict[key.strip()] = value.strip()
</code>```

Here, *_ consumes an arbitrary number of values - but not the first or last, since key and value are before and after it and both consume exactly one value. The symbol * denotes the arbitrary size, while _ is a regular name that is just conventionally used for unused values.

If your delimiter also appears in the value, splitting is not robust. Use a regular expression to define the grammar of your delimiter, and capture key and value. For example, if your delimiter is . and you expect float values, the following works:

```<code>import re

kv_pattern = re.compile(r'^(.+?)\.+(.+?)$')
#                           ^   ^   ^ capture shortest match for any character sequence
#                           ^   ^ longest match of delimiter sequence
#                           ^ capture shortest match for any character sequence

data = {}
input_data = ['cats....5.0', 'doggie...6', 'ox.......7.']
for line in input_data:
    key, value = kv_pattern.match(line).groups()
    data[key.strip()] = value.strip()
</code>```

Body:
I am trying to convert an file.txt into dictionary. I know if the delimiter is only used one time, Then the code is as follows:

dict = {}
with open('file.txt') as input_file:
for line in input_file:
    entry = line.split(":")
    dict[entry[0].strip()] = entry[1].strip()

However, how do you turn a input file into a dictionary with no clear delimiter?

file.txt:

cats****5
doggie**6
ox******7

output:

dict = {'cats':5,  'doggie':6, 'ox':7}

Thank you for your help :)

Body:
You can simply split on your delimeter as before, but take the first and last field:

for line in input_file:
    entry = line.split("*")
    dict[entry[0].strip()] = entry[-1].strip()

Negative indices fetch elements from the back of the list - the index -1 is the last element, -2 is the second-to-last element, and so on.

You can also use unpacking, which allows for self-documenting variable naming:

for line in input_file:
    key, *_, value = line.split("*")
    dict[key.strip()] = value.strip()

Here, *_ consumes an arbitrary number of values - but not the first or last, since key and value are before and after it and both consume exactly one value. The symbol * denotes the arbitrary size, while _ is a regular name that is just conventionally used for unused values.

If your delimiter also appears in the value, splitting is not robust. Use a regular expression to define the grammar of your delimiter, and capture key and value. For example, if your delimiter is . and you expect float values, the following works:

import re

kv_pattern = re.compile(r'^(.+?)\.+(.+?)$')
#                           ^   ^   ^ capture shortest match for any character sequence
#                           ^   ^ longest match of delimiter sequence
#                           ^ capture shortest match for any character sequence

data = {}
input_data = ['cats....5.0', 'doggie...6', 'ox.......7.']
for line in input_data:
    key, value = kv_pattern.match(line).groups()
    data[key.strip()] = value.strip()


答:
You can try:

```<code>response.data.result = response.data.result.slice(1)
</code>```

Title: Remove first element of JSON object array

Body:
You can try:

response.data.result = response.data.result.slice(1)


问:
Subtract month/year to get years
```<code>data = data.frame("start"= c("1/2000","8/2004","99/9999"),
                  "stop"=c("1/2001","2/2007","09/2010"),
                  "WANTYEARS"= c(1,2.5,NA))
</code>```

I have date in month/year format and want to subtract to get the years.

My attempt of simple data$stop - data$start did not yield the desired results. THank you.

答:
One possibility involving dplyr and lubridate could be:

```<code>data %>%
 mutate_at(vars(1:2), list(~ parse_date_time(., "my"))) %>%
 mutate(WANTYEARS =  round(time_length(stop - start, "years"), 1))

       start       stop WANTYEARS
1 2000-01-01 2001-01-01       1.0
2 2004-08-01 2007-02-01       2.5
3       <NA> 2010-09-01        NA
</code>```

Title: Subtract month/year to get years

Body:
data = data.frame("start"= c("1/2000","8/2004","99/9999"),
                  "stop"=c("1/2001","2/2007","09/2010"),
                  "WANTYEARS"= c(1,2.5,NA))

I have date in month/year format and want to subtract to get the years.

My attempt of simple data$stop - data$start did not yield the desired results. THank you.

Body:
One possibility involving dplyr and lubridate could be:

data %>%
 mutate_at(vars(1:2), list(~ parse_date_time(., "my"))) %>%
 mutate(WANTYEARS =  round(time_length(stop - start, "years"), 1))

       start       stop WANTYEARS
1 2000-01-01 2001-01-01       1.0
2 2004-08-01 2007-02-01       2.5
3       <NA> 2010-09-01        NA


答:
As a variation to Rui's answer, we can combine some steps by grouping by Date = as.Date(Date)  (this will preserve the POSIXct datetime formatting of the underlying Date column, but group by date alone), and use mutate instead of summarize. This will bring the max L1 value for the day into every row, saving us the step of joining back to the original data.

```<code>library(dplyr)
L1 <- L1 %>% mutate(Date = as.POSIXct(Date, format = "%d.%m.%Y %H:%M"))

max24h_L1 <- L1 %>%
  group_by(Date = as.Date(Date)) %>%
  mutate(maxL1 = max(L1, na.rm = TRUE)) %>%
  mutate(NewL1 = 0.714 * (maxL1/L1 - 1)^1.231)
</code>```

Title: find 24 h max of a day and multiply by data of the day

Body:
I want to find the max of 24h of L1 and multiply the max of 24 by a formula with the data.

What I've tried:

require(dplyr)

    max24h_L1 <-L1 %>%
      group_by(Date = cut(Date, breaks="24 h")) %>%
      summarize(`L1` = max(`L1`, na.rm =T))

    max24h_L1 <- ((0.714) * ((max24h_L1/L1)-1)^1.231)

Data:

structure(list(Date = structure(1:10, .Label = c("08.04.2019 14:45",
"08.04.2019 14:50", "08.04.2019 14:55", "08.04.2019 15:00", "08.04.2019 15:05",
"08.04.2019 15:10", "08.04.2019 15:15", "08.04.2019 15:20", "08.04.2019 15:25",
"08.04.2019 15:30", "08.04.2019 15:35", "08.04.2019 15:40", "08.04.2019 15:45",
"08.04.2019 15:50", "08.04.2019 15:55", "08.04.2019 16:00", "08.04.2019 16:05",
"08.04.2019 16:10", "08.04.2019 16:15", "08.04.2019 16:20", "08.04.2019 16:25",
"08.04.2019 16:30", "08.04.2019 16:35", "08.04.2019 16:40", "08.04.2019 16:45",
"08.04.2019 16:50", "08.04.2019 16:55", "08.04.2019 17:00", "08.04.2019 17:05",
"08.04.2019 17:10", "08.04.2019 17:15", "08.04.2019 17:20", "08.04.2019 17:25",
"08.04.2019 17:30", "08.04.2019 17:35", "08.04.2019 17:40", "08.04.2019 17:45",
"08.04.2019 17:50", "08.04.2019 17:55", "08.04.2019 18:00", "08.04.2019 18:05",
"08.04.2019 18:10", "08.04.2019 18:15", "08.04.2019 18:20", "08.04.2019 18:25",
"08.04.2019 18:30", "08.04.2019 18:35", "08.04.2019 18:40", "08.04.2019 18:45",
"08.04.2019 18:50", "08.04.2019 18:55", "08.04.2019 19:00", "08.04.2019 19:05",
"08.04.2019 19:10", "08.04.2019 19:15", "08.04.2019 19:20", "08.04.2019 19:25",
"08.04.2019 19:30", "08.04.2019 19:35", "08.04.2019 19:40", "08.04.2019 19:45",
"08.04.2019 19:50", "08.04.2019 19:55", "08.04.2019 20:00", "08.04.2019 20:05",
"08.04.2019 20:10", "08.04.2019 20:15", "08.04.2019 20:20", "08.04.2019 20:25",
"08.04.2019 20:30", "08.04.2019 20:35", "08.04.2019 20:40", "08.04.2019 20:45",
"08.04.2019 20:50", "08.04.2019 20:55", "08.04.2019 21:00", "08.04.2019 21:05",
"08.04.2019 21:10", "08.04.2019 21:15", "08.04.2019 21:20", "08.04.2019 21:25",
"08.04.2019 21:30", "08.04.2019 21:35", "08.04.2019 21:40", "08.04.2019 21:45",
"08.04.2019 21:50", "08.04.2019 21:55", "08.04.2019 22:00", "08.04.2019 22:05",
"08.04.2019 22:10", "08.04.2019 22:15", "08.04.2019 22:20", "08.04.2019 22:25",
"08.04.2019 22:30", "08.04.2019 22:35", "08.04.2019 22:40", "08.04.2019 22:45",
"08.04.2019 22:50", "08.04.2019 22:55", "08.04.2019 23:00", "08.04.2019 23:05",
"08.04.2019 23:10", "08.04.2019 23:15", "08.04.2019 23:20", "08.04.2019 23:25",
"08.04.2019 23:30", "08.04.2019 23:35", "08.04.2019 23:40", "08.04.2019 23:45",
"08.04.2019 23:50", "08.04.2019 23:55", "09.04.2019 00:00", "09.04.2019 00:05",
"09.04.2019 00:10", "09.04.2019 00:15", "09.04.2019 00:20", "09.04.2019 00:25",
"09.04.2019 00:30", "09.04.2019 00:35", "09.04.2019 00:40", "09.04.2019 00:45",
"09.04.2019 00:50", "09.04.2019 00:55", "09.04.2019 01:00", "09.04.2019 01:05",
"09.04.2019 01:10", "09.04.2019 01:15", "09.04.2019 01:20", "09.04.2019 01:25",
"09.04.2019 01:30", "09.04.2019 01:35", "09.04.2019 01:40", "09.04.2019 01:45",
"09.04.2019 01:50", "09.04.2019 01:55", "09.04.2019 02:00", "09.04.2019 02:05",
"09.04.2019 02:10", "09.04.2019 02:15", "09.04.2019 02:20", "09.04.2019 02:25",
"09.04.2019 02:30", "09.04.2019 02:35", "09.04.2019 02:40", "09.04.2019 02:45",
"09.04.2019 02:50", "09.04.2019 02:55", "09.04.2019 03:00", "09.04.2019 03:05",
"09.04.2019 03:10", "09.04.2019 03:15", "09.04.2019 03:20", "09.04.2019 03:25",
"09.04.2019 03:30", "09.04.2019 03:35", "09.04.2019 03:40", "09.04.2019 03:45",
"09.04.2019 03:50", "09.04.2019 03:55", "09.04.2019 04:00", "09.04.2019 04:05",
"09.04.2019 04:10", "09.04.2019 04:15", "09.04.2019 04:20", "09.04.2019 04:25",
"09.04.2019 04:30", "09.04.2019 04:35", "09.04.2019 04:40", "09.04.2019 04:45",
"09.04.2019 04:50", "09.04.2019 04:55", "09.04.2019 05:00", "09.04.2019 05:05",
"09.04.2019 05:10", "09.04.2019 05:15", "09.04.2019 05:20", "09.04.2019 05:25",
"09.04.2019 05:30", "09.04.2019 05:35", "09.04.2019 05:40", "09.04.2019 05:45",
"09.04.2019 05:50", "09.04.2019 05:55", "09.04.2019 06:00", "09.04.2019 06:05",
"09.04.2019 06:10", "09.04.2019 06:15", "09.04.2019 06:20", "09.04.2019 06:25",
"09.04.2019 06:30", "09.04.2019 06:35", "09.04.2019 06:40", "09.04.2019 06:45",
"09.04.2019 06:50", "09.04.2019 06:55", "09.04.2019 07:00", "09.04.2019 07:05",
"09.04.2019 07:10", "09.04.2019 07:15", "09.04.2019 07:20", "09.04.2019 07:25",
"09.04.2019 07:30", "09.04.2019 07:35", "09.04.2019 07:40", "09.04.2019 07:45",
"09.04.2019 07:50", "09.04.2019 07:55", "09.04.2019 08:00", "09.04.2019 08:05",
"09.04.2019 08:10", "09.04.2019 08:15", "09.04.2019 08:20", "09.04.2019 08:25",
"09.04.2019 08:30", "09.04.2019 08:35", "09.04.2019 08:40", "09.04.2019 08:45",
"09.04.2019 08:50", "09.04.2019 08:55", "09.04.2019 09:00", "09.04.2019 09:05",
"09.04.2019 09:10", "09.04.2019 09:15", "09.04.2019 09:20", "09.04.2019 09:25",
"09.04.2019 09:30", "09.04.2019 09:35", "09.04.2019 09:40", "09.04.2019 09:45",
"09.04.2019 09:50", "09.04.2019 09:55", "09.04.2019 10:00", "09.04.2019 10:05"
), class = "factor"), L1 = c(0.654, 0.656, 0.653, 0.652, 0.657,
0.649, 0.665, 0.647, 0.66, 0.666)), row.names = c(NA, 10L), class = "data.frame")
>

Body:
As a variation to Rui's answer, we can combine some steps by grouping by Date = as.Date(Date)  (this will preserve the POSIXct datetime formatting of the underlying Date column, but group by date alone), and use mutate instead of summarize. This will bring the max L1 value for the day into every row, saving us the step of joining back to the original data.

library(dplyr)
L1 <- L1 %>% mutate(Date = as.POSIXct(Date, format = "%d.%m.%Y %H:%M"))

max24h_L1 <- L1 %>%
  group_by(Date = as.Date(Date)) %>%
  mutate(maxL1 = max(L1, na.rm = TRUE)) %>%
  mutate(NewL1 = 0.714 * (maxL1/L1 - 1)^1.231)


问:
GNU make: how prevent '-include file.ext' from executing a rule the target of which is 'file.ext'?
Just to review the terminology, this is the structure of a makefile 'rule':

```<code>target:   dependencies ...
          commands
          ...
</code>```

This is the makefile I've written:

```<code>CC = mpicc
SHAREDLIB = libfmd.so
CFLAGS = -fPIC -Wall -Wno-unused-result -O3 -fopenmp
LFLAGS = -lm -fopenmp -lgsl -lgslcblas

OBJS = $(patsubst %.c,%.o,$(wildcard *.c))

.PHONY: all shared clean
all: shared
shared: $(SHAREDLIB)
$(SHAREDLIB): depend.mk $(OBJS)
    $(CC) $(OBJS) -shared -o $@ $(LFLAGS)
depend.mk: *.c *.h
    $(CC) -MM *.c > depend.mk
-include depend.mk
clean:
    rm -f *.o libfmd.so depend.mk
</code>```

When the folder is clean, and I enter make clean, the following lines are shown:

```<code>mpicc -MM *.c > depend.mk
rm -f *.o libfmd.so depend.mk
</code>```

It seems to me that -include depend.mk in addition to including depend.mk, executes the rule that depend.mk is its target. I'd like to stop this behavior.

答:
You are correct.  See How Makefiles are Remade in the documentation.

There is no way to prevent this behavior: if there's a rule that creates an included makefile, make will always rebuild it if it's out of date, then re-invoke itself to read the latest version.

The question is, why do you want to avoid it?  Maybe if you explained the behavior you are actually looking for at a higher level we could help.  As you have it here it's possible for .o files to be created without any depend.mk file created, then a compile fails, you modify a header file to fix it, but since the depend.mk file doesn't exist when you re-run make the source files are not rebuilt properly.

If you want to get accurate handling of C/C++ dependencies with GCC you might take a look at Auto-Dependency Generation.

Body:
Just to review the terminology, this is the structure of a makefile 'rule':

target:   dependencies ...
          commands
          ...

This is the makefile I've written:

CC = mpicc
SHAREDLIB = libfmd.so
CFLAGS = -fPIC -Wall -Wno-unused-result -O3 -fopenmp
LFLAGS = -lm -fopenmp -lgsl -lgslcblas

OBJS = $(patsubst %.c,%.o,$(wildcard *.c))

.PHONY: all shared clean
all: shared
shared: $(SHAREDLIB)
$(SHAREDLIB): depend.mk $(OBJS)
    $(CC) $(OBJS) -shared -o $@ $(LFLAGS)
depend.mk: *.c *.h
    $(CC) -MM *.c > depend.mk
-include depend.mk
clean:
    rm -f *.o libfmd.so depend.mk

When the folder is clean, and I enter make clean, the following lines are shown:

mpicc -MM *.c > depend.mk
rm -f *.o libfmd.so depend.mk

It seems to me that -include depend.mk in addition to including depend.mk, executes the rule that depend.mk is its target. I'd like to stop this behavior.


问:
Python kivy: How can I fix "TypeError: object.__init__() takes no parameters"?
I have a problem with my code here. I want to implement a string with data in the kv language right in my python file to add a design to the "MDTextFieldClear". I am not sure if the error has to be in kv string but after a bit of testing with the classes and the indentation of the kv string I think it could be the reason.
Here's a bit of code:

```<code>from kivymd.theming import ThemeManager
from kivymd.textfields import MDTextFieldClear    # KivyMD imports

class LayoutPy(FloatLayout):    # Widget class
    def __init__(self, **kwargs):
        super(LayoutPy, self).__init__(**kwargs)
        self.get_voc = MDTextFieldClear(helper_text="Please enter the translation", helper_text_mode="on_focus", max_text_length=12, multiline=False, color_mode="accent")
        self.add_widget(self.get_voc)

        # ... (few more widgets) ...#

Builder.load_string("""
#:import MDTextField kivymd.textfields.MDTextField
#:import MDTextFieldRound kivymd.textfields.MDTextFieldRound
#:import MDTextFieldClear kivymd.textfields.MDTextFieldClear
#:import MDTextFieldRect kivymd.textfields.MDTextFieldRect

<LayoutPy>:
    orientation: 'vertical'
    FloatLayout:
        MDTextFieldClear:
            hint_text: ""
            helper_text: "Enter translation"
            helper_text_mode: "on_focus"
            max_text_length: 10
""")

class KivyGUI(App):          # Main class for build
    theme_cls = ThemeManager()
    theme_cls.primary_palette = ("Blue")
    title = ('Lingu Trainer')
    main_widget = None

    def build(self):
        c = LayoutPy()
        d = Factory.TextFields()
        return c

if __name__ == "__main__":
    KivyGUI().run()
</code>```

The error is as follows:

Traceback (most recent call last):
     File "PATH_TO_MY_PYTHON_FILE", line 106, in
       KivyGUI().run()

File "C:\Users\username\Anaconda3\lib\site-packages\kivy\app.py", line 800, in run
       root = self.build()

File "PATH_TO_MY_PYTHON_FILE", line 100, in build
       c = LayoutPy()

File "PATH_TO_MY_PYTHON_FILE", line 54, in init
       self.get_voc = MDTextFieldClear(helper_text="Please enter the translation", helper_text_mode="on_focus", max_text_length=12, multiline=False, color_mode="accent")

File "C:\Users\username\Anaconda3\lib\site-packages\kivy\uix\boxlayout.py", line 131, in init
       super(BoxLayout, self).init(**kwargs)

File "C:\Users\username\Anaconda3\lib\site-packages\kivy\uix\layout.py", line 76, in init
       super(Layout, self).init(**kwargs)

File "C:\Users\username\Anaconda3\lib\site-packages\kivy\uix\widget.py", line 340, in init
       super(Widget, self).init(**kwargs)

File "kivy_event.pyx", line 243, in kivy._event.EventDispatcher.init
   TypeError: object.init() takes no parameters

答:
Problem 1 - TypeError

```<code> TypeError: object.__init__() takes exactly one argument (the instance to initialize)
</code>```

Root Cause

The error was due to the attributes, color_mode and/or multiline.

Problem 2 - Inheritance Mismatch

In your kv file, the attribute, orientation is declared for class rule, <LayoutPy>:. This attribute is applicable to BoxLayout. But in your Python script, class LayoutPy() has an inheritance of FloatLayout.

Solution

The following example use BoxLayout as the root.

main.py

```<code>from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout

from kivymd.theming import ThemeManager
from kivymd.textfields import MDTextFieldClear

class LayoutPy(BoxLayout):

    def __init__(self, **kwargs):
        super(LayoutPy, self).__init__(**kwargs)

        self.get_voc = MDTextFieldClear(helper_text="Please enter the translation",
                                        helper_text_mode="on_focus", max_text_length=12,
                                        hint_text="Created in py"
                                        )
        self.add_widget(self.get_voc)

Builder.load_string("""
#:import MDTextFieldClear kivymd.textfields.MDTextFieldClear

<LayoutPy>:
    orientation: 'vertical'

    FloatLayout:
        MDTextFieldClear:
            hint_text: "kv: Created"
            helper_text: "Enter translation"
            helper_text_mode: "on_focus"
            max_text_length: 10

""")

class KivyGUI(App):
    theme_cls = ThemeManager()
    theme_cls.primary_palette = "Blue"
    title = 'Lingu Trainer'

    def build(self):
        return LayoutPy()

if __name__ == "__main__":
    KivyGUI().run()
</code>```

Output

Body:
I have a problem with my code here. I want to implement a string with data in the kv language right in my python file to add a design to the "MDTextFieldClear". I am not sure if the error has to be in kv string but after a bit of testing with the classes and the indentation of the kv string I think it could be the reason.
Here's a bit of code:

from kivymd.theming import ThemeManager
from kivymd.textfields import MDTextFieldClear    # KivyMD imports

class LayoutPy(FloatLayout):    # Widget class
    def __init__(self, **kwargs):
        super(LayoutPy, self).__init__(**kwargs)
        self.get_voc = MDTextFieldClear(helper_text="Please enter the translation", helper_text_mode="on_focus", max_text_length=12, multiline=False, color_mode="accent")
        self.add_widget(self.get_voc)

        # ... (few more widgets) ...#

Builder.load_string("""
#:import MDTextField kivymd.textfields.MDTextField
#:import MDTextFieldRound kivymd.textfields.MDTextFieldRound
#:import MDTextFieldClear kivymd.textfields.MDTextFieldClear
#:import MDTextFieldRect kivymd.textfields.MDTextFieldRect

<LayoutPy>:
    orientation: 'vertical'
    FloatLayout:
        MDTextFieldClear:
            hint_text: ""
            helper_text: "Enter translation"
            helper_text_mode: "on_focus"
            max_text_length: 10
""")

class KivyGUI(App):          # Main class for build
    theme_cls = ThemeManager()
    theme_cls.primary_palette = ("Blue")
    title = ('Lingu Trainer')
    main_widget = None

    def build(self):
        c = LayoutPy()
        d = Factory.TextFields()
        return c

if __name__ == "__main__":
    KivyGUI().run()

The error is as follows:

Traceback (most recent call last):
     File "PATH_TO_MY_PYTHON_FILE", line 106, in
       KivyGUI().run()

File "C:\Users\username\Anaconda3\lib\site-packages\kivy\app.py", line 800, in run
       root = self.build()

File "PATH_TO_MY_PYTHON_FILE", line 100, in build
       c = LayoutPy()

File "PATH_TO_MY_PYTHON_FILE", line 54, in init
       self.get_voc = MDTextFieldClear(helper_text="Please enter the translation", helper_text_mode="on_focus", max_text_length=12, multiline=False, color_mode="accent")

File "C:\Users\username\Anaconda3\lib\site-packages\kivy\uix\boxlayout.py", line 131, in init
       super(BoxLayout, self).init(**kwargs)

File "C:\Users\username\Anaconda3\lib\site-packages\kivy\uix\layout.py", line 76, in init
       super(Layout, self).init(**kwargs)

File "C:\Users\username\Anaconda3\lib\site-packages\kivy\uix\widget.py", line 340, in init
       super(Widget, self).init(**kwargs)

File "kivy_event.pyx", line 243, in kivy._event.EventDispatcher.init
   TypeError: object.init() takes no parameters

Body:
Problem 1 - TypeError

 TypeError: object.__init__() takes exactly one argument (the instance to initialize)

Root Cause

The error was due to the attributes, color_mode and/or multiline.

Problem 2 - Inheritance Mismatch

In your kv file, the attribute, orientation is declared for class rule, <LayoutPy>:. This attribute is applicable to BoxLayout. But in your Python script, class LayoutPy() has an inheritance of FloatLayout.

Solution

The following example use BoxLayout as the root.

main.py

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout

from kivymd.theming import ThemeManager
from kivymd.textfields import MDTextFieldClear

class LayoutPy(BoxLayout):

    def __init__(self, **kwargs):
        super(LayoutPy, self).__init__(**kwargs)

        self.get_voc = MDTextFieldClear(helper_text="Please enter the translation",
                                        helper_text_mode="on_focus", max_text_length=12,
                                        hint_text="Created in py"
                                        )
        self.add_widget(self.get_voc)

Builder.load_string("""
#:import MDTextFieldClear kivymd.textfields.MDTextFieldClear

<LayoutPy>:
    orientation: 'vertical'

    FloatLayout:
        MDTextFieldClear:
            hint_text: "kv: Created"
            helper_text: "Enter translation"
            helper_text_mode: "on_focus"
            max_text_length: 10

""")

class KivyGUI(App):
    theme_cls = ThemeManager()
    theme_cls.primary_palette = "Blue"
    title = 'Lingu Trainer'

    def build(self):
        return LayoutPy()

if __name__ == "__main__":
    KivyGUI().run()

Output


问:
JavaFX: Moving a circle with Threads
I'm trying to create an animation, but without using built in features like TranslateTransition. On an Anchor Pane I created a circle, and I want it to move constantly along some line like this:

```<code> public void initialize()  {
        MyThread task = new MyThread();
        new Thread(task).start();
    }
</code>```

```<code>class MyThread extends Task<Integer>
{
    @FXML
    Circle myCircle;
    @Override
    protected Integer call() throws Exception
    {
        int i= 737; //starting position
        while(true)
        {
            ((Node) myCircle).setLayoutX(i);
            i--;
            if(i%109==0) //ending position
                i=737;

        }
    }

}
</code>```

But it doesn't move at all. I'm new to threads in javaFX, so I don't really know what I'm doing wrong. But when I just printed some numbers out like this it worked just fine:

```<code>class MyThread extends Task<Integer>
{
    @Override
    protected Integer call() throws Exception
    {
        for(int i=0; i<10;i++)
        {
            count(i);
            count10(i);
        }

    protected void count(int i)
    {
        System.out.println(i);
    }

    protected void count10(int i)
    {
        System.out.println(10*i);
    }

}
</code>```

答:
JavaFX nodes should only be modified from the JavaFX application thread. You're modifying the layoutX property from a background thread which yields unreliable results.

You can update the value property and use a listener for the Task.value property to take care of the synchronisation for you:

```<code>class MyThread extends Task<Integer> {

    @Override
    protected Integer call() throws Exception {
        final int minX = (737 / 109) * 109; // use rounding of integer division to find greatest int <= 737 divisible by 109

        while(true) {
            for (int i = 737; i >= minX; i--) {
                updateValue(i);
            }
        }
    }

}
</code>```

```<code>MyThread task = new MyThread();
task.valueProperty().addListener((o, oldValue, newValue) -> circle.setLayoutX(newValue.doubleValue()));
new Thread(task).start();
</code>```

Note that the results of this code could be quite unpredictable: There is no delay between updates so the value at the time the binding is updated is likely to be random...

Otherwise you have to use Platform.runLater to update the GUI, but this is quite tricky with your code, since you do updates with a high enough frequency that JavaFX won't be able to cope with all the Runnables submitted.

I do recommend using a JavaFX class like AnimationTimer instead. These kind of classes are provided to be used. Trying to implement something like this yourself is likely to be more trouble than it's worth, especially as inexperienced programmer.

Title: JavaFX: Moving a circle with Threads

Body:
I'm trying to create an animation, but without using built in features like TranslateTransition. On an Anchor Pane I created a circle, and I want it to move constantly along some line like this:

 public void initialize()  {
        MyThread task = new MyThread();
        new Thread(task).start();
    }

class MyThread extends Task<Integer>
{
    @FXML
    Circle myCircle;
    @Override
    protected Integer call() throws Exception
    {
        int i= 737; //starting position
        while(true)
        {
            ((Node) myCircle).setLayoutX(i);
            i--;
            if(i%109==0) //ending position
                i=737;

        }
    }

}

But it doesn't move at all. I'm new to threads in javaFX, so I don't really know what I'm doing wrong. But when I just printed some numbers out like this it worked just fine:

class MyThread extends Task<Integer>
{
    @Override
    protected Integer call() throws Exception
    {
        for(int i=0; i<10;i++)
        {
            count(i);
            count10(i);
        }

    protected void count(int i)
    {
        System.out.println(i);
    }

    protected void count10(int i)
    {
        System.out.println(10*i);
    }

}

Body:
JavaFX nodes should only be modified from the JavaFX application thread. You're modifying the layoutX property from a background thread which yields unreliable results.

You can update the value property and use a listener for the Task.value property to take care of the synchronisation for you:

class MyThread extends Task<Integer> {

    @Override
    protected Integer call() throws Exception {
        final int minX = (737 / 109) * 109; // use rounding of integer division to find greatest int <= 737 divisible by 109

        while(true) {
            for (int i = 737; i >= minX; i--) {
                updateValue(i);
            }
        }
    }

}

MyThread task = new MyThread();
task.valueProperty().addListener((o, oldValue, newValue) -> circle.setLayoutX(newValue.doubleValue()));
new Thread(task).start();

Note that the results of this code could be quite unpredictable: There is no delay between updates so the value at the time the binding is updated is likely to be random...

Otherwise you have to use Platform.runLater to update the GUI, but this is quite tricky with your code, since you do updates with a high enough frequency that JavaFX won't be able to cope with all the Runnables submitted.

I do recommend using a JavaFX class like AnimationTimer instead. These kind of classes are provided to be used. Trying to implement something like this yourself is likely to be more trouble than it's worth, especially as inexperienced programmer.


问:
Axios params returns data inside an object instead of array
When using axios.get without the params all data is returned inside of array like it is supposed to be, but when I use params all objects are returned inside an object and I'cant map it. How can put all objects inside of array? If I try to put it inside of array it only puts the object that contains all the objects I need.

```<code>axios
  .get("http://api.digiart.lt/items/", { params: { category: "latte" } })
  .then((response) => {
    let coffee = response.data;
    this.props.onLoadData(coffee);
    console.log(response.data);
  });
</code>```

returns like this

```<code>{…}
count: 10,
items: Object { 0: {…}, 2: {…}, 3: {…}, … },
<prototype>: Object { … }
</code>```

supposed to be like this

```<code>Array(41) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ]
</code>```

答:
try this</p>

```<code>axios.get('http://api.digiart.lt/items/',
        { params:
            { category:"latte" }} )
    .then(response => {
        let coffee = Object.keys(response.items).map(i => response.items[i])
</code>```

Body:
When using axios.get without the params all data is returned inside of array like it is supposed to be, but when I use params all objects are returned inside an object and I'cant map it. How can put all objects inside of array? If I try to put it inside of array it only puts the object that contains all the objects I need.

axios
  .get("http://api.digiart.lt/items/", { params: { category: "latte" } })
  .then((response) => {
    let coffee = response.data;
    this.props.onLoadData(coffee);
    console.log(response.data);
  });

returns like this

{…}
count: 10,
items: Object { 0: {…}, 2: {…}, 3: {…}, … },
<prototype>: Object { … }

supposed to be like this

Array(41) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ]

Body:
try this

axios.get('http://api.digiart.lt/items/',
        { params:
            { category:"latte" }} )
    .then(response => {
        let coffee = Object.keys(response.items).map(i => response.items[i])


问:
How to insert student subject and grade into the database in a better way?
I am a beginner to php and am designing student information system where students need to enter 9 subject and its corresponding grade based on the number of sittings. Is there any better way to do this apart from what I have been doing?

These are my codes.

```
<pre class="snippet-code-css lang-css prettyprint-override"><code><style>
    .striped-border {
        border: 1px solid #0d4115;
        margin: auto;
        margin-top: 5%;
        margin-bottom: 2%;
    }

    .form2a{
      display: none;
    }
    </style></code>```

  <form name="register" method="POST" action="process2.php"  >

    Select Number of Sitting(s)
 <select name="sitting" id="sitting" class="form-control" onchange="showDiv(this)">
                  <option value="1">1</option>
                  <option value="2">2</option>

              </select>

                School Name
                <input type="text" name="schoolname1" id="schoolname" class="form-control" placeholder="School Name" required>

    Exam Type
 <select name="examboard1" id="examboard" class="form-control" required>
                  <option value="">Exam Type</option>
                  <option value="WAEC">WAEC(SSCE)</option>
                  <option value="WAEC">WAEC(GCE)</option>
                  <option value="NECO">NECO(SSCE)</option>
                  <option value="NECO">NECO(GCE)</option>
                  <option value="NABTEB">NABTEB(SSCE)</option>
                  <option value="NABTEB">NABTEB(GCE)</option>
                  <option value="OTHERS">OTHERS</option>

              </select>

    Exam Date
  <?php
  $examyear = range(1960, 2050);
  ?>
   <select class="form-control" name="examdate1" id="examdate" placeholder="Exam Date">
     <option value="">Select date</option>
      <?php
      foreach($examyear as $examdate){
        echo '<option value= "' .$examdate.'">'.$examdate.'</option>';
      }
?>

   </select>

    Exam Number
   <input type="text" class="form-control" name="examno1" id="examno" placeholder="Exam Number">

              S/NO
              SUBJECTS
              GRADE

                        1

              <?php include("config.php");
    $sql = "SELECT * FROM subjects ORDER BY subject_name ASC";
    $query = mysqli_query($conn, $sql);
    $count  = mysqli_num_rows($query);
?>
                <select name="subject11" class="form-control" id="subject">
<option value="" selected="selected">Select subject</option>
    <?php
    if($count > 0){
      while($row = mysqli_fetch_assoc($query)){
        $subject_id = $row['subject_id'];
        $subject_name = $row['subject_name'];
        echo "<option>" . $row['subject_name'] . "</option>";
      }
    }else{
      echo "<option value = ''>Subject not available</option>";
    }
?>
</select>

              <select name="grade11" class="form-control">
                   <option value=""> Select</option>
<option value="A1">A1</option>
<option value="B2">B2</option>
<option value="B3">B3</option>
<option value="C4">C4</option>
<option value="C5">C5</option>
<option value="C6">C6</option>
<option value="D7">D7</option>
<option value="E8">E8</option>
<option value="F9">F9</option>              </select>

              2

              <?php include("config.php");
    $sql = "SELECT * FROM subjects ORDER BY subject_name ASC";
    $query = mysqli_query($conn, $sql);
    $count  = mysqli_num_rows($query);
?>
                <select name="subject12" class="form-control" id="subject">
<option value="" selected="selected">Select subject</option>
    <?php
    if($count > 0){
      while($row = mysqli_fetch_assoc($query)){
        $subject_id = $row['subject_id'];
        $subject_name = $row['subject_name'];
        echo "<option>" . $row['subject_name'] . "</option>";
      }
    }else{
      echo "<option value = ''>Subject not available</option>";
    }
?>
</select>

              <select name="grade12" class="form-control">
                   <option value=""> Select </option>
<option value="A1">A1</option>
<option value="B2">B2</option>
<option value="B3">B3</option>
<option value="C4">C4</option>
<option value="C5">C5</option>
<option value="C6">C6</option>
<option value="D7">D7</option>
<option value="E8">E8</option>
<option value="F9">F9</option>              </select>

              3

              <?php include("config.php");
    $sql = "SELECT * FROM subjects ORDER BY subject_name ASC";
    $query = mysqli_query($conn, $sql);
    $count  = mysqli_num_rows($query);
?>
                <select name="subject13" class="form-control" id="subject">
<option value="" selected="selected">Select subject</option>
    <?php
    if($count > 0){
      while($row = mysqli_fetch_assoc($query)){
        $subject_id = $row['subject_id'];
        $subject_name = $row['subject_name'];
        echo "<option>" . $row['subject_name'] . "</option>";
      }
    }else{
      echo "<option value = ''>Subject not available</option>";
    }
?>
</select>

              <select name="grade13" class="form-control">
                   <option value=""> Select </option>
<option value="A1">A1</option>
<option value="B2">B2</option>
<option value="B3">B3</option>
<option value="C4">C4</option>
<option value="C5">C5</option>
<option value="C6">C6</option>
<option value="D7">D7</option>
<option value="E8">E8</option>
<option value="F9">F9</option>              </select>

              4

              <?php include("config.php");
    $sql = "SELECT * FROM subjects ORDER BY subject_name ASC";
    $query = mysqli_query($conn, $sql);
    $count  = mysqli_num_rows($query);
?>
                <select name="subject14" class="form-control" id="subject">
<option value="" selected="selected">Select subject</option>
    <?php
    if($count > 0){
      while($row = mysqli_fetch_assoc($query)){
        $subject_id = $row['subject_id'];
        $subject_name = $row['subject_name'];
        echo "<option>" . $row['subject_name'] . "</option>";
      }
    }else{
      echo "<option value = ''>Subject not available</option>";
    }
?>

</select>

              <select name="grade14" class="form-control">
                   <option value=""> Select </option>
<option value="A1">A1</option>
<option value="B2">B2</option>
<option value="B3">B3</option>
<option value="C4">C4</option>
<option value="C5">C5</option>
<option value="C6">C6</option>
<option value="D7">D7</option>
<option value="E8">E8</option>
<option value="F9">F9</option>              </select>

              5

          <?php include("config.php");
    $sql = "SELECT * FROM subjects ORDER BY subject_name ASC";
    $query = mysqli_query($conn, $sql);
    $count  = mysqli_num_rows($query);
?>
                <select name="subject15" class="form-control" id="subject">
<option value="" selected="selected">Select subject</option>
    <?php
    if($count > 0){
      while($row = mysqli_fetch_assoc($query)){
        $subject_id = $row['subject_id'];
        $subject_name = $row['subject_name'];
        echo "<option>" . $row['subject_name'] . "</option>";
      }
    }else{
      echo "<option value = ''>Subject not available</option>";
    }
?>

</select>

              <select name="grade15" class="form-control">
                   <option value="">Select </option>
<option value="A1">A1</option>
<option value="B2">B2</option>
<option value="B3">B3</option>
<option value="C4">C4</option>
<option value="C5">C5</option>
<option value="C6">C6</option>
<option value="D7">D7</option>
<option value="E8">E8</option>
<option value="F9">F9</option>              </select>

 SECOND SITTING

                School Name
                <input type="text" name="schoolname2" id="schoolname" class="form-control" placeholder="School Name" required>

    Exam Type
 <select name="examboard2" id="examboard" class="form-control" required>
                  <option value="">Exam Type</option>
                  <option value="WAEC">WAEC(SSCE)</option>
                  <option value="WAEC">WAEC(GCE)</option>
                  <option value="NECO">NECO(SSCE)</option>
                  <option value="NECO">NECO(GCE)</option>
                  <option value="NABTEB">NABTEB(SSCE)</option>
                  <option value="NABTEB">NABTEB(GCE)</option>
                  <option value="OTHERS">OTHERS</option>

              </select>

    Exam Date
  <?php
  $examyear = range(1960, 2099);
  ?>
   <select class="form-control" name="examdate2" id="examdate" placeholder="Exam Date">
     <option value="">Select date</option>
      <?php
      foreach($examyear as $examdate){
        echo '<option value= "' .$examdate.'">'.$examdate.'</option>';
      }
?>

   </select>

    Exam Number
   <input type="text" class="form-control" name="examno2" id="examno" placeholder="Exam Number">

              S/NO
              SUBJECTS
              GRADE

              1

              <?php include("config.php");
    $sql = "SELECT * FROM subjects ORDER BY subject_name ASC";
    $query = mysqli_query($conn, $sql);
    $count  = mysqli_num_rows($query);
?>
                <select name="subject21" class="form-control" id="subject">
<option value="" selected="selected">Select subject</option>
    <?php
    if($count > 0){
      while($row = mysqli_fetch_assoc($query)){
        $subject_id = $row['subject_id'];
        $subject_name = $row['subject_name'];
        echo "<option>" . $row['subject_name'] . "</option>";
      }
    }else{
      echo "<option value = ''>Subject not available</option>";
    }
?>
</select>

              <select name="grade21" class="form-control">
                   <option value=""> Select</option>
<option value="A1">A1</option>
<option value="B2">B2</option>
<option value="B3">B3</option>
<option value="C4">C4</option>
<option value="C5">C5</option>
<option value="C6">C6</option>
<option value="D7">D7</option>
<option value="E8">E8</option>
<option value="F9">F9</option>              </select>

              2

              <?php include("config.php");
    $sql = "SELECT * FROM subjects ORDER BY subject_name ASC";
    $query = mysqli_query($conn, $sql);
    $count  = mysqli_num_rows($query);
?>
                <select name="subject22" class="form-control" id="subject">
<option value="" selected="selected">Select subject</option>
    <?php
    if($count > 0){
      while($row = mysqli_fetch_assoc($query)){
        $subject_id = $row['subject_id'];
        $subject_name = $row['subject_name'];
        echo "<option>" . $row['subject_name'] . "</option>";
      }
    }else{
      echo "<option value = ''>Subject not available</option>";
    }
?>
</select>

              <select name="grade22" class="form-control">
                   <option value=""> Select </option>
<option value="A1">A1</option>
<option value="B2">B2</option>
<option value="B3">B3</option>
<option value="C4">C4</option>
<option value="C5">C5</option>
<option value="C6">C6</option>
<option value="D7">D7</option>
<option value="E8">E8</option>
<option value="F9">F9</option>              </select>

              3

              <?php include("config.php");
    $sql = "SELECT * FROM subjects ORDER BY subject_name ASC";
    $query = mysqli_query($conn, $sql);
    $count  = mysqli_num_rows($query);
?>
                <select name="subject23" class="form-control" id="subject">
<option value="" selected="selected">Select subject</option>
    <?php
    if($count > 0){
      while($row = mysqli_fetch_assoc($query)){
        $subject_id = $row['subject_id'];
        $subject_name = $row['subject_name'];
        echo "<option>" . $row['subject_name'] . "</option>";
      }
    }else{
      echo "<option value = ''>Subject not available</option>";
    }
?>
</select>

              <select name="grade23" class="form-control">
                   <option value=""> Select </option>
<option value="A1">A1</option>
<option value="B2">B2</option>
<option value="B3">B3</option>
<option value="C4">C4</option>
<option value="C5">C5</option>
<option value="C6">C6</option>
<option value="D7">D7</option>
<option value="E8">E8</option>
<option value="F9">F9</option>              </select>

              4

              <?php include("config.php");
    $sql = "SELECT * FROM subjects ORDER BY subject_name ASC";
    $query = mysqli_query($conn, $sql);
    $count  = mysqli_num_rows($query);
?>
                <select name="subject24" class="form-control" id="subject">
<option value="" selected="selected">Select subject</option>
    <?php
    if($count > 0){
      while($row = mysqli_fetch_assoc($query)){
        $subject_id = $row['subject_id'];
        $subject_name = $row['subject_name'];
        echo "<option>" . $row['subject_name'] . "</option>";
      }
    }else{
      echo "<option value = ''>Subject not available</option>";
    }
?>

</select>

              <select name="grade24" class="form-control">
                   <option value=""> Select </option>
<option value="A1">A1</option>
<option value="B2">B2</option>
<option value="B3">B3</option>
<option value="C4">C4</option>
<option value="C5">C5</option>
<option value="C6">C6</option>
<option value="D7">D7</option>
<option value="E8">E8</option>
<option value="F9">F9</option>              </select>

              5

          <?php include("config.php");
    $sql = "SELECT * FROM subjects ORDER BY subject_name ASC";
    $query = mysqli_query($conn, $sql);
    $count  = mysqli_num_rows($query);
?>
                <select name="subject25" class="form-control" id="subject">
<option value="" selected="selected">Select subject</option>
    <?php
    if($count > 0){
      while($row = mysqli_fetch_assoc($query)){
        $subject_id = $row['subject_id'];
        $subject_name = $row['subject_name'];
        echo "<option>" . $row['subject_name'] . "</option>";
      }
    }else{
      echo "<option value = ''>Subject not available</option>";
    }
?>

</select>

              <select name="grade25" class="form-control">
                   <option value="">Select </option>
<option value="A1">A1</option>
<option value="B2">B2</option>
<option value="B3">B3</option>
<option value="C4">C4</option>
<option value="C5">C5</option>
<option value="C6">C6</option>
<option value="D7">D7</option>
<option value="E8">E8</option>
<option value="F9">F9</option>              </select>

   <button type="submit" class="btn btn-primary" name="submit">Submit</button>

  </form>
            ```
</div>
</div>
</p>

<p>The above is my HTML and JavaScript codes. Am using that JavaScript to display form based on the no of sittings selected.</p>

<p>Below is my PHP code</p>

```$sitting = mysqli_real_escape_string($conn, $_POST['sitting']);
$schoolname1 = mysqli_real_escape_string($conn, $_POST['schoolname1']);
$examboard1 = mysqli_real_escape_string($conn, $_POST['examboard1']);
$examdate1 = mysqli_real_escape_string($conn, $_POST['examdate1']);
$examno1 = mysqli_real_escape_string($conn, $_POST['examno1']);
$subject11 = mysqli_real_escape_string($conn, $_POST['subject11']);
$grade11 = mysqli_real_escape_string($conn, $_POST['grade11']);
$subject12 = mysqli_real_escape_string($conn, $_POST['subject12']);
$grade12 = mysqli_real_escape_string($conn, $_POST['grade12']);
$subject13 = mysqli_real_escape_string($conn, $_POST['subject13']);
$grade13 = mysqli_real_escape_string($conn, $_POST['grade13']);
$subject14 = mysqli_real_escape_string($conn, $_POST['subject14']);
$grade14 = mysqli_real_escape_string($conn, $_POST['grade14']);
$subject15 = mysqli_real_escape_string($conn, $_POST['subject15']);
$grade15 = mysqli_real_escape_string($conn, $_POST['grade15']);
$schoolname2 = mysqli_real_escape_string($conn, $_POST['schoolname2']);
$examboard2 = mysqli_real_escape_string($conn, $_POST['examboard2']);
$examdate2 = mysqli_real_escape_string($conn, $_POST['examdate2']);
$examno2 = mysqli_real_escape_string($conn, $_POST['examno2']);
$subject21 = mysqli_real_escape_string($conn, $_POST['subject21']);
$grade21 = mysqli_real_escape_string($conn, $_POST['grade21']);
$subject22 = mysqli_real_escape_string($conn, $_POST['subject22']);
$grade22 = mysqli_real_escape_string($conn, $_POST['grade22']);
$subject23 = mysqli_real_escape_string($conn, $_POST['subject23']);
$grade23 = mysqli_real_escape_string($conn, $_POST['grade23']);
$subject24 = mysqli_real_escape_string($conn, $_POST['subject24']);
$grade24 = mysqli_real_escape_string($conn, $_POST['grade24']);
$subject25 = mysqli_real_escape_string($conn, $_POST['subject25']);
$grade25 = mysqli_real_escape_string($conn, $_POST['grade25']);

$enter = "INSERT INTO applicants(sitting, schoolname1,  examboard1,
examdate1, examno1, subject11, grade11, subject12, grade12, subject13,
grade13, subject14, grade14, subject15, grade15, schoolname2, examboard2,
examdate2, examno2, subject21, grade21, subject22, grade22, subject23,
grade23, subject24, grade24, subject25, grade25) VALUES('$sitting',
'$schoolname1', '$examboard1', '$examdate1', '$examno1', '$subject11',
'$grade11', '$subject12', '$grade12', '$subject13', '$grade13',
'$subject14', '$grade14', '$subject15', '$grade15','$schoolname2',
'$examboard2', '$examdate2', '$examno2', '$subject21', '$grade21',
'$subject22', '$grade22', '$subject23', '$grade23', '$subject24',
'$grade24', '$subject25', '$grade25')";
$result = mysqli_query($conn, $enter);
if($result){
 echo "";
header('location: success.php');
}else{
echo "";

}
}
```

Is there any better way to do this without repeating all those subjects and grades?

答:
You're getting into a pickle with your form names. PHP makes this a little bit easier by allowing you to specify array names in forms:

```<code><?php
if ($_POST)
{
    echo "```";
    print_r($_POST);
    echo "```";
}
?>
<form method="post">
    Grades:
    <input name="grade[]" type="text">
    <input name="grade[]" type="text">
    <input name="grade[]" type="text">

    <hr>
    <input type="submit" value="Submit">
</form>
</code>```

This produces this post output, which is easy to loop over:

```<code>Array
(
    [grade] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

)
</code>```

That works for lists of data, but your use-case has an additional dimension, which makes this harder. You have:

a first-order list containing school name, exam board, exam date, and exam number

a second-order list belonging to the first one, which contains subjects and grades

However, PHP will support that too, by letting you specify which sub-list the second-order lists belong to:

```<code><?php
if ($_POST)
{
    echo "```";
    print_r($_POST);
    echo "```";
}
?>
<form method="post">
    Board: <input name="board[]" type="text">
    Grades:

    <input name="grade[0][]" type="text">
    <input name="grade[0][]" type="text">
    <input name="grade[0][]" type="text">

    <hr>
    Board: <input name="board[]" type="text">
    Grades:

    <input name="grade[1][]" type="text">
    <input name="grade[1][]" type="text">
    <input name="grade[1][]" type="text">
    <hr>
    <input type="submit" value="Submit">
</form>
</code>```

This produces this arrangement:

```<code>Array
(
    [board] => Array
        (
            [0] => a
            [1] => b
        )

    [grade] => Array
        (
            [0] => Array
                (
                    [0] => 1
                    [1] => 2
                    [2] => 3
                )

            [1] => Array
                (
                    [0] => 4
                    [1] => 5
                    [2] => 6
                )

        )

)
</code>```

You can see here that the 0th entry in board is the exam board (first order list) and the 0th entry in grade is a list in itself (second order list pertaining to the 0th board).

I will leave it to you as a valuable exercise to add the other elements to the first and second-order lists here.

In relation to the table, that is a broad enough topic to merit another question on its own. The structure of this needs to be normalised, so you hold exam boards, exams, students and grades in separate tables. The "grade" is probably the central table, since that requires an exam and a student, and the exam in turn requires a board.

Body:
I am a beginner to php and am designing student information system where students need to enter 9 subject and its corresponding grade based on the number of sittings. Is there any better way to do this apart from what I have been doing?

These are my codes.

  <form name="register" method="POST" action="process2.php"  >

    Select Number of Sitting(s)
 <select name="sitting" id="sitting" class="form-control" onchange="showDiv(this)">
                  <option value="1">1</option>
                  <option value="2">2</option>

              </select>

                School Name
                <input type="text" name="schoolname1" id="schoolname" class="form-control" placeholder="School Name" required>

    Exam Type
 <select name="examboard1" id="examboard" class="form-control" required>
                  <option value="">Exam Type</option>
                  <option value="WAEC">WAEC(SSCE)</option>
                  <option value="WAEC">WAEC(GCE)</option>
                  <option value="NECO">NECO(SSCE)</option>
                  <option value="NECO">NECO(GCE)</option>
                  <option value="NABTEB">NABTEB(SSCE)</option>
                  <option value="NABTEB">NABTEB(GCE)</option>
                  <option value="OTHERS">OTHERS</option>

              </select>

    Exam Date
  <?php
  $examyear = range(1960, 2050);
  ?>
   <select class="form-control" name="examdate1" id="examdate" placeholder="Exam Date">
     <option value="">Select date</option>
      <?php
      foreach($examyear as $examdate){
        echo '<option value= "' .$examdate.'">'.$examdate.'</option>';
      }
?>

   </select>

    Exam Number
   <input type="text" class="form-control" name="examno1" id="examno" placeholder="Exam Number">

              S/NO
              SUBJECTS
              GRADE

                        1

              <?php include("config.php");
    $sql = "SELECT * FROM subjects ORDER BY subject_name ASC";
    $query = mysqli_query($conn, $sql);
    $count  = mysqli_num_rows($query);
?>
                <select name="subject11" class="form-control" id="subject">
<option value="" selected="selected">Select subject</option>
    <?php
    if($count > 0){
      while($row = mysqli_fetch_assoc($query)){
        $subject_id = $row['subject_id'];
        $subject_name = $row['subject_name'];
        echo "<option>" . $row['subject_name'] . "</option>";
      }
    }else{
      echo "<option value = ''>Subject not available</option>";
    }
?>
</select>

              <select name="grade11" class="form-control">
                   <option value=""> Select</option>
<option value="A1">A1</option>
<option value="B2">B2</option>
<option value="B3">B3</option>
<option value="C4">C4</option>
<option value="C5">C5</option>
<option value="C6">C6</option>
<option value="D7">D7</option>
<option value="E8">E8</option>
<option value="F9">F9</option>              </select>

              2

              <?php include("config.php");
    $sql = "SELECT * FROM subjects ORDER BY subject_name ASC";
    $query = mysqli_query($conn, $sql);
    $count  = mysqli_num_rows($query);
?>
                <select name="subject12" class="form-control" id="subject">
<option value="" selected="selected">Select subject</option>
    <?php
    if($count > 0){
      while($row = mysqli_fetch_assoc($query)){
        $subject_id = $row['subject_id'];
        $subject_name = $row['subject_name'];
        echo "<option>" . $row['subject_name'] . "</option>";
      }
    }else{
      echo "<option value = ''>Subject not available</option>";
    }
?>
</select>

              <select name="grade12" class="form-control">
                   <option value=""> Select </option>
<option value="A1">A1</option>
<option value="B2">B2</option>
<option value="B3">B3</option>
<option value="C4">C4</option>
<option value="C5">C5</option>
<option value="C6">C6</option>
<option value="D7">D7</option>
<option value="E8">E8</option>
<option value="F9">F9</option>              </select>

              3

              <?php include("config.php");
    $sql = "SELECT * FROM subjects ORDER BY subject_name ASC";
    $query = mysqli_query($conn, $sql);
    $count  = mysqli_num_rows($query);
?>
                <select name="subject13" class="form-control" id="subject">
<option value="" selected="selected">Select subject</option>
    <?php
    if($count > 0){
      while($row = mysqli_fetch_assoc($query)){
        $subject_id = $row['subject_id'];
        $subject_name = $row['subject_name'];
        echo "<option>" . $row['subject_name'] . "</option>";
      }
    }else{
      echo "<option value = ''>Subject not available</option>";
    }
?>
</select>

              <select name="grade13" class="form-control">
                   <option value=""> Select </option>
<option value="A1">A1</option>
<option value="B2">B2</option>
<option value="B3">B3</option>
<option value="C4">C4</option>
<option value="C5">C5</option>
<option value="C6">C6</option>
<option value="D7">D7</option>
<option value="E8">E8</option>
<option value="F9">F9</option>              </select>

              4

              <?php include("config.php");
    $sql = "SELECT * FROM subjects ORDER BY subject_name ASC";
    $query = mysqli_query($conn, $sql);
    $count  = mysqli_num_rows($query);
?>
                <select name="subject14" class="form-control" id="subject">
<option value="" selected="selected">Select subject</option>
    <?php
    if($count > 0){
      while($row = mysqli_fetch_assoc($query)){
        $subject_id = $row['subject_id'];
        $subject_name = $row['subject_name'];
        echo "<option>" . $row['subject_name'] . "</option>";
      }
    }else{
      echo "<option value = ''>Subject not available</option>";
    }
?>

</select>

              <select name="grade14" class="form-control">
                   <option value=""> Select </option>
<option value="A1">A1</option>
<option value="B2">B2</option>
<option value="B3">B3</option>
<option value="C4">C4</option>
<option value="C5">C5</option>
<option value="C6">C6</option>
<option value="D7">D7</option>
<option value="E8">E8</option>
<option value="F9">F9</option>              </select>

              5

          <?php include("config.php");
    $sql = "SELECT * FROM subjects ORDER BY subject_name ASC";
    $query = mysqli_query($conn, $sql);
    $count  = mysqli_num_rows($query);
?>
                <select name="subject15" class="form-control" id="subject">
<option value="" selected="selected">Select subject</option>
    <?php
    if($count > 0){
      while($row = mysqli_fetch_assoc($query)){
        $subject_id = $row['subject_id'];
        $subject_name = $row['subject_name'];
        echo "<option>" . $row['subject_name'] . "</option>";
      }
    }else{
      echo "<option value = ''>Subject not available</option>";
    }
?>

</select>

              <select name="grade15" class="form-control">
                   <option value="">Select </option>
<option value="A1">A1</option>
<option value="B2">B2</option>
<option value="B3">B3</option>
<option value="C4">C4</option>
<option value="C5">C5</option>
<option value="C6">C6</option>
<option value="D7">D7</option>
<option value="E8">E8</option>
<option value="F9">F9</option>              </select>

 SECOND SITTING

                School Name
                <input type="text" name="schoolname2" id="schoolname" class="form-control" placeholder="School Name" required>

    Exam Type
 <select name="examboard2" id="examboard" class="form-control" required>
                  <option value="">Exam Type</option>
                  <option value="WAEC">WAEC(SSCE)</option>
                  <option value="WAEC">WAEC(GCE)</option>
                  <option value="NECO">NECO(SSCE)</option>
                  <option value="NECO">NECO(GCE)</option>
                  <option value="NABTEB">NABTEB(SSCE)</option>
                  <option value="NABTEB">NABTEB(GCE)</option>
                  <option value="OTHERS">OTHERS</option>

              </select>

    Exam Date
  <?php
  $examyear = range(1960, 2099);
  ?>
   <select class="form-control" name="examdate2" id="examdate" placeholder="Exam Date">
     <option value="">Select date</option>
      <?php
      foreach($examyear as $examdate){
        echo '<option value= "' .$examdate.'">'.$examdate.'</option>';
      }
?>

   </select>

    Exam Number
   <input type="text" class="form-control" name="examno2" id="examno" placeholder="Exam Number">

              S/NO
              SUBJECTS
              GRADE

              1

              <?php include("config.php");
    $sql = "SELECT * FROM subjects ORDER BY subject_name ASC";
    $query = mysqli_query($conn, $sql);
    $count  = mysqli_num_rows($query);
?>
                <select name="subject21" class="form-control" id="subject">
<option value="" selected="selected">Select subject</option>
    <?php
    if($count > 0){
      while($row = mysqli_fetch_assoc($query)){
        $subject_id = $row['subject_id'];
        $subject_name = $row['subject_name'];
        echo "<option>" . $row['subject_name'] . "</option>";
      }
    }else{
      echo "<option value = ''>Subject not available</option>";
    }
?>
</select>

              <select name="grade21" class="form-control">
                   <option value=""> Select</option>
<option value="A1">A1</option>
<option value="B2">B2</option>
<option value="B3">B3</option>
<option value="C4">C4</option>
<option value="C5">C5</option>
<option value="C6">C6</option>
<option value="D7">D7</option>
<option value="E8">E8</option>
<option value="F9">F9</option>              </select>

              2

              <?php include("config.php");
    $sql = "SELECT * FROM subjects ORDER BY subject_name ASC";
    $query = mysqli_query($conn, $sql);
    $count  = mysqli_num_rows($query);
?>
                <select name="subject22" class="form-control" id="subject">
<option value="" selected="selected">Select subject</option>
    <?php
    if($count > 0){
      while($row = mysqli_fetch_assoc($query)){
        $subject_id = $row['subject_id'];
        $subject_name = $row['subject_name'];
        echo "<option>" . $row['subject_name'] . "</option>";
      }
    }else{
      echo "<option value = ''>Subject not available</option>";
    }
?>
</select>

              <select name="grade22" class="form-control">
                   <option value=""> Select </option>
<option value="A1">A1</option>
<option value="B2">B2</option>
<option value="B3">B3</option>
<option value="C4">C4</option>
<option value="C5">C5</option>
<option value="C6">C6</option>
<option value="D7">D7</option>
<option value="E8">E8</option>
<option value="F9">F9</option>              </select>

              3

              <?php include("config.php");
    $sql = "SELECT * FROM subjects ORDER BY subject_name ASC";
    $query = mysqli_query($conn, $sql);
    $count  = mysqli_num_rows($query);
?>
                <select name="subject23" class="form-control" id="subject">
<option value="" selected="selected">Select subject</option>
    <?php
    if($count > 0){
      while($row = mysqli_fetch_assoc($query)){
        $subject_id = $row['subject_id'];
        $subject_name = $row['subject_name'];
        echo "<option>" . $row['subject_name'] . "</option>";
      }
    }else{
      echo "<option value = ''>Subject not available</option>";
    }
?>
</select>

              <select name="grade23" class="form-control">
                   <option value=""> Select </option>
<option value="A1">A1</option>
<option value="B2">B2</option>
<option value="B3">B3</option>
<option value="C4">C4</option>
<option value="C5">C5</option>
<option value="C6">C6</option>
<option value="D7">D7</option>
<option value="E8">E8</option>
<option value="F9">F9</option>              </select>

              4

              <?php include("config.php");
    $sql = "SELECT * FROM subjects ORDER BY subject_name ASC";
    $query = mysqli_query($conn, $sql);
    $count  = mysqli_num_rows($query);
?>
                <select name="subject24" class="form-control" id="subject">
<option value="" selected="selected">Select subject</option>
    <?php
    if($count > 0){
      while($row = mysqli_fetch_assoc($query)){
        $subject_id = $row['subject_id'];
        $subject_name = $row['subject_name'];
        echo "<option>" . $row['subject_name'] . "</option>";
      }
    }else{
      echo "<option value = ''>Subject not available</option>";
    }
?>

</select>

              <select name="grade24" class="form-control">
                   <option value=""> Select </option>
<option value="A1">A1</option>
<option value="B2">B2</option>
<option value="B3">B3</option>
<option value="C4">C4</option>
<option value="C5">C5</option>
<option value="C6">C6</option>
<option value="D7">D7</option>
<option value="E8">E8</option>
<option value="F9">F9</option>              </select>

              5

          <?php include("config.php");
    $sql = "SELECT * FROM subjects ORDER BY subject_name ASC";
    $query = mysqli_query($conn, $sql);
    $count  = mysqli_num_rows($query);
?>
                <select name="subject25" class="form-control" id="subject">
<option value="" selected="selected">Select subject</option>
    <?php
    if($count > 0){
      while($row = mysqli_fetch_assoc($query)){
        $subject_id = $row['subject_id'];
        $subject_name = $row['subject_name'];
        echo "<option>" . $row['subject_name'] . "</option>";
      }
    }else{
      echo "<option value = ''>Subject not available</option>";
    }
?>

</select>

              <select name="grade25" class="form-control">
                   <option value="">Select </option>
<option value="A1">A1</option>
<option value="B2">B2</option>
<option value="B3">B3</option>
<option value="C4">C4</option>
<option value="C5">C5</option>
<option value="C6">C6</option>
<option value="D7">D7</option>
<option value="E8">E8</option>
<option value="F9">F9</option>              </select>

   <button type="submit" class="btn btn-primary" name="submit">Submit</button>

  </form>

The above is my HTML and JavaScript codes. Am using that JavaScript to display form based on the no of sittings selected.

Below is my PHP code

$sitting = mysqli_real_escape_string($conn, $_POST['sitting']);
$schoolname1 = mysqli_real_escape_string($conn, $_POST['schoolname1']);
$examboard1 = mysqli_real_escape_string($conn, $_POST['examboard1']);
$examdate1 = mysqli_real_escape_string($conn, $_POST['examdate1']);
$examno1 = mysqli_real_escape_string($conn, $_POST['examno1']);
$subject11 = mysqli_real_escape_string($conn, $_POST['subject11']);
$grade11 = mysqli_real_escape_string($conn, $_POST['grade11']);
$subject12 = mysqli_real_escape_string($conn, $_POST['subject12']);
$grade12 = mysqli_real_escape_string($conn, $_POST['grade12']);
$subject13 = mysqli_real_escape_string($conn, $_POST['subject13']);
$grade13 = mysqli_real_escape_string($conn, $_POST['grade13']);
$subject14 = mysqli_real_escape_string($conn, $_POST['subject14']);
$grade14 = mysqli_real_escape_string($conn, $_POST['grade14']);
$subject15 = mysqli_real_escape_string($conn, $_POST['subject15']);
$grade15 = mysqli_real_escape_string($conn, $_POST['grade15']);
$schoolname2 = mysqli_real_escape_string($conn, $_POST['schoolname2']);
$examboard2 = mysqli_real_escape_string($conn, $_POST['examboard2']);
$examdate2 = mysqli_real_escape_string($conn, $_POST['examdate2']);
$examno2 = mysqli_real_escape_string($conn, $_POST['examno2']);
$subject21 = mysqli_real_escape_string($conn, $_POST['subject21']);
$grade21 = mysqli_real_escape_string($conn, $_POST['grade21']);
$subject22 = mysqli_real_escape_string($conn, $_POST['subject22']);
$grade22 = mysqli_real_escape_string($conn, $_POST['grade22']);
$subject23 = mysqli_real_escape_string($conn, $_POST['subject23']);
$grade23 = mysqli_real_escape_string($conn, $_POST['grade23']);
$subject24 = mysqli_real_escape_string($conn, $_POST['subject24']);
$grade24 = mysqli_real_escape_string($conn, $_POST['grade24']);
$subject25 = mysqli_real_escape_string($conn, $_POST['subject25']);
$grade25 = mysqli_real_escape_string($conn, $_POST['grade25']);

$enter = "INSERT INTO applicants(sitting, schoolname1,  examboard1,
examdate1, examno1, subject11, grade11, subject12, grade12, subject13,
grade13, subject14, grade14, subject15, grade15, schoolname2, examboard2,
examdate2, examno2, subject21, grade21, subject22, grade22, subject23,
grade23, subject24, grade24, subject25, grade25) VALUES('$sitting',
'$schoolname1', '$examboard1', '$examdate1', '$examno1', '$subject11',
'$grade11', '$subject12', '$grade12', '$subject13', '$grade13',
'$subject14', '$grade14', '$subject15', '$grade15','$schoolname2',
'$examboard2', '$examdate2', '$examno2', '$subject21', '$grade21',
'$subject22', '$grade22', '$subject23', '$grade23', '$subject24',
'$grade24', '$subject25', '$grade25')";
$result = mysqli_query($conn, $enter);
if($result){
 echo "";
header('location: success.php');
}else{
echo "";

}
}

Is there any better way to do this without repeating all those subjects and grades?

Body:
You're getting into a pickle with your form names. PHP makes this a little bit easier by allowing you to specify array names in forms:

<?php
if ($_POST)
{
    echo "<pre>";
    print_r($_POST);
    echo "</pre>";
}
?>
<form method="post">
    Grades:
    <input name="grade[]" type="text">
    <input name="grade[]" type="text">
    <input name="grade[]" type="text">

    <hr>
    <input type="submit" value="Submit">
</form>

This produces this post output, which is easy to loop over:

Array
(
    [grade] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

)

That works for lists of data, but your use-case has an additional dimension, which makes this harder. You have:

a first-order list containing school name, exam board, exam date, and exam number

a second-order list belonging to the first one, which contains subjects and grades

However, PHP will support that too, by letting you specify which sub-list the second-order lists belong to:

<?php
if ($_POST)
{
    echo "<pre>";
    print_r($_POST);
    echo "</pre>";
}
?>
<form method="post">
    Board: <input name="board[]" type="text">
    Grades:

    <input name="grade[0][]" type="text">
    <input name="grade[0][]" type="text">
    <input name="grade[0][]" type="text">

    <hr>
    Board: <input name="board[]" type="text">
    Grades:

    <input name="grade[1][]" type="text">
    <input name="grade[1][]" type="text">
    <input name="grade[1][]" type="text">
    <hr>
    <input type="submit" value="Submit">
</form>

This produces this arrangement:

Array
(
    [board] => Array
        (
            [0] => a
            [1] => b
        )

    [grade] => Array
        (
            [0] => Array
                (
                    [0] => 1
                    [1] => 2
                    [2] => 3
                )

            [1] => Array
                (
                    [0] => 4
                    [1] => 5
                    [2] => 6
                )

        )

)

You can see here that the 0th entry in board is the exam board (first order list) and the 0th entry in grade is a list in itself (second order list pertaining to the 0th board).

I will leave it to you as a valuable exercise to add the other elements to the first and second-order lists here.

In relation to the table, that is a broad enough topic to merit another question on its own. The structure of this needs to be normalised, so you hold exam boards, exams, students and grades in separate tables. The "grade" is probably the central table, since that requires an exam and a student, and the exam in turn requires a board.