问:
How to configure toolchain in Bazel
We plan to use Bazel to cross-compile for different arch target and we get some problems about toolchain:

As per the docs, we configured the toolchain as:

```<code>toolchain_include_directories_feature = feature(
        name = "toolchain_include_directories",
        enabled = True,
        flag_sets = [
            flag_set(
                actions = [
                    "ACTION_NAMES.assemble",
                    "ACTION_NAMES.preprocess_assemble",
                    "ACTION_NAMES.linkstamp_compile",
                    "ACTION_NAMES.c_compile",
                    "ACTION_NAMES.cpp_compile",
                    "ACTION_NAMES.cpp_header_parsing",
                    "ACTION_NAMES.cpp_module_compile",
                    "ACTION_NAMES.cpp_module_codegen",
                    "ACTION_NAMES.lto_backend",
                    "ACTION_NAMES.clif_match",
                ],
                flag_groups = [
                    flag_group(
                        flags = [
                             "-isystem",
                             "/opt/buildtools/sdk/usr/include",
                        ],
                    ),
                ],
            ),
        ],
    )
</code>```

and we get the error:

```<code>ERROR: /home/project/aa/BUILD:1:1: undeclared inclusion(s) in rule '//aa:mylib':
this rule is missing dependency declarations for the following files included by 'aa/source/export.c':
  '/opt/buildtools/sdk/usr/include/stdc-predef.h'
</code>```

Any ideas, thanks.

Added: the environment info

```<code>LSB Version:    n/a
Distributor ID: SUSE
Description:    SUSE Linux Enterprise Server 12 SP4
Release:        12.4
Codename:       n/a
4.12.14-94.41-default #1 SMP Wed Oct 31 12:25:04 UTC 2018 (3090901) x86_64 x86_64 x86_64 GNU/Linux

Bazel version: 0.24.1
</code>```

答:
When you create the toolchain config with create_cc_toolchain_config_info, don't forget to set up its cxx_builtin_include_directories parameter by adding the usual include paths as well, like

def _impl(ctx):
    #  [...]
    cxx_builtin_include_directories = [
        "/opt/buildtools/sdk/usr/include/",
        "/usr/include",
    ]

    return [
        cc_common.create_cc_toolchain_config_info(
            cxx_builtin_include_directories = cxx_builtin_include_directories,
            #  [...]
        ),
    ]
```

Title: How to configure toolchain in Bazel

Body:
We plan to use Bazel to cross-compile for different arch target and we get some problems about toolchain:

As per the docs, we configured the toolchain as:

toolchain_include_directories_feature = feature(
        name = "toolchain_include_directories",
        enabled = True,
        flag_sets = [
            flag_set(
                actions = [
                    "ACTION_NAMES.assemble",
                    "ACTION_NAMES.preprocess_assemble",
                    "ACTION_NAMES.linkstamp_compile",
                    "ACTION_NAMES.c_compile",
                    "ACTION_NAMES.cpp_compile",
                    "ACTION_NAMES.cpp_header_parsing",
                    "ACTION_NAMES.cpp_module_compile",
                    "ACTION_NAMES.cpp_module_codegen",
                    "ACTION_NAMES.lto_backend",
                    "ACTION_NAMES.clif_match",
                ],
                flag_groups = [
                    flag_group(
                        flags = [
                             "-isystem",
                             "/opt/buildtools/sdk/usr/include",
                        ],
                    ),
                ],
            ),
        ],
    )

and we get the error:

ERROR: /home/project/aa/BUILD:1:1: undeclared inclusion(s) in rule '//aa:mylib':
this rule is missing dependency declarations for the following files included by 'aa/source/export.c':
  '/opt/buildtools/sdk/usr/include/stdc-predef.h'

Any ideas, thanks.

Added: the environment info

LSB Version:    n/a
Distributor ID: SUSE
Description:    SUSE Linux Enterprise Server 12 SP4
Release:        12.4
Codename:       n/a
4.12.14-94.41-default #1 SMP Wed Oct 31 12:25:04 UTC 2018 (3090901) x86_64 x86_64 x86_64 GNU/Linux

Bazel version: 0.24.1


来源: stackexchange

问:
electron - window.postMessage to talk between preload and renderer with specific target origin
I would like to validate/differentiate the origin of a message using the targetOrigin of postMessage between preload.js and renderer.js with contextIsolation enabled.

So if a message come from preload.js, the originTarget being something like file://preload.js, and from renderer file://renderer.js.

Setting file://preload.js or file://renderer.js, make the error Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('file://') does not match the recipient window's origin ('file://')..

Does someone know how to achieve what I’m trying to achieve?
Thank you

答:
To quote MDN web docs:

Lastly, posting a message to a page at a file: URL currently requires that the targetOrigin argument be "*". file:// cannot be used as a security restriction; this restriction may be modified in the future.

So in preload.js you need to use * as targetOrigin:

window.addEventListener("DOMContentLoaded", () => {
  window.postMessage({ type: "fooType", text: "barMsg" }, "*")
})
```
<p>In the receiving renderer (webpage), restrict message processing to <code>file://</code> scheme and <code>window</code> object reference for security reasons:</p>
<pre class="lang-js prettyprint-override"><code>window.addEventListener(
  "message",
  event => {
    if (event.origin === "file://" && event.source === window) {
      console.log(event.data)
    }
  },
  false
)
</code>```

This will also work with a more restrictive config as follows (webPreferences for BrowserWindow):

{
  nodeIntegration: false,
  contextIsolation: true,
  enableRemoteModule: false,
  preload: path.join(__dirname, "preload.js")
}
```

ContentLicense: CC BY-SA 4.0

Body:
To quote MDN web docs:

Lastly, posting a message to a page at a file: URL currently requires that the targetOrigin argument be "*". file:// cannot be used as a security restriction; this restriction may be modified in the future.

So in preload.js you need to use * as targetOrigin:

window.addEventListener("DOMContentLoaded", () => {
  window.postMessage({ type: "fooType", text: "barMsg" }, "*")
})

In the receiving renderer (webpage), restrict message processing to file:// scheme and window object reference for security reasons:

window.addEventListener(
  "message",
  event => {
    if (event.origin === "file://" && event.source === window) {
      console.log(event.data)
    }
  },
  false
)

This will also work with a more restrictive config as follows (webPreferences for BrowserWindow):

{
  nodeIntegration: false,
  contextIsolation: true,
  enableRemoteModule: false,
  preload: path.join(__dirname, "preload.js")
}


问:
Android Wrap Shell Script Doesn't Work as Expected
I have a C library to be integrated with my project, but upon working, I got a stack corruption error. I decided that a malloc debug might help in my case, but can't seemed to configure it properly.

I have tried to follow this tutorial : https://developer.android.com/ndk/guides/wrap-script

I wrote my wrap script, which just contains the following line (I don't even add the malloc debug options yet) :

```<code>#!/system/bin/sh
exec "$@"
</code>```

I put the script on the default resources/lib/{arch} folder and verified that it is indeed got packaged correctly into the apk in the lib folder.

But upon launching the app, it seemed to stuck, and just displayed an empty white screen (I have verified the app working properly without the wrapping shell script, at least until the stack corruption occurred).

I have noticed that the logcat print the following lines :

```<code>2019-05-24 16:35:00.524 1927-1942/? W/ActivityManager: Launch timeout has expired, giving up wake lock!
2019-05-24 16:35:00.680 1927-1942/? W/ActivityManager: Process ProcessRecord{e1f6d50 6975:my.package.name/u0a85} failed to attach
2019-05-24 16:35:00.681 1927-1942/? I/ActivityManager: Killing 6975:my.package.name/u0a85 (adj -10000): start time
</code>```

I had tried using non rooted android 8.1 device, Android Pie, even with Pixel on Android Q, but the result is the same. I tried to move to emulator, but no avail, it fails with the same result. I had tried using both NDK 17c and NDK 19, both produced the same result. I'm working on windows, if that might relevant.

Any help is appreciated.

答: After trying various alternative, turns out the problem happened because of the different EOL format between windows (my workstation) and linux (the android device). After converting my wrap.sh file EOL fromat from Windows (CR LF) to Unix EOL format (LF), I managed to get it running.</p>

Body:
I have a C library to be integrated with my project, but upon working, I got a stack corruption error. I decided that a malloc debug might help in my case, but can't seemed to configure it properly.

I have tried to follow this tutorial : https://developer.android.com/ndk/guides/wrap-script

I wrote my wrap script, which just contains the following line (I don't even add the malloc debug options yet) :

#!/system/bin/sh
exec "$@"

I put the script on the default resources/lib/{arch} folder and verified that it is indeed got packaged correctly into the apk in the lib folder.

But upon launching the app, it seemed to stuck, and just displayed an empty white screen (I have verified the app working properly without the wrapping shell script, at least until the stack corruption occurred).

I have noticed that the logcat print the following lines :

2019-05-24 16:35:00.524 1927-1942/? W/ActivityManager: Launch timeout has expired, giving up wake lock!
2019-05-24 16:35:00.680 1927-1942/? W/ActivityManager: Process ProcessRecord{e1f6d50 6975:my.package.name/u0a85} failed to attach
2019-05-24 16:35:00.681 1927-1942/? I/ActivityManager: Killing 6975:my.package.name/u0a85 (adj -10000): start time

I had tried using non rooted android 8.1 device, Android Pie, even with Pixel on Android Q, but the result is the same. I tried to move to emulator, but no avail, it fails with the same result. I had tried using both NDK 17c and NDK 19, both produced the same result. I'm working on windows, if that might relevant.

Any help is appreciated.


问:
Select NULL Values in SQLAlchemy
Here's my (PostgreSQL) table --

```<code>test=> create table people (name varchar primary key,
                            marriage_status varchar) ;

test=> insert into people values ('Ken', 'married');
test=> insert into people values ('May', 'single');
test=> insert into people values ('Joe', NULL);
</code>```

I want to select all people that are not known to be married, i.e., including those with NULL marriage_status.

This does not work --

```<code>test=> select * from people where marriage_status != 'married' ;
 name | marriage_status
------+-----------------
 May  | single
(1 row)
</code>```

Of course this does --

```<code>test=> select * from people where marriage_status != 'married'
       or marriage_status is NULL ;
 name | marriage_status
------+-----------------
 May  | single
 Joe  |
</code>```

The problem is that I'm accessing it from SQLAlchemy with --

```<code>...filter(or_(people.marriage_status!='married',
              people.marriage_status is None))
</code>```

which gets translated to --

```<code>SELECT people.name as name,
       people.marriage_status as marriage_status
FROM people
WHERE people.marriage_status != %(status_1)s OR False
sqlalchemy.engine.base.Engine.... {'status_1': 'married'}
</code>```

And does not work --

```<code>test=> select * from people where marriage_status != 'married'
       or False;
 name | marriage_status
------+-----------------
 May  | single
(1 row)
</code>```

neither does --

```<code>test=> select * from people where marriage_status != 'married'
       or NULL;
 name | marriage_status
------+-----------------
 May  | single
(1 row)
</code>```

How should I select NULL values through SQLAlchemy?

答:
For SQLAlchemy 0.7.9 and newer
Please use the answer from @jsnow. !!!

For SQLAlchemy 0.7.8 and older

(as indicated by @augurar): Because sqlalchemy uses magic methods (operator overloading) to create SQL constructs, it can only handle operator such as != or ==, but is not able to work with is (which is a very valid Python construct).

Therefore, to make it work with sqlalchemy, you should use:

```<code>...filter(or_(people.marriage_status!='married', people.marriage_status == None))
</code>```

, basically replace the is None with == None. In this case your query will be translated properly to the following SQL:

```<code>SELECT people.name AS people_name, people.marriage_status AS people_marriage_status
FROM people
WHERE people.marriage_status IS NULL OR people.marriage_status != ?
</code>```

See IS NULL in the documentation.

ContentLicense: CC BY-SA 3.0

Title: Select NULL Values in SQLAlchemy

Body:
Here's my (PostgreSQL) table --

test=> create table people (name varchar primary key,
                            marriage_status varchar) ;

test=> insert into people values ('Ken', 'married');
test=> insert into people values ('May', 'single');
test=> insert into people values ('Joe', NULL);

I want to select all people that are not known to be married, i.e., including those with NULL marriage_status.

This does not work --

test=> select * from people where marriage_status != 'married' ;
 name | marriage_status
------+-----------------
 May  | single
(1 row)

Of course this does --

test=> select * from people where marriage_status != 'married'
       or marriage_status is NULL ;
 name | marriage_status
------+-----------------
 May  | single
 Joe  |

The problem is that I'm accessing it from SQLAlchemy with --

...filter(or_(people.marriage_status!='married',
              people.marriage_status is None))

which gets translated to --

SELECT people.name as name,
       people.marriage_status as marriage_status
FROM people
WHERE people.marriage_status != %(status_1)s OR False
sqlalchemy.engine.base.Engine.... {'status_1': 'married'}

And does not work --

test=> select * from people where marriage_status != 'married'
       or False;
 name | marriage_status
------+-----------------
 May  | single
(1 row)

neither does --

test=> select * from people where marriage_status != 'married'
       or NULL;
 name | marriage_status
------+-----------------
 May  | single
(1 row)

How should I select NULL values through SQLAlchemy?

Body:
For SQLAlchemy 0.7.9 and newer
Please use the answer from @jsnow. !!!

For SQLAlchemy 0.7.8 and older

(as indicated by @augurar): Because sqlalchemy uses magic methods (operator overloading) to create SQL constructs, it can only handle operator such as != or ==, but is not able to work with is (which is a very valid Python construct).

Therefore, to make it work with sqlalchemy, you should use:

...filter(or_(people.marriage_status!='married', people.marriage_status == None))

, basically replace the is None with == None. In this case your query will be translated properly to the following SQL:

SELECT people.name AS people_name, people.marriage_status AS people_marriage_status
FROM people
WHERE people.marriage_status IS NULL OR people.marriage_status != ?

See IS NULL in the documentation.


问:
VueJs "global" event not being triggered inside my class file
I have a piece of code (auth.js) that is supposed to be triggered after a user successfully logs in.  But I noticed that 2 lines do not seem working.  it is not tiggered.

this.$axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
and
this.$eventHub.$emit('userLoggedIn');

is there something i need to do to make both work?  i have set them up to be accessible globally.  i checked out the line:
localStorage.setItem('user', JSON.stringify(user));
and seems to work fine.

i have tried remove this word but to no avail.

main.js

import auth from '@/auth'

import axios from 'axios'

Vue.prototype.$axios = axios
Vue.prototype.$auth = auth
Vue.prototype.$eventHub = new Vue();
```

<p>auth.js</p>

<pre class="lang-js prettyprint-override"><code>class Auth {
    constructor() {
        this.token = null;
        this.user = null;
    }
    login(token, user) {

        localStorage.setItem('token', token);
        localStorage.setItem('user', JSON.stringify(user));

        this.$axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;

        this.token = token;
        this.user = user;

        this.$eventHub.$emit('userLoggedIn');
    }
    check() {
        return !! this.token;
    }
}
export default new Auth();
</code>```

this is the code inside my Login.vue which calls the auth.js login method:

```<code>        login() {
            let data = {
                email: this.username,
                password: this.password
            };
            this.$axios.post('http://127.0.0.1:8000/api/login', data)
            .then(({data}) => {
                if (data.status == 200) {
                    this.$auth.login(data.data.token, data.data.user);
                    this.$router.replace('about');
                } else {
                    // console.log("Error");
                }
            })
            .catch(() => {
                //alert(response.data.message);
            });
        }
</code>```

答:
The this keyword in the Auth class is not pointing to the Vue instance. You can pass the Vue instance as a parameter of login method like this:

```<code>class Auth {
    constructor() {
        this.token = null;
        this.user = null;
    }
    login(vue, token, user) {

        localStorage.setItem('token', token);
        localStorage.setItem('user', JSON.stringify(user));

        vue.$axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;

        this.token = token;
        this.user = user;

        vue.$eventHub.$emit('userLoggedIn');
    }
    check() {
        return !! this.token;
    }
}
export default new Auth();
</code>```

And then call login method this way:

```<code>this.$auth.login(this, data.data.token, data.data.user);
</code>```

Body:
I have a piece of code (auth.js) that is supposed to be triggered after a user successfully logs in.  But I noticed that 2 lines do not seem working.  it is not tiggered.

this.$axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
and
this.$eventHub.$emit('userLoggedIn');

is there something i need to do to make both work?  i have set them up to be accessible globally.  i checked out the line:
localStorage.setItem('user', JSON.stringify(user));
and seems to work fine.

i have tried remove this word but to no avail.

main.js

import auth from '@/auth'

import axios from 'axios'

Vue.prototype.$axios = axios
Vue.prototype.$auth = auth
Vue.prototype.$eventHub = new Vue();

auth.js

class Auth {
    constructor() {
        this.token = null;
        this.user = null;
    }
    login(token, user) {

        localStorage.setItem('token', token);
        localStorage.setItem('user', JSON.stringify(user));

        this.$axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;

        this.token = token;
        this.user = user;

        this.$eventHub.$emit('userLoggedIn');
    }
    check() {
        return !! this.token;
    }
}
export default new Auth();

this is the code inside my Login.vue which calls the auth.js login method:

        login() {
            let data = {
                email: this.username,
                password: this.password
            };
            this.$axios.post('http://127.0.0.1:8000/api/login', data)
            .then(({data}) => {
                if (data.status == 200) {
                    this.$auth.login(data.data.token, data.data.user);
                    this.$router.replace('about');
                } else {
                    // console.log("Error");
                }
            })
            .catch(() => {
                //alert(response.data.message);
            });
        }

Body:
The this keyword in the Auth class is not pointing to the Vue instance. You can pass the Vue instance as a parameter of login method like this:

class Auth {
    constructor() {
        this.token = null;
        this.user = null;
    }
    login(vue, token, user) {

        localStorage.setItem('token', token);
        localStorage.setItem('user', JSON.stringify(user));

        vue.$axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;

        this.token = token;
        this.user = user;

        vue.$eventHub.$emit('userLoggedIn');
    }
    check() {
        return !! this.token;
    }
}
export default new Auth();

And then call login method this way:

this.$auth.login(this, data.data.token, data.data.user);


问:
XML Variable Substitution on VSTS Release Management Definition
I created a release definition on Visual Studio Team Services for my Windows console application. This app runs on a Virtual Machine so I basically perform the deployment using a Windows Machine File Copy task.

Now I need to create two environments (stage and production) and each of these environments must use different app.config variables.

Recently, I have successfully performed this transformation for a web app using the Azure App Service Deploy XML Variable Substitution. But this is not an available option for file copy task.

How can I make this work?

答:
You can use the File Transform task from Microsoft in order to replace the environment variables in the XML config file.

This task both updates tokens and replaces them which means that you only need this single task in addition to the Copy Files task in your case.


问:
Access main activity FloatingActionButton from Fragments
I have a an activity with 3 fragments. Each fragment has to have a FAB with different icon an action.
The FAB is defined on the main activity layout. Now I saw that I cannot access it from fragments. How can I do it?

Here's my code:
main_activity layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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">

    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        app:layout_constraintBottom_toTopOf="parent"
        app:layout_constraintTop_toBottomOf="parent"
        tools:layout_editor_absoluteX="16dp">

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabGravity="fill"
            app:tabMode="fixed" />
    </android.support.v4.view.ViewPager>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="24dp"
        android:src="@android:drawable/ic_dialog_email"
        android:visibility="visible"
        app:layout_constraintBottom_toTopOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

</android.support.constraint.ConstraintLayout>
</code>```

my fragment layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorBackgroundFragment">

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/contact_recycleview">

    </android.support.v7.widget.RecyclerView>

</LinearLayout>
</code>```

inflating the fragment:

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    v= inflater.inflate(R.layout.filters_fragment,container,false);

    myrecyclerview = (RecyclerView) v.findViewById(R.id.contact_recycleview);
    recyclerAdapter = new RecyclerViewAdapterCall(getContext(), lstCall);
    myrecyclerview.setLayoutManager(new LinearLayoutManager((getActivity())));
    myrecyclerview.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
    myrecyclerview.setAdapter(recyclerAdapter);

    return v;
}
</code>```

so here I'll like to change icon an action, how?

答:
Call this from Fragment

```<code> Objects.requireNonNull(getActivity()).someOperationOnFab();
</code>```

where someOperationOnFab() is defined in MainActivity

```<code> public void someOperationOnFab(){
     yourFab. blah
}
</code>```

Body:
I have a an activity with 3 fragments. Each fragment has to have a FAB with different icon an action.
The FAB is defined on the main activity layout. Now I saw that I cannot access it from fragments. How can I do it?

Here's my code:
main_activity layout:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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">

    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        app:layout_constraintBottom_toTopOf="parent"
        app:layout_constraintTop_toBottomOf="parent"
        tools:layout_editor_absoluteX="16dp">

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabGravity="fill"
            app:tabMode="fixed" />
    </android.support.v4.view.ViewPager>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="24dp"
        android:src="@android:drawable/ic_dialog_email"
        android:visibility="visible"
        app:layout_constraintBottom_toTopOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

</android.support.constraint.ConstraintLayout>

my fragment layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorBackgroundFragment">

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/contact_recycleview">

    </android.support.v7.widget.RecyclerView>

</LinearLayout>

inflating the fragment:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    v= inflater.inflate(R.layout.filters_fragment,container,false);

    myrecyclerview = (RecyclerView) v.findViewById(R.id.contact_recycleview);
    recyclerAdapter = new RecyclerViewAdapterCall(getContext(), lstCall);
    myrecyclerview.setLayoutManager(new LinearLayoutManager((getActivity())));
    myrecyclerview.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
    myrecyclerview.setAdapter(recyclerAdapter);

    return v;
}

so here I'll like to change icon an action, how?

Body:
Call this from Fragment

 Objects.requireNonNull(getActivity()).someOperationOnFab();

where someOperationOnFab() is defined in MainActivity

 public void someOperationOnFab(){
     yourFab. blah
}


问:
sed: How to join the lines of a record with an empty line delimiting records
I would like to use 'sed' to joins three lines that make up a record, with records separated by empty lines, and record fields separated by a space.

Here's a snip of data from the file:

```<code>KDFW
N 32°53.83'
W 097°02.26'

TOC
N 32°48.49'
W 097°01.39'

DART
N 32°17.15'
W 096°48.66'
</code>```

I need to combine the lines like this:

```<code>KDFW N 32°53.83' W 097°02.26'
TOC N 32°48.49' W 097°01.39'
DART N 32°17.15' W 096°48.66'
</code>```

I'm a novice with sed but pieced together this ugly line.

```<code>sed 'N;s/\n/ /' navlog.txt | sed 'N;s/\n/ /'
</code>```

yea - there is a better way...

答:
Perl:

```<code>perl -pe 's/\n/ / if /./' navlog.txt
</code>```

Or:

```<code>perl -pe 's/\n/ / if $.%4' navlog.txt
</code>```

Body:
I would like to use 'sed' to joins three lines that make up a record, with records separated by empty lines, and record fields separated by a space.

Here's a snip of data from the file:

KDFW
N 32°53.83'
W 097°02.26'

TOC
N 32°48.49'
W 097°01.39'

DART
N 32°17.15'
W 096°48.66'

I need to combine the lines like this:

KDFW N 32°53.83' W 097°02.26'
TOC N 32°48.49' W 097°01.39'
DART N 32°17.15' W 096°48.66'

I'm a novice with sed but pieced together this ugly line.

sed 'N;s/\n/ /' navlog.txt | sed 'N;s/\n/ /'

yea - there is a better way...

Body:
Perl:

perl -pe 's/\n/ / if /./' navlog.txt

Or:

perl -pe 's/\n/ / if $.%4' navlog.txt


问:
Random double-quote character in jsp output
I have a .jsp page I'm compiling with ant and deploying to a Tomcat 7 server. A couple of times the output source document has a double-quote character added at a point where it shouldn't be added. It seems to persist through multiple compiles and deploys, but they've always gone away after a while.

Here is a section of the jsp:

```<code>  <form action="SetDocName" method="post" accept-charset="UTF-8">
    <input type="text" name="new-doc-name" /> <input type="submit" value="<%= uiStrings.getString("change_doc_name") %>" />
  </form>
</code>```

and here's the final output:

```<code>  <form action="SetDocName" method="post" accept-charset="UTF-8">
    <input type="text" name="new-doc-name" /> <input type="submit" value="Change document name" />"
  </form>
</code>```

notice the double-quote next to the second input element.

Any idea what's going on here? It's not a major problem at the moment, but it is puzzling.

答:
I never really got to the bottom of this completely, in the absence of an explanation I guess the fix is the closest to an answer:

My comment: "The issue seems to be the web page editor plugin somehow inserting some sort of character that shows up as whitespace in the editor but is interpreted differently by Tomcat. Replacing the whitespace with new whitespace fixed it and it hasn't happened since."

ContentLicense: CC BY-SA 2.5

Body:
I have a .jsp page I'm compiling with ant and deploying to a Tomcat 7 server. A couple of times the output source document has a double-quote character added at a point where it shouldn't be added. It seems to persist through multiple compiles and deploys, but they've always gone away after a while.

Here is a section of the jsp:

  <form action="SetDocName" method="post" accept-charset="UTF-8">
    <input type="text" name="new-doc-name" /> <input type="submit" value="<%= uiStrings.getString("change_doc_name") %>" />
  </form>

and here's the final output:

  <form action="SetDocName" method="post" accept-charset="UTF-8">
    <input type="text" name="new-doc-name" /> <input type="submit" value="Change document name" />"
  </form>

notice the double-quote next to the second input element.

Any idea what's going on here? It's not a major problem at the moment, but it is puzzling.


答: Add Floating action buttons to your fragments. Add it in Fragments layout. In this way it will be easier and clearer approach.</p>

Title: Access main activity FloatingActionButton from Fragments


问:
How could I get changed value from vuetify select by emitting in atomic design pattern?
I am trying to get the changed value of vuetify v-select by using $emit but it doesn't work.
I divided components by applying atomic design pattern (atoms(child component and not to connect with the store), organisms(parent component)) and vuex stores.
I think $emit data is OK but anything doesn't work after the process.

This is for a new application for management page with
using vue, vuex, vuetify, atomic design connecting to API server.

Components

child component - in atoms folder

```<code><template>
  <v-select
    :items="list"
    :label="label"
    v-model="selected"
    item-value="id"
    item-text="name"
    return-object
    @change="changeSelected"
  ></v-select>
</template>

<script>
export default {
  props: ["list", "label", "defaultSelected"],
  data() {
    return {
      selected: this.defaultSelected
    };
  },
  methods: {
    changeSelected(newValue) {
      console.log(newValue);    // display changed new data
      this.$emit("changeSelected", newValue);
    }
  }
};
</script>

</code>```

parent component - in organisms folder

```<code><template>
  <v-select-child
    :select-label="label"
    :select-list="list"
    :default-selected="selected"
    @change-selected="changeSelected"    // problem issue?
  >
  </v-select-child>
</template>
<script>
import { mapState } from "vuex";
export default {
  data() {
    ...
  },
  computed: {
    ...mapState({
      list: state => state.list
    })
  },
  methods: {
    changeSelected() {
      console.log("changeSelected");    // doesn't work
      this.$store.dispatch("setSelected", { payload: this.selected });
    }
  }
};
</script>
</code>```

vuex stores

index.js

```<code>export default new Vuex.Store({
  modules: {
    xxx
  },
  state: {
    list: [
      {
        name: "aaaaa",
        id: "001"
      },
      {
        name: "bbbbb",
        id: "002"
      }
    ]
  },
  getters: {},
  mutations: {},
  actions: {}
});

</code>```

xxx.js

```<code>export default {
    selected: { id: "001" }
  },

  getters: {
    //
  },

  mutations: {
    updateSelected(state, payload) {
      console.log("payload");    // doesn't work
      console.log(payload);
      state.selected = payload;
      console.log(state.selected);
    }
  },

  actions: {
    setSelected({ commit }, payload) {
      console.log("Action");    // doesn't work
      commit("updateSelected", payload);
    }
  }
};
</code>```

It does not print any console log after changeSelected function.

答:
In document

Unlike components and props, event names don’t provide any automatic
case transformation. Instead, the name of an emitted event must
exactly match the name used to listen to that event.

That means if you emit event like $emit('changeSelected'), then you need to use @changeSelected. @change-selected will not work.

```<code> <v-select-child
    :select-label="label"
    :select-list="list"
    :default-selected="selected"
    @changeSelected="changeSelected"
  >
</v-select-child>
</code>```

Body:
I am trying to get the changed value of vuetify v-select by using $emit but it doesn't work.
I divided components by applying atomic design pattern (atoms(child component and not to connect with the store), organisms(parent component)) and vuex stores.
I think $emit data is OK but anything doesn't work after the process.

This is for a new application for management page with
using vue, vuex, vuetify, atomic design connecting to API server.

Components

child component - in atoms folder

<template>
  <v-select
    :items="list"
    :label="label"
    v-model="selected"
    item-value="id"
    item-text="name"
    return-object
    @change="changeSelected"
  ></v-select>
</template>

parent component - in organisms folder

<template>
  <v-select-child
    :select-label="label"
    :select-list="list"
    :default-selected="selected"
    @change-selected="changeSelected"    // problem issue?
  >
  </v-select-child>
</template>

vuex stores

index.js

export default new Vuex.Store({
  modules: {
    xxx
  },
  state: {
    list: [
      {
        name: "aaaaa",
        id: "001"
      },
      {
        name: "bbbbb",
        id: "002"
      }
    ]
  },
  getters: {},
  mutations: {},
  actions: {}
});

xxx.js

export default {
    selected: { id: "001" }
  },

  getters: {
    //
  },

  mutations: {
    updateSelected(state, payload) {
      console.log("payload");    // doesn't work
      console.log(payload);
      state.selected = payload;
      console.log(state.selected);
    }
  },

  actions: {
    setSelected({ commit }, payload) {
      console.log("Action");    // doesn't work
      commit("updateSelected", payload);
    }
  }
};

It does not print any console log after changeSelected function.

Body:
In document

Unlike components and props, event names don’t provide any automatic
case transformation. Instead, the name of an emitted event must
exactly match the name used to listen to that event.

That means if you emit event like $emit('changeSelected'), then you need to use @changeSelected. @change-selected will not work.

 <v-select-child
    :select-label="label"
    :select-list="list"
    :default-selected="selected"
    @changeSelected="changeSelected"
  >
</v-select-child>


问:
How to Select between two periode of month and year eg: january 2018 - january 2019?
SQL query problem</p>

```<code>select *
from app_contract_hd
where year(created_datetime) between 2018 and 2018 and MONTH(created_datetime)between 4 and 4
</code>```

答:
As you have TIME in your created_datetime field, its better if you check the upper range less than +1 day with your original upper range date</p>

```<code>SELECT *
FROM app_contract_hd
WHERE created_datetime >= '20180101'
AND created_datetime < '20180201'
</code>```

Body:
SQL query problem

select *
from app_contract_hd
where year(created_datetime) between 2018 and 2018 and MONTH(created_datetime)between 4 and 4

Body:
As you have TIME in your created_datetime field, its better if you check the upper range less than +1 day with your original upper range date

SELECT *
FROM app_contract_hd
WHERE created_datetime >= '20180101'
AND created_datetime < '20180201'


问:
Kubernetes send HTTP request from Pods
Currently I have an Kubernetes cluster which is to analyze Video Feeds and send particular results based on the video. I wish to send an HTTP request from my Kubernetes pod from from time to time if the requested Video needs to be retrieved over the internet. However all of these requests seem to Fail. When I issued a CURL command in the shell of the container I receive an error message saying

```<code>could not resolve host
</code>```

I have looked into a few answers and many of them involve exposing a port in the container running a server to the Kubernetes node and making it publicly available through a external IP which I have already Implemented.

I am still very much a Novice in this area. So any guidance is appreciated

答: Answered in comments, kube-dns was unavailable due to resource constraints.</p>

Title: Kubernetes send HTTP request from Pods

Body:
Currently I have an Kubernetes cluster which is to analyze Video Feeds and send particular results based on the video. I wish to send an HTTP request from my Kubernetes pod from from time to time if the requested Video needs to be retrieved over the internet. However all of these requests seem to Fail. When I issued a CURL command in the shell of the container I receive an error message saying

could not resolve host

I have looked into a few answers and many of them involve exposing a port in the container running a server to the Kubernetes node and making it publicly available through a external IP which I have already Implemented.

I am still very much a Novice in this area. So any guidance is appreciated


问:
how start up other apps and help to fill the data on android
I want to develop an app that help users to start up other apps which needs username and password,so I must start up other apps and help to fill the username and password into the login userface of the apps,
   for example,I want to start up an app that helps user to login the facebook and fill the username and password in the login userface of the facebook app in my app,now I only konw the name of the facebookapp,
   1.how to start up it in my app?(I don't know the package name of the app started up)
   2.when I have started the app,how to automatically fill the username and password?</p>

答:
You probably don't.

AFAIK, for example with HTC's "Sense", Facebook credentials are stored as a sync account in the accounts api.

Since I think it is not encouraged to override common Android use cases, you will have to find out which Accounts they are storing.

For this, try to find out how android.accounts is working. The SampleSyncAdapter deluivered with the SDK dev sample applications also is a good place to start.


问:
if this.somefield refers to the object say X that is initialized by "using" statement, will garbage collector makes X to be null in the future?
there is a c# class having some fields (p1,p2,p3)and in one of the method,
p1 gets initialized as

```<code>using(Object X = new Object()){
this.p1 = X ;
}
</code>```

After the closure of using block, anytime later Will X be collected by garbage collector and this.p1 becomes null because of that

OR

Because of the reference to X from this.p1 , will X never become null till application is killed?

答:
As long as you work in the same scope of X creation, X will never be elegible for collection.

As long as the object referred by this will be alive, X will never be elegible for collection, cause this.p1 is referring to X.

Body:
there is a c# class having some fields (p1,p2,p3)and in one of the method,
p1 gets initialized as

using(Object X = new Object()){
this.p1 = X ;
}

After the closure of using block, anytime later Will X be collected by garbage collector and this.p1 becomes null because of that

OR

Because of the reference to X from this.p1 , will X never become null till application is killed?


问:
Characters change from danish
In a SSIS-package i load alot of columns from one stagetable in a source system into another table in the Data Warehouse.
2 columns can contain the danish letters.
Name - varchar(200)
Address1 - varchar(100)
They both have code page 1252.
Name haas æøå changed to other chars but address1 works fine.
If i put a data viewer on the line exiting the Sourcecomponent it will show the changes already there. In preview on the sourcecomponent everything looks fine.
How do i fix this?

I have tried making a new package from ground.

I need the danish letters ÆØÅ in the outgoing result

答: I decided to cast the NAME column as nvarchar and then make a transformationtask that changed it back to varchar. That worked for some reason. But still not the solution i was hoping for.</p>

Title: Characters change from danish


问:
How should I handle "above the range (U+0000-U+FFFF) allowed by Tcl"?
It is a known problem of Tkinter/Tcl in Python3 that it only supports characters between U+0000-U+FFFF.

There are some solutions around parsing strings and replacing the not allowed characters with placeholders or codes. But I have to know that there is a disallowed character in before this make sense.

Do I really have to use this parsing-replacing-algorithms for every string I put in my Tkinter GUI? The essential point of my question is that I have data (webfeeds) I don't know. Do I have to parse this big amount of data only because one of some millions of this data pieces use unallowed characters?

Is there a pythonic way to solve this? Can I use parsing-replacing-algorithms without wasting too many resources?

```<code>#!/usr/bin/env python3

from tkinter import *

if __name__ == '__main__':
    root = Tk()

    l = Listbox(root)
    l.pack()

    d = ['A', 'B', u'\U0001F384', 'D']

    for s in d:
        l.insert(END, s)

    root.mainloop()
</code>```

答:
The first solution was really to parse such characters for myself and replace them.

The second and later solution was to switch to a different GUI toolkit. I am using Gtk (PyGObject) now.

Body:
It is a known problem of Tkinter/Tcl in Python3 that it only supports characters between U+0000-U+FFFF.

There are some solutions around parsing strings and replacing the not allowed characters with placeholders or codes. But I have to know that there is a disallowed character in before this make sense.

Do I really have to use this parsing-replacing-algorithms for every string I put in my Tkinter GUI? The essential point of my question is that I have data (webfeeds) I don't know. Do I have to parse this big amount of data only because one of some millions of this data pieces use unallowed characters?

Is there a pythonic way to solve this? Can I use parsing-replacing-algorithms without wasting too many resources?

#!/usr/bin/env python3

from tkinter import *

if __name__ == '__main__':
    root = Tk()

    l = Listbox(root)
    l.pack()

    d = ['A', 'B', u'\U0001F384', 'D']

    for s in d:
        l.insert(END, s)

    root.mainloop()


问:
How to extract anchor elements nested in multiple division elements
I am trying to extract anchor elements from my beautiful soup object with a common class attr each nested in multiple divisions. The divisions are repeated and separated with some scripts

I have tried to take advantage of the common class attrs in the anchor elements to extract them

The code I got:

```<code><div id='container'>
<div class='nested'>
<a href='some url' class='link'>
</a>
</div>
</div>

#some scripts ....

<div id='container'>
<div class='nested'>
<a href='some url' class='link'>
</a>
</div>
</div>
</code>```

What I tried:

```<code>import requests, bs4, webbrowser

webpage=requests.get('some url')
webpage.raise_for_status()
soup=bs4.BeautifulSoup(webpage.text)
links=soup.select('.link a')

for i in range(0,5):
  webrowser.open('intial site url'+links[i].get('href'))
print(links)
</code>```

No tabs were opened.Print links gave a blank list

答:
.link a will do all child a tags with parents having class link. The space between is actually a css descendant combinator which means the lhs is parent and rhs is child. Remove the space to apply to same element. Notice that you need to extract the href attribute from the matched tags.

```<code>links = [item['href'] for item in soup.select('a.link')]
</code>```

If you need to specify the parent div by class then it is

```<code>.nested a.link
</code>```

or more simply

```<code>.nested .link
</code>```

Body:
I am trying to extract anchor elements from my beautiful soup object with a common class attr each nested in multiple divisions. The divisions are repeated and separated with some scripts

I have tried to take advantage of the common class attrs in the anchor elements to extract them

The code I got:

#some scripts ....

What I tried:

import requests, bs4, webbrowser

webpage=requests.get('some url')
webpage.raise_for_status()
soup=bs4.BeautifulSoup(webpage.text)
links=soup.select('.link a')

for i in range(0,5):
  webrowser.open('intial site url'+links[i].get('href'))
print(links)

No tabs were opened.Print links gave a blank list

Body:
.link a will do all child a tags with parents having class link. The space between is actually a css descendant combinator which means the lhs is parent and rhs is child. Remove the space to apply to same element. Notice that you need to extract the href attribute from the matched tags.

links = [item['href'] for item in soup.select('a.link')]

If you need to specify the parent div by class then it is

.nested a.link

or more simply

.nested .link


问:
ember assets - "public" assets should not be fingerprinted but they are?
In my Ember.js 3.8 project I have an image file in :

/public/assets/images/foo.png

... According to this (admittedly a little out of date) files put in public/assets/images should be available unchanged when referenced as assets/images.

This is up to date, a little less explicit but says that items placed beneath public will end up beneath assets.

When I do a production build the file I have in /public/assets/images/ ends up /dist/assets/images/ but with a finger print, eg foo-97cf8c0765aefa517d22e1fc71f43d6e.png.

Am I meant to explicitly suppress the finger-printing ? The doco seems to suggest that's not necessary ?

答:
You can disable fingerprint in your ember-cli-build.js, fingerprinting is enabled by default if current environment is production.

```<code>// ember-cli-build.js

const EmberApp = require('ember-cli/lib/broccoli/ember-app');

module.exports = function(defaults) {
  let app = new EmberApp({
    fingerprint: {
      enabled: false
    }
  });

  //...
  return app.toTree();
};
</code>```

More information you can find by this link

Body:
You can disable fingerprint in your ember-cli-build.js, fingerprinting is enabled by default if current environment is production.

// ember-cli-build.js

const EmberApp = require('ember-cli/lib/broccoli/ember-app');

module.exports = function(defaults) {
  let app = new EmberApp({
    fingerprint: {
      enabled: false
    }
  });

  //...
  return app.toTree();
};

More information you can find by this link


问:
Is there anyway passing variable from C# to javascript "dynamically"?
I want to send a variable from C# to Javascript dynamic.

I have tried the following code down below.

But the method or the variable will only read once.

How can I make it work ?

in aspx.cs

```<code>    public partial class WebForm2 : System.Web.UI.Page
    {
        internal static string timer = "false";

        protected void Page_Load(object sender, EventArgs e)
        {

        }
        public string MyMethod()
        {
            return timer;
        }
    }
</code>```

in aspx

```<code><script>
    function GetMyName()
    {
        setInterval(function() {
            dynamic xx = "<%=MyMethod()%>";
            console.log(xx);
        }, 1000);
    }
</script>
</code>```

答:
Just create a property for your MyMethod()

```<code>protected string MyMethod { get { return timer; } }
</code>```

Then in JS

```<code><script>
function GetMyName()
{
    setInterval(function() {
        dynamic xx = "<%=MyMethod%>";
        console.log(xx);
    }, 1000);
}
</code>```

Body:
I want to send a variable from C# to Javascript dynamic.

I have tried the following code down below.

But the method or the variable will only read once.

How can I make it work ?

in aspx.cs

    public partial class WebForm2 : System.Web.UI.Page
    {
        internal static string timer = "false";

        protected void Page_Load(object sender, EventArgs e)
        {

        }
        public string MyMethod()
        {
            return timer;
        }
    }

in aspx

Body:
Just create a property for your MyMethod()

protected string MyMethod { get { return timer; } }

Then in JS

<script>
function GetMyName()
{
    setInterval(function() {
        dynamic xx = "<%=MyMethod%>";
        console.log(xx);
    }, 1000);
}


答:
Take a look at these ember-cli docs, specifically:

When the environment is production (e.g. ember build
  --environment=production), the addon will automatically fingerprint your js, css, png, jpg, and gif assets by appending an md5 checksum to
  the end of their filename (e.g.
  assets/yourapp-9c2cbd818d09a4a742406c6cb8219b3b.js). In addition, your
  html, js, and css files will be re-written to include the new name.
  There are a few options you can pass in to EmberApp in your
  ember-cli-build.js to customize this behavior.

From a fingerprinting perspective, it makes sense to fingerprint even your images, since you may need to change them and do not want to have to wait until cache TTLs expire.

You can remove specific files as such

```<code>fingerprint: {
  exclude: ['assets/images/user.png']
}
</code>```

or whole file extensions

```<code>fingerprint:{
  extensions: ['js', 'css', /* all the extensions you do want excluding image ones */]
}
</code>```

Title: ember assets - "public" assets should not be fingerprinted but they are?

Body:
In my Ember.js 3.8 project I have an image file in :

/public/assets/images/foo.png

... According to this (admittedly a little out of date) files put in public/assets/images should be available unchanged when referenced as assets/images.

This is up to date, a little less explicit but says that items placed beneath public will end up beneath assets.

When I do a production build the file I have in /public/assets/images/ ends up /dist/assets/images/ but with a finger print, eg foo-97cf8c0765aefa517d22e1fc71f43d6e.png.

Am I meant to explicitly suppress the finger-printing ? The doco seems to suggest that's not necessary ?

Body:
Take a look at these ember-cli docs, specifically:

When the environment is production (e.g. ember build
  --environment=production), the addon will automatically fingerprint your js, css, png, jpg, and gif assets by appending an md5 checksum to
  the end of their filename (e.g.
  assets/yourapp-9c2cbd818d09a4a742406c6cb8219b3b.js). In addition, your
  html, js, and css files will be re-written to include the new name.
  There are a few options you can pass in to EmberApp in your
  ember-cli-build.js to customize this behavior.

From a fingerprinting perspective, it makes sense to fingerprint even your images, since you may need to change them and do not want to have to wait until cache TTLs expire.

You can remove specific files as such

fingerprint: {
  exclude: ['assets/images/user.png']
}

or whole file extensions

fingerprint:{
  extensions: ['js', 'css', /* all the extensions you do want excluding image ones */]
}


问:
Prevent 3rd party libraries to get my push notifications
My app is implementing FCM as so as a 3rd party library I use. My Problem is every time I send a notification through the console the 3rd Party has a broadcast receiver registered like this

```<code>    <receiver
        android:name=".ThirdPartyReceiver"
        android:exported="true"
        android:permission="com.google.android.c2dm.permission.SEND" >
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        </intent-filter>
    </receiver>
</code>```

that is able to get the content of all my notifications, how I can prevent this? atm I'm initializing and using an instance of firebase app using my credentials like this:

```<code>FirebaseOptions.Builder()
        .setApplicationId(id)
        .setApiKey(api)
        .setDatabaseUrl(databaseurl)
        .setGcmSenderId(senderId)
        .setProjectId(projectId)
        .build()
</code>```

But looks like FCM only rely on the packageName to deliver push notifications and any third-party library contained in my project can register to get the push notifications, is there a way to prevent this?

Observation, manually disabling all unknown receivers prevents this, but then the library doesn't get the notifications anymore and I break its functionality.

答:
One way of doing it is giving highest priority (Max 1000) to your receiver and use  abortBroadcast(); to stop it from forwarding to next receiver but you need correct permission added in your AndroidManifest.xml

Above code will be absolute soon don't use broadcast receiver. Read bellow link.

https://developers.google.com/cloud-messaging/android/client

Now you have to migrate to new mechanism. Follow this link for migration.

https://developers.google.com/cloud-messaging/android/android-migrate-fcm

Body:
My app is implementing FCM as so as a 3rd party library I use. My Problem is every time I send a notification through the console the 3rd Party has a broadcast receiver registered like this

    <receiver
        android:name=".ThirdPartyReceiver"
        android:exported="true"
        android:permission="com.google.android.c2dm.permission.SEND" >
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        </intent-filter>
    </receiver>

that is able to get the content of all my notifications, how I can prevent this? atm I'm initializing and using an instance of firebase app using my credentials like this:

FirebaseOptions.Builder()
        .setApplicationId(id)
        .setApiKey(api)
        .setDatabaseUrl(databaseurl)
        .setGcmSenderId(senderId)
        .setProjectId(projectId)
        .build()

But looks like FCM only rely on the packageName to deliver push notifications and any third-party library contained in my project can register to get the push notifications, is there a way to prevent this?

Observation, manually disabling all unknown receivers prevents this, but then the library doesn't get the notifications anymore and I break its functionality.


问:
Getting the sum of several comboboxes value into a single textbox
A simple Point of Sale system, that shows 2 product: Apple and Banana each price of 10.  I need to have a display of the total sum.

I used cmbApple_Change() event
I used if elseif statement

I was able to get the result only for 1 combobox.

```<code>Private Sub cmbApple_Change()

If cmbApple.Value = 0 Then
    txtTotal.Text = 0
ElseIf cmbApple.Value = 1 Then
    txtTotal.Text = 10
ElseIf cmbApple.Value = 2 Then
    txtTotal.Text = 20
ElseIf cmbApple.Value = 3 Then
    txtTotal.Text = 30
End If

End Sub
</code>```

Error:

答:
This way you will always have the total value:

```<code>Private Sub cmbApple_Change()

    Dim BananaItems As Byte
    Dim AppleItems As Byte

    On Error Resume Next
    AppleItems = cmbApple.Value
    BananaItems = cmbBanana.Value
    On Error GoTo 0

    TxtTotal.Text = AppleItems * 10 + BananaItems * 10

End Sub
Private Sub cmbBanana_Change()

    Dim BananaItems As Byte
    Dim AppleItems As Byte

    On Error Resume Next
    AppleItems = cmbApple.Value
    BananaItems = cmbBanana.Value
    On Error GoTo 0

    TxtTotal.Text = AppleItems * 10 + BananaItems * 10

End Sub
Private Sub UserForm_Initialize()

    Dim i As Byte

    With cmbApple
        For i = 0 To 5
            .AddItem (i)
        Next i
    End With
    With cmbBanana
        For i = 0 To 5
            .AddItem (i)
        Next i
    End With

End Sub
</code>```

It is simple, but works for your example. In case you need to change the price often there are other ways.

Edit: Check the edited answer, also changed your code to add items, you can change the For i = 0 to 5 to any number you want (max 256)

Body:
A simple Point of Sale system, that shows 2 product: Apple and Banana each price of 10.  I need to have a display of the total sum.

I used cmbApple_Change() event
I used if elseif statement

I was able to get the result only for 1 combobox.

Private Sub cmbApple_Change()

If cmbApple.Value = 0 Then
    txtTotal.Text = 0
ElseIf cmbApple.Value = 1 Then
    txtTotal.Text = 10
ElseIf cmbApple.Value = 2 Then
    txtTotal.Text = 20
ElseIf cmbApple.Value = 3 Then
    txtTotal.Text = 30
End If

End Sub

Error:

Body:
This way you will always have the total value:

Private Sub cmbApple_Change()

    Dim BananaItems As Byte
    Dim AppleItems As Byte

    On Error Resume Next
    AppleItems = cmbApple.Value
    BananaItems = cmbBanana.Value
    On Error GoTo 0

    TxtTotal.Text = AppleItems * 10 + BananaItems * 10

End Sub
Private Sub cmbBanana_Change()

    Dim BananaItems As Byte
    Dim AppleItems As Byte

    On Error Resume Next
    AppleItems = cmbApple.Value
    BananaItems = cmbBanana.Value
    On Error GoTo 0

    TxtTotal.Text = AppleItems * 10 + BananaItems * 10

End Sub
Private Sub UserForm_Initialize()

    Dim i As Byte

    With cmbApple
        For i = 0 To 5
            .AddItem (i)
        Next i
    End With
    With cmbBanana
        For i = 0 To 5
            .AddItem (i)
        Next i
    End With

End Sub

It is simple, but works for your example. In case you need to change the price often there are other ways.

Edit: Check the edited answer, also changed your code to add items, you can change the For i = 0 to 5 to any number you want (max 256)


问:
CryptoNG: Exporting RSA key with BCryptExportKey fails with STATUS_INVALID_HANDLE
Using the Cryptography Next Generation API (aka CryptoAPI Next Generation, aka CryptoNG, aka Cng, aka BestCrypt, aka bcrypt), i'm trying to export a newly generated RSA private key pair:

Edit: Shorter code version:

```<code>BCRYPT_ALG_HANDLE alg;
BCryptOpenAlgorithmProvider(out alg, BCRYPT_RSA_ALGORITHM, null, 0);

BCRYPT_KEY_HANDLE key;
BCryptGenerateKeyPair(alg, out key, 4096, 0);

DWORD cbResult;
BCryptExportKey(key, 0, BCRYPT_RSAFULLPRIVATE_BLOB, null, 0, out cbResult, 0);
</code>```

Longer code version:

```<code>NTSTATUS nt;

// Open the RSA algorithm provider
BCRYPT_ALG_HANDLE alg;
nt = BCryptOpenAlgorithmProvider(out alg, BCRYPT_RSA_ALGORITHM, null, 0);
NTStatusCheck(nt);
      // Successfully opened the RSA algorithm provider

// Generate a 4096 bit RSA public-private key pair
BCRYPT_KEY_HANDLE key;
nt = BCryptGenerateKeyPair(alg, out key, 4096, 0);
NTStatusCheck(nt);
      // Successfully generates a key pair (key <-- $4E737A0)

// Ask for the buffer size required to export the key pair
DWORD cbResult;
nt = BCryptExportKey(key, 0, BCRYPT_RSAFULLPRIVATE_BLOB, null, 0, out cbResult, 0);
NTStatusCheck(nt);
      // Fails with 0xC0000008 (STATUS_INVALID_HANDLE)
</code>```

What am I doing wrong?

Bonus Reading

MSDN: BCryptGenerateKeyPair function

MSDN: BCryptExportKey function

Complete minimal example (Delphi)

```<code>program Project1;

{$APPTYPE CONSOLE}

uses
  SysUtils, Windows, ComObj, ActiveX;

type
  NTSTATUS = Cardinal;
const
    BCRYPT_RSA_ALGORITHM:       WideString = 'RSA';
  BCRYPT_RSAFULLPRIVATE_BLOB: WideString = 'RSAFULLPRIVATEBLOB';
  BCRYPT_RSAPRIVATE_BLOB:     WideString = 'RSAPRIVATEBLOB';
  BCRYPT_RSAPUBLIC_BLOB:      WideString = 'RSAPUBLICBLOB';
  LEGACY_RSAPRIVATE_BLOB:     WideString = 'CAPIPRIVATEBLOB';
  LEGACY_RSAPUBLIC_BLOB:      WideString = 'CAPIPUBLICBLOB';

function BCryptOpenAlgorithmProvider(out hAlgorithm: THandle; pszAlgId, pszImplementation: PWideChar; dwFlags: Cardinal): NTSTATUS; stdcall; external 'bcrypt.dll';
function BCryptGenerateKeyPair(hAlgorithm: THandle; out phKey: THandle; dwLength: Cardinal; dwFlags: Cardinal): NTSTATUS; stdcall; external 'bcrypt.dll';
function BCryptExportKey(hKey: THandle; hExportKey: THandle; pszBlobType: PWideChar; pbOutput: Pointer; cbOutput: Cardinal; out pcbResult: Cardinal; dwFlags: Cardinal): NTSTATUS; stdcall; external 'bcrypt.dll';

procedure Main;
var
  nt: Cardinal;
  alg: THandle;
  key: THandle;
  cbResult: Cardinal;
begin
  // Open the RSA algorithm provider
  WriteLn('Opening algorithm provider');
  nt := BCryptOpenAlgorithmProvider({out} alg, PWideChar(BCRYPT_RSA_ALGORITHM), nil, 0);
  OleCheck(HRESULT(nt));

  // Generate a RSA public-private key pair
  WriteLn('Generating key pair');
  key := 0;
  nt := BCryptGenerateKeyPair(alg, {out} key, 1024, 0);
  OleCheck(HRESULT(nt));

  // Ask for the buffer size required to export the key pair
  WriteLn('Exporting full private blob');
  cbResult := 0;
  nt := BCryptExportKey(key, 0, PWideChar(BCRYPT_RSAFULLPRIVATE_BLOB), nil, 0, {out} cbResult, 0);
  OleCheck(HRESULT(nt));

  WriteLn('Success');
end;

begin
    Main;
  WriteLn('Press enter to close...');
  ReadLn;
end.
</code>```

Complete Minimal Example (C#)

```<code>using System;
using System.Runtime.InteropServices;

namespace ConsoleApp1
{
    class Program
    {
        [DllImport("bcrypt.dll", CharSet = CharSet.Unicode)]
        internal static extern Int32 BCryptOpenAlgorithmProvider(out IntPtr phAlgorithm, [In] string pszAlgId, [In] string pszImplementation, [In] int dwFlags);

        [DllImport("bcrypt.dll")]
        internal static extern Int32 BCryptGenerateKeyPair([In] IntPtr hAlgorithm, out IntPtr phKey, [In] UInt32 dwLength, [In] UInt32 dwFlags);

        [DllImport("bcrypt.dll", CharSet = CharSet.Unicode)]
        internal static extern Int32 BCryptExportKey([In] IntPtr hKey, [In] IntPtr hExportKey, [MarshalAs(UnmanagedType.LPWStr)] [In] string pszBlobType, [MarshalAs(UnmanagedType.LPArray)] [Out] byte[] pbOutput, [In] int cbOutput, [In] ref UInt32 cbResult, [In] int dwFlags);

        static void Main(string[] args)
        {
            Int32 nt;

            IntPtr alg;
            nt = BCryptOpenAlgorithmProvider(out alg, "RSA", null, 0);
            if (nt < 0)
                throw new COMException("Open algorithm", (int)nt);

            IntPtr key;
            nt = BCryptGenerateKeyPair(alg, out key, 1024, 0);
            if (nt < 0)
                throw new COMException("Generate key", nt);

            UInt32 cbResult = 0;
            nt = BCryptExportKey(key, IntPtr.Zero, "RSAPRIVATEBLOB", null, 0, ref cbResult, 0);
            if (nt < 0)
                throw new COMException("Export", nt);
        }
    }
}
</code>```

答:
After BCryptGenerateKeyPair you should call BCryptFinalizeKeyPair. Before BCryptFinalizeKeyPair key pair doesn't actually exist.

After you create a key by using this function, [...] the key cannot be used until the BCryptFinalizeKeyPair function is called.

So:

```<code>BCRYPT_ALG_HANDLE alg;
BCryptOpenAlgorithmProvider(out alg, BCRYPT_RSA_ALGORITHM, null, 0);

BCRYPT_KEY_HANDLE key;
BCryptGenerateKeyPair(alg, out key, 4096, 0);

BCryptFinalizeKeyPair(key, 0); //finalize the key so we can use it

DWORD cbResult;
BCryptExportKey(key, 0, BCRYPT_RSAFULLPRIVATE_BLOB, null, 0, out cbResult, 0);
</code>```

Body:
Using the Cryptography Next Generation API (aka CryptoAPI Next Generation, aka CryptoNG, aka Cng, aka BestCrypt, aka bcrypt), i'm trying to export a newly generated RSA private key pair:

Edit: Shorter code version:

BCRYPT_ALG_HANDLE alg;
BCryptOpenAlgorithmProvider(out alg, BCRYPT_RSA_ALGORITHM, null, 0);

BCRYPT_KEY_HANDLE key;
BCryptGenerateKeyPair(alg, out key, 4096, 0);

DWORD cbResult;
BCryptExportKey(key, 0, BCRYPT_RSAFULLPRIVATE_BLOB, null, 0, out cbResult, 0);

Longer code version:

NTSTATUS nt;

// Open the RSA algorithm provider
BCRYPT_ALG_HANDLE alg;
nt = BCryptOpenAlgorithmProvider(out alg, BCRYPT_RSA_ALGORITHM, null, 0);
NTStatusCheck(nt);
      // Successfully opened the RSA algorithm provider

// Generate a 4096 bit RSA public-private key pair
BCRYPT_KEY_HANDLE key;
nt = BCryptGenerateKeyPair(alg, out key, 4096, 0);
NTStatusCheck(nt);
      // Successfully generates a key pair (key <-- $4E737A0)

// Ask for the buffer size required to export the key pair
DWORD cbResult;
nt = BCryptExportKey(key, 0, BCRYPT_RSAFULLPRIVATE_BLOB, null, 0, out cbResult, 0);
NTStatusCheck(nt);
      // Fails with 0xC0000008 (STATUS_INVALID_HANDLE)

What am I doing wrong?

Bonus Reading

MSDN: BCryptGenerateKeyPair function

MSDN: BCryptExportKey function

Complete minimal example (Delphi)

program Project1;

{$APPTYPE CONSOLE}

uses
  SysUtils, Windows, ComObj, ActiveX;

type
  NTSTATUS = Cardinal;
const
    BCRYPT_RSA_ALGORITHM:       WideString = 'RSA';
  BCRYPT_RSAFULLPRIVATE_BLOB: WideString = 'RSAFULLPRIVATEBLOB';
  BCRYPT_RSAPRIVATE_BLOB:     WideString = 'RSAPRIVATEBLOB';
  BCRYPT_RSAPUBLIC_BLOB:      WideString = 'RSAPUBLICBLOB';
  LEGACY_RSAPRIVATE_BLOB:     WideString = 'CAPIPRIVATEBLOB';
  LEGACY_RSAPUBLIC_BLOB:      WideString = 'CAPIPUBLICBLOB';

function BCryptOpenAlgorithmProvider(out hAlgorithm: THandle; pszAlgId, pszImplementation: PWideChar; dwFlags: Cardinal): NTSTATUS; stdcall; external 'bcrypt.dll';
function BCryptGenerateKeyPair(hAlgorithm: THandle; out phKey: THandle; dwLength: Cardinal; dwFlags: Cardinal): NTSTATUS; stdcall; external 'bcrypt.dll';
function BCryptExportKey(hKey: THandle; hExportKey: THandle; pszBlobType: PWideChar; pbOutput: Pointer; cbOutput: Cardinal; out pcbResult: Cardinal; dwFlags: Cardinal): NTSTATUS; stdcall; external 'bcrypt.dll';

procedure Main;
var
  nt: Cardinal;
  alg: THandle;
  key: THandle;
  cbResult: Cardinal;
begin
  // Open the RSA algorithm provider
  WriteLn('Opening algorithm provider');
  nt := BCryptOpenAlgorithmProvider({out} alg, PWideChar(BCRYPT_RSA_ALGORITHM), nil, 0);
  OleCheck(HRESULT(nt));

  // Generate a RSA public-private key pair
  WriteLn('Generating key pair');
  key := 0;
  nt := BCryptGenerateKeyPair(alg, {out} key, 1024, 0);
  OleCheck(HRESULT(nt));

  // Ask for the buffer size required to export the key pair
  WriteLn('Exporting full private blob');
  cbResult := 0;
  nt := BCryptExportKey(key, 0, PWideChar(BCRYPT_RSAFULLPRIVATE_BLOB), nil, 0, {out} cbResult, 0);
  OleCheck(HRESULT(nt));

  WriteLn('Success');
end;

begin
    Main;
  WriteLn('Press enter to close...');
  ReadLn;
end.

Complete Minimal Example (C#)

using System;
using System.Runtime.InteropServices;

namespace ConsoleApp1
{
    class Program
    {
        [DllImport("bcrypt.dll", CharSet = CharSet.Unicode)]
        internal static extern Int32 BCryptOpenAlgorithmProvider(out IntPtr phAlgorithm, [In] string pszAlgId, [In] string pszImplementation, [In] int dwFlags);

        [DllImport("bcrypt.dll")]
        internal static extern Int32 BCryptGenerateKeyPair([In] IntPtr hAlgorithm, out IntPtr phKey, [In] UInt32 dwLength, [In] UInt32 dwFlags);

        [DllImport("bcrypt.dll", CharSet = CharSet.Unicode)]
        internal static extern Int32 BCryptExportKey([In] IntPtr hKey, [In] IntPtr hExportKey, [MarshalAs(UnmanagedType.LPWStr)] [In] string pszBlobType, [MarshalAs(UnmanagedType.LPArray)] [Out] byte[] pbOutput, [In] int cbOutput, [In] ref UInt32 cbResult, [In] int dwFlags);

        static void Main(string[] args)
        {
            Int32 nt;

            IntPtr alg;
            nt = BCryptOpenAlgorithmProvider(out alg, "RSA", null, 0);
            if (nt < 0)
                throw new COMException("Open algorithm", (int)nt);

            IntPtr key;
            nt = BCryptGenerateKeyPair(alg, out key, 1024, 0);
            if (nt < 0)
                throw new COMException("Generate key", nt);

            UInt32 cbResult = 0;
            nt = BCryptExportKey(key, IntPtr.Zero, "RSAPRIVATEBLOB", null, 0, ref cbResult, 0);
            if (nt < 0)
                throw new COMException("Export", nt);
        }
    }
}

Body:
After BCryptGenerateKeyPair you should call BCryptFinalizeKeyPair. Before BCryptFinalizeKeyPair key pair doesn't actually exist.

After you create a key by using this function, [...] the key cannot be used until the BCryptFinalizeKeyPair function is called.

So:

BCRYPT_ALG_HANDLE alg;
BCryptOpenAlgorithmProvider(out alg, BCRYPT_RSA_ALGORITHM, null, 0);

BCRYPT_KEY_HANDLE key;
BCryptGenerateKeyPair(alg, out key, 4096, 0);

BCryptFinalizeKeyPair(key, 0); //finalize the key so we can use it

DWORD cbResult;
BCryptExportKey(key, 0, BCRYPT_RSAFULLPRIVATE_BLOB, null, 0, out cbResult, 0);


问:
in ASP.NET MVC3 how can I see the request?
I'm using a simple route as

```<code>routes.MapRoute(
    "Default2", // Route name
    "{cliurl}/{id}", // URL with parameters
    new { cliurl = "none", controller = "ABook", action = "Index", id = "none" } // Parameter defaults
);

routes.MapRoute(
    "Default", // Route name
    "{cliurl}/{controller}/{action}/{id}", // URL with parameters
    new { cliurl = "none", controller = "ABook", action = "Index", id = "none" } // Parameter defaults
);
</code>```

and when I debug the website (VS2010 SP1), I have a breakpoint in my ABook Controller, inside the Index action method witch contains only:

```<code>//
// GET: /ABook/
public ActionResult Index()
{
    if (currentClient == null)
        return RedirectToAction("Empty");

    return View();
}

//
// GET: /Empty/
public ActionResult Empty()
{
    return View();
}
</code>```

The thing is that, when I insert this in the browser:

```<code>http://localhost:14951/client_name/hashed_id
</code>```

I get 3 breaks in that breakpoint.

How can I see what in the world is going on? why 3 times when I just requested 1, what is exactly the browser requesting?

I can only get the Route Parameters and I do get the first correct, but 2nd and 3rd are using the default values, and I tried to navigate through the RequestContext and I can't see anything useful :(

Just want to know if there is a way to really see what's been requested.

答: You can use fiddler to see what the browser requests or you could try the routdebugger download from Nuget.

Body:
I'm using a simple route as

routes.MapRoute(
    "Default2", // Route name
    "{cliurl}/{id}", // URL with parameters
    new { cliurl = "none", controller = "ABook", action = "Index", id = "none" } // Parameter defaults
);

routes.MapRoute(
    "Default", // Route name
    "{cliurl}/{controller}/{action}/{id}", // URL with parameters
    new { cliurl = "none", controller = "ABook", action = "Index", id = "none" } // Parameter defaults
);

and when I debug the website (VS2010 SP1), I have a breakpoint in my ABook Controller, inside the Index action method witch contains only:

//
// GET: /ABook/
public ActionResult Index()
{
    if (currentClient == null)
        return RedirectToAction("Empty");

    return View();
}

//
// GET: /Empty/
public ActionResult Empty()
{
    return View();
}

The thing is that, when I insert this in the browser:

http://localhost:14951/client_name/hashed_id

I get 3 breaks in that breakpoint.

How can I see what in the world is going on? why 3 times when I just requested 1, what is exactly the browser requesting?

I can only get the Route Parameters and I do get the first correct, but 2nd and 3rd are using the default values, and I tried to navigate through the RequestContext and I can't see anything useful :(

Just want to know if there is a way to really see what's been requested.


问:
Removing the help icon from the homepage header servicenow
I just started with servicenow.
I am looking for the way to modify the header and hide the help icon, only for the homepage. Any suggestion or useful articles - much appreciated.</p>

答:
This Toggle Help Sidebar is added by a embedded help plugin.
  In order to hide it , you need to traverse through the sys_properties.list << com.glide.embedded_help.enabled << Set Value as false.
  logout and login back again with the new user session.

https://community.servicenow.com/community?id=community_question&sys_id=d0ac07e5db9cdbc01dcaf3231f96195c

If you want to hide it for a single page you can write a global UI script and hide the DOM element if the URL is the right one.


问:
Runing a "child" python file as regular user when main python file needs to be run as root
I'm doing a python program (and using PyQt5 for GUI) that needs to be run as root (because I'm programming sockets on it). It has a button,when I click on it, it opens another python file (the "child" file: chrometest.py, it's based on this library, eel: https://www.youtube.com/watch?v=2kbeBzEQfXE, it lets me open a js file). The problem is that eel won't work when it's run as root, so I don't know how I could switch users to run only this function as regular user.

Main python program (sample, the one runing as root)

```<code>import os
import sys
from PyQt5 import QtCore, QtGui, QtWidgets

class Window(QtWidgets.QMainWindow):
    def __init__(self, *args):
        super(Window, self).__init__()
        self.img = QtWidgets.QLabel()
        self.open_js= QtWidgets.QPushButton('Load')
        self.width = 400
        self.height = 150
        self.init_ui()

    def init_ui(self):
        self.img.setPixmap(QtGui.QPixmap("someimage.png"))
        self.open_js.clicked.connect(self.openjs)
        central_widget = QtWidgets.QWidget()
        self.setCentralWidget(central_widget)
        h_layout = QtWidgets.QHBoxLayout(central_widget)
        h_layout.addWidget(self.img)
        h_layout.addWidget(self.open_js)
        self.setWindowTitle('Main Window')
        self.setGeometry(600,150,self.width,self.height)

    def openjs(self):
        #here is where I think I need to switch to regular user
        exec(open("chrometest.py").read())

def main():
    app = QtWidgets.QApplication(sys.argv)
    main = Window()
    main.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
</code>```

chrometest.py (program that needs to be run as regular user)

```<code>import eel
eel.init('webfiles')
eel.start('index.html')
</code>```

I tried to use this tutorial https://www.tutorialspoint.com/python/os_chown.htm in the line commented but it didn't work

答:
Like Mani Kandan said, you can run process by os.system, but if you already working under root, it will be executed with same privileges.

You can run program under specified user using sudo -u or sudo --user argument like

sudo -u regular_user "python3 chrometest.py"

So, in Python it will look like:

```<code>import os
os.system('sudo -u regular_user python3 chrometest.py')
</code>```

and about your TabError: inconsistent use of tabs and spaces in indentation error: change all tabs in your script to spaces or vice versa.

Body:
I'm doing a python program (and using PyQt5 for GUI) that needs to be run as root (because I'm programming sockets on it). It has a button,when I click on it, it opens another python file (the "child" file: chrometest.py, it's based on this library, eel: https://www.youtube.com/watch?v=2kbeBzEQfXE, it lets me open a js file). The problem is that eel won't work when it's run as root, so I don't know how I could switch users to run only this function as regular user.

Main python program (sample, the one runing as root)

import os
import sys
from PyQt5 import QtCore, QtGui, QtWidgets

class Window(QtWidgets.QMainWindow):
    def __init__(self, *args):
        super(Window, self).__init__()
        self.img = QtWidgets.QLabel()
        self.open_js= QtWidgets.QPushButton('Load')
        self.width = 400
        self.height = 150
        self.init_ui()

    def init_ui(self):
        self.img.setPixmap(QtGui.QPixmap("someimage.png"))
        self.open_js.clicked.connect(self.openjs)
        central_widget = QtWidgets.QWidget()
        self.setCentralWidget(central_widget)
        h_layout = QtWidgets.QHBoxLayout(central_widget)
        h_layout.addWidget(self.img)
        h_layout.addWidget(self.open_js)
        self.setWindowTitle('Main Window')
        self.setGeometry(600,150,self.width,self.height)

    def openjs(self):
        #here is where I think I need to switch to regular user
        exec(open("chrometest.py").read())

def main():
    app = QtWidgets.QApplication(sys.argv)
    main = Window()
    main.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

chrometest.py (program that needs to be run as regular user)

import eel
eel.init('webfiles')
eel.start('index.html')

I tried to use this tutorial https://www.tutorialspoint.com/python/os_chown.htm in the line commented but it didn't work

Body:
Like Mani Kandan said, you can run process by os.system, but if you already working under root, it will be executed with same privileges.

You can run program under specified user using sudo -u or sudo --user argument like

sudo -u regular_user "python3 chrometest.py"

So, in Python it will look like:

import os
os.system('sudo -u regular_user python3 chrometest.py')

and about your TabError: inconsistent use of tabs and spaces in indentation error: change all tabs in your script to spaces or vice versa.


问:
Xamarin forms splash screen with lottie animation
Is it possible to have a lottie animation when the splash screen is launched?

any examples out there on xamarin?

thanks

答:
No, it's impossible on iOS. The launch screen on iOS only accepts the static image and we can't add any code behind to adjust its display.

If you want to implement it on Xamarin. I recommend you to use a splash page as the App's MainPage first. Place your animation there. Then change the App's MainPage to your first page after the animation has finished.


问:
woocommerce hook add to cart button and save custom fields
I first followed the guideline to override the single product page by creating a woocommerce folder in my theme root, then created a single.product.php, and inside this file, I added the following:

```<code><div class="product-content flex">
    <figure class="thumbnail">
        <?php the_post_thumbnail(); ?>
    </figure>
    <main id="product-content">
        <h1><?php the_title(); ?></h1>
        <p>R <?php echo get_post_meta( get_the_ID(), '_regular_price', true); ?></p>
        <div class="description">
            <?php the_content();  ?>
        </div>
        <div class="flex size">
            <span>Product size</span>
            <select name="product_size" id="product_size">
                <option value="small">Small</option>
                <option value="medium">Medium</option>
                <option value="large">Large</option>
            </select>
        </div>
        <div class="flex quantity">
            <span>Quantity</span>
            <input type="number" name="quanitity" id="product_quantity">
        </div>
    </main>
</div>
</code>```

First: how can I now hook up the add to cart button?
Lastly, after hooking the add to cart, how can I save the size and quantity?

答: Why not use default woocommerce variable product - Variable Product?</p>

Body:
I first followed the guideline to override the single product page by creating a woocommerce folder in my theme root, then created a single.product.php, and inside this file, I added the following:

        <?php the_post_thumbnail(); ?>

<?php the_title(); ?>

R <?php echo get_post_meta( get_the_ID(), '_regular_price', true); ?>

            <?php the_content();  ?>

            Product size
            <select name="product_size" id="product_size">
                <option value="small">Small</option>
                <option value="medium">Medium</option>
                <option value="large">Large</option>
            </select>

            Quantity
            <input type="number" name="quanitity" id="product_quantity">

First: how can I now hook up the add to cart button?
Lastly, after hooking the add to cart, how can I save the size and quantity?


问:
Run Clojure GraalVM native image on AWS Lambda custom runtime
Is there an easy way to deploy a Clojure application compiled with GraalVM native-image tool to AWS Lambda custom runtime?

答:
There is a Leiningen template that could help with this problem.

Example:

```<code>lein new clojure-graalvm-aws-lambda your-lambda
cd your-lambda
make deploy-lambda-via-container
</code>```

This example assumes that you have make and Docker installed in your system.

Note that the generated project is not a Leiningen project but a tools-deps project.

Body:
There is a Leiningen template that could help with this problem.

Example:

lein new clojure-graalvm-aws-lambda your-lambda
cd your-lambda
make deploy-lambda-via-container

This example assumes that you have make and Docker installed in your system.

Note that the generated project is not a Leiningen project but a tools-deps project.


问:
Why is my .htaccess www. force causing external forms to fail without www.?
Because of strange cross domain AJAX problems, causing AJAX requests to fail when not using www.(the PHP handler communicating with the request is given in a relative path, so it can't be an address issue or something - that's what this question is about though), I have forced www. using .htaccess :

```<code>#enable rewrite engine and set options
Options +FollowSymLinks
RewriteEngine on

#only www.
RewriteCond %{HTTP_HOST} !^www.domain.com$
RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301]
</code>```

This works great. However, I want to allow other webmasters to post one of my forms on their website, using my form URL in their form's action attribute. This always worked, however after my .htaccess change the forms are only submitted when the webmaster adds www. to the action value. Without www. the form will not get submitted.

How should I change my .htaccess file to make sure that these forms are also submitted without www.?

答:
Most browsers don't forward POSTed data when 301 Redirected... So you will see those requests as a GET of your action url instead.

This behaviour is technically non-compliant but seems to be the commonly accepted approach.

(c.f. http://www.lassosoft.com/Documentation/TotW/index.lasso?9083, http://www.nkuttler.de/2008/11/09/mailman-and-301-redirects/.)

Maybe try 307 Temporary Redirects for your forms? 307 specifically instructs the browser to re-POST the data. http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#3xx_Redirection

OwnerDisplayName: Tom

Body:
Because of strange cross domain AJAX problems, causing AJAX requests to fail when not using www.(the PHP handler communicating with the request is given in a relative path, so it can't be an address issue or something - that's what this question is about though), I have forced www. using .htaccess :

#enable rewrite engine and set options
Options +FollowSymLinks
RewriteEngine on

#only www.
RewriteCond %{HTTP_HOST} !^www.domain.com$
RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301]

This works great. However, I want to allow other webmasters to post one of my forms on their website, using my form URL in their form's action attribute. This always worked, however after my .htaccess change the forms are only submitted when the webmaster adds www. to the action value. Without www. the form will not get submitted.

How should I change my .htaccess file to make sure that these forms are also submitted without www.?

OwnerDisplayName: Stobor


问:
How can I properly load A page or A div automatically?
I'm creating A simple queuing system, right now when ever I click my button called BtnNxt() it will dequeue my enqueued data and render it to my page. and it also render from another page. which is my call screen page, but when I click it again my call screen page needs to be refresh to update the current number from my queue. so what I want is , Ithink i need to refresh my page or maybe my div to update it?

Here is my BtnNext() controller :

```<code>   public ActionResult BtnNext()
    {
        System.Threading.Thread.Sleep(500);
        var first = MyQueue.todayQueue.Dequeue();
        MyQueue.todayQueue.Count();
        TempData["QueueItem"] = first;
        TempData.Keep();
        return PartialView("_queuenumber");
    }
</code>```

and here is my callscreen page:

```<code>@{
    var item = (Rosh.QueueMe.Web.Models.MyQueue)TempData["QueueItem"];
}
<table>
    <tr>
        <th scope="tickets">TICKETS</th>
        <th scope="name">NAME</th>
        <th scope="counter">COUNTER</th>
        <th scope="service">SERVICE</th>
    </tr>
    <tr class="data">
        <td>#@item.QueueNumber</td>
        <td>@item.Name</td>
        <td>Desk 1</td>
        <td>@item.ServiceId</td>
    </tr>
</table>
</code>```

I tried to use this code

```<code><meta http-equiv="refresh" content="1" />
</code>```

this code refresh my page every 1 sec, but is it possible to just reload the div? maybe using ajax?

答: use asyn keyword both side server & client, add the spinner loaders to each and every div which you want to make automatically load. don't make any custom tread because sometime thread take more time but actually he didn't need more time for sleep, so best solution is make every controller ayns and caller must be asyn as well.</p>

Body:
I'm creating A simple queuing system, right now when ever I click my button called BtnNxt() it will dequeue my enqueued data and render it to my page. and it also render from another page. which is my call screen page, but when I click it again my call screen page needs to be refresh to update the current number from my queue. so what I want is , Ithink i need to refresh my page or maybe my div to update it?

Here is my BtnNext() controller :

   public ActionResult BtnNext()
    {
        System.Threading.Thread.Sleep(500);
        var first = MyQueue.todayQueue.Dequeue();
        MyQueue.todayQueue.Count();
        TempData["QueueItem"] = first;
        TempData.Keep();
        return PartialView("_queuenumber");
    }

and here is my callscreen page:

@{
    var item = (Rosh.QueueMe.Web.Models.MyQueue)TempData["QueueItem"];
}

        TICKETS
        NAME
        COUNTER
        SERVICE

        #@item.QueueNumber
        @item.Name
        Desk 1
        @item.ServiceId

I tried to use this code

<meta http-equiv="refresh" content="1" />

this code refresh my page every 1 sec, but is it possible to just reload the div? maybe using ajax?


问:
Use CASE THEN in SQL
I have three tables which I want to query in MySQL as follows:

Table Notes

```<code>id  | note
-------------------
1   | note 1
2   | note 2
</code>```

Table Indices

```<code>id  | name
-----------
1   | height
2   | weight
3   | other
</code>```

Table Detail

```<code>  note_id    |  indices_id |  value
-------------------------------------
    1        |     1       |   50
    1        |     2       |   60
    1        |     3       |   20
    2        |     1       |   40
    2        |     2       |   10
    2        |     3       |   50
</code>```

I need to query the result as follows:

```<code>  indices.name    |  note_id = 1 |  note_id = 2
------------------------------------------------
    height        |     50       |   40
    weight        |     60       |   10
    other         |     20       |   50
</code>```

I tried this query:

```<code>SELECT i.name,
(CASE WHEN d.note_id = 1 THEN d.value END) as Col2,
(CASE WHEN d.note_id = 2 THEN d.value END) as Col3
FROM notes n,indices i,detail d
WHERE n.id = d.note_id AND i.id = d.indices_id
GROUP BY i.name
</code>```

But Column Col3 result is null

Any help much appreciated! Thanks very much!

答:
You need to use an aggregation function so that you don't get random row data on Col2 and Col3. MAX will work as it will ignore NULL values when the note_id doesn't match. Also, you should use explicit JOIN syntax:

```<code>SELECT i.name,
       MAX(CASE WHEN d.note_id = 1 THEN d.value END) as Col2,
       MAX(CASE WHEN d.note_id = 2 THEN d.value END) as Col3
FROM notes n
JOIN detail d ON n.id = d.note_id
JOIN indices i ON i.id = d.indices_id
GROUP BY i.name
</code>```

Output:

```<code>name    Col2    Col3
height  50      40
other   20      50
weight  60      10
</code>```

Demo on dbfiddle

Title: Use CASE THEN in SQL

Body:
I have three tables which I want to query in MySQL as follows:

Table Notes

id  | note
-------------------
1   | note 1
2   | note 2

Table Indices

id  | name
-----------
1   | height
2   | weight
3   | other

Table Detail

  note_id    |  indices_id |  value
-------------------------------------
    1        |     1       |   50
    1        |     2       |   60
    1        |     3       |   20
    2        |     1       |   40
    2        |     2       |   10
    2        |     3       |   50

I need to query the result as follows:

  indices.name    |  note_id = 1 |  note_id = 2
------------------------------------------------
    height        |     50       |   40
    weight        |     60       |   10
    other         |     20       |   50

I tried this query:

SELECT i.name,
(CASE WHEN d.note_id = 1 THEN d.value END) as Col2,
(CASE WHEN d.note_id = 2 THEN d.value END) as Col3
FROM notes n,indices i,detail d
WHERE n.id = d.note_id AND i.id = d.indices_id
GROUP BY i.name

But Column Col3 result is null

Any help much appreciated! Thanks very much!

Body:
You need to use an aggregation function so that you don't get random row data on Col2 and Col3. MAX will work as it will ignore NULL values when the note_id doesn't match. Also, you should use explicit JOIN syntax:

SELECT i.name,
       MAX(CASE WHEN d.note_id = 1 THEN d.value END) as Col2,
       MAX(CASE WHEN d.note_id = 2 THEN d.value END) as Col3
FROM notes n
JOIN detail d ON n.id = d.note_id
JOIN indices i ON i.id = d.indices_id
GROUP BY i.name

Output:

name    Col2    Col3
height  50      40
other   20      50
weight  60      10

Demo on dbfiddle


问:
Postgres closes connection during query after a few hundred seconds when using Psycopg2
I'm running PostgreSQL 9.6 (in Docker, using the postgres:9.6.13 image) and psycopg2 2.8.2.

My PostgreSQL server (local) hosts two databases. My goal is to create materialized views in one of the databases that use data from the other database using Postgres's foreign data wrappers. I do all this from a Python script that uses psycopg2.

This works well as long as creating the materialized view does not take too long (i.e. if the amount of data being imported isn't too large). However, if the process takes longer than roughly ~250 seconds, psycopg2 throws the exception

```<code>psycopg2.OperationalError: server closed the connection unexpectedly
    This probably means the server terminated abnormally
    before or while processing the request.
</code>```

No error message (or any message concerning this whatsoever) can be found in Postgres's logs.

Materialized view creation completes successfully if I do it from an SQL client (Postico).

This code illustrates roughly what I'm doing in the Python script:

db = pg.connect(
    dbname=config.db_name,
    user=config.db_user,
    password=config.db_password,
    host=config.db_host,
    port=config.db_port
)
with db.cursor() as c:
    c.execute("""
        CREATE EXTENSION IF NOT EXISTS postgres_fdw;
        CREATE SERVER fdw FOREIGN DATA WRAPPER postgres_fdw OPTIONS (...);
        CREATE USER MAPPING FOR CURRENT_USER SERVER fdw OPTIONS (...);
        CREATE SCHEMA foreign;
        IMPORT FOREIGN SCHEMA foreign_schema FROM SERVER fdw INTO foreign;
    """)
    c.execute("""
        CREATE MATERIALIZED VIEW IF NOT EXISTS my_view AS (
            SELECT (...)
            FROM foreign.foreign_table
        );
    """)
```

答:
It might be that PostgreSQL 9.6 kills your connections after the new timeout mentioned at https://stackoverflow.com/a/45627782/1587329. In that case, you could set

the statement_timeout in postgresql.conf

but it is not recommended.

It might work in Postico because the value has been set there.

To log an error you need to set log_min_error_statement to ERROR or lower for it to show.

Body:
I'm running PostgreSQL 9.6 (in Docker, using the postgres:9.6.13 image) and psycopg2 2.8.2.

My PostgreSQL server (local) hosts two databases. My goal is to create materialized views in one of the databases that use data from the other database using Postgres's foreign data wrappers. I do all this from a Python script that uses psycopg2.

This works well as long as creating the materialized view does not take too long (i.e. if the amount of data being imported isn't too large). However, if the process takes longer than roughly ~250 seconds, psycopg2 throws the exception

psycopg2.OperationalError: server closed the connection unexpectedly
    This probably means the server terminated abnormally
    before or while processing the request.

No error message (or any message concerning this whatsoever) can be found in Postgres's logs.

Materialized view creation completes successfully if I do it from an SQL client (Postico).

This code illustrates roughly what I'm doing in the Python script:

db = pg.connect(
    dbname=config.db_name,
    user=config.db_user,
    password=config.db_password,
    host=config.db_host,
    port=config.db_port
)
with db.cursor() as c:
    c.execute("""
        CREATE EXTENSION IF NOT EXISTS postgres_fdw;
        CREATE SERVER fdw FOREIGN DATA WRAPPER postgres_fdw OPTIONS (...);
        CREATE USER MAPPING FOR CURRENT_USER SERVER fdw OPTIONS (...);
        CREATE SCHEMA foreign;
        IMPORT FOREIGN SCHEMA foreign_schema FROM SERVER fdw INTO foreign;
    """)
    c.execute("""
        CREATE MATERIALIZED VIEW IF NOT EXISTS my_view AS (
            SELECT (...)
            FROM foreign.foreign_table
        );
    """)


问:
Model State Always true even when the required field is not sent
I am simply calling an API and passing an object as a parameter and everything works fine. But then i wanted to validate the model before going any further so i simply wrote [Required] above the fields i always wanted filled.
MODEL

```<code>public class Consent
{
    public Consent()
    {

    }
    public int Id { get; set; }
    [Required]
    public int FacilityId { get; set; }
    public string Heading { get; set; }
    public string Description { get; set; }
}

</code>```

and validate the model state in controller like this

```<code>public ActionResult<int> AddConsent(Consent consent)
{
    if(!ModelState.IsValid){
        throw new CustomException("000-0000-000", "Validation failed");

    }
    //Further Code
}
</code>```

By this i expected model state to be false when i don't send the facilityId when i call the api
JSON

```<code>{
    "heading": "HeadingFromPostman5",
    "description": "DiscriptiomFromPostman5"
}
</code>```

but its still true . I know .Net core is allocating 0 to int value when null but how can i validate it then? Whats the work around for this?

答:
Simply replace this line:

```<code>[Required]
public int FacilityId { get; set; }
</code>```

With this:

```<code>[Required]
public int? FacilityId { get; set; }
</code>```

Body:
I am simply calling an API and passing an object as a parameter and everything works fine. But then i wanted to validate the model before going any further so i simply wrote [Required] above the fields i always wanted filled.
MODEL

public class Consent
{
    public Consent()
    {

    }
    public int Id { get; set; }
    [Required]
    public int FacilityId { get; set; }
    public string Heading { get; set; }
    public string Description { get; set; }
}

and validate the model state in controller like this

public ActionResult<int> AddConsent(Consent consent)
{
    if(!ModelState.IsValid){
        throw new CustomException("000-0000-000", "Validation failed");

    }
    //Further Code
}

By this i expected model state to be false when i don't send the facilityId when i call the api
JSON

{
    "heading": "HeadingFromPostman5",
    "description": "DiscriptiomFromPostman5"
}

but its still true . I know .Net core is allocating 0 to int value when null but how can i validate it then? Whats the work around for this?

Body:
Simply replace this line:

[Required]
public int FacilityId { get; set; }

With this:

[Required]
public int? FacilityId { get; set; }