问:
Get the actual position of element in XSLT
I want to get the actual position of the
 using XSLT.

Input:

```<code><root>
    <p>
        <pPr>
            <pStyle val="EQsolutionlist1"/>
        </pPr>
    </p>
   <p>
       <pPr>
           <pStyle val="AAA"/>
       </pPr>
   </p>
   <p>
       <pPr>
           <pStyle val="EQsolutionlist1"/>
       </pPr>
   </p>
</root>
</code>```

Output should be:

```<code><abc>
  <q>1</q>
  <q>2</q>
</abc>
</code>```

Tried code:

```<code><xsl:template match="p/pPr[pStyle[@val = 'EQsolutionlist1']]">
   <abc>
     <q>
        <xsl:value-of select="ancestor::root//pPr[pStyle[val = 'EQsolutionlist1']]/position()"/>
     </q>
   </abc>
  </xsl:template>
</code>```

The Output I am getting:

```<code><abc>
  <q>1 2</q>
  <q>1 2</q>
</abc>
</code>```

This means, there are two p[pPr[pStyle[@val = 'EQsolutionlist1']]] in input. I want to print the position separately. As my code all positions printing in the output. How can I solve this.

I am using XSLT 2.0

答:
If you use xsl:number you can do:

```<code>  <xsl:template match="p/pPr[pStyle[@val = 'EQsolutionlist1']]">
      <q>
          <xsl:number count="pPr[pStyle[@val = 'EQsolutionlist1']]" level="any"/>
      </q>
  </xsl:template>
</code>```

The abc result element would need to be created higher up in the input tree matching as you want a single one and not one for each pr:

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="#all"
    version="3.0">

  <xsl:strip-space elements="*"/>
  <xsl:output indent="yes"/>

  <xsl:template match="root">
      <abc>
          <xsl:apply-templates/>
      </abc>
  </xsl:template>

  <xsl:template match="p/pPr[pStyle[@val = 'EQsolutionlist1']]">
      <q>
          <xsl:number count="pPr[pStyle[@val = 'EQsolutionlist1']]" level="any"/>
      </q>
  </xsl:template>

</xsl:stylesheet>
</code>```

https://xsltfiddle.liberty-development.net/6rexjif

Body:
I want to get the actual position of the
 using XSLT.

Input:

<root>

        <pPr>
            <pStyle val="EQsolutionlist1"/>
        </pPr>

       <pPr>
           <pStyle val="AAA"/>
       </pPr>

       <pPr>
           <pStyle val="EQsolutionlist1"/>
       </pPr>

</root>

Output should be:

<abc>
  <q>1</q>
  <q>2</q>
</abc>

Tried code:

<xsl:template match="p/pPr[pStyle[@val = 'EQsolutionlist1']]">
   <abc>
     <q>
        <xsl:value-of select="ancestor::root//pPr[pStyle[val = 'EQsolutionlist1']]/position()"/>
     </q>
   </abc>
  </xsl:template>

The Output I am getting:

<abc>
  <q>1 2</q>
  <q>1 2</q>
</abc>

This means, there are two p[pPr[pStyle[@val = 'EQsolutionlist1']]] in input. I want to print the position separately. As my code all positions printing in the output. How can I solve this.

I am using XSLT 2.0

Body:
If you use xsl:number you can do:

  <xsl:template match="p/pPr[pStyle[@val = 'EQsolutionlist1']]">
      <q>
          <xsl:number count="pPr[pStyle[@val = 'EQsolutionlist1']]" level="any"/>
      </q>
  </xsl:template>

The abc result element would need to be created higher up in the input tree matching as you want a single one and not one for each pr:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="#all"
    version="3.0">

  <xsl:strip-space elements="*"/>
  <xsl:output indent="yes"/>

  <xsl:template match="root">
      <abc>
          <xsl:apply-templates/>
      </abc>
  </xsl:template>

  <xsl:template match="p/pPr[pStyle[@val = 'EQsolutionlist1']]">
      <q>
          <xsl:number count="pPr[pStyle[@val = 'EQsolutionlist1']]" level="any"/>
      </q>
  </xsl:template>

</xsl:stylesheet>

https://xsltfiddle.liberty-development.net/6rexjif


来源: stackexchange

问:
Batch script with for loop and pipe
I would like all the csv files in a directory which filename does not contain word "summary". Inside the command prompt I can type the following command

```<code>dir /b my_dir\*.csv | find /V "summary"
</code>```

When I try to transfer the above command into a batch file I run into a problem in that the pipe command is not supported in the for loop. That is I cannot do the following

```<code>FOR /f %%A in ('dir /b my_dir\*.csv | find /V "summary"') do (
rem want to do something here
)
</code>```

Can somebody shed some light to me on how to solve the problem above?

Thanks in advance!

答: have a look at the Windows PowerShell. Not that I have ever used it myself, mind.</p>

ContentLicense: CC BY-SA 3.0

Title: Batch script with for loop and pipe

Body:
I would like all the csv files in a directory which filename does not contain word "summary". Inside the command prompt I can type the following command

dir /b my_dir\*.csv | find /V "summary"

When I try to transfer the above command into a batch file I run into a problem in that the pipe command is not supported in the for loop. That is I cannot do the following

FOR /f %%A in ('dir /b my_dir\*.csv | find /V "summary"') do (
rem want to do something here
)

Can somebody shed some light to me on how to solve the problem above?

Thanks in advance!


问:
ClassCastException - getting Activity's view reference from adapter class for dialog fragment
I have an activity that has an EditText and a Dialogfragment. For DialogFragment I have a ListView and an Adapter class for that listview. The listview has a TextView and a button. I want to write the listitem's text to EditText of Activity on listitem's Button click (and then dismiss the Dialog). Pretty much I've achieved this all but it's showing ClassCastException in some devices. Here is the list item's Button clickListener:

```<code>holder.button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            EditText editText=((MainActivity)v.getContext()).findViewById(R.id.write_text);
            editText.removeTextChangedListener(((MainActivity) Objects.requireNonNull(v.getContext())).textWatcher);
            editText.addTextChangedListener(((MainActivity) Objects.requireNonNull(v.getContext())).textWatcher2);

            editText.getText().insert(editText.getSelectionStart(), listData.get(position).getBio());

            editText.removeTextChangedListener(((MainActivity) Objects.requireNonNull(v.getContext())).textWatcher2);
            editText.addTextChangedListener(((MainActivity) Objects.requireNonNull(v.getContext())).textWatcher);

            dialog.dismiss();

        }
    });
</code>```

I don't understand why is there ClassCastException. Here is the stack trace from Crashlytics:

```<code>Fatal Exception: java.lang.ClassCastException: b.b.q.v0 cannot be cast to com.xx.xx.xx.MainActivity
       at com.xx.xx.Adapters.ListAdapter.access$000(ListAdapter.java)
       at android.view.View.performClick(View.java:4508)
       at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java)
       at android.view.View$PerformClick.run(View.java:18675)
       at android.os.Handler.handleCallback(Handler.java:733)
       at android.os.Handler.dispatchMessage(Handler.java:95)
       at android.os.Looper.loop(Looper.java:136)
       at android.app.ActivityThread.main(ActivityThread.java:5590)
       at java.lang.reflect.Method.invokeNative(Method.java)
       at java.lang.reflect.Method.invoke(Method.java:515)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1280)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1096)
       at dalvik.system.NativeStart.main(NativeStart.java)
</code>```

Any help will be highy appreciated.

EDIT: It's happening only in Android 4.4 devices.

答:
when you initialize your adapter class as an alternative could be pass an activity reference as below.

```<code>public class MyAdapter(Activity activity)
</code>```

and when you create an instance of your adapter in the dialog fragment

```<code>Adapter adapter = new Adapter(getActivity());
</code>```

in that case getActivity method will return you the attached activity to dialog fragment.

And finally you'll be able to use activity instance your adapter as below

```<code> EditText editText = activity.findViewById(R.id.write_text);
</code>```

another approach could be to create a communication through interfaces

regards

ContentLicense: CC BY-SA 4.0

Body:
I have an activity that has an EditText and a Dialogfragment. For DialogFragment I have a ListView and an Adapter class for that listview. The listview has a TextView and a button. I want to write the listitem's text to EditText of Activity on listitem's Button click (and then dismiss the Dialog). Pretty much I've achieved this all but it's showing ClassCastException in some devices. Here is the list item's Button clickListener:

holder.button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            EditText editText=((MainActivity)v.getContext()).findViewById(R.id.write_text);
            editText.removeTextChangedListener(((MainActivity) Objects.requireNonNull(v.getContext())).textWatcher);
            editText.addTextChangedListener(((MainActivity) Objects.requireNonNull(v.getContext())).textWatcher2);

            editText.getText().insert(editText.getSelectionStart(), listData.get(position).getBio());

            editText.removeTextChangedListener(((MainActivity) Objects.requireNonNull(v.getContext())).textWatcher2);
            editText.addTextChangedListener(((MainActivity) Objects.requireNonNull(v.getContext())).textWatcher);

            dialog.dismiss();

        }
    });

I don't understand why is there ClassCastException. Here is the stack trace from Crashlytics:

Fatal Exception: java.lang.ClassCastException: b.b.q.v0 cannot be cast to com.xx.xx.xx.MainActivity
       at com.xx.xx.Adapters.ListAdapter.access$000(ListAdapter.java)
       at android.view.View.performClick(View.java:4508)
       at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java)
       at android.view.View$PerformClick.run(View.java:18675)
       at android.os.Handler.handleCallback(Handler.java:733)
       at android.os.Handler.dispatchMessage(Handler.java:95)
       at android.os.Looper.loop(Looper.java:136)
       at android.app.ActivityThread.main(ActivityThread.java:5590)
       at java.lang.reflect.Method.invokeNative(Method.java)
       at java.lang.reflect.Method.invoke(Method.java:515)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1280)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1096)
       at dalvik.system.NativeStart.main(NativeStart.java)

Any help will be highy appreciated.

EDIT: It's happening only in Android 4.4 devices.

Body:
when you initialize your adapter class as an alternative could be pass an activity reference as below.

public class MyAdapter(Activity activity)

and when you create an instance of your adapter in the dialog fragment

Adapter adapter = new Adapter(getActivity());

in that case getActivity method will return you the attached activity to dialog fragment.

And finally you'll be able to use activity instance your adapter as below

 EditText editText = activity.findViewById(R.id.write_text);

another approach could be to create a communication through interfaces

regards


问:
if else condition not evaluating in react component
So I'm making a todo list app and to provide alternate colors to new todo items as they are added in the todolist i have used the if else statement in React component but i think it is not evaluating.

Below are the two classes from my css file that i'm using -->

```<code> .bgColorItem1{
    background-color: white;
}

.bgColorItem2{
    background-color:grey;
}
</code>```

Below is the component that accepts arguments item(todo item that will be added to the list) and key(index passed as key) from todolist -->

```<code>  import React from 'react';
    import './App.css';

    const TodoItem=({item,key})=>{
        let settingClass="";

    // *****so the problem is here in the if condn that's not putting settingClass as bgColorItem1*****
        if(key%2===0){
            settingClass="bgColorItem1";
        }else{
        settingClass="bgColorItem2";
    }

    return <div className={`boxSpace centerAligning ${settingClass}`}>{item}</div>
}

export default TodoItem;
</code>```

So what i expect from this code that key which was index in todolist component passed to todo here above should return 0 for even so that settingClass can have alternate values and hence provide alternate colors.But that is not the case.

答:
key "prop" is reserved in React. You cannot use it. Rename this props to "idx"
See: Special props</p>

Body:
So I'm making a todo list app and to provide alternate colors to new todo items as they are added in the todolist i have used the if else statement in React component but i think it is not evaluating.

Below are the two classes from my css file that i'm using -->

 .bgColorItem1{
    background-color: white;
}

.bgColorItem2{
    background-color:grey;
}

Below is the component that accepts arguments item(todo item that will be added to the list) and key(index passed as key) from todolist -->

  import React from 'react';
    import './App.css';

    const TodoItem=({item,key})=>{
        let settingClass="";

    // *****so the problem is here in the if condn that's not putting settingClass as bgColorItem1*****
        if(key%2===0){
            settingClass="bgColorItem1";
        }else{
        settingClass="bgColorItem2";
    }

    return <div className={`boxSpace centerAligning ${settingClass}`}>{item}

}

export default TodoItem;

So what i expect from this code that key which was index in todolist component passed to todo here above should return 0 for even so that settingClass can have alternate values and hence provide alternate colors.But that is not the case.


问:
Firebase Firestore cloud function to watch user email updated
As part of building out a production app, I have a way to change a user's email address. I do this using

```<code>firebase.auth().updateEmail(newEmail);
</code>```

This works well, and I am sent a email that says that my email has been changed. My issue is, I also get sent a link that allows me to recover my old email (a handy feature for security etc), but that causes the issue where the email address I store can get out of sync.

I store information about the user in a collection, when they change their email address using the above code, I also update the collection with their new email.

The problem is, if they click the recover link, there email address is reset back on on the user authentication side of things, but is not reset on my collection.

What I have been trying to find is something that behaves like this, but I cant find it

```<code>functions.auth.user().onEmailChange(async (newEmail, context) =>
{
    admin.firestore().collection(Collections.USERS_PRIVATE).doc(context.params.uid).update({ email: newEmail });
});
</code>```

That way I can mirror my collection to always be in sync with the user authentication email address.

答: I think you can do this by using a Custom Email Handler (https://firebase.google.com/docs/auth/custom-email-handler). Just as you do it on the initial change, this lets you run some extra code when the user reverts the email back.</p>

Body:
As part of building out a production app, I have a way to change a user's email address. I do this using

firebase.auth().updateEmail(newEmail);

This works well, and I am sent a email that says that my email has been changed. My issue is, I also get sent a link that allows me to recover my old email (a handy feature for security etc), but that causes the issue where the email address I store can get out of sync.

I store information about the user in a collection, when they change their email address using the above code, I also update the collection with their new email.

The problem is, if they click the recover link, there email address is reset back on on the user authentication side of things, but is not reset on my collection.

What I have been trying to find is something that behaves like this, but I cant find it

functions.auth.user().onEmailChange(async (newEmail, context) =>
{
    admin.firestore().collection(Collections.USERS_PRIVATE).doc(context.params.uid).update({ email: newEmail });
});

That way I can mirror my collection to always be in sync with the user authentication email address.


问:
Global API call Vue.js
I'm having trouble creating a global variable that contains API.
I need to use this variable throughout my app, so it will be easier to change API link when the time comes.
How can I do that?
So far I've done the following:

Created a file called config.js

```<code>const baseURL = 'http://myapi'

export default {
    baseURL
}
</code>```

I'm using Vuex to make api calls so the part where I try to receive data looks like this in my store:

```<code>import baseURL from '../../../config.js'

    async fetchStaff({ commit }, id, baseURL) {
    if (id === undefined) {
        const response = await axios.get(baseURL + `/employee/staff`, { headers: { Authorization: `Bearer ${sessionStorage.getItem('token')}` } });
        commit('setStaff', response.data);
        // eslint-disable-next-line no-console
        console.log(response.data)
    } else {
        const response = await axios.get(baseURL + `/employee/${id}`, { headers: { Authorization: `Bearer ${sessionStorage.getItem('token')}` } });
        commit('setStaff', response.data);
    }
},
</code>```

baseURL is undefind in store.
Can someone point out the mistake here, please?

答:
First, you're exporting an object in your config.js.
so if you import it like below:

import baseURL from '../../../config.js'

Then you will get the whole object of configs. Instead, you could import the baseURL variable by doing this:

import { baseURL } from '../../../config.js'

Second, in this line:

async fetchStaff({ commit }, id, baseURL)

baseURL is recognized as a parameter. that's why it always has no value or undefined, I would recommend removing it from the function parameter.
So it will probably look like  below:

```<code>import { baseURL } from '../../../config.js'

async fetchStaff({ commit }, id) {
    if (id === undefined) {
        const response = await axios.get(baseURL + `/employee/staff`, { headers: { Authorization: `Bearer ${sessionStorage.getItem('token')}` } });
        commit('setStaff', response.data);
        // eslint-disable-next-line no-console
        console.log(response.data)
    } else {
        const response = await axios.get(baseURL + `/employee/${id}`, { headers: { Authorization: `Bearer ${sessionStorage.getItem('token')}` } });
        commit('setStaff', response.data);
    }
},
</code>```

thanks

Title: Global API call Vue.js

Body:
I'm having trouble creating a global variable that contains API.
I need to use this variable throughout my app, so it will be easier to change API link when the time comes.
How can I do that?
So far I've done the following:

Created a file called config.js

const baseURL = 'http://myapi'

export default {
    baseURL
}

I'm using Vuex to make api calls so the part where I try to receive data looks like this in my store:

import baseURL from '../../../config.js'

    async fetchStaff({ commit }, id, baseURL) {
    if (id === undefined) {
        const response = await axios.get(baseURL + `/employee/staff`, { headers: { Authorization: `Bearer ${sessionStorage.getItem('token')}` } });
        commit('setStaff', response.data);
        // eslint-disable-next-line no-console
        console.log(response.data)
    } else {
        const response = await axios.get(baseURL + `/employee/${id}`, { headers: { Authorization: `Bearer ${sessionStorage.getItem('token')}` } });
        commit('setStaff', response.data);
    }
},

baseURL is undefind in store.
Can someone point out the mistake here, please?

Body:
First, you're exporting an object in your config.js.
so if you import it like below:

import baseURL from '../../../config.js'

Then you will get the whole object of configs. Instead, you could import the baseURL variable by doing this:

import { baseURL } from '../../../config.js'

Second, in this line:

async fetchStaff({ commit }, id, baseURL)

baseURL is recognized as a parameter. that's why it always has no value or undefined, I would recommend removing it from the function parameter.
So it will probably look like  below:

import { baseURL } from '../../../config.js'

async fetchStaff({ commit }, id) {
    if (id === undefined) {
        const response = await axios.get(baseURL + `/employee/staff`, { headers: { Authorization: `Bearer ${sessionStorage.getItem('token')}` } });
        commit('setStaff', response.data);
        // eslint-disable-next-line no-console
        console.log(response.data)
    } else {
        const response = await axios.get(baseURL + `/employee/${id}`, { headers: { Authorization: `Bearer ${sessionStorage.getItem('token')}` } });
        commit('setStaff', response.data);
    }
},

thanks


问:
Trying to install manjaro and have a problem with allocating of the disk free space
I'm trying to install manjaro on laptop with oem windows 10 on board, I do it using
manjaro architect cli installer. I've created LVM, parted logical volumes, made luks on LVM, formatted partitions to btrfs and mounted it. When I moved next and began installing DE I caught the error:

```<code>checking available disk space...
error: Partition /mnt too full: 1333620 blocks needed, 0 blocks free
error: not enough free disk space
error: failed to commit transaction (not enough free disk space)
Errors occurred, no packages were upgraded.
==> ERROR: Failed to install packages to new root
</code>```

Then I type df -hT and see this:

```<code>Filesystem                       Type      Size  Used Avail Use% Mounted on
dev                              devtmpfs  6.8G     0  6.8G   0% /dev
run                              tmpfs     6.9G  101M  6.8G   2% /run
/dev/sdb1                        iso9660   2.7G  2.7G     0 100% /run/miso/bootmnt
cowspace                         tmpfs     256M     0  256M   0% /run/miso/cowspace
overlay_root                     tmpfs      11G  189M   11G   2% /run/miso/overlay_root
/dev/loop0                       squashfs   21M   21M     0 100% /run/miso/sfs/livefs
/dev/loop1                       squashfs  457M  457M     0 100% /run/miso/sfs/mhwdfs
/dev/loop2                       squashfs  1.6G  1.6G     0 100% /run/miso/sfs/desktopfs
/dev/loop3                       squashfs  592M  592M     0 100% /run/miso/sfs/rootfs
overlay                          overlay    11G  189M   11G   2% /
tmpfs                            tmpfs     6.9G  121M  6.8G   2% /dev/shm
tmpfs                            tmpfs     6.9G     0  6.9G   0% /sys/fs/cgroup
tmpfs                            tmpfs     6.9G   48M  6.8G   1% /tmp
tmpfs                            tmpfs     6.9G  2.3M  6.9G   1% /etc/pacman.d/gnupg
tmpfs                            tmpfs     1.4G   12K  1.4G   1% /run/user/1000
/dev/mapper/vg--default-lv--root btrfs     162G  1.1G     0 100% /mnt
/dev/mapper/crypto-home          btrfs      60G  3.4M   60G   1% /mnt/home
/dev/mapper/crypto-project       btrfs      40G  3.4M   40G   1% /mnt/home/project
/dev/nvme0n1p4                   fuseblk   200G   20G  181G  10% /mnt/windows
/dev/nvme0n1p7                   vfat       99M   512   99M   1% /mnt/boot/efi
</code>```

What is wrong with the row?

```<code>/dev/mapper/vg--default-lv--root btrfs     162G  1.1G     0 100% /mnt
</code>```

How can it be so - Use% 100% and Avail 0, but only 1.1G is used from 162G?

答:
The solution is to manually unmount and remount the filesystem before installing packages. Possibly, closing and reopening the btrfs volume is also necessary. If you run into the issue while packages are being installed, you can do the mount/remount and then just redo the package installation step without formatting.

Previously I wrote the following, however it did not help in a recent install:

I ran into the same issue. This is some sort of bug in btrfs. I stumbled upon a workaround. After manually creating a file and writing to it (touch /mnt/temp, dd if=/dev/zero of=/mnt/temp bs=1M count=1000), df began to report correct available space and I was able to resume the installation.

P.S. I am using btrfs directly over luks over block device.

Body:
I'm trying to install manjaro on laptop with oem windows 10 on board, I do it using
manjaro architect cli installer. I've created LVM, parted logical volumes, made luks on LVM, formatted partitions to btrfs and mounted it. When I moved next and began installing DE I caught the error:

checking available disk space...
error: Partition /mnt too full: 1333620 blocks needed, 0 blocks free
error: not enough free disk space
error: failed to commit transaction (not enough free disk space)
Errors occurred, no packages were upgraded.
==> ERROR: Failed to install packages to new root

Then I type df -hT and see this:

Filesystem                       Type      Size  Used Avail Use% Mounted on
dev                              devtmpfs  6.8G     0  6.8G   0% /dev
run                              tmpfs     6.9G  101M  6.8G   2% /run
/dev/sdb1                        iso9660   2.7G  2.7G     0 100% /run/miso/bootmnt
cowspace                         tmpfs     256M     0  256M   0% /run/miso/cowspace
overlay_root                     tmpfs      11G  189M   11G   2% /run/miso/overlay_root
/dev/loop0                       squashfs   21M   21M     0 100% /run/miso/sfs/livefs
/dev/loop1                       squashfs  457M  457M     0 100% /run/miso/sfs/mhwdfs
/dev/loop2                       squashfs  1.6G  1.6G     0 100% /run/miso/sfs/desktopfs
/dev/loop3                       squashfs  592M  592M     0 100% /run/miso/sfs/rootfs
overlay                          overlay    11G  189M   11G   2% /
tmpfs                            tmpfs     6.9G  121M  6.8G   2% /dev/shm
tmpfs                            tmpfs     6.9G     0  6.9G   0% /sys/fs/cgroup
tmpfs                            tmpfs     6.9G   48M  6.8G   1% /tmp
tmpfs                            tmpfs     6.9G  2.3M  6.9G   1% /etc/pacman.d/gnupg
tmpfs                            tmpfs     1.4G   12K  1.4G   1% /run/user/1000
/dev/mapper/vg--default-lv--root btrfs     162G  1.1G     0 100% /mnt
/dev/mapper/crypto-home          btrfs      60G  3.4M   60G   1% /mnt/home
/dev/mapper/crypto-project       btrfs      40G  3.4M   40G   1% /mnt/home/project
/dev/nvme0n1p4                   fuseblk   200G   20G  181G  10% /mnt/windows
/dev/nvme0n1p7                   vfat       99M   512   99M   1% /mnt/boot/efi

What is wrong with the row?

/dev/mapper/vg--default-lv--root btrfs     162G  1.1G     0 100% /mnt

How can it be so - Use% 100% and Avail 0, but only 1.1G is used from 162G?


问:
Deploy server binaries on google cloud
I have a server binary (gitea) which I am trying to deploy on google cloud App Engine. I can run it successfully on the google cloud console,  checked it using web viewer provided in the console. I have few doubts regarding the deployment on google cloud, which I am listing down here.

Is there any difference between running a server in console versus deploying it?
  If there is a difference how can I deploy the binaries on google cloud App Engine?

答:
It's generally not as simple as plonking a binary on a VM. Not because this approach doesn't work but because you want to consider security (access|control) and maintainability too.

I recommend you spend some time reading Google's documentation and continue to learn-by-doing to familiar yourself with Cloud Platform.

Some pointers:

There are multiple compute services for you to choose between on Google Cloud Platform (Cloud Shell, App Engine standard or flexible, Compute Engine, Kubernetes Engine, Cloud Run, Cloud Functions etc.). Each, mostly (!) addresses a well-defined use-case.

App Engine has 2 flavors: standard and flexible. Using Flexible, you may deploy a container containing your gitea binary. But, you will need to use a  container (and I believe gitea provides one) that includes the binary. See custom runtimes.

Cloud Shell is a Compute Engine VM but it's intended as more of a development tool. Yes, you can run binaries on it and yes you can access these remotely but this is likely not the best solution for you in this case.

Alternatively, (but still containerized) you may also be interested to review Cloud Run, Kubernetes Engine (probably overkill in this case).

Lastly, you could create a Compute Engine instance (VM) and run the binary on it. This is a valid solution too.

Title: Deploy server binaries on google cloud


问:
React Native Run Child Reference Method From Another Component
I am trying to run a component method of another component. I am trying this using react ref. I am also following this link:
https://medium.freecodecamp.org/react-changing-state-of-child-component-from-parent-8ab547436271 But my structure is a bit more complicated.

List.js

```<code>class List extends Component {

    constructor(){
        super()
        this.LoadCounterElement = React.createRef()
    }

    render(){
        return(
            <View>
                <ItemGenerator />
                <LoadCounter ref={this.LoadCounterElement}/>
            </View>
        )
    }
}

function mapStateToProps(state) {
    return {
        counter: state.counter.counter
    }
}

function mapDispatchToProps(dispatch) {
    return {
        increaseCounter: () => dispatch({ type: 'INCREASE_COUNTER' }),
        decreaseCounter: () => dispatch({ type: 'DECREASE_COUNTER' }),
    }
}

export default connect(mapStateToProps)(List);
</code>```

ItemGenerator.js

```<code>class ItemGenerator extends Component {

    render() {
        return (
            <ScrollView>
                {
                    this.state.data.map((item, index) => {
                        return(<ItemList navigate={this.props.navigate} data={item} key={index}/>)
                    })
                }
            </ScrollView>
        )
    }

}
</code>```

LoadCounter.js

```<code>class LoadCounter extends Component {

    constructor(props) {
        super(props)
        this.state = {
            count : 0,
        }
    }

    componentDidMount() {
        this._renderCount()
    }

    _renderCount = () => {
        this.setState({count:this.props.counter})
    }

    render(){
        return(
            <View>
                <Text>{this.state.count}</Text>
            </View>
        )
    }
}

function mapStateToProps(state) {
    return {
        counter: state.counter.counter
    }
}

export default connect(mapStateToProps)(withNavigation(LoadCounter));
</code>```

ItemList.js

```<code>class ItemList extends Component {
    render() {
        return(
            <View>
                <TouchableOpacity onPress={() => {
                    this.props.increaseCounter()
                    this.LoadCounterElement.current._renderCount()
                }}>
                    <Card containerStyle={{margin: 0}}>
                        <View style={{flex:1, flexDirection:'row', height:70, alignItems:'center', justifyContent:'space-between'}}>
                            <View style={{flexDirection:'row', alignItems:'center', width:'55%'}}>
                                <View style={{flexDirection:'column', marginLeft:10}}>
                                    <Text style={{...}}>{this.props.data.name}</Text>
                                </View>
                            </View>
                        </View>
                    </Card>
                </TouchableOpacity>
            </View>
        )
    }
}

function mapDispatchToProps(dispatch) {
    return {
        increaseCounter: () => dispatch({ type: 'INCREASE_COUNTER' }),
        decreaseCounter: () => dispatch({ type: 'DECREASE_COUNTER' }),
    }
}

export default connect(mapStateToProps)(ItemList);
</code>```

counterReducer.js

```<code>const initialState = {
    counter: 1
}
const counterReducer = (state = initialState, action) => {
    switch (action.type) {
        case 'INCREASE_COUNTER':
            return { counter: state.counter + 1 }
        case 'DECREASE_COUNTER':
            return { counter: state.counter - 1 }
    }
    return state
}

export default counterReducer;
</code>```

As you can see in ItemLiist Component, i am trying to run _renderCount method which is in Component LoadCounter. But its not working. Kindly guide what i am missing?

答:
The problem here is that you have some data in child component that should be reflected in a parent component. I would recommend that you move the shared state in the parent component or to the reducer state.

It is odd that you are using an action creator to increment/decrement counts - which I am thinking that updates some reducer state. If this is the case, why store that state in the local component state again ? You could just read the counter state from the reducer in your parent component.

Parent.js

class Parent extends React.Component {
  render() {
    return (

        {this.props.count}

    );
  }
}

const mapStateToProps = state => ({
  count: state.yourCountReducer.count,
});

export default connect(mapStateToProps)(Parent);
```

<p><code>Child.js</code></p>

<pre class="lang-js prettyprint-override"><code>class Child extends React.Component {
  render() {
    return (
      <div>
        <button onClick={() => this.props.increaseCounter()}>+</button>
        <button onClick={() => this.props.decreaseCounter()}>-</button>
      </div>
    );
  }
}

const mapDispatchToProps = dispatch => ({
  increaseCounter: () => dispatch({ type: 'INCREASE_COUNTER' }),
  decreaseCounter: () => dispatch({ type: 'DECREASE_COUNTER' }),
});

export default connect(null, mapDispatchToProps)(Child);
</code>```

This way, the parent component will show the updated counter state when the child component updates the count. From your sample code, I am not sure if there is any good reason to store a shared reducer state in any component's local state.

Body:
I am trying to run a component method of another component. I am trying this using react ref. I am also following this link:
https://medium.freecodecamp.org/react-changing-state-of-child-component-from-parent-8ab547436271 But my structure is a bit more complicated.

List.js

class List extends Component {

    constructor(){
        super()
        this.LoadCounterElement = React.createRef()
    }

    render(){
        return(
            <View>
                <ItemGenerator />
                <LoadCounter ref={this.LoadCounterElement}/>
            </View>
        )
    }
}

function mapStateToProps(state) {
    return {
        counter: state.counter.counter
    }
}

function mapDispatchToProps(dispatch) {
    return {
        increaseCounter: () => dispatch({ type: 'INCREASE_COUNTER' }),
        decreaseCounter: () => dispatch({ type: 'DECREASE_COUNTER' }),
    }
}

export default connect(mapStateToProps)(List);

ItemGenerator.js

class ItemGenerator extends Component {

    render() {
        return (
            <ScrollView>
                {
                    this.state.data.map((item, index) => {
                        return(<ItemList navigate={this.props.navigate} data={item} key={index}/>)
                    })
                }
            </ScrollView>
        )
    }

}

LoadCounter.js

class LoadCounter extends Component {

    constructor(props) {
        super(props)
        this.state = {
            count : 0,
        }
    }

    componentDidMount() {
        this._renderCount()
    }

    _renderCount = () => {
        this.setState({count:this.props.counter})
    }

    render(){
        return(
            <View>
                <Text>{this.state.count}</Text>
            </View>
        )
    }
}

function mapStateToProps(state) {
    return {
        counter: state.counter.counter
    }
}

export default connect(mapStateToProps)(withNavigation(LoadCounter));

ItemList.js

class ItemList extends Component {
    render() {
        return(
            <View>
                <TouchableOpacity onPress={() => {
                    this.props.increaseCounter()
                    this.LoadCounterElement.current._renderCount()
                }}>
                    <Card containerStyle={{margin: 0}}>
                        <View style={{flex:1, flexDirection:'row', height:70, alignItems:'center', justifyContent:'space-between'}}>
                            <View style={{flexDirection:'row', alignItems:'center', width:'55%'}}>
                                <View style={{flexDirection:'column', marginLeft:10}}>
                                    <Text style={{...}}>{this.props.data.name}</Text>
                                </View>
                            </View>
                        </View>
                    </Card>
                </TouchableOpacity>
            </View>
        )
    }
}

function mapDispatchToProps(dispatch) {
    return {
        increaseCounter: () => dispatch({ type: 'INCREASE_COUNTER' }),
        decreaseCounter: () => dispatch({ type: 'DECREASE_COUNTER' }),
    }
}

export default connect(mapStateToProps)(ItemList);

counterReducer.js

const initialState = {
    counter: 1
}
const counterReducer = (state = initialState, action) => {
    switch (action.type) {
        case 'INCREASE_COUNTER':
            return { counter: state.counter + 1 }
        case 'DECREASE_COUNTER':
            return { counter: state.counter - 1 }
    }
    return state
}

export default counterReducer;

As you can see in ItemLiist Component, i am trying to run _renderCount method which is in Component LoadCounter. But its not working. Kindly guide what i am missing?

Body:
The problem here is that you have some data in child component that should be reflected in a parent component. I would recommend that you move the shared state in the parent component or to the reducer state.

It is odd that you are using an action creator to increment/decrement counts - which I am thinking that updates some reducer state. If this is the case, why store that state in the local component state again ? You could just read the counter state from the reducer in your parent component.

Parent.js

class Parent extends React.Component {
  render() {
    return (
      <div>
        <span>{this.props.count}</span>
      </div>
    );
  }
}

const mapStateToProps = state => ({
  count: state.yourCountReducer.count,
});

export default connect(mapStateToProps)(Parent);

Child.js

class Child extends React.Component {
  render() {
    return (
      <div>
        <button onClick={() => this.props.increaseCounter()}>+</button>
        <button onClick={() => this.props.decreaseCounter()}>-</button>
      </div>
    );
  }
}

const mapDispatchToProps = dispatch => ({
  increaseCounter: () => dispatch({ type: 'INCREASE_COUNTER' }),
  decreaseCounter: () => dispatch({ type: 'DECREASE_COUNTER' }),
});

export default connect(null, mapDispatchToProps)(Child);

This way, the parent component will show the updated counter state when the child component updates the count. From your sample code, I am not sure if there is any good reason to store a shared reducer state in any component's local state.


问:
RabbitMq refuses connection when run in docker
My docker-compose file looks like this:

```<code>version: '2'

services:
  explore:
    image: explore
    build:
      context: ./Explore
      dockerfile: VsDockerfile
    environment:
      - "ElasticUrl=http://localhost:9200"
      - "RabbitMq/Host=localhost"
      - "RabbitMq/Username=guest"
      - "RabbitMq/Password=guest"
    networks:
      - localnet

  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:5.4.3
    container_name: elasticsearch
    environment:
      - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
    ports:
      - 9200:9200
    volumes:
      - ./esdata:/usr/share/elasticsearch/data
    networks:
      - localnet

  rabbit:
    image: rabbitmq:3.6.7-management
    hostname: rabbit
    ports:
      - 15672:15672
      - 5672:5672
    networks:
      - localnet

networks:
  localnet:
    external:
      name: localnet
</code>```

If I type http://localhost:15672 in the browser, I get the rabbitmq interface, but if I tries to connect from my Explore project like this:

```<code>public SqlToRabbitProcessor(SqlToRabbitRepository sqlToRabbitRepository)
{
    _sqlToRabbitRepository = sqlToRabbitRepository;

    var factory = new ConnectionFactory
    {
        HostName = Environment.GetEnvironmentVariable("RabbitMq/Host"),
        UserName = Environment.GetEnvironmentVariable("RabbitMq/Username"),
        Password = Environment.GetEnvironmentVariable("RabbitMq/Password")
    };

    var rabbit = factory.CreateConnection();
    channel = rabbit.CreateModel();
}
</code>```

Then it breaks in the line

```<code>var rabbit = factory.CreateConnection();
</code>```

with the error saying

ExtendedSocketException: Connection refused 127.0.0.1:5672
System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)

ConnectFailureException: Connection failed
RabbitMQ.Client.EndpointResolverExtensions.SelectOne(IEndpointResolver resolver, Func selector)

BrokerUnreachableException: None of the specified endpoints were reachable
RabbitMQ.Client.ConnectionFactory.CreateConnection(IEndpointResolver endpointResolver, string clientProvidedName)

答:
Follow instructions on this post.

Just to benefit people that stumble upon this question. The --link feature is now considered legacy and is a prime candidate to be deprecated by docker.
The easiest way is to use

depends_on:
  In order to do this, its recommended to first create a network like so"

```<code>docker network create <network_name>
</code>```

Then use docker-compose up to spawn services that bind with each other. Look at the example below where I've bound my spring-boot app to rabbit-mq. You can clone my repo from here

version: "3.1"
services:
  rabbitmq-container:
    image: rabbitmq:3.5.3-management
    hostname: rabbitmq-container
    ports:
      - 5673:5673
      - 5672:5672
      - 15672:15672
    networks:
      - resolute

  resolute-container:
    build: .
    ports:
      - 8080:8080
    environment:
      - spring_rabbitmq_host=rabbitmq-container
      - spring_rabbitmq_port=5672
      - spring_rabbitmq_username=guest
      - spring_rabbitmq_password=guest
      - resolute_rabbitmq_publishQueueName=resolute-run-request
      - resolute_rabbitmq_exchange=resolute
    depends_on:
      - rabbitmq-container
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    networks:
      - resolute

networks:
  resolute:
    external:
      name: resolute```

See how I've created a network called resolute and bound the apps to the same network. I've also given my rabbitmq-container a hostname. This is because docker now prepends the container name and that makes it difficult to bind services by name.

Body:
My docker-compose file looks like this:

version: '2'

services:
  explore:
    image: explore
    build:
      context: ./Explore
      dockerfile: VsDockerfile
    environment:
      - "ElasticUrl=http://localhost:9200"
      - "RabbitMq/Host=localhost"
      - "RabbitMq/Username=guest"
      - "RabbitMq/Password=guest"
    networks:
      - localnet

  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:5.4.3
    container_name: elasticsearch
    environment:
      - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
    ports:
      - 9200:9200
    volumes:
      - ./esdata:/usr/share/elasticsearch/data
    networks:
      - localnet

  rabbit:
    image: rabbitmq:3.6.7-management
    hostname: rabbit
    ports:
      - 15672:15672
      - 5672:5672
    networks:
      - localnet

networks:
  localnet:
    external:
      name: localnet

If I type http://localhost:15672 in the browser, I get the rabbitmq interface, but if I tries to connect from my Explore project like this:

public SqlToRabbitProcessor(SqlToRabbitRepository sqlToRabbitRepository)
{
    _sqlToRabbitRepository = sqlToRabbitRepository;

    var factory = new ConnectionFactory
    {
        HostName = Environment.GetEnvironmentVariable("RabbitMq/Host"),
        UserName = Environment.GetEnvironmentVariable("RabbitMq/Username"),
        Password = Environment.GetEnvironmentVariable("RabbitMq/Password")
    };

    var rabbit = factory.CreateConnection();
    channel = rabbit.CreateModel();
}

Then it breaks in the line

var rabbit = factory.CreateConnection();

with the error saying

ExtendedSocketException: Connection refused 127.0.0.1:5672
System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)

ConnectFailureException: Connection failed
RabbitMQ.Client.EndpointResolverExtensions.SelectOne(IEndpointResolver resolver, Func selector)

BrokerUnreachableException: None of the specified endpoints were reachable
RabbitMQ.Client.ConnectionFactory.CreateConnection(IEndpointResolver endpointResolver, string clientProvidedName)

Body:
Follow instructions on this post.

Just to benefit people that stumble upon this question. The --link feature is now considered legacy and is a prime candidate to be deprecated by docker.
The easiest way is to use

depends_on:
  In order to do this, its recommended to first create a network like so"

docker network create <network_name>

Then use docker-compose up to spawn services that bind with each other. Look at the example below where I've bound my spring-boot app to rabbit-mq. You can clone my repo from here

version: "3.1"
services:
  rabbitmq-container:
    image: rabbitmq:3.5.3-management
    hostname: rabbitmq-container
    ports:
      - 5673:5673
      - 5672:5672
      - 15672:15672
    networks:
      - resolute

  resolute-container:
    build: .
    ports:
      - 8080:8080
    environment:
      - spring_rabbitmq_host=rabbitmq-container
      - spring_rabbitmq_port=5672
      - spring_rabbitmq_username=guest
      - spring_rabbitmq_password=guest
      - resolute_rabbitmq_publishQueueName=resolute-run-request
      - resolute_rabbitmq_exchange=resolute
    depends_on:
      - rabbitmq-container
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    networks:
      - resolute

networks:
  resolute:
    external:
      name: resolute

See how I've created a network called resolute and bound the apps to the same network. I've also given my rabbitmq-container a hostname. This is because docker now prepends the container name and that makes it difficult to bind services by name.


问:
Post requisition failed
I'm trying to make a POST request, to convert and download a file to pdf, but I have this error:
documento.service.ts :

```<code>  download(documento: IDocumento) {
    return this.http.post(SERVER_API_URL + "api/download/", documento).subscribe((response) => {
      saveAs(response, documento.tituloDocumento + "." + "pdf");
    });
  }
</code>```

DocumentResource

```<code>    @RequestMapping(value = "/download", method = RequestMethod.POST)
public void download(HttpServletResponse response, @RequestBody DocumentoDTO documentoDTO) throws IOException {
    File file = new File(documentoDTO.getPathorigdoc());
    response.setContentType("pdf");
    response.setHeader("Content-disposition", "attachment;" + documentoDTO.getTituloDocumento());
    response.getOutputStream().write(Files.readAllBytes(file.toPath()));
}

</code>```

```<code>Access to XMLHttpRequest at 'https://autenticacao.campogrande.ms.gov.br/auth/realms/dev/protocol/openid-connect/auth?response_type=code&client_id=web_app&scope=openid%20offline_access%20profile%20email%20address%20phone%20roles%20web-origins%20jhipster&state=DooRYbdfmKCip2apn-NOTWQOqWBGkeh-AigMtoJVfcM%3D&redirect_uri=http://localhost:9000/login/oauth2/code/oidc' (redirected from 'http://localhost:9000/api/download/') from origin 'http://localhost:9000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
autenticacao.campogrande.ms.gov.br/auth/realms/dev/protocol/openid-connect/auth?response_type=code&client_id=web_app&scope=openid%20offline_access%20profile%20email%20address%20phone%20roles%20web-origins%20jhipster&state=DooRYbdfmKCip2apn-NOTWQOqWBGkeh-AigMtoJVfcM%3D&redirect_uri=http://localhost:9000/login/oauth2/code/oidc:1 Failed to load resource: net::ERR_FAILED
webpack-internal:///./node_modules/@angular/core/fesm5/core.js:6249 ERROR HttpErrorResponse
</code>```

答:
Being able to solve, but you are not managing the download, I believe it is because or the answer is returning null, do I need to fix anything?

```<code>    @PostMapping(value = "/download")
public void download(HttpServletResponse response, @RequestBody DocumentoDTO documentoDTO) throws IOException {
    String caminho = "";

    caminho += "/arquivos/leisweb" + File.separator + documentoDTO.getPathorigdoc();

    File file = new File(caminho);
    response.setContentType("application/pdf");
    response.setHeader("Content-disposition", "attachment;" + documentoDTO.getTituloDocumento() + ".pdf");
    response.getOutputStream().write(Files.readAllBytes(file.toPath()));
}

  download(documento: IDocumento) {
    return this.http.post(SERVER_API_URL + "api/download", documento).subscribe((response) => {
      saveAs(response, documento.tituloDocumento + "." + "pdf");
    });
  }
</code>```

Return:  Exit: .web.rest.DocumentoResource.download() with result = null

Title: Post requisition failed

Body:
I'm trying to make a POST request, to convert and download a file to pdf, but I have this error:
documento.service.ts :

  download(documento: IDocumento) {
    return this.http.post(SERVER_API_URL + "api/download/", documento).subscribe((response) => {
      saveAs(response, documento.tituloDocumento + "." + "pdf");
    });
  }

DocumentResource

    @RequestMapping(value = "/download", method = RequestMethod.POST)
public void download(HttpServletResponse response, @RequestBody DocumentoDTO documentoDTO) throws IOException {
    File file = new File(documentoDTO.getPathorigdoc());
    response.setContentType("pdf");
    response.setHeader("Content-disposition", "attachment;" + documentoDTO.getTituloDocumento());
    response.getOutputStream().write(Files.readAllBytes(file.toPath()));
}

Access to XMLHttpRequest at 'https://autenticacao.campogrande.ms.gov.br/auth/realms/dev/protocol/openid-connect/auth?response_type=code&client_id=web_app&scope=openid%20offline_access%20profile%20email%20address%20phone%20roles%20web-origins%20jhipster&state=DooRYbdfmKCip2apn-NOTWQOqWBGkeh-AigMtoJVfcM%3D&redirect_uri=http://localhost:9000/login/oauth2/code/oidc' (redirected from 'http://localhost:9000/api/download/') from origin 'http://localhost:9000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
autenticacao.campogrande.ms.gov.br/auth/realms/dev/protocol/openid-connect/auth?response_type=code&client_id=web_app&scope=openid%20offline_access%20profile%20email%20address%20phone%20roles%20web-origins%20jhipster&state=DooRYbdfmKCip2apn-NOTWQOqWBGkeh-AigMtoJVfcM%3D&redirect_uri=http://localhost:9000/login/oauth2/code/oidc:1 Failed to load resource: net::ERR_FAILED
webpack-internal:///./node_modules/@angular/core/fesm5/core.js:6249 ERROR HttpErrorResponse

Body:
Being able to solve, but you are not managing the download, I believe it is because or the answer is returning null, do I need to fix anything?

    @PostMapping(value = "/download")
public void download(HttpServletResponse response, @RequestBody DocumentoDTO documentoDTO) throws IOException {
    String caminho = "";

    caminho += "/arquivos/leisweb" + File.separator + documentoDTO.getPathorigdoc();

    File file = new File(caminho);
    response.setContentType("application/pdf");
    response.setHeader("Content-disposition", "attachment;" + documentoDTO.getTituloDocumento() + ".pdf");
    response.getOutputStream().write(Files.readAllBytes(file.toPath()));
}

  download(documento: IDocumento) {
    return this.http.post(SERVER_API_URL + "api/download", documento).subscribe((response) => {
      saveAs(response, documento.tituloDocumento + "." + "pdf");
    });
  }

Return:  Exit: .web.rest.DocumentoResource.download() with result = null


问:
Use solve_ivp() from Scipy with dynamic args
I am trying to use solve_ivp() function to solve for an ODE with state-dependent args. The idea is to update the ODE at each time instants given the current state of the trajectory.

Given the ODE model as the following:

```<code>def model(t, y, arg1, arg2):
    '''
    Some Dynamics model that includes arg1 and arg 2
    '''
    return dy_dt
</code>```

The arg1 and arg2 are calculated using some other function:

```<code>def gen_args(y):
    '''
    Calculate arg1 and arg2 based on the state y
    '''
    return arg1, arg2
</code>```

Then I want to integrate over the ODE model:

```<code>scipy.integrate.solve_ivp(model, t_span, y0, method='RK45', t_eval=None, dense_output=False, events=None, vectorized=False)
</code>```

What would be a nice way to implement this?

I have checked similar questions like here and here, But all the args are external constants.

答:
Adding on to @Warren Weckesser answer

It makes very less sense to include any state and (or) time-dependent arguments in the args parameter of 'solve_ivp'. They should be included in the
'fun' parameter of 'solve_ivp' itself.
Including any state and (or) time-dependent arguments analogous to this answer inspired by @Warren Weckesser is not possible. The args parameter in

solve_ivp( fun, t_span, y0, method='RK45', t_eval=None, dense_output=False, events=None, vectorized=False, args=None, **options, )

can only take in a tuple of constant arguments (for example floats, integers, etc)

Body:
I am trying to use solve_ivp() function to solve for an ODE with state-dependent args. The idea is to update the ODE at each time instants given the current state of the trajectory.

Given the ODE model as the following:

def model(t, y, arg1, arg2):
    '''
    Some Dynamics model that includes arg1 and arg 2
    '''
    return dy_dt

The arg1 and arg2 are calculated using some other function:

def gen_args(y):
    '''
    Calculate arg1 and arg2 based on the state y
    '''
    return arg1, arg2

Then I want to integrate over the ODE model:

scipy.integrate.solve_ivp(model, t_span, y0, method='RK45', t_eval=None, dense_output=False, events=None, vectorized=False)

What would be a nice way to implement this?

I have checked similar questions like here and here, But all the args are external constants.


答:
You can't use key property as it is reserved, also you will get a warning for it:

Warning: ListItem: key is not a prop. Trying to access it will result in undefined being returned. If you need to access the same value within the child component, you should pass it as a different prop.

Simple example:

```<code>const ListItem = ({ key }) => {
  console.log(key);
  return <div>{key}</div>;
};

const App = () => {
  return (
    <>
      {[0, 1, 2, 4].map(item => (
        <ListItem key={item} />
      ))}
    </>
  );
};
</code>```

Title: if else condition not evaluating in react component

Body:
You can't use key property as it is reserved, also you will get a warning for it:

Warning: ListItem: key is not a prop. Trying to access it will result in undefined being returned. If you need to access the same value within the child component, you should pass it as a different prop.

Simple example:

const ListItem = ({ key }) => {
  console.log(key);
  return <div>{key}</div>;
};

const App = () => {
  return (
    <>
      {[0, 1, 2, 4].map(item => (
        <ListItem key={item} />
      ))}
    </>
  );
};


问:
Google Drive API v3 find all files in folder and children
I have google api client for java script
I created all requests.
Last request in my app it is get all files in folder and children folders.
It is request get all files in parent folder.

```<code>   let files = await obj.staticProperty.gapi.client.drive.files.list({
                'q': `'${object['folder']['id']}' in parents`,
                'pageSize': 10
            })
</code>```

How can i get also all files in children folders ?

答:
I do it recursively, note that I have a callback that collects files - I'm using Redux with React so it just dispatches an action that adds the bunch of files to the state each time the method gets more files:

```<code>function getAllFiles(bearerToken, pageToken = undefined, q = undefined,
                     callback = (files) => console.log('No callback provided',
                         files),
                     onComplete = () => console.log('No onComplete provided'),
) {
  axios.get('https://www.googleapis.com/drive/v3/files', {
    params: {
      corpora: 'user',
      fields: 'files(id,name,size,mimeType,parents,webViewLink,trashed),nextPageToken',
      // q: 'mimeType = \'application/vnd.google-apps.folder\'',
      q: q,
      pageSize: 1000,
      pageToken: pageToken,
    },
    headers: {
      'Accept': 'application/json',
      'Authorization': 'Bearer ' + bearerToken,
    },
  }).then((result) => {
    callback(result.data.files);
    if (result.data.nextPageToken) {
      getAllFiles(bearerToken, result.data.nextPageToken, q, callback,
          onComplete);
    } else {
      onComplete();
    }
  }).catch((error) => {
    console.error('Error folders result', error);
  });
}
</code>```

This is from the code for my "Drive Dashboard" at https://drivedashboard.saisols.com/

Body:
I have google api client for java script
I created all requests.
Last request in my app it is get all files in folder and children folders.
It is request get all files in parent folder.

   let files = await obj.staticProperty.gapi.client.drive.files.list({
                'q': `'${object['folder']['id']}' in parents`,
                'pageSize': 10
            })

How can i get also all files in children folders ?

Body:
I do it recursively, note that I have a callback that collects files - I'm using Redux with React so it just dispatches an action that adds the bunch of files to the state each time the method gets more files:

function getAllFiles(bearerToken, pageToken = undefined, q = undefined,
                     callback = (files) => console.log('No callback provided',
                         files),
                     onComplete = () => console.log('No onComplete provided'),
) {
  axios.get('https://www.googleapis.com/drive/v3/files', {
    params: {
      corpora: 'user',
      fields: 'files(id,name,size,mimeType,parents,webViewLink,trashed),nextPageToken',
      // q: 'mimeType = \'application/vnd.google-apps.folder\'',
      q: q,
      pageSize: 1000,
      pageToken: pageToken,
    },
    headers: {
      'Accept': 'application/json',
      'Authorization': 'Bearer ' + bearerToken,
    },
  }).then((result) => {
    callback(result.data.files);
    if (result.data.nextPageToken) {
      getAllFiles(bearerToken, result.data.nextPageToken, q, callback,
          onComplete);
    } else {
      onComplete();
    }
  }).catch((error) => {
    console.error('Error folders result', error);
  });
}

This is from the code for my "Drive Dashboard" at https://drivedashboard.saisols.com/


问:
Pull data from server onmousewheel?
I have a POST request that pulls data from a server, according to parameters that are adjustable by the user through number inputs. Simply listening to the change event is not enough, because I want the data to refresh while using the mousewheel to change the input value.

Calling my refresh function with something like that is clearly not optimal:

```<code>$('input').on('mousewheel', function(){
    refresh_data();
});
</code>```

There would be a lot of requests, and because they are asynchronous, I can never know for sure if the last request to be completed will be the last one I send.

What I currently use is a setInterval to watch an object containing intervals (rounded timestamps) where a refresh has been requested. Inside the mousewheel listener, I add the next interval to the object, as a property/key, to avoid duplicates.

Something like that:

```<code>var i = 100;
var obj = [];

$('input').on('mousewheel', function(){
    // add next interval to obj;
    obj[Math.ceil(Date.now()/i)*i] = true;
});

var check = setInterval(function(){
    // refresh if current interval is in obj
    var t = Math.floor(Date.now()/i)*i;
    if(obj[t]){
        delete obj[t]; // remove from obj
        refresh_data();
    }
}, i);
</code>```

I tested this code, on my machine, with i=50, and the object is always empty, which is what we want, but with i=30, as soon as I go too fast with the wheel, I see some old intervals accumulating in the object. This is caused by the setInterval is skipping beats, so whatever value I choose for i, some user with less CPU could "skip the wrong beat", and end up finishing his mouse wheel movement seeing a result that does not match the parameters value.

I feel like maybe i'm making this more complicated than it has to be, so i'm asking:

What would be the best way to pull data from server onmousewheel, considering:

1: I want to constantly refresh the data as the user rolls the wheel over an input field.

2: I want to be 100% sure the presented data after the wheel movement is always accurate.

答:
Try using the document offsetheight like the below code. This will work when user scrolls down and reaches the end of scroll. The behavior is kind of like a recycler view of android.</p>

```<code>window.onscroll = function(ev) {
      if ((window.innerHeight + window.pageYOffset ) >=
      document.body.offsetHeight) {
           alert("you're at the bottom of the page");
     }
  };
</code>```

Title: Pull data from server onmousewheel?

Body:
I have a POST request that pulls data from a server, according to parameters that are adjustable by the user through number inputs. Simply listening to the change event is not enough, because I want the data to refresh while using the mousewheel to change the input value.

Calling my refresh function with something like that is clearly not optimal:

$('input').on('mousewheel', function(){
    refresh_data();
});

There would be a lot of requests, and because they are asynchronous, I can never know for sure if the last request to be completed will be the last one I send.

What I currently use is a setInterval to watch an object containing intervals (rounded timestamps) where a refresh has been requested. Inside the mousewheel listener, I add the next interval to the object, as a property/key, to avoid duplicates.

Something like that:

var i = 100;
var obj = [];

$('input').on('mousewheel', function(){
    // add next interval to obj;
    obj[Math.ceil(Date.now()/i)*i] = true;
});

var check = setInterval(function(){
    // refresh if current interval is in obj
    var t = Math.floor(Date.now()/i)*i;
    if(obj[t]){
        delete obj[t]; // remove from obj
        refresh_data();
    }
}, i);

I tested this code, on my machine, with i=50, and the object is always empty, which is what we want, but with i=30, as soon as I go too fast with the wheel, I see some old intervals accumulating in the object. This is caused by the setInterval is skipping beats, so whatever value I choose for i, some user with less CPU could "skip the wrong beat", and end up finishing his mouse wheel movement seeing a result that does not match the parameters value.

I feel like maybe i'm making this more complicated than it has to be, so i'm asking:

What would be the best way to pull data from server onmousewheel, considering:

1: I want to constantly refresh the data as the user rolls the wheel over an input field.

2: I want to be 100% sure the presented data after the wheel movement is always accurate.

Body:
Try using the document offsetheight like the below code. This will work when user scrolls down and reaches the end of scroll. The behavior is kind of like a recycler view of android.

window.onscroll = function(ev) {
      if ((window.innerHeight + window.pageYOffset ) >=
      document.body.offsetHeight) {
           alert("you're at the bottom of the page");
     }
  };


问:
Combine multiple conditions with Having clause
Given this user and User's items table:

With this select below I'm able to get the candidates that have both item 3 and 4:

```<code>Select
     U.Id,
     U.[Name],
     STRING_AGG(UI.ItemId, ',') as Items
from Users U
     Left Join UserItems UI on UI.UserId = U.Id
Where (
     UI.ItemId IN (3, 4)
)
Group By U.Id, U.[Name]
Having Count(*) = 2
</code>```

But how can I get all candidates using more conditions?
For example:

UI.ItemId IN (2, 7) OR UI.ItemId IN (3,4) OR UI.ItemId = 2

Any idea on how to solve this?

答:
If you want to get all users with their ItemIds try this:

```<code>Select
     U.Id,
     U.[Name],
     STRING_AGG(UI.ItemId, ',') as Items
from Users U
     left JOIN UserItems UI on UI.UserId = U.Id
Group By U.Id, U.[Name]
</code>```

You should remove 'where clause' if you want all users. Do not use 'Having clause' in this case

Body:
Given this user and User's items table:

With this select below I'm able to get the candidates that have both item 3 and 4:

Select
     U.Id,
     U.[Name],
     STRING_AGG(UI.ItemId, ',') as Items
from Users U
     Left Join UserItems UI on UI.UserId = U.Id
Where (
     UI.ItemId IN (3, 4)
)
Group By U.Id, U.[Name]
Having Count(*) = 2

But how can I get all candidates using more conditions?
For example:

UI.ItemId IN (2, 7) OR UI.ItemId IN (3,4) OR UI.ItemId = 2

Any idea on how to solve this?

Body:
If you want to get all users with their ItemIds try this:

Select
     U.Id,
     U.[Name],
     STRING_AGG(UI.ItemId, ',') as Items
from Users U
     left JOIN UserItems UI on UI.UserId = U.Id
Group By U.Id, U.[Name]

You should remove 'where clause' if you want all users. Do not use 'Having clause' in this case


问:
Why does the java compiler create a synthetic constructor in outer class?
I can't understand oracle java tutorial that writes:

```<code>public class SyntheticConstructor {
    private SyntheticConstructor() {}
    class Inner {
    // Compiler will generate a synthetic constructor since
    // SyntheticConstructor() is private.
    Inner() { new SyntheticConstructor(); }
    }
}
</code>```

Since the inner class's constructor references the private constructor of the enclosing class, the compiler must generate a package-private constructor of the enclosing class(that is SyntheticConstructor here).

So why does the java compiler have to create the synthetic constructor in the outer class SyntheticConstructor?

答:
This is caused by a discrepancy between the access rules of the Java language and the access rules of the JVM.

The JVM doesn't have the concept of inner classes, that is entirely a made-up construct invented by the Java compiler. The compiled code of that source file is 2 independent classes.

When the source code is:

```<code>public class SyntheticConstructor {
    private SyntheticConstructor() {}
    class Inner {
       Inner() { new SyntheticConstructor(); }
    }
}
</code>```

The compiler generates .class files equivalent to the following source code (from javap disassembled byte code):

```<code>public class SyntheticConstructor extends Object {
    private SyntheticConstructor() {
        super();
        return;
    }
}

class SyntheticConstructor$Inner extends Object {
    final SyntheticConstructor this$0;

    SyntheticConstructor$Inner(SyntheticConstructor outer) {
        this.this$0 = outer;
        super();
        new SyntheticConstructor();
        return;
    }
}
</code>```

In that code, the new SyntheticConstructor() expression is trying to invoke the private constructor of another class. Since that is not allowed by the JVM, the compiler must create a hidden synthetic non-private constructor that it can call instead.

This is true whenever code in an outer/inner/nested class accesses a private member of another outer/inner/nested class of the same top-level class.

Body:
I can't understand oracle java tutorial that writes:

public class SyntheticConstructor {
    private SyntheticConstructor() {}
    class Inner {
    // Compiler will generate a synthetic constructor since
    // SyntheticConstructor() is private.
    Inner() { new SyntheticConstructor(); }
    }
}

Since the inner class's constructor references the private constructor of the enclosing class, the compiler must generate a package-private constructor of the enclosing class(that is SyntheticConstructor here).

So why does the java compiler have to create the synthetic constructor in the outer class SyntheticConstructor?

Body:
This is caused by a discrepancy between the access rules of the Java language and the access rules of the JVM.

The JVM doesn't have the concept of inner classes, that is entirely a made-up construct invented by the Java compiler. The compiled code of that source file is 2 independent classes.

When the source code is:

public class SyntheticConstructor {
    private SyntheticConstructor() {}
    class Inner {
       Inner() { new SyntheticConstructor(); }
    }
}

The compiler generates .class files equivalent to the following source code (from javap disassembled byte code):

public class SyntheticConstructor extends Object {
    private SyntheticConstructor() {
        super();
        return;
    }
}

class SyntheticConstructor$Inner extends Object {
    final SyntheticConstructor this$0;

    SyntheticConstructor$Inner(SyntheticConstructor outer) {
        this.this$0 = outer;
        super();
        new SyntheticConstructor();
        return;
    }
}

In that code, the new SyntheticConstructor() expression is trying to invoke the private constructor of another class. Since that is not allowed by the JVM, the compiler must create a hidden synthetic non-private constructor that it can call instead.

This is true whenever code in an outer/inner/nested class accesses a private member of another outer/inner/nested class of the same top-level class.


问:
VideoJs display current time in minutes and seconds instead of microseconds
So I made a script to display the current time outside of the player, and everything works fine. The problem is that it renders in microseconds and I want to display it as H:MM:SS

Here's the code so you can understand what I'm talking about:

HTML

```<code><link href="http://vjs.zencdn.net/4.12/video-js.css" rel="stylesheet">
<script src="http://vjs.zencdn.net/4.12/video.js"></script>

<video id="MY_VIDEO_1" class="video-js vjs-default-skin" autoplay controls preload="auto" width="800" height="450" data-setup="{}">
  <source src="http://vjs.zencdn.net/v/oceans.mp4" type='video/mp4'>
    <source src="http://vjs.zencdn.net/v/oceans.webm" type='video/webm'>
      <p class="vjs-no-js">To view this video please enable JavaScript, and consider upgrading to a web browser that <a href="http://videojs.com/html5-video-support/" target="_blank">supports HTML5 video</a></p>
</video>
Current time: <div id="current_time"></div>
</code>```

JavaScript

```<code>setInterval(function() {
  var myPlayer = videojs('MY_VIDEO_1');
  var whereYouAt = myPlayer.currentTime();
  document.getElementById("current_time").innerHTML = whereYouAt;
}, 400);
</code>```

And a working example: http://codepen.io/BeBeINC/pen/VLBPLz

答:
i had the same problem as you and i created a simple equation to solve it here it is

```<code>  min = minutes ;
  sec = seconds;
  vid.currentTime =  min * 60 + (sec/60) * 60 ;
</code>```

for example

```<code>  min = 1 ;
  sec = 14 ;
  vid.currentTime =  min * 60 + (sec/60) * 60 ;
</code>```

the output is 74 and it is converted from min and seconds into seconds and it is  an integer so that the curretTime does accept it

Body:
So I made a script to display the current time outside of the player, and everything works fine. The problem is that it renders in microseconds and I want to display it as H:MM:SS

Here's the code so you can understand what I'm talking about:

HTML

<link href="http://vjs.zencdn.net/4.12/video-js.css" rel="stylesheet">

<video id="MY_VIDEO_1" class="video-js vjs-default-skin" autoplay controls preload="auto" width="800" height="450" data-setup="{}">
  <source src="http://vjs.zencdn.net/v/oceans.mp4" type='video/mp4'>
    <source src="http://vjs.zencdn.net/v/oceans.webm" type='video/webm'>

To view this video please enable JavaScript, and consider upgrading to a web browser that supports HTML5 video

</video>
Current time:

JavaScript

setInterval(function() {
  var myPlayer = videojs('MY_VIDEO_1');
  var whereYouAt = myPlayer.currentTime();
  document.getElementById("current_time").innerHTML = whereYouAt;
}, 400);

And a working example: http://codepen.io/BeBeINC/pen/VLBPLz

Body:
i had the same problem as you and i created a simple equation to solve it here it is

  min = minutes ;
  sec = seconds;
  vid.currentTime =  min * 60 + (sec/60) * 60 ;

for example

  min = 1 ;
  sec = 14 ;
  vid.currentTime =  min * 60 + (sec/60) * 60 ;

the output is 74 and it is converted from min and seconds into seconds and it is  an integer so that the curretTime does accept it


问:
Ansible inventory for environment variables within a role
I got an Ansible role that Im wanting to execute a psql script with. The name of the role is "db_scripts" and I will list the contents of respective directories/files below.

db_scripts/tasks/mail.yml

```<code>-
  name: "Run the SQLS"
  command: "psql -f \"{{ script }}\"/files/my_sql_script.sql"
  environment:
    PGDATABASE: "{{ db_name }}"
    PGUSER: "{{ db_user }}"
    PGHOST: "{{ db_host }}"
    PGPORT: "{{ db_port }}"
  delegate_to: localhost
</code>```

db_scripts/files/my_sql_script.yml

```<code>insert into employees(name, contact) values (Jack, 5555555);
</code>```

db_scripts/default/main.yml

```<code>script: "{{ role_path }}"
</code>```

/app/production/inventory

```<code>[dbservers]
db_host=192.168.1.100 db_name=mycompany db_user=abc db_port=3308
</code>```

/app/playbooks/run_sqls.yml

```<code>- name: Run sql
  hosts: dbservers
  roles:
    - db_scripts
</code>```

I run the playbook "run_sqls" as follows.

```<code>ansible-playbook run_sqls.yml -i inventories/app/production/inventory
</code>```

What I want to understand is that how I should specify the values for following environment vars so that they can be dynamic and can be used by the hosts of other environments i.e: development etc..

```<code>PGDATABASE: "{{ db_name }}"
PGUSER: "{{ db_user }}"
PGHOST: "{{ db_host }}"
PGPORT: "{{ db_port }}"
</code>```

Specifying them in respective inventory file doesn't seem to work,playbook errors out for "undefined vars" which make sense. Following is how I've attempted.
/app/production/inventory

```<code>[dbservers]
192.168.1.100 db_name=mycompany db_user=abc db_port=3308
</code>```

The error when the playbook is run

```<code>TASK [db_scripts : Run the SQLS] ******************************************************************************************************************************************************************
fatal: [localhost]: FAILED! => {"msg": "The field 'environment' has an invalid value, which includes an undefined variable. The error was: 'db_host' is undefined\n\nThe error appears to be in '/home/db_scripts/tasks/mail.yml': line 37, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n-\n  name: \"Run the SQLS\"\n  ^ here\n"}
</code>```

Please note when the values for the said env vars are specified under "db_scripts/default/main.yml"
,playbook Runs perfectly. Really appreciate some inputs. I've just started with ansible so please be as simple as you can be with examples. Thanks in advance :)

答:
```<code>[dbservers]
192.168.1.100 db_name=mycompany db_user=abc db_port=3308
</code>```

Q: "Specifying them (vars) in respective inventory file doesn't seem to work, playbook errors out for "undefined vars" which make sense."

A: The variables from this inventory should work as expected. Simply test it

```<code>- hosts: dbservers
  tasks:
    - debug:
        msg:
          - '{{ db_name }}'
          - '{{ db_user }}'
          - '{{ db_host }}'
          - '{{ db_port }}'
</code>```

There are 2 problems

1) db_host is missing in the inventory

2) The path in command inventories/app/production/inventory is different from the path described /app/production/inventory

```<code>ansible-playbook run_sqls.yml -i inventories/app/production/inventory
</code>```

Body:
I got an Ansible role that Im wanting to execute a psql script with. The name of the role is "db_scripts" and I will list the contents of respective directories/files below.

db_scripts/tasks/mail.yml

-
  name: "Run the SQLS"
  command: "psql -f \"{{ script }}\"/files/my_sql_script.sql"
  environment:
    PGDATABASE: "{{ db_name }}"
    PGUSER: "{{ db_user }}"
    PGHOST: "{{ db_host }}"
    PGPORT: "{{ db_port }}"
  delegate_to: localhost

db_scripts/files/my_sql_script.yml

insert into employees(name, contact) values (Jack, 5555555);

db_scripts/default/main.yml

script: "{{ role_path }}"

/app/production/inventory

[dbservers]
db_host=192.168.1.100 db_name=mycompany db_user=abc db_port=3308

/app/playbooks/run_sqls.yml

- name: Run sql
  hosts: dbservers
  roles:
    - db_scripts

I run the playbook "run_sqls" as follows.

ansible-playbook run_sqls.yml -i inventories/app/production/inventory

What I want to understand is that how I should specify the values for following environment vars so that they can be dynamic and can be used by the hosts of other environments i.e: development etc..

PGDATABASE: "{{ db_name }}"
PGUSER: "{{ db_user }}"
PGHOST: "{{ db_host }}"
PGPORT: "{{ db_port }}"

Specifying them in respective inventory file doesn't seem to work,playbook errors out for "undefined vars" which make sense. Following is how I've attempted.
/app/production/inventory

[dbservers]
192.168.1.100 db_name=mycompany db_user=abc db_port=3308

The error when the playbook is run

TASK [db_scripts : Run the SQLS] ******************************************************************************************************************************************************************
fatal: [localhost]: FAILED! => {"msg": "The field 'environment' has an invalid value, which includes an undefined variable. The error was: 'db_host' is undefined\n\nThe error appears to be in '/home/db_scripts/tasks/mail.yml': line 37, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n-\n  name: \"Run the SQLS\"\n  ^ here\n"}

Please note when the values for the said env vars are specified under "db_scripts/default/main.yml"
,playbook Runs perfectly. Really appreciate some inputs. I've just started with ansible so please be as simple as you can be with examples. Thanks in advance :)

Body:
[dbservers]
192.168.1.100 db_name=mycompany db_user=abc db_port=3308

Q: "Specifying them (vars) in respective inventory file doesn't seem to work, playbook errors out for "undefined vars" which make sense."

A: The variables from this inventory should work as expected. Simply test it

- hosts: dbservers
  tasks:
    - debug:
        msg:
          - '{{ db_name }}'
          - '{{ db_user }}'
          - '{{ db_host }}'
          - '{{ db_port }}'

There are 2 problems

1) db_host is missing in the inventory

2) The path in command inventories/app/production/inventory is different from the path described /app/production/inventory

ansible-playbook run_sqls.yml -i inventories/app/production/inventory


问:
How can I get better accuracy from my neural network.What is wrong with my code?
```<code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import preprocessing
data = pd.read_csv('Boston.csv')
X1 = data.iloc[:,1:5]
X2 = data.iloc[:,6:14]
X = pd.concat([X1,X2],axis=1)
y = pd.DataFrame(data.iloc[:,14])

'''
from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X = sc_X.fit_transform(X)
'''
#X = (X - X.mean(axis=0)) / X.std(axis=0)
X = preprocessing.normalize(X)

from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.1)

import keras
from keras.models import Sequential
from keras.layers import Dense

# Initialising the ANN
classifier = Sequential()

classifier.add(Dense(output_dim = 512, init = 'normal', activation = 'relu', input_dim = 12))
classifier.add(Dense(output_dim = 128, init = 'normal', activation = 'relu'))
classifier.add(Dense(output_dim = 1, init = 'normal', activation = 'relu'))

classifier.compile(optimizer = 'adam', loss = 'mse', metrics = ['accuracy'])

classifier.fit(X_train, y_train, batch_size = 10, nb_epoch = 100)
</code>```

I have tried data preprocessing and adding more layers/neurons but still i'm getting accuracy below 2%.what is wrong with my code.
I Have tried diffrent methods for preprocessing like standard scaler, normalization etc.
I have also tried many activation functions like relu, linear, sigmoid.
This is my first time developing a neural network so sorry the messy code...

EDIT: Dataset used is boston housing dataset. https://www.cs.toronto.edu/~delve/data/boston/bostonDetail.html

答:
You are in a regression setting, where accuracy is meaningless (it is meaningful only for classification settings). In such settings, the MSE itself is the performance metric (apart from being also the loss) - see own answer (and discussion) in What function defines accuracy in Keras when the loss is mean squared error (MSE)?.

For the same reason, you should not use activation = 'relu' for your final layer - in regression settings we use activation = 'linear' (or we leave it empty, since this is the default activation used in Keras when nothing is specified).

Body:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import preprocessing
data = pd.read_csv('Boston.csv')
X1 = data.iloc[:,1:5]
X2 = data.iloc[:,6:14]
X = pd.concat([X1,X2],axis=1)
y = pd.DataFrame(data.iloc[:,14])

'''
from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X = sc_X.fit_transform(X)
'''
#X = (X - X.mean(axis=0)) / X.std(axis=0)
X = preprocessing.normalize(X)

from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.1)

import keras
from keras.models import Sequential
from keras.layers import Dense

# Initialising the ANN
classifier = Sequential()

classifier.add(Dense(output_dim = 512, init = 'normal', activation = 'relu', input_dim = 12))
classifier.add(Dense(output_dim = 128, init = 'normal', activation = 'relu'))
classifier.add(Dense(output_dim = 1, init = 'normal', activation = 'relu'))

classifier.compile(optimizer = 'adam', loss = 'mse', metrics = ['accuracy'])

classifier.fit(X_train, y_train, batch_size = 10, nb_epoch = 100)

I have tried data preprocessing and adding more layers/neurons but still i'm getting accuracy below 2%.what is wrong with my code.
I Have tried diffrent methods for preprocessing like standard scaler, normalization etc.
I have also tried many activation functions like relu, linear, sigmoid.
This is my first time developing a neural network so sorry the messy code...

EDIT: Dataset used is boston housing dataset. https://www.cs.toronto.edu/~delve/data/boston/bostonDetail.html


问:
Compress in Java, decompress in Python - snappy/redis-py-cluster
I am writing cron script in python for a redis cluster and using redis-py-cluster for only reading data from a prod server. A separate Java application is writing to redis cluster with snappy compression and java string codec utf-8.

I am able to read data but not able to decode it.

```<code>from rediscluster import RedisCluster
import snappy

host, port ="127.0.0.1", "30001"
startup_nodes = [{"host": host, "port": port}]
print("Trying connecting to redis cluster host=" + host +  ", port=" + str(port))

rc = RedisCluster(startup_nodes=startup_nodes, max_connections=32, decode_responses=True)
print("Connected",  rc)

print("Reading all keys, value ...\n\n")
for key in rc.scan_iter("uidx:*"):
   value = rc.get(key)
   #uncompress = snappy.uncompress(value, decoding="utf-8")
   print(key, value)
   print('\n')

print("Done. exit()")
exit()
</code>```

decode_responses=False is working fine with the comment. however changing decode_responses=True is throwing error. My guess is its not able to get the correct decoder.

```<code>Traceback (most recent call last):
File "splooks_cron.py", line 22, in <module>
print(key, rc.get(key))
File "/Library/Python/2.7/site-packages/redis/client.py", line 1207, in get
return self.execute_command('GET', name)
File "/Library/Python/2.7/site-packages/rediscluster/utils.py", line 101, in inner
return func(*args, **kwargs)
File "/Library/Python/2.7/site-packages/rediscluster/client.py", line 410, in execute_command
return self.parse_response(r, command, **kwargs)
File "/Library/Python/2.7/site-packages/redis/client.py", line 768, in parse_response
response = connection.read_response()
File "/Library/Python/2.7/site-packages/redis/connection.py", line 636, in read_response
raise e
: 'utf8' codec can't decode byte 0x82 in position 0: invalid start byte
</code>```

PS: Uncommenting this line uncompress = snappy.uncompress(value, decoding="utf-8") is breaking with error

```<code>Traceback (most recent call last):
File "splooks_cron.py", line 27, in <module>
uncompress = snappy.uncompress(value, decoding="utf-8")
File "/Library/Python/2.7/site-packages/snappy/snappy.py", line 91, in uncompress
return _uncompress(data).decode(decoding)
snappy.UncompressError: Error while decompressing: invalid input
</code>```

答:
After hours of debugging, I was finally able to solve this.

I am using xerial/snappy-java compressor in my Java code which is writing to redis cluster. Interesting thing is that during compression xerial SnappyOutputStream adds some offset at the beginning of the compress data. In my case this looks something like this

```<code>"\x82SNAPPY\x00\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x01\xb6\x8b\x06\\******actual data here*****
</code>```

Due to this, the decompressor was not able to figure out. I modified code as below and remove offset form the value. it's working fine now.

```<code>for key in rc.scan_iter("uidx:*"):
   value = rc.get(key)
   #in my case offset was 20 and utf-8 is default ecoder/decoder for snappy
   # https://github.com/andrix/python-snappy/blob/master/snappy/snappy.py
   uncompress_value = snappy.decompress(value[20:])
   print(key, uncompress_value)
   print('\n')
</code>```

Body:
I am writing cron script in python for a redis cluster and using redis-py-cluster for only reading data from a prod server. A separate Java application is writing to redis cluster with snappy compression and java string codec utf-8.

I am able to read data but not able to decode it.

from rediscluster import RedisCluster
import snappy

host, port ="127.0.0.1", "30001"
startup_nodes = [{"host": host, "port": port}]
print("Trying connecting to redis cluster host=" + host +  ", port=" + str(port))

rc = RedisCluster(startup_nodes=startup_nodes, max_connections=32, decode_responses=True)
print("Connected",  rc)

print("Reading all keys, value ...\n\n")
for key in rc.scan_iter("uidx:*"):
   value = rc.get(key)
   #uncompress = snappy.uncompress(value, decoding="utf-8")
   print(key, value)
   print('\n')

print("Done. exit()")
exit()

decode_responses=False is working fine with the comment. however changing decode_responses=True is throwing error. My guess is its not able to get the correct decoder.

Traceback (most recent call last):
File "splooks_cron.py", line 22, in <module>
print(key, rc.get(key))
File "/Library/Python/2.7/site-packages/redis/client.py", line 1207, in get
return self.execute_command('GET', name)
File "/Library/Python/2.7/site-packages/rediscluster/utils.py", line 101, in inner
return func(*args, **kwargs)
File "/Library/Python/2.7/site-packages/rediscluster/client.py", line 410, in execute_command
return self.parse_response(r, command, **kwargs)
File "/Library/Python/2.7/site-packages/redis/client.py", line 768, in parse_response
response = connection.read_response()
File "/Library/Python/2.7/site-packages/redis/connection.py", line 636, in read_response
raise e
: 'utf8' codec can't decode byte 0x82 in position 0: invalid start byte

PS: Uncommenting this line uncompress = snappy.uncompress(value, decoding="utf-8") is breaking with error

Traceback (most recent call last):
File "splooks_cron.py", line 27, in <module>
uncompress = snappy.uncompress(value, decoding="utf-8")
File "/Library/Python/2.7/site-packages/snappy/snappy.py", line 91, in uncompress
return _uncompress(data).decode(decoding)
snappy.UncompressError: Error while decompressing: invalid input

Body:
After hours of debugging, I was finally able to solve this.

I am using xerial/snappy-java compressor in my Java code which is writing to redis cluster. Interesting thing is that during compression xerial SnappyOutputStream adds some offset at the beginning of the compress data. In my case this looks something like this

"\x82SNAPPY\x00\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x01\xb6\x8b\x06\\******actual data here*****

Due to this, the decompressor was not able to figure out. I modified code as below and remove offset form the value. it's working fine now.

for key in rc.scan_iter("uidx:*"):
   value = rc.get(key)
   #in my case offset was 20 and utf-8 is default ecoder/decoder for snappy
   # https://github.com/andrix/python-snappy/blob/master/snappy/snappy.py
   uncompress_value = snappy.decompress(value[20:])
   print(key, uncompress_value)
   print('\n')


问:
how can i use rspec correctly?
My code creates a github gist using the github API. After creating the gist, the API returns a status code to me. If the code is "201" the gist was created. But if it is "400" there was an error. In my code the variable that saves that state is response_status

This is my code:

```<code>require 'net/http'
require 'json'
require 'uri'

class Gist
   attr_reader :response_status
   attr_reader :try_again

   def initialize(filename,description,state,content)
       @filename = filename
       @description = description
       @state = state
       @content = content
   end

   def post(uri, request)
       request.basic_auth("my_username", "my_token")

       request.body = JSON.dump({
           "description" => @description,
           "public" => @state,
           "files" => {
               @filename => {
                   "content" => @content
               }
           }
       })

       req_options = { use_ssl: uri.scheme == "https" }

       begin
           response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
               http.request(request)
       end

       json = response.body
       parsed = JSON.parse(json)
       @response_status = "#{ response.code }"

       if @response_status == "201"
           puts "Tu gist se ha creado con exito. La URL de su gist es: "+ parsed["url"]
       end

       rescue SocketError => se
           puts "Ha ocurrido un error de conexión. Quiere intentar nuevamente?"
           @try_again = gets.chomp.capitalize
       end
   end
end

loop do
   filename= gets.chomp

   if File.exist?("#{filename}")
       description = gets.chomp
       state = gets.chomp.capitalize

       if state == "Si"
           state = true;
       elsif state == "No"
           state = false;
       end

       open(filename, "r") { |file| @contenido = file.read() }
       content = @contenido
       uri = URI.parse("https://api.github.com/gists")
       request = Net::HTTP::Post.new(uri)
       gist = Gist.new(filename,description,state,content)
       gist.post(uri, request)

       break if gist.response_status == "201"
       break if gist.try_again == "No"
   else
       puts "The file does not exist"
       continue = gets.chomp.capitalize
       break if continue == "No"
   end
end
</code>```

I want to test test cases using rspec, but I did not understand.

It occurred to me as a test case that a Gist be created. For example, I thought about checking if the variable that returns the state of the Gist is equal to "201", but that didn't work for me.

This is my rspec file:

```<code>require './git_clases.rb'

RSpec.describe Gist do
    describe "#Gist" do
        it "#Gist created" do
            expect(response_status)==("201")
        end
    end
end
</code>```

答:
response_status is a method on your Gist object. You need to create a Gist object, call post on it, and check response_status on your object.

```<code>RSpec.describe Gist do
  # Generally organize by method
  describe "#post" do
    # Example descriptions read grammatically correct
    # "Gist #post creates a gist"
    it "creates a gist" do
      filename = "test.txt"
      description = "testing gist"
      state = "dunno what goes here"
      content = "some test content"

      gist = described_class.new(filename, description, state, content)

      uri = URI.parse("https://api.github.com/gists")
      request = Net::HTTP::Post.new(uri)
      gist.post(uri, request)

      expect(gist.response_status).to eq 201
    end
  end
end
</code>```

described_class is Gist from RSpec.describe Gist. It's preferable to hard coding the class name into the example in case that example becomes shared or the class name changes.

expect(gist.response_status).to eq 201 is really expect(gist.response_status).to( eq(201) ). This compares gist.response_status using the matcher eq(201) which just checks that it equals 201. This might seem a bit much for a simple equality check, but it allows rspec to provide a wide variety of complex matchers as well as custom ones.

Your post method is a bit odd in that the user is expected to initialize and pass in the URL and Request object. That should probably be done by Gist.

There is no need to turn the response_status into a string. It's preferable to leave it as an Integer. If you do need it as a string, use response.code.to_s.

Title: how can i use rspec correctly?

Body:
My code creates a github gist using the github API. After creating the gist, the API returns a status code to me. If the code is "201" the gist was created. But if it is "400" there was an error. In my code the variable that saves that state is response_status

This is my code:

require 'net/http'
require 'json'
require 'uri'

class Gist
   attr_reader :response_status
   attr_reader :try_again

   def initialize(filename,description,state,content)
       @filename = filename
       @description = description
       @state = state
       @content = content
   end

   def post(uri, request)
       request.basic_auth("my_username", "my_token")

       request.body = JSON.dump({
           "description" => @description,
           "public" => @state,
           "files" => {
               @filename => {
                   "content" => @content
               }
           }
       })

       req_options = { use_ssl: uri.scheme == "https" }

       begin
           response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
               http.request(request)
       end

       json = response.body
       parsed = JSON.parse(json)
       @response_status = "#{ response.code }"

       if @response_status == "201"
           puts "Tu gist se ha creado con exito. La URL de su gist es: "+ parsed["url"]
       end

       rescue SocketError => se
           puts "Ha ocurrido un error de conexión. Quiere intentar nuevamente?"
           @try_again = gets.chomp.capitalize
       end
   end
end

loop do
   filename= gets.chomp

   if File.exist?("#{filename}")
       description = gets.chomp
       state = gets.chomp.capitalize

       if state == "Si"
           state = true;
       elsif state == "No"
           state = false;
       end

       open(filename, "r") { |file| @contenido = file.read() }
       content = @contenido
       uri = URI.parse("https://api.github.com/gists")
       request = Net::HTTP::Post.new(uri)
       gist = Gist.new(filename,description,state,content)
       gist.post(uri, request)

       break if gist.response_status == "201"
       break if gist.try_again == "No"
   else
       puts "The file does not exist"
       continue = gets.chomp.capitalize
       break if continue == "No"
   end
end

I want to test test cases using rspec, but I did not understand.

It occurred to me as a test case that a Gist be created. For example, I thought about checking if the variable that returns the state of the Gist is equal to "201", but that didn't work for me.

This is my rspec file:

require './git_clases.rb'

RSpec.describe Gist do
    describe "#Gist" do
        it "#Gist created" do
            expect(response_status)==("201")
        end
    end
end

Body:
response_status is a method on your Gist object. You need to create a Gist object, call post on it, and check response_status on your object.

RSpec.describe Gist do
  # Generally organize by method
  describe "#post" do
    # Example descriptions read grammatically correct
    # "Gist #post creates a gist"
    it "creates a gist" do
      filename = "test.txt"
      description = "testing gist"
      state = "dunno what goes here"
      content = "some test content"

      gist = described_class.new(filename, description, state, content)

      uri = URI.parse("https://api.github.com/gists")
      request = Net::HTTP::Post.new(uri)
      gist.post(uri, request)

      expect(gist.response_status).to eq 201
    end
  end
end

described_class is Gist from RSpec.describe Gist. It's preferable to hard coding the class name into the example in case that example becomes shared or the class name changes.

expect(gist.response_status).to eq 201 is really expect(gist.response_status).to( eq(201) ). This compares gist.response_status using the matcher eq(201) which just checks that it equals 201. This might seem a bit much for a simple equality check, but it allows rspec to provide a wide variety of complex matchers as well as custom ones.

Your post method is a bit odd in that the user is expected to initialize and pass in the URL and Request object. That should probably be done by Gist.

There is no need to turn the response_status into a string. It's preferable to leave it as an Integer. If you do need it as a string, use response.code.to_s.