问:
Error while building the first flutter project and running it on external device with error "Gradle task assembleDebug failed with exit code 1"
Below is the body of the error which I get when I try to build and run the flutter project on an external device.

```<code>Exception in thread "main" java.util.zip.ZipException: error in opening zip file
at java.util.zip.ZipFile.open(Native Method)
at java.util.zip.ZipFile.<init>(ZipFile.java:219)
at java.util.zip.ZipFile.<init>(ZipFile.java:149)
at java.util.zip.ZipFile.<init>(ZipFile.java:163)
at org.gradle.wrapper.Install.unzip(Install.java:214)
at org.gradle.wrapper.Install.access$600(Install.java:27)
at org.gradle.wrapper.Install$1.call(Install.java:74)
at org.gradle.wrapper.Install$1.call(Install.java:48)
at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:65)
at org.gradle.wrapper.Install.createDist(Install.java:48)
at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:128)
at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)

[!] Gradle threw an error while downloading artifacts from the network. Retrying to download...
Running Gradle task 'assembleDebug'...
Exception in thread "main" java.util.zip.ZipException: error in opening zip file
    at java.util.zip.ZipFile.open(Native Method)
    at java.util.zip.ZipFile.<init>(ZipFile.java:219)
    at java.util.zip.ZipFile.<init>(ZipFile.java:149)
    at java.util.zip.ZipFile.<init>(ZipFile.java:163)
    at org.gradle.wrapper.Install.unzip(Install.java:214)
    at org.gradle.wrapper.Install.access$600(Install.java:27)
    at org.gradle.wrapper.Install$1.call(Install.java:74)
    at org.gradle.wrapper.Install$1.call(Install.java:48)
    at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:65)
    at org.gradle.wrapper.Install.createDist(Install.java:48)
    at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:128)
    at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)
[!] Gradle threw an error while downloading artifacts from the network. Retrying to download...
Exception: Gradle task assembleDebug failed with exit code 1
</code>```

Any help is welcomed. Thanks in advance :)

答:
It seems that your Gradle is somehow corrupted, maybe.
Like "r0ly4ud" said here (https://github.com/flutter/flutter/issues/51195#issuecomment-591247333):

"Download the gradle in our flutter app, then extract it in C: \ Users \ yourpc \ .gradle \ wrapper \ dists \ gradle-5.6.2-all
  Then run your flutter app again. And make sure your internet connection is good. May be useful".

Body:
Below is the body of the error which I get when I try to build and run the flutter project on an external device.

Exception in thread "main" java.util.zip.ZipException: error in opening zip file
at java.util.zip.ZipFile.open(Native Method)
at java.util.zip.ZipFile.<init>(ZipFile.java:219)
at java.util.zip.ZipFile.<init>(ZipFile.java:149)
at java.util.zip.ZipFile.<init>(ZipFile.java:163)
at org.gradle.wrapper.Install.unzip(Install.java:214)
at org.gradle.wrapper.Install.access$600(Install.java:27)
at org.gradle.wrapper.Install$1.call(Install.java:74)
at org.gradle.wrapper.Install$1.call(Install.java:48)
at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:65)
at org.gradle.wrapper.Install.createDist(Install.java:48)
at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:128)
at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)

[!] Gradle threw an error while downloading artifacts from the network. Retrying to download...
Running Gradle task 'assembleDebug'...
Exception in thread "main" java.util.zip.ZipException: error in opening zip file
    at java.util.zip.ZipFile.open(Native Method)
    at java.util.zip.ZipFile.<init>(ZipFile.java:219)
    at java.util.zip.ZipFile.<init>(ZipFile.java:149)
    at java.util.zip.ZipFile.<init>(ZipFile.java:163)
    at org.gradle.wrapper.Install.unzip(Install.java:214)
    at org.gradle.wrapper.Install.access$600(Install.java:27)
    at org.gradle.wrapper.Install$1.call(Install.java:74)
    at org.gradle.wrapper.Install$1.call(Install.java:48)
    at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:65)
    at org.gradle.wrapper.Install.createDist(Install.java:48)
    at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:128)
    at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)
[!] Gradle threw an error while downloading artifacts from the network. Retrying to download...
Exception: Gradle task assembleDebug failed with exit code 1

Any help is welcomed. Thanks in advance :)


来源: stackexchange

问:
Fragment overlapping tab layout
When I start my app everything is fine except fragment overlapping my tab layout. Switching tab is fine, but it seems that fragment layout cover whole screen instead being under layout. Does anyone know solution ?
Screenshot: https://imgur.com/a/odeKD0W
Hope I didn't forgot to add something, if so, ask me.
Thanks.

ActivityMain

```<code>    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TabLayout tabLayout = findViewById(R.id.tabBar);
        TabItem tabItem1 = findViewById(R.id.tab1);
        TabItem tabItem2 = findViewById(R.id.tab2);
        TabItem tabItem3 = findViewById(R.id.tab3);
        final ViewPager viewPager = findViewById(R.id.viewPager);

        PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());

        viewPager.setAdapter(pagerAdapter);

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        viewPager.addOnPageChangeListener(new TabLayout
                .TabLayoutOnPageChangeListener(tabLayout));
    }
}
</code>```

PagerAdapter class

```<code>public class PagerAdapter extends FragmentPagerAdapter {

    private int numOfTabs;
    public PagerAdapter (FragmentManager fm, int numOfTabs) {
        super (fm);
        this.numOfTabs = numOfTabs;
    }
    @NonNull
    @Override
    public Fragment getItem(int position) {
        switch (position){
            case 0:
                return new FragmentTab1();
            case 1:
                return new FragmentTab2();
            case 2:
                return new FragmentTab3();
            default:
                return null;
        }

    }

    @Override
    public int getCount() {
        return numOfTabs;
    }
}
</code>```

Activity_Main xml

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tabBar"
        android:layout_width="409dp"
        android:layout_height="0dp"
        android:layout_marginStart="1dp"
        android:layout_marginEnd="1dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tab1"
            android:text="Tab 1" />

        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tab2"
            android:text="Tab 2" />

        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tab3"
            android:text="Tab 3" />
    </com.google.android.material.tabs.TabLayout>

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@id/tabBar" />
  </androidx.constraintlayout.widget.ConstraintLayout>
</code>```

答:
You are using

```<code>app:layout_constraintTop_toTopOf="@id/tabBar"
</code>```

Instead of

```<code>app:layout_constraintTop_toBottomOf="@id/tabBar"
</code>```

The first align the top of the fragment to that of the tablayout and they will overlap. The top of the fragment should instead be constrained to the bottom of the tabbar.

ContentLicense: CC BY-SA 4.0

Title: Fragment overlapping tab layout

Body:
When I start my app everything is fine except fragment overlapping my tab layout. Switching tab is fine, but it seems that fragment layout cover whole screen instead being under layout. Does anyone know solution ?
Screenshot: https://imgur.com/a/odeKD0W
Hope I didn't forgot to add something, if so, ask me.
Thanks.

ActivityMain

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TabLayout tabLayout = findViewById(R.id.tabBar);
        TabItem tabItem1 = findViewById(R.id.tab1);
        TabItem tabItem2 = findViewById(R.id.tab2);
        TabItem tabItem3 = findViewById(R.id.tab3);
        final ViewPager viewPager = findViewById(R.id.viewPager);

        PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());

        viewPager.setAdapter(pagerAdapter);

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        viewPager.addOnPageChangeListener(new TabLayout
                .TabLayoutOnPageChangeListener(tabLayout));
    }
}

PagerAdapter class

public class PagerAdapter extends FragmentPagerAdapter {

    private int numOfTabs;
    public PagerAdapter (FragmentManager fm, int numOfTabs) {
        super (fm);
        this.numOfTabs = numOfTabs;
    }
    @NonNull
    @Override
    public Fragment getItem(int position) {
        switch (position){
            case 0:
                return new FragmentTab1();
            case 1:
                return new FragmentTab2();
            case 2:
                return new FragmentTab3();
            default:
                return null;
        }

    }

    @Override
    public int getCount() {
        return numOfTabs;
    }
}

Activity_Main xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tabBar"
        android:layout_width="409dp"
        android:layout_height="0dp"
        android:layout_marginStart="1dp"
        android:layout_marginEnd="1dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tab1"
            android:text="Tab 1" />

        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tab2"
            android:text="Tab 2" />

        <com.google.android.material.tabs.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tab3"
            android:text="Tab 3" />
    </com.google.android.material.tabs.TabLayout>

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@id/tabBar" />
  </androidx.constraintlayout.widget.ConstraintLayout>

Body:
You are using

app:layout_constraintTop_toTopOf="@id/tabBar"

Instead of

app:layout_constraintTop_toBottomOf="@id/tabBar"

The first align the top of the fragment to that of the tablayout and they will overlap. The top of the fragment should instead be constrained to the bottom of the tabbar.


问:
Bootstrap modal - backdrop stays when I use the back button from the browser
When I display an error message to the user, I use the following script to open a modal message:

```<code>jQuery('#errorDialog').modal({
    keyboard: false,
    show: true,
    backdrop: 'static'
});
</code>```

It works very well and displays the message as I wanted to.

The problem is that when I use the back button from the browser, it takes me to the previous page in the history (all good) but the backdrop is still on the screen.

I tried to remove the backdrop: 'static' line which had the effect of dismissing the modal message when I clicked the anywhere on the backdrop. Nevertheless, it still stays when going back the the previous page.

Is there a way to remove it when I use the back button (or navigate through browser history otherwise)?

答:
If you are working with a SPA javascript framework like for example Vue, React or Angular, is normal that when there is a back button pressed, the bootstrap or jQuery UI backdrop stays visible.

The reason is because the backdrop div is inserted usually at the top of the DOM and when back is pressed, it just re-renders the Node more down in the DOM.

The solution is for example, detect every history change and execute:

```<code>$(".modal-backdrop").remove()
</code>```

In the case of Vue for example, it can be done in the vue-router like so:

```<code>router.beforeEach((to, from, next) => {
  $(".modal-backdrop").remove();
  next();
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
When I display an error message to the user, I use the following script to open a modal message:

jQuery('#errorDialog').modal({
    keyboard: false,
    show: true,
    backdrop: 'static'
});

It works very well and displays the message as I wanted to.

The problem is that when I use the back button from the browser, it takes me to the previous page in the history (all good) but the backdrop is still on the screen.

I tried to remove the backdrop: 'static' line which had the effect of dismissing the modal message when I clicked the anywhere on the backdrop. Nevertheless, it still stays when going back the the previous page.

Is there a way to remove it when I use the back button (or navigate through browser history otherwise)?

Body:
If you are working with a SPA javascript framework like for example Vue, React or Angular, is normal that when there is a back button pressed, the bootstrap or jQuery UI backdrop stays visible.

The reason is because the backdrop div is inserted usually at the top of the DOM and when back is pressed, it just re-renders the Node more down in the DOM.

The solution is for example, detect every history change and execute:

$(".modal-backdrop").remove()

In the case of Vue for example, it can be done in the vue-router like so:

router.beforeEach((to, from, next) => {
  $(".modal-backdrop").remove();
  next();
});


问:
How to check if a "leave" member exists without testing existence of its parents
Imagine this code:

```<code>var obj = {};
obj.x = {};
obj.x.y = {};

if (obj.x.y.z) {
  //the test work, I know obj.x.z.z do not exist
}

if (obj.a.b) {
  //fail because "cannot read property 'b' of undefined
}
</code>```

The question is : How I can check the existence of a "leave" (if "b" exist, it must inside "a") without making the test of each its parents before ?

答:
You can use elvis operator. </p>

```<code>if (obj.a?.b) { // no error thrown
  console.log('error'); // 'error' isn't be logged
}
</code>```

Body:
Imagine this code:

var obj = {};
obj.x = {};
obj.x.y = {};

if (obj.x.y.z) {
  //the test work, I know obj.x.z.z do not exist
}

if (obj.a.b) {
  //fail because "cannot read property 'b' of undefined
}

The question is : How I can check the existence of a "leave" (if "b" exist, it must inside "a") without making the test of each its parents before ?

Body:
You can use elvis operator.

if (obj.a?.b) { // no error thrown
  console.log('error'); // 'error' isn't be logged
}


问:
Put elements of a list into accessor in R
I have a vector with some data, and a list of vectors whose elements represent indices in that vector.

```<code>v <- c("A","B","C","D")
l <- list(c(3,2,1),c(4,1))
</code>```

I would like to convert the list according to the vector. So, what I want is

```<code>[[1]]
[1] "C" "B" "A"

[[2]]
[1] "D" "A"
</code>```

Of course, I can do this:

```<code>access <- function(x, vec) {
  return (vec[x])
}
lapply(l, access, vec = v)
</code>```

And this gives me the result I wanted. Nevertheless, I feel there must be some less awkward way of doing something so simple, perhaps using the "[" function. I tried this:

```<code>lapply(l, "[", v)
</code>```

It seems like this does the reverse of what I want, i.e. it uses the elements of v as the index to access elements of the list. So it tries to do something like

```<code>l[[i]]["A","B","C","D"]
</code>```

Which is obviously not what I want. So, is there a way to use "[" or some other function to access a vector using the elements of a list?

答:
We can create a function on the fly

```<code>lapply(l, function(x) v[x])
</code>```

With purrr, the anonymous call can be more compact

```<code>library(purrr)
map(l, ~ v[.x])
</code>```

Body:
I have a vector with some data, and a list of vectors whose elements represent indices in that vector.

v <- c("A","B","C","D")
l <- list(c(3,2,1),c(4,1))

I would like to convert the list according to the vector. So, what I want is

[[1]]
[1] "C" "B" "A"

[[2]]
[1] "D" "A"

Of course, I can do this:

access <- function(x, vec) {
  return (vec[x])
}
lapply(l, access, vec = v)

And this gives me the result I wanted. Nevertheless, I feel there must be some less awkward way of doing something so simple, perhaps using the "[" function. I tried this:

lapply(l, "[", v)

It seems like this does the reverse of what I want, i.e. it uses the elements of v as the index to access elements of the list. So it tries to do something like

l[[i]]["A","B","C","D"]

Which is obviously not what I want. So, is there a way to use "[" or some other function to access a vector using the elements of a list?

Body:
We can create a function on the fly

lapply(l, function(x) v[x])

With purrr, the anonymous call can be more compact

library(purrr)
map(l, ~ v[.x])


问:
how can i ignore error in python properly?
I'm trying to web scraping.

using BeautifulSoup, i'm parsing several objects and confronted with a problem.

The problem is, i can't predict where the error occur using "find" method.

it looks like

```<code>a = soup.find(something).find(something)
b = soup.find(something)
...
f = soup.find(something).find(something)
</code>```

among a,b,c,d,e,f, error can happen anywhere and their code should not be revised.

the variable 'b' is not matter because it would be None, which is ok.

but variable 'a' or 'f' is problem, because it would end the script.

i know there is "try - exception" grammar but that's not what i want.
of course it can be written like this:

```<code>try :
 a = soup.find(something).find(something)
except Exception:
 a = None
...
try :
 f = soup.find(something).find(something)
except Exception:
 f = None
</code>```

looks ridiculous, doesnt it?

how can i handle it gracefully?

答:
I hope this solves your issue here. Just add pass in except statement</p>

```<code>except:
    pass
</code>```

Body:
I'm trying to web scraping.

using BeautifulSoup, i'm parsing several objects and confronted with a problem.

The problem is, i can't predict where the error occur using "find" method.

it looks like

a = soup.find(something).find(something)
b = soup.find(something)
...
f = soup.find(something).find(something)

among a,b,c,d,e,f, error can happen anywhere and their code should not be revised.

the variable 'b' is not matter because it would be None, which is ok.

but variable 'a' or 'f' is problem, because it would end the script.

i know there is "try - exception" grammar but that's not what i want.
of course it can be written like this:

try :
 a = soup.find(something).find(something)
except Exception:
 a = None
...
try :
 f = soup.find(something).find(something)
except Exception:
 f = None

looks ridiculous, doesnt it?

how can i handle it gracefully?

Body:
I hope this solves your issue here. Just add pass in except statement

except:
    pass


问:
Reactjs - state updating - Ajax - Axios
Im trying to update my states after a form submit , without refreshing the page.
part of my ReactJs code :

```<code>export default class DashboardRA extends Component {

constructor(props)
{
    super(props);
    this.state = {
      json:JSON.parse(props.data),//data received from a laravel controller used to implement the page.
      pdf: '',
    ...
    ...

    async onSubmitButton(e) {
    e.preventDefault();
    const formData = new FormData();
    formData.append("pdf", this.state.pdf);
    ...
    const response = await axios.post("/uploadFile", formData, {
    headers: {
    "Content-Type": "multipart/form-data"
    }
    })
    .then(function (response) {
      // console.log(response.data); //data from the DB
      this.setState({
        json:JSON.parse(response.data)
      });
    })
    .catch(err => {
        console.log(err);
        this.setState({errorMessage: err.message});
    })
}
</code>```

but it shows the following error : Cannot read property 'setState' of undefined

答:
Just change your code to

```<code>.then((response) => {
  // console.log(response.data); //data from the DB
  this.setState({
    json:JSON.parse(response.data)
  });
})
</code>```

You're gwtting the error because when you refer to this in function you refer to whatever context this function is called in (some Promise internals). By using arrow syntax you're automatically binding it to the context it's declared in (component in your case)

Title: Reactjs - state updating - Ajax - Axios

Body:
Im trying to update my states after a form submit , without refreshing the page.
part of my ReactJs code :

export default class DashboardRA extends Component {

constructor(props)
{
    super(props);
    this.state = {
      json:JSON.parse(props.data),//data received from a laravel controller used to implement the page.
      pdf: '',
    ...
    ...

    async onSubmitButton(e) {
    e.preventDefault();
    const formData = new FormData();
    formData.append("pdf", this.state.pdf);
    ...
    const response = await axios.post("/uploadFile", formData, {
    headers: {
    "Content-Type": "multipart/form-data"
    }
    })
    .then(function (response) {
      // console.log(response.data); //data from the DB
      this.setState({
        json:JSON.parse(response.data)
      });
    })
    .catch(err => {
        console.log(err);
        this.setState({errorMessage: err.message});
    })
}

but it shows the following error : Cannot read property 'setState' of undefined

Body:
Just change your code to

.then((response) => {
  // console.log(response.data); //data from the DB
  this.setState({
    json:JSON.parse(response.data)
  });
})

You're gwtting the error because when you refer to this in function you refer to whatever context this function is called in (some Promise internals). By using arrow syntax you're automatically binding it to the context it's declared in (component in your case)


问:
Issues with android permissions in Cordova
I'm working on a demo app for android that needs to get information about the phone, the SIM, the network, etc..  I put all the code in a plugin and my Java function that that retrieves the SIM info looks like this:

```<code>
  private boolean getSIMInfo(CallbackContext cbc) throws JSONException {

    // tm is a TelephonyManager instantiated in initialize
    JSONObject res = new JSONObject()
      .put("carrierID", tm.getSimCarrierId())
      .put("carrierName", tm.getSimCarrierIdName())
      .put("countryIso", tm.getSimCountryIso())
      .put("operator", tm.getSimOperator())
      .put("operatorName", tm.getSimOperatorName())
      .put("state", tm.getSimState())
      .put("msisdn", tm.getLine1Number()) // <== Requires permission
      ;
    cbc.success(res);
    return true;
  }

</code>```

As long as I dont call getLine1Number() everything goes fine.

getLine1Number() requires either android.permission.READ_PHONE_STATE or a.p.READ_SMS or a.p.READ_PHONE_NUMBERS to be set. I first declared a.p.READ_PHONE_STATE in plugin's plugin.xml and I checked it was injected into AndroidManifest.xml.

The platform part of the plugin.xml looks like this:

```<code>  <platform name="android">

    <config-file target="res/xml/config.xml" parent="/*">
      <feature name="TelPlugin">
        <param name="android-package" value="org.buguigny.CordovaPlugin.TelPlugin"/>
      </feature>
    </config-file>

    <config-file parent="/*" target="AndroidManifest.xml" />
    <config-file target="AndroidManifest.xml" parent="/*">
      <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    </config-file>
    <source-file src="src/TelPlugin.java" target-dir="src/org/buguigny/CordovaPlugin/TelPlugin" />

  </platform>`

</code>```

Upon execution I get the error:

```<code>getLine1NumberForDisplay: Neither user 10190 nor current process has
   android.permission.READ_PHONE_STATE, android.permission.READ_SMS, or
   android.permission.READ_PHONE_NUMBERS
</code>```

I tried with the other permissions: same error.

Any idea what I'm doing wrong ?

答:
On Android >=6.0, Android app should request permission runtime.

So in Cordova, you can use the permission plugin like following

```<code>permissions.requestPermission(permissions.READ_PHONE_STATE, success, error);

function error() {
  console.warn('Camera permission is not turned on');
}

function success( status ) {
  if( !status.hasPermission ) error();
}
</code>```

Body:
I'm working on a demo app for android that needs to get information about the phone, the SIM, the network, etc..  I put all the code in a plugin and my Java function that that retrieves the SIM info looks like this:

  private boolean getSIMInfo(CallbackContext cbc) throws JSONException {

    // tm is a TelephonyManager instantiated in initialize
    JSONObject res = new JSONObject()
      .put("carrierID", tm.getSimCarrierId())
      .put("carrierName", tm.getSimCarrierIdName())
      .put("countryIso", tm.getSimCountryIso())
      .put("operator", tm.getSimOperator())
      .put("operatorName", tm.getSimOperatorName())
      .put("state", tm.getSimState())
      .put("msisdn", tm.getLine1Number()) // <== Requires permission
      ;
    cbc.success(res);
    return true;
  }

As long as I dont call getLine1Number() everything goes fine.

getLine1Number() requires either android.permission.READ_PHONE_STATE or a.p.READ_SMS or a.p.READ_PHONE_NUMBERS to be set. I first declared a.p.READ_PHONE_STATE in plugin's plugin.xml and I checked it was injected into AndroidManifest.xml.

The platform part of the plugin.xml looks like this:

  <platform name="android">

    <config-file target="res/xml/config.xml" parent="/*">
      <feature name="TelPlugin">
        <param name="android-package" value="org.buguigny.CordovaPlugin.TelPlugin"/>
      </feature>
    </config-file>

    <config-file parent="/*" target="AndroidManifest.xml" />
    <config-file target="AndroidManifest.xml" parent="/*">
      <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    </config-file>
    <source-file src="src/TelPlugin.java" target-dir="src/org/buguigny/CordovaPlugin/TelPlugin" />

  </platform>`

Upon execution I get the error:

getLine1NumberForDisplay: Neither user 10190 nor current process has
   android.permission.READ_PHONE_STATE, android.permission.READ_SMS, or
   android.permission.READ_PHONE_NUMBERS

I tried with the other permissions: same error.

Any idea what I'm doing wrong ?

Body:
On Android >=6.0, Android app should request permission runtime.

So in Cordova, you can use the permission plugin like following

permissions.requestPermission(permissions.READ_PHONE_STATE, success, error);

function error() {
  console.warn('Camera permission is not turned on');
}

function success( status ) {
  if( !status.hasPermission ) error();
}


问:
Error : Python module tensorflow.python.keras was not found
I want to convert some numeric values into category.
I am using 'keras' package for image classification.

When I am using to_categorical(trainy), getting "Error: Python module tensorflow.python.keras was not found."

I have taken trainy <- c(0,0,0,0,0,1,1,1,1,1) and convert it into categorical values.

```<code>library(keras)
library(tensorflow)
trainy <- c(0,0,0,0,0,1,1,1,1,1)
trainLabels <- to_categorical(trainy)
</code>```

The values in that vector should be converted into categorical values.

答:
```<code>conda create -n tf tensorflow
conda activate tf
</code>```

Or, to install the current release of GPU TensorFlow on Linux or Windows:

```<code>conda create -n tf-gpu tensorflow-gpu
conda activate tf-gpu
</code>```

Install GPU TensorFlow on Windows using Anaconda prompt with above command.Then re install the tensorflow package in RStudio, load the library (tensorflow). Now run the command

```<code>trainLabels <- to_categorical(trainy)
</code>```

This worked for me.

Body:
I want to convert some numeric values into category.
I am using 'keras' package for image classification.

When I am using to_categorical(trainy), getting "Error: Python module tensorflow.python.keras was not found."

I have taken trainy <- c(0,0,0,0,0,1,1,1,1,1) and convert it into categorical values.

library(keras)
library(tensorflow)
trainy <- c(0,0,0,0,0,1,1,1,1,1)
trainLabels <- to_categorical(trainy)

The values in that vector should be converted into categorical values.

Body:
conda create -n tf tensorflow
conda activate tf

Or, to install the current release of GPU TensorFlow on Linux or Windows:

conda create -n tf-gpu tensorflow-gpu
conda activate tf-gpu

Install GPU TensorFlow on Windows using Anaconda prompt with above command.Then re install the tensorflow package in RStudio, load the library (tensorflow). Now run the command

trainLabels <- to_categorical(trainy)

This worked for me.


答:
There is a proposal in the works for an operator that looks like ?. called optional chaining

You would then use it on your example like

obj.a?.b
```

<p>For now though, you'll have to write more to safely access nested properties</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var obj = {};
obj.x = {};
obj.x.y = {};

if (obj.x.y.z) {
  //the test work, I know obj.x.z.z do not exist
}

if (obj && obj.a && obj.a.b) {
  // will not throw
} else {
  console.log('didn\'t throw!')
}</code>```

Title: How to check if a "leave" member exists without testing existence of its parents

Body:
There is a proposal in the works for an operator that looks like ?. called optional chaining

You would then use it on your example like

obj.a?.b

For now though, you'll have to write more to safely access nested properties

var obj = {};
obj.x = {};
obj.x.y = {};

if (obj.x.y.z) {
  //the test work, I know obj.x.z.z do not exist
}

if (obj && obj.a && obj.a.b) {
  // will not throw
} else {
  console.log('didn\'t throw!')
}


答:
It will be because your trying to acces to a method which is no defined in your response function. You have to assign this to variable before running axios. please check this out</p>

```<code>export default class DashboardRA extends Component {

constructor(props)
{
    super(props);
    this.state = {
      json:JSON.parse(props.data),//data received from a laravel controller used to implement the page.
      pdf: '',
    ...
    ...

    async onSubmitButton(e) {
    e.preventDefault();
    const formData = new FormData();
    formData.append("pdf", this.state.pdf);
    ...

    const my_this = this;

    const response = await axios.post("/uploadFile", formData, {
    headers: {
    "Content-Type": "multipart/form-data"
    }
    })
    .then(function (response) {
      // console.log(response.data); //data from the DB
      my_this.setState({
        json:JSON.parse(response.data)
      });
    })
    .catch(err => {
        console.log(err);
        my_this.setState({errorMessage: err.message});
    })
}
</code>```

Title: Reactjs - state updating - Ajax - Axios

Body:
It will be because your trying to acces to a method which is no defined in your response function. You have to assign this to variable before running axios. please check this out

export default class DashboardRA extends Component {

constructor(props)
{
    super(props);
    this.state = {
      json:JSON.parse(props.data),//data received from a laravel controller used to implement the page.
      pdf: '',
    ...
    ...

    async onSubmitButton(e) {
    e.preventDefault();
    const formData = new FormData();
    formData.append("pdf", this.state.pdf);
    ...

    const my_this = this;

    const response = await axios.post("/uploadFile", formData, {
    headers: {
    "Content-Type": "multipart/form-data"
    }
    })
    .then(function (response) {
      // console.log(response.data); //data from the DB
      my_this.setState({
        json:JSON.parse(response.data)
      });
    })
    .catch(err => {
        console.log(err);
        my_this.setState({errorMessage: err.message});
    })
}


问:
How to return referece to base class in C++
I have a base struct which include 2 members of1 and of2.

The Derived class derived inherent it,

which has a function to return a reference to member of Base class.

I hope Derived can be used in the main as following:

```<code>struct Base {
 public:
  std::ofstream of1;
  std::ofstream of2;
};
class Derived : public Base {
 public:
  Base& write_file() {
    return Base;
  }
};

int main (){
  Derived d;
  d.write_file().of1 << "I'm of1" << std::endl;
  d.write_file().of2 << "I'm of2" << std::endl;
}
</code>```

Compiler throws error about return Base :

```<code>type name is not allowed
</code>```

How do I fix it?

答:
Base is a class and it is not an expression that can be returned.

You can get pointer to the current object with the keyword this. You can indirect through that pointer to get a reference to the current object. That reference implicitly converts to reference to base. So, correct solution is:

```<code>Base& write_file() {
    return *this;
}
</code>```

Body:
I have a base struct which include 2 members of1 and of2.

The Derived class derived inherent it,

which has a function to return a reference to member of Base class.

I hope Derived can be used in the main as following:

struct Base {
 public:
  std::ofstream of1;
  std::ofstream of2;
};
class Derived : public Base {
 public:
  Base& write_file() {
    return Base;
  }
};

int main (){
  Derived d;
  d.write_file().of1 << "I'm of1" << std::endl;
  d.write_file().of2 << "I'm of2" << std::endl;
}

Compiler throws error about return Base :

type name is not allowed

How do I fix it?

Body:
Base is a class and it is not an expression that can be returned.

You can get pointer to the current object with the keyword this. You can indirect through that pointer to get a reference to the current object. That reference implicitly converts to reference to base. So, correct solution is:

Base& write_file() {
    return *this;
}


问:
How do I fix a node server error, npm ERR! code ELIFECYCLE npm ERR! errno 1?

npm ERR! code ELIFECYCLE
  npm ERR! errno 1
  npm ERR! node-express@1.0.0 start: node server
  npm ERR! Exit status 1
  npm ERR!
  npm ERR! Failed at the node-express@1.0.0 start script.
  npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
  npm ERR!     /Users/teevee/.npm/_logs/2020-05-30T18_42_30_526Z-debug.log

I haven't had any issues until I had to add routes for partners and promotions in my project.  I don't know how to debug this type of error in order to make the needed changes. What can possibly be the issue? I'm still learning.  Here is a link: https://github.com/TanishaV842/node-express/tree/master/routes

答:
It looks like you're mixing up regular router.get() with router.route().get() method parameters.

Because you're using the router.route() method, your:

.get()
.post()
.delete()

call can't pass in a string and a callback. They only except a callback function.

To fix,

change all of the router.route(...).get('<path>', (req, res) => {})

to something like:

router.route(...).get((req, res) => {})

No path parameter.


问:
Write Host Variables to file in a loop with ansible
I am trying to build up a config file that contains the list of my inventory host servers and their fields eg. IP,FQDN etc.

Here is my part of inventory file :

```<code>ocp_cluster:
   hosts:
     anbootstrap.ocp.hattusas.tst:
         fqdn: anbootstrap.ocp.hattusas.tst
         ip: 10.72.217.92
     anmaster1.ocp.hattusas.tst:
         fqdn: anmaster1.ocp.hattusas.tst
         ip: 10.72.217.93
     anmaster2.ocp.hattusas.tst:
         fqdn: anmaster2.ocp.hattusas.tst
         ip: 10.72.217.94
     anmaster3.ocp.hattusas.tst:
</code>```

And here is my playbook:

```<code>  - name: Adding OCP Clusters to DHCP configuration
    debug:
      "{{ hostvars[item][fqdn] }}"
    loop: "{{ groups['ocp_cluster'] }}"
</code>```

(I will use blockinfile soon)

When I ran my playbook I am getting undefined error fqdn. I tried using a for loop and it didn't help. Any suggestions?
Thanks a lot.

答:
The fixed task is below

- debug:
    msg: "{{ hostvars[item]['fqdn'] }}"
  loop: "{{ groups['ocp_cluster'] }}"
```

<ul>
<li>Debug parameter <code>msg</code> was missing</li>
<li><code>fqdn</code> is an attribute of a dictionary. It must be quoted in brackets. Similar to <code>ocp_cluster</code>.</li>
<li>It's possible to use the dot notation and simplify the references to the attributes of the dictionaries</li>
</ul>

<pre class="lang-yaml prettyprint-override"><code>- debug:
    msg: "{{ hostvars[item].fqdn }}"
  loop: "{{ groups.ocp_cluster }}"
</code>```

Body:
I am trying to build up a config file that contains the list of my inventory host servers and their fields eg. IP,FQDN etc.

Here is my part of inventory file :

ocp_cluster:
   hosts:
     anbootstrap.ocp.hattusas.tst:
         fqdn: anbootstrap.ocp.hattusas.tst
         ip: 10.72.217.92
     anmaster1.ocp.hattusas.tst:
         fqdn: anmaster1.ocp.hattusas.tst
         ip: 10.72.217.93
     anmaster2.ocp.hattusas.tst:
         fqdn: anmaster2.ocp.hattusas.tst
         ip: 10.72.217.94
     anmaster3.ocp.hattusas.tst:

And here is my playbook:

  - name: Adding OCP Clusters to DHCP configuration
    debug:
      "{{ hostvars[item][fqdn] }}"
    loop: "{{ groups['ocp_cluster'] }}"

(I will use blockinfile soon)

When I ran my playbook I am getting undefined error fqdn. I tried using a for loop and it didn't help. Any suggestions?
Thanks a lot.

Body:
The fixed task is below

- debug:
    msg: "{{ hostvars[item]['fqdn'] }}"
  loop: "{{ groups['ocp_cluster'] }}"

Debug parameter msg was missing

fqdn is an attribute of a dictionary. It must be quoted in brackets. Similar to ocp_cluster.

It's possible to use the dot notation and simplify the references to the attributes of the dictionaries

- debug:
    msg: "{{ hostvars[item].fqdn }}"
  loop: "{{ groups.ocp_cluster }}"


问:
Copy files from docker volume
i have pem files to use in a lots of containers, however i would like to store this file into a unique volume call keys.

I create the volume:

```<code>docker run -v /data --name keys busybox
</code>```

And add the files there:

```<code>docker cp JWT_PRIVATE_KEY.pem keys:/data/
</code>```

Now, when a build the services whom need those files a want to copy them from keys:data to my /api workdir.

This is my docker-compose:

```<code>version: '3'

services:
  my_api:
    container_name: my_api
    build: .
    ports:
      - "5555:5555"
    volumes:
      - keys:/data
    networks:
      - my-network
    env_file:
      - .env

volumes:
  keys:

networks:
  my-network:
    external: true
</code>```

and this is my DockerFile:

```<code>FROM node:lts-alpine

WORKDIR /api

COPY package.json /api

RUN yarn install

COPY . /api

RUN yarn build

COPY ./docker-entrypoint.sh /

EXPOSE 5555

RUN ["chmod", "+x", "/docker-entrypoint.sh"]

ENTRYPOINT ["/docker-entrypoint.sh"]
</code>```

答:
If you have something like a TLS key and certificate that exist outside of Docker space, it will generally be easier to inject it into the container using a bind mount than a named volume.

volumes:
  # this references a local directory holding the keys
  - ./keys:/data
```

<p>In the setup you show above, you have a <em>container</em> named <code>keys</code>, with an anonymous volume mounted on <code>/data</code>, but this is separate from the volume with the Compose name of <code>keys</code> (and with a <code>docker volume ls</code> name that will be something like <code>api_keys</code>, starting with the name of the current directory).</p>

<p>If you really need to use a named volume here, probably the easiest way to copy data into it is to <code>docker-compose run</code> a temporary container:</p>

```docker-compose run \
  -v $PWD:/keys \
  my_api \
  cp /keys/* /data
```

This should inherit the volumes: from the docker-compose.yml file (so mounting the volume on /data), but also adds a bind-mount from the host system.  In that temporary container you copy the files from the host bind mount into the named volume mount, and then they'll persist.

A named-volume setup makes more sense if you're using something like Let's Encrypt where the certificates can be obtained and managed entirely within Docker space.

Title: Copy files from docker volume

Body:
i have pem files to use in a lots of containers, however i would like to store this file into a unique volume call keys.

I create the volume:

docker run -v /data --name keys busybox

And add the files there:

docker cp JWT_PRIVATE_KEY.pem keys:/data/

Now, when a build the services whom need those files a want to copy them from keys:data to my /api workdir.

This is my docker-compose:

version: '3'

services:
  my_api:
    container_name: my_api
    build: .
    ports:
      - "5555:5555"
    volumes:
      - keys:/data
    networks:
      - my-network
    env_file:
      - .env

volumes:
  keys:

networks:
  my-network:
    external: true

and this is my DockerFile:

FROM node:lts-alpine

WORKDIR /api

COPY package.json /api

RUN yarn install

COPY . /api

RUN yarn build

COPY ./docker-entrypoint.sh /

EXPOSE 5555

RUN ["chmod", "+x", "/docker-entrypoint.sh"]

ENTRYPOINT ["/docker-entrypoint.sh"]

Body:
If you have something like a TLS key and certificate that exist outside of Docker space, it will generally be easier to inject it into the container using a bind mount than a named volume.

volumes:
  # this references a local directory holding the keys
  - ./keys:/data

In the setup you show above, you have a container named keys, with an anonymous volume mounted on /data, but this is separate from the volume with the Compose name of keys (and with a docker volume ls name that will be something like api_keys, starting with the name of the current directory).

If you really need to use a named volume here, probably the easiest way to copy data into it is to docker-compose run a temporary container:

docker-compose run \
  -v $PWD:/keys \
  my_api \
  cp /keys/* /data

This should inherit the volumes: from the docker-compose.yml file (so mounting the volume on /data), but also adds a bind-mount from the host system.  In that temporary container you copy the files from the host bind mount into the named volume mount, and then they'll persist.

A named-volume setup makes more sense if you're using something like Let's Encrypt where the certificates can be obtained and managed entirely within Docker space.


问:
JavaScript: Object Rename Key
Is there a clever (i.e. optimized) way to rename a key in a javascript object?

A non-optimized way would be:

```<code>o[ new_key ] = o[ old_key ];
delete o[ old_key ];
</code>```

答:
just try it in your favorite editor <3</p>

```<code>const obj = {1: 'a', 2: 'b', 3: 'c'}

const OLD_KEY = 1
const NEW_KEY = 10

const { [OLD_KEY]: replaceByKey, ...rest } = obj
const new_obj = {
  ...rest,
  [NEW_KEY]: replaceByKey
}
</code>```

Title: JavaScript: Object Rename Key

Body:
Is there a clever (i.e. optimized) way to rename a key in a javascript object?

A non-optimized way would be:

o[ new_key ] = o[ old_key ];
delete o[ old_key ];

Body:
just try it in your favorite editor <3

const obj = {1: 'a', 2: 'b', 3: 'c'}

const OLD_KEY = 1
const NEW_KEY = 10

const { [OLD_KEY]: replaceByKey, ...rest } = obj
const new_obj = {
  ...rest,
  [NEW_KEY]: replaceByKey
}


问:
How to trigger useEffect to re-render again after update request
```<code>import React, { useState, useEffect } from "react";
import axios from "axios";
import styled from "styled-components";
import Form from "react-bootstrap/Form";
import Col from "react-bootstrap/Col";
import Button from "react-bootstrap/Button";
//import Spinner from "react-bootstrap/Spinner";
import FormLoader from "./FormLoader";

function MainSettings() {
const initialState = {
enableCovertMode: false,
safetyInstructions: "",
selectedVisitorReminder: "",
selectedVisitorReminderMeans: "",
selectedNotificationToHost: "",
selectedNotificationVisitor: "",
selectedCheckOutNotificationToHost: "",
selectedCheckOutNotificationToVisitor: "",
enableGuestModule: false,
enableGuestSmsConfirmation: false,
enableGuestAgreement: false,
enableGuestQrcode: false,
isLoading: true,
};
const [state, setState] = useState(initialState);
const [isLoading, setLoading] = useState(false);

const handleChange = (event) => {
const { name, value } = event.target;
setState({
  ...state,
  [name]: value,
});
};

useEffect(() => {
(async () => {
  const header = {
    headers: {
      "Content-Type": "application/json",
      Authorization:
        "Bearer NgTHTNmqFQpV7PyIzX8BBth3rmm0mArg5TqOIQeJUUH5Oa8DXb7UK4ulwyM88Cd7lBJ1n7DG73efcmc4",
    },
  };
  try {
    const res = await axios.get("/api/tenant/all-settings", header);
    const { code, data } = res.data;
    if (code === 200) {
      setState((state) => ({
        ...state,
        isLoading: false,
        enableCovertMode:
          data.mainSettings.enable_covet_mode === 1 ? true : false,
        safetyInstructions: data.mainSettings.safety_instructions,
        selectedVisitorReminder: `${data.mainSettings.enable_visitor_reminder}`,
        selectedVisitorReminderMeans: `${data.mainSettings.visitor_reminder}`,
        selectedNotificationToHost: `${data.mainSettings.visitor_checkin_notification_to_host}`,
        selectedNotificationVisitor: `${data.mainSettings.visitor_checkin_notification_to_visitor}`,
        selectedCheckOutNotificationToHost: `${data.mainSettings.visitor_checkout_notification_to_host}`,
        selectedCheckOutNotificationToVisitor: `${data.mainSettings.visitor_checkout_notification_to_visitor}`,
        enableGuestModule:
          data.guestSettings.enable_guest_module === 1 ? true : false,
        enableGuestSmsConfirmation:
          data.guestSettings.enable_sms_confirmation === 1 ? true : false,
        enableGuestAgreement:
          data.guestSettings.enable_agreement === 1 ? true : false,
        enableGuestQrcode:
          data.guestSettings.enable_scan_qrcode === 1 ? true : false,
      }));

      window.scroll({
        top: 0,
        left: 0,
        behavior: "smooth",
       });
      }
     } catch (err) {
    console.log(err.response.data);
   }
   })();
  const element = document.querySelector(".container");
  console.log(element);
  element.scrollIntoView({ behavior: "smooth" });
  }, []);

 const handleSubmit = async (event) => {
 event.preventDefault();
 try {
  setLoading(true);
  const formData = {
    mainSettings: {
      enable_multiple_qrcode_scan: 0,
      enable_covet_mode: state.enableCovertMode,
      safety_instructions: state.safetyInstructions,
      emergency_sms: state.setEmergencySms,
      visitor_reminder: state.selectedVisitorReminderMeans,
      enable_visitor_reminder: state.selectedVisitorReminder,
      enable_visitor__record_deletion: state.enableVisitorDeletion,
      visitor_deletion_period: state.visitorDeletionPeriod,
      visitor_checkin_notification_to_host:
        state.selectedNotificationToHost,
      visitor_checkin_notification_to_visitor:
        state.selectedNotificationVisitor,
      visitor_checkout_notification_to_host:
        state.selectedCheckOutNotificationToHost,
      visitor_checkout_notification_to_visitor:
        state.selectedCheckOutNotificationToVisitor,
    },
    guestSettings: {
      enable_guest_module: state.enableGuestModule,
      enable_sms_confirmation: state.enableGuestSmsConfirmation,
      enable_agreement: state.enableGuestAgreement,
      enable_scan_qrcode: state.enableGuestQrcode,
      enable_signature: state.enableGuestSignature,
      enable_phone_number_as_required: state.enableGuestPhoneAsRequired,
      enable_checkin_receipt_printing: state.enableGuestCheckInReceipt,
      enable_checkout_receipt_printing: state.enableGuestCheckOutReceipt,
      qrcode_prefix: state.guestQrcodePrefix,
    },
  };
  const header = {
    headers: {
      "Content-Type": "application/json",
      Authorization:
        "Bearer NgTHTNmqFQpV7PyIzX8BBth3rmm0mArg5TqOIQeJUUH5Oa8DXb7UK4ulwyM88Cd7lBJ1n7DG73efcmc4",
    },
  };
  const response = await axios.put(
    "/api/tenant/all-settings",
    formData,
    header
  );

  const res = response.data;
  setLoading(false);
  if (res.code === 200) {
    console.log("sbmitted", res.message);
  }
} catch (error) {
  console.log(error.response.data);
 }
};

return (
 <div id="formId">
  {state.isLoading ? (
    <FormLoader />
  ) : (
    <Form onSubmit={handleSubmit}>
      <h6 className="mt-4"> Watchlist Settings</h6>
      <hr />
      <br />
      <Form.Row>
        <Form.Group as={Col} md="4">
          <Form.Check
            type="switch"
            id="enableCovertMode"
            label="Enable Convert Mode"
            checked={state.enableCovertMode}
            onChange={() =>
              setState({
                ...state,
                enableCovertMode: !state.enableCovertMode,
              })
            }
          />
        </Form.Group>
      </Form.Row>
      <SubmitBtn>
        <Button type="submit" disabled={isLoading}>
          {/*              {" "}
          {isLoading ? (
           <Spinner animation="border" />
          ) : (
            "Submit Form"
          )} */}
          Submit Form
        </Button>
      </SubmitBtn>
    </Form>
  )}
</div>
);
}
</code>```

I have an initial state and after making an HTTP request I update the initial state with values from the request. When the user updates those values I make another HTTP request to update those values. I have an useEffect from where I fetch data to update the initial state values. In that useEffect if I add the state dependency it causes an infinite loop. Since my form fields are a lot I want after submitting the form the useEffect to run again which will trigger a re-render and automatically scroll to the top. Since the form is quite a lot I have cut short some of the fields from the question. What dependency do I use to cause the useEffect to run again and re-render for the automatic scroll to work.

答:
Since on update of API you don't want to make a get request, you need not run the first useEffect. What you can do is take out the scroll logic into another useEffect</p>

```<code>useEffect(() => {
(async () => {
  const header = {
    headers: {
      "Content-Type": "application/json",
      Authorization:
        "Bearer NgTHTNmqFQpV7PyIzX8BBth3rmm0mArg5TqOIQeJUUH5Oa8DXb7UK4ulwyM88Cd7lBJ1n7DG73efcmc4",
    },
  };
  try {
    const res = await axios.get("/api/tenant/all-settings", header);
    const { code, data } = res.data;
    if (code === 200) {
      setState((state) => ({
        ...state,
        isLoading: false,
        enableCovertMode:
          data.mainSettings.enable_covet_mode === 1 ? true : false,
        safetyInstructions: data.mainSettings.safety_instructions,
        selectedVisitorReminder: `${data.mainSettings.enable_visitor_reminder}`,
        selectedVisitorReminderMeans: `${data.mainSettings.visitor_reminder}`,
        selectedNotificationToHost: `${data.mainSettings.visitor_checkin_notification_to_host}`,
        selectedNotificationVisitor: `${data.mainSettings.visitor_checkin_notification_to_visitor}`,
        selectedCheckOutNotificationToHost: `${data.mainSettings.visitor_checkout_notification_to_host}`,
        selectedCheckOutNotificationToVisitor: `${data.mainSettings.visitor_checkout_notification_to_visitor}`,
        enableGuestModule:
          data.guestSettings.enable_guest_module === 1 ? true : false,
        enableGuestSmsConfirmation:
          data.guestSettings.enable_sms_confirmation === 1 ? true : false,
        enableGuestAgreement:
          data.guestSettings.enable_agreement === 1 ? true : false,
        enableGuestQrcode:
          data.guestSettings.enable_scan_qrcode === 1 ? true : false,
      }));

      window.scroll({
        top: 0,
        left: 0,
        behavior: "smooth",
       });
      }
     } catch (err) {
    console.log(err.response.data);
   }
   })();
  }, []);

useEffect(() => {
   if(isLoading === false && state.isLoading === false) {
       const element = document.querySelector(".container"); // use ref instead of document selector
       console.log(element);
       element.scrollIntoView({ behavior: "smooth" });
   }
},[state.isLoading, isLoading]); // allow scroll based on loading state
</code>```

Body:
import React, { useState, useEffect } from "react";
import axios from "axios";
import styled from "styled-components";
import Form from "react-bootstrap/Form";
import Col from "react-bootstrap/Col";
import Button from "react-bootstrap/Button";
//import Spinner from "react-bootstrap/Spinner";
import FormLoader from "./FormLoader";

function MainSettings() {
const initialState = {
enableCovertMode: false,
safetyInstructions: "",
selectedVisitorReminder: "",
selectedVisitorReminderMeans: "",
selectedNotificationToHost: "",
selectedNotificationVisitor: "",
selectedCheckOutNotificationToHost: "",
selectedCheckOutNotificationToVisitor: "",
enableGuestModule: false,
enableGuestSmsConfirmation: false,
enableGuestAgreement: false,
enableGuestQrcode: false,
isLoading: true,
};
const [state, setState] = useState(initialState);
const [isLoading, setLoading] = useState(false);

const handleChange = (event) => {
const { name, value } = event.target;
setState({
  ...state,
  [name]: value,
});
};

useEffect(() => {
(async () => {
  const header = {
    headers: {
      "Content-Type": "application/json",
      Authorization:
        "Bearer NgTHTNmqFQpV7PyIzX8BBth3rmm0mArg5TqOIQeJUUH5Oa8DXb7UK4ulwyM88Cd7lBJ1n7DG73efcmc4",
    },
  };
  try {
    const res = await axios.get("/api/tenant/all-settings", header);
    const { code, data } = res.data;
    if (code === 200) {
      setState((state) => ({
        ...state,
        isLoading: false,
        enableCovertMode:
          data.mainSettings.enable_covet_mode === 1 ? true : false,
        safetyInstructions: data.mainSettings.safety_instructions,
        selectedVisitorReminder: `${data.mainSettings.enable_visitor_reminder}`,
        selectedVisitorReminderMeans: `${data.mainSettings.visitor_reminder}`,
        selectedNotificationToHost: `${data.mainSettings.visitor_checkin_notification_to_host}`,
        selectedNotificationVisitor: `${data.mainSettings.visitor_checkin_notification_to_visitor}`,
        selectedCheckOutNotificationToHost: `${data.mainSettings.visitor_checkout_notification_to_host}`,
        selectedCheckOutNotificationToVisitor: `${data.mainSettings.visitor_checkout_notification_to_visitor}`,
        enableGuestModule:
          data.guestSettings.enable_guest_module === 1 ? true : false,
        enableGuestSmsConfirmation:
          data.guestSettings.enable_sms_confirmation === 1 ? true : false,
        enableGuestAgreement:
          data.guestSettings.enable_agreement === 1 ? true : false,
        enableGuestQrcode:
          data.guestSettings.enable_scan_qrcode === 1 ? true : false,
      }));

      window.scroll({
        top: 0,
        left: 0,
        behavior: "smooth",
       });
      }
     } catch (err) {
    console.log(err.response.data);
   }
   })();
  const element = document.querySelector(".container");
  console.log(element);
  element.scrollIntoView({ behavior: "smooth" });
  }, []);

 const handleSubmit = async (event) => {
 event.preventDefault();
 try {
  setLoading(true);
  const formData = {
    mainSettings: {
      enable_multiple_qrcode_scan: 0,
      enable_covet_mode: state.enableCovertMode,
      safety_instructions: state.safetyInstructions,
      emergency_sms: state.setEmergencySms,
      visitor_reminder: state.selectedVisitorReminderMeans,
      enable_visitor_reminder: state.selectedVisitorReminder,
      enable_visitor__record_deletion: state.enableVisitorDeletion,
      visitor_deletion_period: state.visitorDeletionPeriod,
      visitor_checkin_notification_to_host:
        state.selectedNotificationToHost,
      visitor_checkin_notification_to_visitor:
        state.selectedNotificationVisitor,
      visitor_checkout_notification_to_host:
        state.selectedCheckOutNotificationToHost,
      visitor_checkout_notification_to_visitor:
        state.selectedCheckOutNotificationToVisitor,
    },
    guestSettings: {
      enable_guest_module: state.enableGuestModule,
      enable_sms_confirmation: state.enableGuestSmsConfirmation,
      enable_agreement: state.enableGuestAgreement,
      enable_scan_qrcode: state.enableGuestQrcode,
      enable_signature: state.enableGuestSignature,
      enable_phone_number_as_required: state.enableGuestPhoneAsRequired,
      enable_checkin_receipt_printing: state.enableGuestCheckInReceipt,
      enable_checkout_receipt_printing: state.enableGuestCheckOutReceipt,
      qrcode_prefix: state.guestQrcodePrefix,
    },
  };
  const header = {
    headers: {
      "Content-Type": "application/json",
      Authorization:
        "Bearer NgTHTNmqFQpV7PyIzX8BBth3rmm0mArg5TqOIQeJUUH5Oa8DXb7UK4ulwyM88Cd7lBJ1n7DG73efcmc4",
    },
  };
  const response = await axios.put(
    "/api/tenant/all-settings",
    formData,
    header
  );

  const res = response.data;
  setLoading(false);
  if (res.code === 200) {
    console.log("sbmitted", res.message);
  }
} catch (error) {
  console.log(error.response.data);
 }
};

return (

  {state.isLoading ? (
    <FormLoader />
  ) : (
    <Form onSubmit={handleSubmit}>

 Watchlist Settings

      <Form.Row>
        <Form.Group as={Col} md="4">
          <Form.Check
            type="switch"
            id="enableCovertMode"
            label="Enable Convert Mode"
            checked={state.enableCovertMode}
            onChange={() =>
              setState({
                ...state,
                enableCovertMode: !state.enableCovertMode,
              })
            }
          />
        </Form.Group>
      </Form.Row>
      <SubmitBtn>
        <Button type="submit" disabled={isLoading}>
          {/*              {" "}
          {isLoading ? (
           <Spinner animation="border" />
          ) : (
            "Submit Form"
          )} */}
          Submit Form
        </Button>
      </SubmitBtn>
    </Form>
  )}

);
}

I have an initial state and after making an HTTP request I update the initial state with values from the request. When the user updates those values I make another HTTP request to update those values. I have an useEffect from where I fetch data to update the initial state values. In that useEffect if I add the state dependency it causes an infinite loop. Since my form fields are a lot I want after submitting the form the useEffect to run again which will trigger a re-render and automatically scroll to the top. Since the form is quite a lot I have cut short some of the fields from the question. What dependency do I use to cause the useEffect to run again and re-render for the automatic scroll to work.

Body:
Since on update of API you don't want to make a get request, you need not run the first useEffect. What you can do is take out the scroll logic into another useEffect

useEffect(() => {
(async () => {
  const header = {
    headers: {
      "Content-Type": "application/json",
      Authorization:
        "Bearer NgTHTNmqFQpV7PyIzX8BBth3rmm0mArg5TqOIQeJUUH5Oa8DXb7UK4ulwyM88Cd7lBJ1n7DG73efcmc4",
    },
  };
  try {
    const res = await axios.get("/api/tenant/all-settings", header);
    const { code, data } = res.data;
    if (code === 200) {
      setState((state) => ({
        ...state,
        isLoading: false,
        enableCovertMode:
          data.mainSettings.enable_covet_mode === 1 ? true : false,
        safetyInstructions: data.mainSettings.safety_instructions,
        selectedVisitorReminder: `${data.mainSettings.enable_visitor_reminder}`,
        selectedVisitorReminderMeans: `${data.mainSettings.visitor_reminder}`,
        selectedNotificationToHost: `${data.mainSettings.visitor_checkin_notification_to_host}`,
        selectedNotificationVisitor: `${data.mainSettings.visitor_checkin_notification_to_visitor}`,
        selectedCheckOutNotificationToHost: `${data.mainSettings.visitor_checkout_notification_to_host}`,
        selectedCheckOutNotificationToVisitor: `${data.mainSettings.visitor_checkout_notification_to_visitor}`,
        enableGuestModule:
          data.guestSettings.enable_guest_module === 1 ? true : false,
        enableGuestSmsConfirmation:
          data.guestSettings.enable_sms_confirmation === 1 ? true : false,
        enableGuestAgreement:
          data.guestSettings.enable_agreement === 1 ? true : false,
        enableGuestQrcode:
          data.guestSettings.enable_scan_qrcode === 1 ? true : false,
      }));

      window.scroll({
        top: 0,
        left: 0,
        behavior: "smooth",
       });
      }
     } catch (err) {
    console.log(err.response.data);
   }
   })();
  }, []);

useEffect(() => {
   if(isLoading === false && state.isLoading === false) {
       const element = document.querySelector(".container"); // use ref instead of document selector
       console.log(element);
       element.scrollIntoView({ behavior: "smooth" });
   }
},[state.isLoading, isLoading]); // allow scroll based on loading state


问:
Need help extracting just the IP address
I am writing a python script that reads all the .html files in a folder, searches them for IP addresses, and then returns the IP addresses.

Currently if my script finds an IP address, it returns a bunch of stuff:

```<code>print result
<re.Match object; span=(21, 30), match='10.6.0.25'>
</code>```

Any suggestions on how I can get just the IP address?

Sorry if my question and terms are vague or incorrect. I'm very new at this.

```<code>#!/usr/bin/env python
import glob
import re
import ipaddress

#Get html files in directory and put them in reports variable
reports_list = glob.glob("*.html")

#opens all reports, and reads through them one by one
for current_report in reports_list:
#opens the current report
    with open(current_report) as input:
        #reads current line from input
        for line in input:
            ip_search_result = re.search(r"[0-9]+(?:\.[0-9]+){3}", line)
            if ip_search_result is not None:
#removes the "none" entries
                ip_search_result = re.search(r'[0-9]+(?:\.[0-9]+){3}', line)
                print(ip_search_result)
</code>```

答:
You can use a DOM parser and extract the URL links and eventually the IP addresses.

An alternative is to use regular expressions matching IP addresses.

Body:
I am writing a python script that reads all the .html files in a folder, searches them for IP addresses, and then returns the IP addresses.

Currently if my script finds an IP address, it returns a bunch of stuff:

print result
<re.Match object; span=(21, 30), match='10.6.0.25'>

Any suggestions on how I can get just the IP address?

Sorry if my question and terms are vague or incorrect. I'm very new at this.

#!/usr/bin/env python
import glob
import re
import ipaddress

#Get html files in directory and put them in reports variable
reports_list = glob.glob("*.html")

#opens all reports, and reads through them one by one
for current_report in reports_list:
#opens the current report
    with open(current_report) as input:
        #reads current line from input
        for line in input:
            ip_search_result = re.search(r"[0-9]+(?:\.[0-9]+){3}", line)
            if ip_search_result is not None:
#removes the "none" entries
                ip_search_result = re.search(r'[0-9]+(?:\.[0-9]+){3}', line)
                print(ip_search_result)


问:
I want to make decimal transformation function
```<code>def replace_base(x):
    x = x.replace('10', 'A')
    x = x.replace('11', 'B')
    x = x.replace('12', 'C')
    x = x.replace('13', 'D')
    x = x.replace('14', 'E')
    x = x.replace('15', 'F')
    x = x.replace('16', 'G')
    return x

def deci_to_any_list():
    n1 = input("Enter a number: ")
    n = int(n1)
    radix1 = input("Enter a radix: ")
    radix = int(radix1)
    converted_number = []
    if n>0:
        if 2<=radix<=16:
            while int(n/radix) == 0:
                converted_number.append(n % radix)
                converted_number.reverse()
                x = ''.join(str(i) for i in converted_number)
                replace_base(x)
            else:
                converted_number.append(n % radix)
        else:
            print("Wrong input!!")
    else:
        print("Wrong input!!")

    print("%d in base 10 is %d in base %d" % (n1,x,radix1))

deci_to_any_list()
</code>```

Input & error,

```<code>Enter a number: 61
Enter a radix: 16
Traceback (most recent call last):
  File "C:/Users/LG/기컴프과제2/Number conversion.py", line 33, in <module>
    deci_to_any_list()
  File "C:/Users/LG/기컴프과제2/Number conversion.py", line 31, in deci_to_any_list
    print("%d in base 10 is %d in base %d" % (n1,x,radix1))
UnboundLocalError: local variable 'x' referenced before assignment

Process finished with exit code 1
</code>```

I want to create a decimal transformation function. I posted a question earlier, but you asked me to give you more details, so I'm leaving a question again. I don't know how to fix the error, and I don't know how to make this function. It can make to divide the quotient by the radix base number until the quotient is 0. And, write remainders in reverse order. I want to make this function using the append, reverse,join function,formatting operator(%). At this time, n shall be positive number and radix shall be 2 to 16. The last result is '61 in base 10 is 3D in base 16'.

答:
In your code, x only gets defined if 2 <= radix <= 16, yet regardless, at the bottom you call print("%d in base 10 is %d in base %d" % (n1,x,radix1)), which attempts to print out x even if it wasn't defined. To fix this, either move your print statement inside the condition if 2 <= radix <= 16, or define x in your else-statement as well.

Also be careful about your indentation, and note that replace_base(x) does not change the value of x unless you do x = replace_base(x).

Body:
def replace_base(x):
    x = x.replace('10', 'A')
    x = x.replace('11', 'B')
    x = x.replace('12', 'C')
    x = x.replace('13', 'D')
    x = x.replace('14', 'E')
    x = x.replace('15', 'F')
    x = x.replace('16', 'G')
    return x

def deci_to_any_list():
    n1 = input("Enter a number: ")
    n = int(n1)
    radix1 = input("Enter a radix: ")
    radix = int(radix1)
    converted_number = []
    if n>0:
        if 2<=radix<=16:
            while int(n/radix) == 0:
                converted_number.append(n % radix)
                converted_number.reverse()
                x = ''.join(str(i) for i in converted_number)
                replace_base(x)
            else:
                converted_number.append(n % radix)
        else:
            print("Wrong input!!")
    else:
        print("Wrong input!!")

    print("%d in base 10 is %d in base %d" % (n1,x,radix1))

deci_to_any_list()

Input & error,

Enter a number: 61
Enter a radix: 16
Traceback (most recent call last):
  File "C:/Users/LG/기컴프과제2/Number conversion.py", line 33, in <module>
    deci_to_any_list()
  File "C:/Users/LG/기컴프과제2/Number conversion.py", line 31, in deci_to_any_list
    print("%d in base 10 is %d in base %d" % (n1,x,radix1))
UnboundLocalError: local variable 'x' referenced before assignment

Process finished with exit code 1

I want to create a decimal transformation function. I posted a question earlier, but you asked me to give you more details, so I'm leaving a question again. I don't know how to fix the error, and I don't know how to make this function. It can make to divide the quotient by the radix base number until the quotient is 0. And, write remainders in reverse order. I want to make this function using the append, reverse,join function,formatting operator(%). At this time, n shall be positive number and radix shall be 2 to 16. The last result is '61 in base 10 is 3D in base 16'.


问:
How do I embed a dynamic Dropdown menu inside a table cell in React JS?
I have a dynamic table with 4 columns. I want to make the fourth column a dynamic dropdown list in which the user should be able to change the value.

For creating a dynamic table I've followed the below tutorial.

https://blog.logrocket.com/complete-guide-building-smart-data-table-react/

I am a newbie to React.

This is how I need the table. Sorry for blurring the content.

答:
Look This Example :

Table.Js

```<code>import React, { Component } from 'react'

      class Table extends Component {
           constructor(props) {
              super(props)
              this.state = {
                 students: [
                    { id: 1, name: 'Wasif', age: 21, email: 'wasif@email.com' },
                    { id: 2, name: 'Ali', age: 19, email: 'ali@email.com' },
                    { id: 3, name: 'Saad', age: 16, email: 'saad@email.com' },
                    { id: 4, name: 'Asad', age: 25, email: 'asad@email.com' }
                 ]
              }
           }

           viewRow(id,e) {
             alert('selectedId:'+ id);
             localStorage.setItem('transactionId',id);
            }

           renderTableData() {
              return this.state.students.map((student, index) => {
                 const { id, name, age, email } = student //destructuring
                 return (
                    <tr key={id}>
                       <td>{id}</td>
                       <td>{name}</td>
                       <td>{age}</td>
                       <td>{email}</td>
                       <td>
                          <select name="cars" id="cars">
          <option value="volvo">Volvo</option>
          <option value="saab">Saab</option>
          <option value="mercedes">Mercedes</option>
          <option value="audi">Audi</option>
        </select>
        </td>
                       <td><button onClick={(e) => this.viewRow(id, e)}>View Row Id</button></td>

                    </tr>
                 )
              })
           }
</code>```

Result :

Body:
Look This Example :

Table.Js

import React, { Component } from 'react'

      class Table extends Component {
           constructor(props) {
              super(props)
              this.state = {
                 students: [
                    { id: 1, name: 'Wasif', age: 21, email: 'wasif@email.com' },
                    { id: 2, name: 'Ali', age: 19, email: 'ali@email.com' },
                    { id: 3, name: 'Saad', age: 16, email: 'saad@email.com' },
                    { id: 4, name: 'Asad', age: 25, email: 'asad@email.com' }
                 ]
              }
           }

           viewRow(id,e) {
             alert('selectedId:'+ id);
             localStorage.setItem('transactionId',id);
            }

           renderTableData() {
              return this.state.students.map((student, index) => {
                 const { id, name, age, email } = student //destructuring
                 return (
                    <tr key={id}>
                       <td>{id}</td>
                       <td>{name}</td>
                       <td>{age}</td>
                       <td>{email}</td>
                       <td>
                          <select name="cars" id="cars">
          <option value="volvo">Volvo</option>
          <option value="saab">Saab</option>
          <option value="mercedes">Mercedes</option>
          <option value="audi">Audi</option>
        </select>
        </td>
                       <td><button onClick={(e) => this.viewRow(id, e)}>View Row Id</button></td>

                    </tr>
                 )
              })
           }

Result :


问:
how to use sql.trans in two methods?
i have cut and paste buttons while cutting i have one sql operation and while pasting one sql operation . how to use transation statement for this .</p>

```<code>protected void btnCut_Click(object sender, EventArgs e)
{
        hidCutnode.Value = TreeView2.SelectedNode.Value;
        string sqlQuery = "update CUSTOMIZEDTREE set parentid='" + 0 + "' where nodeid='" + hidCutnode.Value + "'";
        string connectionString = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=10.69.200.62)(PORT=1521)))(CONNECT_DATA=(SID=orcl)));User Id=apex_demo;Password=apex_demo;";
        OracleConnection con = new OracleConnection(connectionString);
        con.Open();
        tran = con.BeginTransaction();
        OracleCommand cmd = new OracleCommand(sqlQuery, con);
        cmd.Transaction = tran;
        cmd.ExecuteNonQuery();
        con.Close();
}

protected void btnPaste_Click(object sender, EventArgs e)
{
        hidPastenode.Value = TreeView2.SelectedNode.Value;
        try
        {
            string sqlQuery = "update CUSTOMIZEDTREE set parentid='" + hidPastenode.Value + "' where nodeid='" + hidCutnode.Value + "'";
            string connectionString = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=10.69.200.62)(PORT=1521)))(CONNECT_DATA=(SID=orcl)));User Id=apex_demo;Password=apex_demo;";
            OracleConnection con = new OracleConnection(connectionString);
            con.Open();
            OracleCommand cmd = new OracleCommand(sqlQuery, con);
            tran = con.BeginTransaction();
           // cmd.Connection = con;
            cmd.Transaction = tran;
            cmd.ExecuteNonQuery();
            tran.Commit();

            con.Close();
            PopulateCustomTree();
        }
        catch (Exception ex)
        {
            tran.Rollback();
            ex.ToString();
        }
}
</code>```

答: Pass transaction object as function parameter to the second method and dont commit in method1. Use BeginTransaction in first method only.

Title: how to use sql.trans in two methods?

Body:
i have cut and paste buttons while cutting i have one sql operation and while pasting one sql operation . how to use transation statement for this .

protected void btnCut_Click(object sender, EventArgs e)
{
        hidCutnode.Value = TreeView2.SelectedNode.Value;
        string sqlQuery = "update CUSTOMIZEDTREE set parentid='" + 0 + "' where nodeid='" + hidCutnode.Value + "'";
        string connectionString = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=10.69.200.62)(PORT=1521)))(CONNECT_DATA=(SID=orcl)));User Id=apex_demo;Password=apex_demo;";
        OracleConnection con = new OracleConnection(connectionString);
        con.Open();
        tran = con.BeginTransaction();
        OracleCommand cmd = new OracleCommand(sqlQuery, con);
        cmd.Transaction = tran;
        cmd.ExecuteNonQuery();
        con.Close();
}

protected void btnPaste_Click(object sender, EventArgs e)
{
        hidPastenode.Value = TreeView2.SelectedNode.Value;
        try
        {
            string sqlQuery = "update CUSTOMIZEDTREE set parentid='" + hidPastenode.Value + "' where nodeid='" + hidCutnode.Value + "'";
            string connectionString = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=10.69.200.62)(PORT=1521)))(CONNECT_DATA=(SID=orcl)));User Id=apex_demo;Password=apex_demo;";
            OracleConnection con = new OracleConnection(connectionString);
            con.Open();
            OracleCommand cmd = new OracleCommand(sqlQuery, con);
            tran = con.BeginTransaction();
           // cmd.Connection = con;
            cmd.Transaction = tran;
            cmd.ExecuteNonQuery();
            tran.Commit();

            con.Close();
            PopulateCustomTree();
        }
        catch (Exception ex)
        {
            tran.Rollback();
            ex.ToString();
        }
}


问:
Linkedin direct share without oauth2
How to share text and url in Linkedin from an iOS app. Is it possible without oAuth2 authentication  and if not can anyone help me with oAuth2 integration and sharing simply.</p>

答:
It's actually very simple.  Just fill in your URL using the format below...

```<code>https://www.linkedin.com/sharing/share-offsite/?url={url}
</code>```

Source: Official LinkedIn Share URL Documentation.

But then, you probably also want to share other information, right?  Like title, description, and all that other good stuff.  Do that using og: meta tags in your HTML header, like so...

<meta property='og:title' content='Title of the article"/>

<meta property='og:image' content='//media.example.com/ 1234567.jpg"/>

<meta property='og:description' content='Description that will show in the preview"/>

<meta property='og:url' content='//www.example.com/URL of the article" />

Source: Official Microsoft "Making Your Website Shareable on LinkedIn" Documentation.

Want to make sure you did it correctly?  That's the easiest part.  Copy the URL of the website you want to share, like example.com, and input it here...

Official LinkedIn Post Inspector

Title: Linkedin direct share without oauth2

Body:
It's actually very simple.  Just fill in your URL using the format below...

https://www.linkedin.com/sharing/share-offsite/?url={url}

Source: Official LinkedIn Share URL Documentation.

But then, you probably also want to share other information, right?  Like title, description, and all that other good stuff.  Do that using og: meta tags in your HTML header, like so...

<meta property='og:title' content='Title of the article"/>

<meta property='og:image' content='//media.example.com/ 1234567.jpg"/>

<meta property='og:description' content='Description that will show in the preview"/>

<meta property='og:url' content='//www.example.com/URL of the article" />

Source: Official Microsoft "Making Your Website Shareable on LinkedIn" Documentation.

Want to make sure you did it correctly?  That's the easiest part.  Copy the URL of the website you want to share, like example.com, and input it here...

Official LinkedIn Post Inspector


问:
How to filter out all the sesions I found using get function
This is the list of session I am getting, Now I want delete all the sessions except where active is true

```<code>const token = 'xxxx-xxx-xxxxx-xxxx-xxxxx';

const session_list = [
{
  "id": "45345345-4534-5435-d1cc1bdb6153410",
  "device": "browser",
  "ip": "xx.xx.xxx.xxx",
  "city": null,
  "country": null,
  "browser_name": "Opera",
  "browser_version": "67.0.3575.115",
  "os_name": "Mac OS"
},
{
  "id": "23213-34234-324234-4234324o",
  "device": "browser",
  "ip": "xx.xx.xxx.xxx",
  "city": null,
  "country": null,
  "browser_name": "Mozila",
  "browser_version": "67.0.3575.115",
  "os_name": "Windows"
},
{
  "id": "324234-sadasd34-sdsda343-3434234234",
  "device": "browser",
  "ip": "xx.xx.xxx.xxx",
  "city": null,
  "country": null,
  "browser_name": "Opera",
  "browser_version": "67.0.3575.115",
  "os_name": "android",
  "active": true
}
]
</code>```

Now I want to call an API to delete the session, Now it takes 3 things in it, token which is static, and ip, session_id which i find in array of the session_list
Now the API delete session one by one by passing the required arguments.

```<code>  const delete_session_api = async (data) => {
    // delete the session
    try {

        const config = {
            data: querystring.stringify(data),
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        };

        const { data: api_res } =
            await axios.delete('/sessions/delete', config);

        return api_res;

    } catch (error) {

        throw error;

    }

    };
</code>```

All I want to delete the sessions from the session_list except the active true one which is the same list.
Can any one help me with the efficient way to do this?

答:
You can use Array.filter() method directly as below.

Say, if you're getting this as part of an API response and you're trying to handle it in the success callback and want to return the active sessions:

const activeSessions = response.data.filter(session => session.active);

or

return response.data.filter(session => session.active);

Note: The result may contain more than one object if the condition is true for multiple sessions.

Refer Mozilla Developer Network Webdocs to understand Array.filter() better. Link here

UPDATE

With the new requirement, you want to first get the sessions which are inactive and make API calls for each (one after the other) to delete them.

Get the list of inactive sessions. i.e., sessions where the active is not true

```<code>const inactiveSessionsList = sessions_list.filter(session => !session.active)
</code>```

With this list, you can make api calls as below.

```<code>inactiveSessionsList.forEach(async (session)=> {
 const payload = {token: token, ip: session.ip, session_id: session.id }
 await delete_session_api(payload);
})
</code>```

Based on the number of items in the inactiveSessionsList, you will be triggering API calls for each inactive session.

Body:
This is the list of session I am getting, Now I want delete all the sessions except where active is true

const token = 'xxxx-xxx-xxxxx-xxxx-xxxxx';

const session_list = [
{
  "id": "45345345-4534-5435-d1cc1bdb6153410",
  "device": "browser",
  "ip": "xx.xx.xxx.xxx",
  "city": null,
  "country": null,
  "browser_name": "Opera",
  "browser_version": "67.0.3575.115",
  "os_name": "Mac OS"
},
{
  "id": "23213-34234-324234-4234324o",
  "device": "browser",
  "ip": "xx.xx.xxx.xxx",
  "city": null,
  "country": null,
  "browser_name": "Mozila",
  "browser_version": "67.0.3575.115",
  "os_name": "Windows"
},
{
  "id": "324234-sadasd34-sdsda343-3434234234",
  "device": "browser",
  "ip": "xx.xx.xxx.xxx",
  "city": null,
  "country": null,
  "browser_name": "Opera",
  "browser_version": "67.0.3575.115",
  "os_name": "android",
  "active": true
}
]

Now I want to call an API to delete the session, Now it takes 3 things in it, token which is static, and ip, session_id which i find in array of the session_list
Now the API delete session one by one by passing the required arguments.

  const delete_session_api = async (data) => {
    // delete the session
    try {

        const config = {
            data: querystring.stringify(data),
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        };

        const { data: api_res } =
            await axios.delete('/sessions/delete', config);

        return api_res;

    } catch (error) {

        throw error;

    }

    };

All I want to delete the sessions from the session_list except the active true one which is the same list.
Can any one help me with the efficient way to do this?

Body:
You can use Array.filter() method directly as below.

Say, if you're getting this as part of an API response and you're trying to handle it in the success callback and want to return the active sessions:

const activeSessions = response.data.filter(session => session.active);

or

return response.data.filter(session => session.active);

Note: The result may contain more than one object if the condition is true for multiple sessions.

Refer Mozilla Developer Network Webdocs to understand Array.filter() better. Link here

UPDATE

With the new requirement, you want to first get the sessions which are inactive and make API calls for each (one after the other) to delete them.

Get the list of inactive sessions. i.e., sessions where the active is not true

const inactiveSessionsList = sessions_list.filter(session => !session.active)

With this list, you can make api calls as below.

inactiveSessionsList.forEach(async (session)=> {
 const payload = {token: token, ip: session.ip, session_id: session.id }
 await delete_session_api(payload);
})

Based on the number of items in the inactiveSessionsList, you will be triggering API calls for each inactive session.


问:
Combine mocha, Typescript (and watch)
I've created a project where I want to use mocha to test my Typescript code.  If I do this:

```<code>mocha ts/test --compilers ts:typescript-require
</code>```

After I make a change, it will fail with a message like:

```<code>error TS2307: Cannot find module 'mocha'.
</code>```

This is strange because if I just run tsc everything is fine (I have all my type definitions and I'm using a tsconfig.json file).  I also installed typescript-require for mocha.

But each time I run the command after that, it works?!?  But if I put mocha in watch mode:

```<code>mocha -w ts/test --compilers ts:typescript-require
</code>```

Then it works the first time through but fails after that.  Ugh!  Any suggestions on how to get a robust setup involving mocha and Typescript so that I can test and watch?

答:
In Mocha 7, --watch flag will only work if you have defined either --watch-files or --extension. So you can choose any of the following config :

```<code>"scripts": {
    "watch": "mocha -r ts-node/register test/*Test.ts  --watch --extensions ts"
}
</code>```

or

```<code>"scripts": {
    "watch": "mocha -r ts-node/register test/*Test.ts  --watch --watch-files test"
}
</code>```

From the Mocha official documentation :

--watch, -w Rerun tests on file changes.

The --watch-files and --watch-ignore options can be used to control
  which files are watched for changes.

Tests may be rerun manually by typing ⓡ ⓢ ⏎ (same shortcut as
  nodemon).

--watch-files  New in v7.0.0

List of paths or globs to watch when --watch is set. If a file
  matching the given glob changes or is added or removed mocha will
  rerun all tests.

If the path is a directory all files and subdirectories will be
  watched.

By default all files in the current directory having one of the
  extensions provided by --extension and not contained in the
  node_modules or .git folders are watched.

The option can be given multiple times. The option accepts a
  comma-delimited list: --watch-files a,b is equivalent to --watch-files
  a --watch-files b

Title: Combine mocha, Typescript (and watch)

Body:
I've created a project where I want to use mocha to test my Typescript code.  If I do this:

mocha ts/test --compilers ts:typescript-require

After I make a change, it will fail with a message like:

error TS2307: Cannot find module 'mocha'.

This is strange because if I just run tsc everything is fine (I have all my type definitions and I'm using a tsconfig.json file).  I also installed typescript-require for mocha.

But each time I run the command after that, it works?!?  But if I put mocha in watch mode:

mocha -w ts/test --compilers ts:typescript-require

Then it works the first time through but fails after that.  Ugh!  Any suggestions on how to get a robust setup involving mocha and Typescript so that I can test and watch?

Body:
In Mocha 7, --watch flag will only work if you have defined either --watch-files or --extension. So you can choose any of the following config :

"scripts": {
    "watch": "mocha -r ts-node/register test/*Test.ts  --watch --extensions ts"
}

or

"scripts": {
    "watch": "mocha -r ts-node/register test/*Test.ts  --watch --watch-files test"
}

From the Mocha official documentation :

--watch, -w Rerun tests on file changes.

The --watch-files and --watch-ignore options can be used to control
  which files are watched for changes.

Tests may be rerun manually by typing ⓡ ⓢ ⏎ (same shortcut as
  nodemon).

--watch-files  New in v7.0.0

List of paths or globs to watch when --watch is set. If a file
  matching the given glob changes or is added or removed mocha will
  rerun all tests.

If the path is a directory all files and subdirectories will be
  watched.

By default all files in the current directory having one of the
  extensions provided by --extension and not contained in the
  node_modules or .git folders are watched.

The option can be given multiple times. The option accepts a
  comma-delimited list: --watch-files a,b is equivalent to --watch-files
  a --watch-files b


问:
SetInterval messages not changing
I'm making a loading screen for a game I'm creating with html and JS.  I want various messages to display, about every three seconds.  The SetInterval function doesn't seem to be rotating the messages, even though it works with something else (like an alert every three seconds).  here's the code I've written for the changing messages.</p>

```<code><!doctype html>
<html>
<head><title>Loading screen</title></head>
<script>
let messageNum = 1;

setInterval(function(){
  messageNum++
 }, 1000);

if (messageNum >3) {
  messageNum = 1;
}

if (messageNum === 1) {
  document.write('Message number ONE');
}

if (messageNum === 2) {
  document.write('Message number TWO');
}

if (messageNum === 3) {
  document.write('Message number THREE');
}
</script>
</html>
</code>```

答:
try to execute your code inside the setInterval-function:

```<code><!doctype html>
<html>
<head><title>Loading screen</title></head>
<script>
let messageNum = 1;

setInterval(function(){
  messageNum++
  if (messageNum >3) {
    messageNum = 1;
  }

  if (messageNum === 1) {
    document.write('Message number ONE');
  }

  if (messageNum === 2) {
    document.write('Message number TWO');
  }

  if (messageNum === 3) {
    document.write('Message number THREE');
  }
 }, 1000);

</script>
</html>
</code>```

Regards

Title: SetInterval messages not changing

Body:
I'm making a loading screen for a game I'm creating with html and JS.  I want various messages to display, about every three seconds.  The SetInterval function doesn't seem to be rotating the messages, even though it works with something else (like an alert every three seconds).  here's the code I've written for the changing messages.

<!doctype html>

<title>Loading screen</title>

Body:
try to execute your code inside the setInterval-function:

<!doctype html>
<html>
<head><title>Loading screen</title></head>
<script>
let messageNum = 1;

setInterval(function(){
  messageNum++
  if (messageNum >3) {
    messageNum = 1;
  }

  if (messageNum === 1) {
    document.write('Message number ONE');
  }

  if (messageNum === 2) {
    document.write('Message number TWO');
  }

  if (messageNum === 3) {
    document.write('Message number THREE');
  }
 }, 1000);

</script>
</html>

Regards


答:
Hope this will help:

```<code><!doctype html>
<html>
<head><title>Loading screen</title></head>
<script>
let messageNum = 1;

const interval = setInterval(function(){
  messageNum++;
  if (messageNum >3) {
  messageNum = 1;
}

if (messageNum === 1) {
  document.write('Message number ONE');
}

if (messageNum === 2) {
  document.write('Message number TWO');
}

if (messageNum === 3) {
  document.write('Message number THREE');
}
 }, 1000);

</script>
</html>
</code>```

Also make sure to clear the interval when needed. It might cause memory leaks. you can clear interval using this code:

```<code>clearInterval(interval)
</code>```

Title: SetInterval messages not changing

Body:
Hope this will help:

<!doctype html>
<html>
<head><title>Loading screen</title></head>
<script>
let messageNum = 1;

const interval = setInterval(function(){
  messageNum++;
  if (messageNum >3) {
  messageNum = 1;
}

if (messageNum === 1) {
  document.write('Message number ONE');
}

if (messageNum === 2) {
  document.write('Message number TWO');
}

if (messageNum === 3) {
  document.write('Message number THREE');
}
 }, 1000);

</script>
</html>

Also make sure to clear the interval when needed. It might cause memory leaks. you can clear interval using this code:

clearInterval(interval)


问:
convenient way to convert seconds into more specific format
Is there any convenient way to convert seconds into more specific format.

For example:

I want to convert

```<code>559 seconds
</code>```

to

```<code>9 min 19 sec
</code>```

答:
```<code>$seconds = 559;

$minutes = floor($seconds / 60);  // 9
$seconds = $seconds % 60;         // 19
</code>```

Body:
Is there any convenient way to convert seconds into more specific format.

For example:

I want to convert

559 seconds

to

9 min 19 sec


问:
why my ObservedObject is updated but not showing its updated content in the View
I trying to show a simple View of counting down the time using ObservableObject but it seems my ObservedObject is updated but not showing its updated content to its binded view. The display stay at 60

```<code>import SwiftUI
import Combine

class myTimer: ObservableObject {

    @Published var timeRemaining = 60
    var timer: Timer?

    init() {
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector (countDownTime), userInfo: nil, repeats: true)
    }

    @objc func countDownTime () {
        if (timeRemaining < 60) {
            timeRemaining -= 1
        }
    }

    func resetCount () {
        timeRemaining = 60
    }
}

struct ContentView: View {

    @ObservedObject var myTimeCount: myTimer = myTimer()

    var body: some View {
        NavigationView{
            VStack {
                Text("Time remaining \(myTimeCount.timeRemaining)")
                    .font(.largeTitle)
                    .fontWeight(.bold)
                    .padding()

                Button(action: resetCount) {
                    Text("Reset Counter")
                }
            }

        }

    }
    func resetCount() {
        myTimeCount.resetCount()
    }
}
</code>```

enter image description here

答:
You can also change your init slightly and get rid of @objc func countDownTime () at all

    init() {
        timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in
            self?.timeRemaining -= 1
        }
    }

```

Body:
I trying to show a simple View of counting down the time using ObservableObject but it seems my ObservedObject is updated but not showing its updated content to its binded view. The display stay at 60

import SwiftUI
import Combine

class myTimer: ObservableObject {

    @Published var timeRemaining = 60
    var timer: Timer?

    init() {
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector (countDownTime), userInfo: nil, repeats: true)
    }

    @objc func countDownTime () {
        if (timeRemaining < 60) {
            timeRemaining -= 1
        }
    }

    func resetCount () {
        timeRemaining = 60
    }
}

struct ContentView: View {

    @ObservedObject var myTimeCount: myTimer = myTimer()

    var body: some View {
        NavigationView{
            VStack {
                Text("Time remaining \(myTimeCount.timeRemaining)")
                    .font(.largeTitle)
                    .fontWeight(.bold)
                    .padding()

                Button(action: resetCount) {
                    Text("Reset Counter")
                }
            }

        }

    }
    func resetCount() {
        myTimeCount.resetCount()
    }
}

enter image description here


答:
setInterval is an asynchronous operation, so your events happen in the wrong order.

You need to run your output logic WHEN the number changes. Right now, you are running all your output logic before the first time the setInterval runs even the first time.

let messageNum = 1;

setInterval(function(){
  outputNum();
  messageNum++;
}, 1000);

function outputNum() {
  if (messageNum > 3) {
    messageNum = 1;
  }

  if (messageNum === 1) {
    document.write('Message number ONE
');
  }

  if (messageNum === 2) {
    document.write('Message number TWO
');
  }

  if (messageNum === 3) {
    document.write('Message number THREE
');
  }
}```

Title: SetInterval messages not changing

Body:
setInterval is an asynchronous operation, so your events happen in the wrong order.

You need to run your output logic WHEN the number changes. Right now, you are running all your output logic before the first time the setInterval runs even the first time.

let messageNum = 1;

setInterval(function(){
  outputNum();
  messageNum++;
}, 1000);

function outputNum() {
  if (messageNum > 3) {
    messageNum = 1;
  }

  if (messageNum === 1) {
    document.write('Message number ONE<br />');
  }

  if (messageNum === 2) {
    document.write('Message number TWO<br />');
  }

  if (messageNum === 3) {
    document.write('Message number THREE<br />');
  }
}