问:
Module parse failed: Unexpected token. react-native/index.js "typeof" operator
I'm quite new to the front end - trying to implement client side on React. After adding "react-native" dependency and running webpack I'm getting the following error:

```<code>ERROR in ./node_modules/react-native/index.js 13:7
Module parse failed: Unexpected token (13:7)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| 'use strict';
|
> import typeof AccessibilityInfo from './Libraries/Components/AccessibilityInfo/AccessibilityInfo';
| import typeof ActivityIndicator from './Libraries/Components/ActivityIndicator/ActivityIndicator';
| import typeof Button from './Libraries/Components/Button';
 @ ./node_modules/@react-navigation/native/lib/module/useBackButton.js 2:0-43 5:25-36
 @ ./node_modules/@react-navigation/native/lib/module/index.js
 @ ./src/main/js/app.js
</code>```

I have the following dependencies in package.json:

```<code> "dependencies": {
    "@react-native-community/masked-view": "^0.1.7",
    "@react-navigation/native": "^5.1.4",
    "@react-navigation/stack": "^5.2.9",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-native": "^0.62.1",
    "react-native-gesture-handler": "^1.6.1",
    "react-native-reanimated": "^1.7.1",
    "react-native-safe-area-context": "^0.7.3",
    "react-native-screens": "^2.4.0",
    "rest": "^2.0.0"
  },
  "scripts": {
    "watch": "webpack --watch -d"
  },
  "devDependencies": {
    "@babel/core": "^7.9.0",
    "@babel/preset-env": "^7.9.0",
    "@babel/preset-react": "^7.9.4",
    "babel-loader": "^8.1.0",
    "webpack": "^4.42.1",
    "webpack-cli": "^3.3.11"
  }
</code>```

I assume that "typeof" operator is not recognized, but why?

答:
I just spent a few hours dealing with this exact issue.

First, you can try adding "@babel/preset-flow" to your .babelrc file (after installing). That was recommended here, but didn't actually work for me.

What worked for me was just adding externals: { "react-native": true }, to my webpack.config.js file. My config file ended up looking like this:

const path = require("path")

module.exports = {
    entry: "./src/index.js",
    output: {
        filename: "main.js",
        path: path.resolve(__dirname, "dist"),
    },
    externals: {
        "react-native": true,
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                use: ["babel-loader"],
            },
            // ...
        ],
    },
}
```

My understanding is that react-native is a dependency, so @babel/preset-flow didn't actually get triggered to help interpret the flow formatting in those files - it may only handle files in the main "entry" location of your webpack.config.js file.

Hopefully this helps someone out there. Feel free to comment on this answer if I'm a bit off-base and I'll update this :)

Body:
I'm quite new to the front end - trying to implement client side on React. After adding "react-native" dependency and running webpack I'm getting the following error:

ERROR in ./node_modules/react-native/index.js 13:7
Module parse failed: Unexpected token (13:7)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| 'use strict';
|
> import typeof AccessibilityInfo from './Libraries/Components/AccessibilityInfo/AccessibilityInfo';
| import typeof ActivityIndicator from './Libraries/Components/ActivityIndicator/ActivityIndicator';
| import typeof Button from './Libraries/Components/Button';
 @ ./node_modules/@react-navigation/native/lib/module/useBackButton.js 2:0-43 5:25-36
 @ ./node_modules/@react-navigation/native/lib/module/index.js
 @ ./src/main/js/app.js

I have the following dependencies in package.json:

 "dependencies": {
    "@react-native-community/masked-view": "^0.1.7",
    "@react-navigation/native": "^5.1.4",
    "@react-navigation/stack": "^5.2.9",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-native": "^0.62.1",
    "react-native-gesture-handler": "^1.6.1",
    "react-native-reanimated": "^1.7.1",
    "react-native-safe-area-context": "^0.7.3",
    "react-native-screens": "^2.4.0",
    "rest": "^2.0.0"
  },
  "scripts": {
    "watch": "webpack --watch -d"
  },
  "devDependencies": {
    "@babel/core": "^7.9.0",
    "@babel/preset-env": "^7.9.0",
    "@babel/preset-react": "^7.9.4",
    "babel-loader": "^8.1.0",
    "webpack": "^4.42.1",
    "webpack-cli": "^3.3.11"
  }

I assume that "typeof" operator is not recognized, but why?

Body:
I just spent a few hours dealing with this exact issue.

First, you can try adding "@babel/preset-flow" to your .babelrc file (after installing). That was recommended here, but didn't actually work for me.

What worked for me was just adding externals: { "react-native": true }, to my webpack.config.js file. My config file ended up looking like this:

const path = require("path")

module.exports = {
    entry: "./src/index.js",
    output: {
        filename: "main.js",
        path: path.resolve(__dirname, "dist"),
    },
    externals: {
        "react-native": true,
    },
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                use: ["babel-loader"],
            },
            // ...
        ],
    },
}

My understanding is that react-native is a dependency, so @babel/preset-flow didn't actually get triggered to help interpret the flow formatting in those files - it may only handle files in the main "entry" location of your webpack.config.js file.

Hopefully this helps someone out there. Feel free to comment on this answer if I'm a bit off-base and I'll update this :)


来源: stackexchange

问:
Issues of String sort with PriorityQueue (Java)
I was trying to use PriorityQueue to sort a list of Strings and remove the duplicates. Initially I used PriorityQueue, it doesn't change the order. After I change to TreeSet, it worked. However, I want to understand what is the issue with priority queue, with defined Comparator. Would love to hear some explanations.

Not working code:

```<code>public class RemoveDuplicateStrings {
    public static ArrayList<String> removeDuplicates(List<String> input) {
        PriorityQueue<String> pq = new PriorityQueue<>((a, b) -> a.compareTo(b));

        for (String s : input) {
            if (!pq.contains(s)) {
                pq.add(s);
            }
        }
        return new ArrayList<String>(pq);
    }

    public static void main(String[] args) {
        List<String> output = removeDuplicates(List.of("Hey", "Hi", "Hello", "Hey", "Hello"));
        System.out.println(output);
    }
}
</code>```

Result I got:
[Hello, Hi, Hey], the correct order should be: hello, hey, hi.

It worked after I changed the data structure to TreeSet with the same Comparator.

答:
You are using ArrayList constructor that copies elements from the collection that is passed as an argument, and invokes toArray method on it. For PriorityQueue it just makes the copy of the underlying array and those elements are in no particular order. From the PriorityQueue::toArray docs :

Returns an array containing all of the elements in this queue. The elements are in no particular order.

However for a TreeSet::toArray (implementation inherited from AbstractCollection):

Returns an array containing all of the elements in this collection. If this collection makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order

And actually the TreeSet makes guarantes about the order of elements returned by it's iterator. From TreeSet::iterator docs :

Returns an iterator over the elements in this set in ascending order.

That is why you get such results. To get what you want you would have to poll your queue to receive elements in comparator defined order :

```<code>public static ArrayList<String> removeDuplicates(List<String> input) {
        PriorityQueue<String> pq = new PriorityQueue<>((a, b) -> a.compareTo(b));

        for (String s : input) {
            if (!pq.contains(s)) {
                pq.add(s);
            }
        }

        ArrayList<String> result = new ArrayList<>();
        while (!pq.isEmpty()) {
            result.add(pq.poll());
        }
        return result;
}
</code>```

The key here is that the iterator of PriorityQueue does not return elements i praticular order, however for TreeSet the order is ascending (taking into account the comparator).

ContentLicense: CC BY-SA 4.0

Body:
I was trying to use PriorityQueue to sort a list of Strings and remove the duplicates. Initially I used PriorityQueue, it doesn't change the order. After I change to TreeSet, it worked. However, I want to understand what is the issue with priority queue, with defined Comparator. Would love to hear some explanations.

Not working code:

public class RemoveDuplicateStrings {
    public static ArrayList<String> removeDuplicates(List<String> input) {
        PriorityQueue<String> pq = new PriorityQueue<>((a, b) -> a.compareTo(b));

        for (String s : input) {
            if (!pq.contains(s)) {
                pq.add(s);
            }
        }
        return new ArrayList<String>(pq);
    }

    public static void main(String[] args) {
        List<String> output = removeDuplicates(List.of("Hey", "Hi", "Hello", "Hey", "Hello"));
        System.out.println(output);
    }
}

Result I got:
[Hello, Hi, Hey], the correct order should be: hello, hey, hi.

It worked after I changed the data structure to TreeSet with the same Comparator.

Body:
You are using ArrayList constructor that copies elements from the collection that is passed as an argument, and invokes toArray method on it. For PriorityQueue it just makes the copy of the underlying array and those elements are in no particular order. From the PriorityQueue::toArray docs :

Returns an array containing all of the elements in this queue. The elements are in no particular order.

However for a TreeSet::toArray (implementation inherited from AbstractCollection):

Returns an array containing all of the elements in this collection. If this collection makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order

And actually the TreeSet makes guarantes about the order of elements returned by it's iterator. From TreeSet::iterator docs :

Returns an iterator over the elements in this set in ascending order.

That is why you get such results. To get what you want you would have to poll your queue to receive elements in comparator defined order :

public static ArrayList<String> removeDuplicates(List<String> input) {
        PriorityQueue<String> pq = new PriorityQueue<>((a, b) -> a.compareTo(b));

        for (String s : input) {
            if (!pq.contains(s)) {
                pq.add(s);
            }
        }

        ArrayList<String> result = new ArrayList<>();
        while (!pq.isEmpty()) {
            result.add(pq.poll());
        }
        return result;
}

The key here is that the iterator of PriorityQueue does not return elements i praticular order, however for TreeSet the order is ascending (taking into account the comparator).


问:
ubuntu 20.04 docker consul image - exited state
followed: https://www.digitalocean.com/community/tutorials/how-to-install-and-use-docker-on-ubuntu-20-04 (those steps always worked for lower version of ubuntu)

docker run -d --name=local-consul -p 8500:8500 -e CONSUL_BIND_INTERFACE=eth0 consul docker

(as I always do)

docker ps

empty

docker ps -a

status: "Exited (0) 4 seconds ago"

docker logs consul-local

==> Found address '172.17.0.2' for interface 'eth0', setting bind option...
/usr/local/bin/docker-entrypoint.sh: exec: line 98: docker: not found

docker --version

Docker version 19.03.11, build 42e35e61f3

systemctl status docker

● docker.service - Docker Application Container Engine
     Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset: enabled)
     Active: active (running) since Mon 2020-06-01 14:30:59 EDT; 22min ago
TriggeredBy: ● docker.socket
       Docs: https://docs.docker.com
   Main PID: 46472 (dockerd)
      Tasks: 56
     Memory: 194.9M
     CGroup: /system.slice/docker.service
             └─46472 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock

Question:
 How to fix /usr/local/bin/docker-entrypoint.sh: exec: line 98: docker: not found

I've checked. I do not have this file on my local machine: /usr/local/bin/docker-entrypoint.sh

答:
-d tells Docker to detach and the run the container in the background. It has nothing to do with when the container exits. The container will exit when the entrypoint process terminates. In this case, the hello-world container just prints a message and exits, so it will not continue running, detached or not.

Edit:

docker run -d --name=local-consul -p 8500:8500 -e CONSUL_BIND_INTERFACE=eth0 consul docker

If you look at the entrypoint script for the consul image, you'll see it runs exec "$@". So the docker run command above will attempt to run docker within the consul container. That command doesn't exist in the container, so you get docker: not found.

You likely just want to run the container without additional arguments:

docker run -d --name=local-consul -p 8500:8500 -e CONSUL_BIND_INTERFACE=eth0 consul

See https://hub.docker.com/_/consul


问:
A-Frame. Zoom on wheel scroll
I've come through the official docs but wasn't able to locate information about how possibility of zooming in/out panorama images, is it supported in the A-Frame or maybe there is a workaround to read about implementing some of three.js on top of it?

答:
Sandy's answer helped me. I want to contribute an answer which shows the full code and enables smoother zooming (increments of 0.1):</p>

```<code><script>
  window.addEventListener("wheel", (event) => {
    // small increments for smoother zooming
    const delta = event.wheelDelta / 120 / 10;
    var mycam = document.getElementById("cam").getAttribute("camera");
    var finalZoom =
      document.getElementById("cam").getAttribute("camera").zoom + delta;

    // limiting the zoom
    if (finalZoom < 0.5) finalZoom = 0.5;
    if (finalZoom > 2) finalZoom = 2;
    mycam.zoom = finalZoom;

    document.getElementById("cam").setAttribute("camera", mycam);
  });
</script>
<a-scene>
  <a-entity
    id="cam"
    camera="zoom: 1"
    look-controls="reverseMouseDrag: true"
  ></a-entity>
  <!-- my pano image stuff -->
  <a-assets>
    <img id="skyTexture" crossorigin="anonymous" />
  </a-assets>
  <a-sky src="#skyTexture"></a-sky>
</a-scene>
</code>```

ContentLicense: CC BY-SA 3.0

Title: A-Frame. Zoom on wheel scroll

Body:
Sandy's answer helped me. I want to contribute an answer which shows the full code and enables smoother zooming (increments of 0.1):

<script>
  window.addEventListener("wheel", (event) => {
    // small increments for smoother zooming
    const delta = event.wheelDelta / 120 / 10;
    var mycam = document.getElementById("cam").getAttribute("camera");
    var finalZoom =
      document.getElementById("cam").getAttribute("camera").zoom + delta;

    // limiting the zoom
    if (finalZoom < 0.5) finalZoom = 0.5;
    if (finalZoom > 2) finalZoom = 2;
    mycam.zoom = finalZoom;

    document.getElementById("cam").setAttribute("camera", mycam);
  });
</script>
<a-scene>
  <a-entity
    id="cam"
    camera="zoom: 1"
    look-controls="reverseMouseDrag: true"
  ></a-entity>
  <!-- my pano image stuff -->
  <a-assets>
    <img id="skyTexture" crossorigin="anonymous" />
  </a-assets>
  <a-sky src="#skyTexture"></a-sky>
</a-scene>


问:
Authenticate Azure Active Directory
I have an excel file that has a macro on it.  I want only the users that are member of a certain Azure Active Directory user group, be able to run the macro.  How can I code the Azure authentication part in VBA?

Thanks so much!

Cheers,
Alan

答:
So for Azure AD the Client libraries/SDKs that are supported are here and you will note that VBA is not one of them.

VBA language wise is a pretty limiting factor here.  I might try to implement a web endpoint/website that you call from the VBA that is AAD integrated (App Services can help with that) and then in the response indicate your yes/no or groups for your VBA code to read.

So:  VBA Code makes HTTP call to Website with AAD integration, (user logs in if needed) Website then responds back to VBA with some JSON or other payload.  VBA reads payload and then acts accordingly.

That website can use the Microsoft Graph to pull all memberships they have in AAD.  Play with the Graph explorer here: https://developer.microsoft.com/en-us/graph/graph-explorer and try this endpoint: https://graph.microsoft.com/v1.0/me/memberOf

Docs: https://learn.microsoft.com/en-us/graph/api/user-list-memberof?view=graph-rest-1.0&tabs=http

Title: Authenticate Azure Active Directory


问:
Absolute layout uasage
Is that ok to use absolute layout in my application if i know exactly the x,y that i'll draw the widget at or it'll affect the application appearance on the device ?

I'm asking this question as I've read that it's deprecated

答:
Even if you know exactly where you want to put each widget, you won't know the exact resolution of the devices which will run your application. Some will have empty space left on the screen, while others might not have room to display all your widgets.

Short version: better not use it, there are always better options.

Title: Absolute layout uasage


问:
What are the types for { dispatch, commit } in vuex?
I got vujes typescript project and in vuex store i got something like:

```<code>async getUserProfile ({ dispatch, commit }: any) {}
</code>```

Well i dont want any because that suck and you dont have help/autocomplete in editor. I found this import { Dispatch, Commit } from "vuex"; but how to pass that info to { dispatch, commit }: any

答:
You can check out available vuex types in this file:

node_modules/vuex/types/index.d.ts

// line 49 :

```<code>export interface Commit {
  (type: string, payload?: any, options?: CommitOptions): void;
  <P extends Payload>(payloadWithType: P, options?: CommitOptions): void;
}

</code>```

you can import and use that instead of ActionContext like so:

```<code>import { Commit } from 'vuex';

const actions = {
    loadUser ({ commit }: { commit: Commit }, user: any) {
        commit('setUser', user);
    },

    ...
};
</code>```

hope that helps :)

Body:
I got vujes typescript project and in vuex store i got something like:

async getUserProfile ({ dispatch, commit }: any) {}

Well i dont want any because that suck and you dont have help/autocomplete in editor. I found this import { Dispatch, Commit } from "vuex"; but how to pass that info to { dispatch, commit }: any

Body:
You can check out available vuex types in this file:

node_modules/vuex/types/index.d.ts

// line 49 :

export interface Commit {
  (type: string, payload?: any, options?: CommitOptions): void;
  <P extends Payload>(payloadWithType: P, options?: CommitOptions): void;
}

you can import and use that instead of ActionContext like so:

import { Commit } from 'vuex';

const actions = {
    loadUser ({ commit }: { commit: Commit }, user: any) {
        commit('setUser', user);
    },

    ...
};

hope that helps :)


问:
Whats the difference between normal recursive solutions and Dynamic Programming related recursive solutions?
Can anyone please help me with this , How is the DP's Iterative approach different from the Recursive Approach.</p>

答:
Dynamic Programming and Recursion aren't necessarily opposites. What you're thinking is Memoization vs. Dynamic Programming.

Dynamic Programming is the approach to a problem that reduces duplicate computations as much as possible. This usually means taking a bottom-up approach - i.e. you calculate answers to smaller scale problems first and then use those answers to calculate higher order problems. Iterative approaches are usually used for Dynamic programming since it seems natural (although you can do it recursively too).

Memoization is the top-down approach to a problem and is usually done through recursion because it is more natural. In this case, you start with a higher order problem and make recursive calls for lower order problems in order to solve it.

In both cases you use a data-structure to store values computed so far.


问:
If <something>, do nothing in Kusto
Use case: Inside Azure Application Insights, create a table of views per page from an Azure web app

Using Kusto in Azure Application Insights, I would like to merge the rows in table 1:

Into table 2:

Unfortunately the query below replaces cells in the first column (except the first row) with the cells in the second column. This is expected based on how the query is written. Unfortunately it is incorrect and not my goal.

```<code>pageViews
| where timestamp between(datetime("2020-03-01T00:00:00.000Z")..datetime("2020-06-01T00:00:00.000Z"))
| extend guide = case(
    url contains "/guide-1/","guide-1",
    url contains "/guide-2/","guide-2",
    url contains "/guide-3/","guide-3",
    "home-page"
)
| extend tag = case(
    url contains "/guide-1/","install",
    guide contains "home-page","home-page",
    "how-to"
)
| extend name = case(
    name contains "Welcome to docs","Welcome to docs",
    "home-page" //This is incorrect - nothing should happen if the name does not contain "Welcome to docs"
)
| summarize Ocurrences=count() by name, tag, guide
</code>```

I have searched Microsoft documentation for a way to "do nothing" if a condition is not met but have not come up with anything, due to my lack of knowledge about Kusto. I tried iff but was not successful.

Thank you for any help, including advice if this approach is not the best.

答:
If you would like to keep the 'name' under certain conditions, you can just do:

| extend name = case(
        name contains "Welcome to docs","Welcome to docs",
        name
    )

```<code>pageViews
| where timestamp between(datetime("2020-03-01T00:00:00.000Z")..datetime("2020-06-01T00:00:00.000Z"))
| extend guide = case(
    url contains "/guide-1/","guide-1",
    url contains "/guide-2/","guide-2",
    url contains "/guide-3/","guide-3",
    "home-page"
)
| extend tag = case(
    url contains "/guide-1/","install",
    guide contains "home-page","home-page",
    "how-to"
)
| extend name = case(
    name contains "Welcome to docs","Welcome to docs",
    name
)
| summarize Ocurrences=count() by name, tag, guide
</code>```

Also, it is better to use 'has' instead of 'contains': 'has' looks for full words and is faster than 'contains'.

Title: If <something>, do nothing in Kusto

Body:
Use case: Inside Azure Application Insights, create a table of views per page from an Azure web app

Using Kusto in Azure Application Insights, I would like to merge the rows in table 1:

Into table 2:

Unfortunately the query below replaces cells in the first column (except the first row) with the cells in the second column. This is expected based on how the query is written. Unfortunately it is incorrect and not my goal.

pageViews
| where timestamp between(datetime("2020-03-01T00:00:00.000Z")..datetime("2020-06-01T00:00:00.000Z"))
| extend guide = case(
    url contains "/guide-1/","guide-1",
    url contains "/guide-2/","guide-2",
    url contains "/guide-3/","guide-3",
    "home-page"
)
| extend tag = case(
    url contains "/guide-1/","install",
    guide contains "home-page","home-page",
    "how-to"
)
| extend name = case(
    name contains "Welcome to docs","Welcome to docs",
    "home-page" //This is incorrect - nothing should happen if the name does not contain "Welcome to docs"
)
| summarize Ocurrences=count() by name, tag, guide

I have searched Microsoft documentation for a way to "do nothing" if a condition is not met but have not come up with anything, due to my lack of knowledge about Kusto. I tried iff but was not successful.

Thank you for any help, including advice if this approach is not the best.

Body:
If you would like to keep the 'name' under certain conditions, you can just do:

| extend name = case(
        name contains "Welcome to docs","Welcome to docs",
        name
    )

pageViews
| where timestamp between(datetime("2020-03-01T00:00:00.000Z")..datetime("2020-06-01T00:00:00.000Z"))
| extend guide = case(
    url contains "/guide-1/","guide-1",
    url contains "/guide-2/","guide-2",
    url contains "/guide-3/","guide-3",
    "home-page"
)
| extend tag = case(
    url contains "/guide-1/","install",
    guide contains "home-page","home-page",
    "how-to"
)
| extend name = case(
    name contains "Welcome to docs","Welcome to docs",
    name
)
| summarize Ocurrences=count() by name, tag, guide

Also, it is better to use 'has' instead of 'contains': 'has' looks for full words and is faster than 'contains'.


问:
Adding new column based on multiple conditio
I have a data that looks like this:

```<code>< Id <- c(A,B,C,D,E)
< Father <- c(2,1,5,4,2)
< Mother <- c(1,3,3,5,1)
</code>```

What I want is to add a new column say parent based on the higher value of father or mother. Basically:

```<code>< Id <- c(A,B,C,D,E)
< Father <- c(2,1,5,4,2)
< Mother <- c(1,3,3,5,1)
< Parent <- c(2,3,5,5,2)
</code>```

答:
We can use pmax to get the elementwise max of multiple columns

```<code>library(dplyr)
df1 %>%
    mutate(Parent = pmax(Father, Mother))
</code>```

Or in base R

```<code>df1$Parent <- with(df1, pmax(Father, Mother))
</code>```

Or another option with ifelse

```<code>df1$Parent <- with(df1, ifelse(Father > Mother, Father, Mother))
</code>```

data

```<code>df1 <- data.frame(Id, Father, Mother)
</code>```

Body:
I have a data that looks like this:

< Id <- c(A,B,C,D,E)
< Father <- c(2,1,5,4,2)
< Mother <- c(1,3,3,5,1)

What I want is to add a new column say parent based on the higher value of father or mother. Basically:

< Id <- c(A,B,C,D,E)
< Father <- c(2,1,5,4,2)
< Mother <- c(1,3,3,5,1)
< Parent <- c(2,3,5,5,2)

Body:
We can use pmax to get the elementwise max of multiple columns

library(dplyr)
df1 %>%
    mutate(Parent = pmax(Father, Mother))

Or in base R

df1$Parent <- with(df1, pmax(Father, Mother))

Or another option with ifelse

df1$Parent <- with(df1, ifelse(Father > Mother, Father, Mother))

data

df1 <- data.frame(Id, Father, Mother)


问:
In Yii2 QueryBuilder, what is the syntax for using a database component not named 'db'?
In a Yii2 project I need to use QueryBuilder with 2 db components named 'dbcore' and 'dbdata'. I have been searching for how to do this and have only found the following (but no example):

"All these query methods take an optional $db parameter representing the DB connection that should be used to perform a DB query. If you omit this parameter, the db application component will be used as the DB connection."
(https://www.yiiframework.com/doc/guide/2.0/en/db-query-builder)

For example, consider this demo case:

```<code>$count = (new Query())->from('user')->count();
</code>```

I have tried Query('dbcore') and Query(['db'=>'dbcore']) and Query([$db=>'dbcore']) without success, but I am groping in the dark. Could someone please advise what the correct syntax is?

NOTE: I did try this workround in the component array and the query works fine, but it is not ideal in my application:

```<code>'db'     => require(__DIR__.'/dbcore.php'),     // 'db' is expected default in Query()
'dbcore' => require(__DIR__.'/dbcore.php'),
'dbdata' => require(__DIR__.'/dbdata.php'),
</code>```

答:
"Query method" in your case is count():

```<code>$count = (new Query())->from('user')->count('*', Yii::$app->dbcore);
</code>```

Body:
In a Yii2 project I need to use QueryBuilder with 2 db components named 'dbcore' and 'dbdata'. I have been searching for how to do this and have only found the following (but no example):

"All these query methods take an optional $db parameter representing the DB connection that should be used to perform a DB query. If you omit this parameter, the db application component will be used as the DB connection."
(https://www.yiiframework.com/doc/guide/2.0/en/db-query-builder)

For example, consider this demo case:

$count = (new Query())->from('user')->count();

I have tried Query('dbcore') and Query(['db'=>'dbcore']) and Query([$db=>'dbcore']) without success, but I am groping in the dark. Could someone please advise what the correct syntax is?

NOTE: I did try this workround in the component array and the query works fine, but it is not ideal in my application:

'db'     => require(__DIR__.'/dbcore.php'),     // 'db' is expected default in Query()
'dbcore' => require(__DIR__.'/dbcore.php'),
'dbdata' => require(__DIR__.'/dbdata.php'),

Body:
"Query method" in your case is count():

$count = (new Query())->from('user')->count('*', Yii::$app->dbcore);


问:
python CSV module vs Pandas
I am using pandas to read CSV file data, but the CSV module is also there to manage the CSV file.

so my questions are :-

what is the difference between these both?

what are the cons of using pandas over the CSV module?

答:
Based upon benchmarks

CSV is faster to load data for smaller datasets (< 1K rows)

Pandas is several times faster for larger datasets

Code to Generate Benchmarks

Benchmarks

Title: python CSV module vs Pandas


问:
How can I create a MessageDialog using winrt-rs?
I am attempting to show a MessageDialog upon keypress. So far, it doesn't seem to do anything. The code does compile, but does not function. The code verifies that the keypress works, but the dialog simply wont display. I have tried taking the returned IAsyncOperation and using 'get()' but that seems to freeze the application completely. What am I missing?</p>

```<code>//#![windows_subsystem = "windows"]
use winit::{
    event::{Event, WindowEvent},
    event_loop::{ControlFlow, EventLoop},
    window::WindowBuilder,
};

use winrt::*;
import!(
    dependencies
        os
    modules
        "windows.data.xml.dom"
        "windows.foundation"
        "windows.ui"
        "windows.ui.popups"
);

fn main() {
    let event_loop = EventLoop::new();
    let window = WindowBuilder::new().build(&event_loop).unwrap();
    event_loop.run(move |event, _, control_flow| {
        *control_flow = ControlFlow::Wait;
        match event {
            Event::WindowEvent {
                event: WindowEvent::CloseRequested,
                window_id,
            } if window_id == window.id() => *control_flow = ControlFlow::Exit,
            Event::WindowEvent {
                event: WindowEvent::Resized (_size),
                ..
            } => (),
            Event::WindowEvent {
                event: WindowEvent::KeyboardInput {input,..},
                ..
            } if input.state == winit::event::ElementState::Pressed => {
                use windows::ui::popups::MessageDialog;
                let mymsg = MessageDialog::create("Test").unwrap().show_async();
                println!("KeyState-{}",input.scancode);
            },
            _ => (),
        }
    });
}
</code>```

答:
This highlights one of the differences in using some WinRT APIs in a Win32 application. In a UWP application, your app has a CoreWindow associated with its main thread. Normally, dialogs query for this window and display themselves as modal to it. However, in a Win32 application the system can't make an assumption about what window you want to use. In these instances, you need to QI for the IInitializeWithWindow interface and call the initialize function with your window handle.

Since the IInitializeWithWindow interface is a pure COM interface and not a WinRT one, winrt-rs doesn't have a projection for it. Instead you'll need to define it yourself (make sure you get the GUID right!):

#[repr(C)]
pub struct abi_IInitializeWithWindow {
    __base: [usize; 3],
    initialize: extern "system" fn(
        winrt::NonNullRawComPtr<InitializeWithWindowInterop>,
        *mut c_void,
    ) -> winrt::ErrorCode,
}

unsafe impl winrt::ComInterface for InitializeWithWindowInterop {
    type VTable = abi_IInitializeWithWindow;

    fn iid() -> winrt::Guid {
        winrt::Guid::from_values(1047057597, 28981, 19728, [128, 24, 159, 182, 217, 243, 63, 161])
    }
}

#[repr(transparent)]
#[derive(Default, Clone)]
pub struct InitializeWithWindowInterop {
    ptr: winrt::ComPtr<InitializeWithWindowInterop>,
}

impl InitializeWithWindowInterop {
    pub fn initialize(
        &self,
        window: *mut c_void,
    ) -> winrt::Result<()> {
        match self.ptr.abi() {
            None => panic!("The `this` pointer was null when calling method"),
            Some(this) => unsafe {
                (this.vtable().initialize)(
                    this,
                    window,
                )
                .ok()?;
                Ok(())
            },
        }
    }
}
```

<p>To get the window handle from your winit Window, you'll need the <code>raw-window-handle</code> crate. From there you can create a helper trait for anything that implements <code>HasRawWindowHandle</code>:</p>

<pre class="lang-rust prettyprint-override"><code>trait InitializeWithWindow {
    fn initialize_with_window<O: RuntimeType + ComInterface>(&self, object: &O) -> winrt::Result<()>;
}

impl<T> InitializeWithWindow for T
where
    T: HasRawWindowHandle,
{
    fn initialize_with_window<O: RuntimeType + ComInterface>(
        &self,
        object: &O,
    ) -> winrt::Result<()> {
        // Get the window handle
        let window_handle = self.raw_window_handle();
        let window_handle = match window_handle {
            raw_window_handle::RawWindowHandle::Windows(window_handle) => window_handle.hwnd,
            _ => panic!("Unsupported platform!"),
        };

        let init: InitializeWithWindowInterop = object.try_into()?;
        init.initialize(window_handle)?;
        Ok(())
    }
}
</code>```

Now in your event loop you can call it using the following:

let dialog = MessageDialog::create("Test").unwrap();
window.initialize_with_window(&dialog).unwrap();
dialog.show_async().unwrap();
println!("KeyState-{}",input.scancode);
```

Note that I'm not waiting on the result of the IAsyncOperation that is retunred by show_async. The reason is because only synchronous waiting it supported by the projection right now, and that would tie up your message pump and cause the window to hang. This means that the print statement will run before the dialog returns. This should improve once broader async support is up and running in the projection.

You can now use your initialize_with_window method on dialogs and pickers (e.g. FileSavePicker, GraphicsCapturePicker).

Body:
I am attempting to show a MessageDialog upon keypress. So far, it doesn't seem to do anything. The code does compile, but does not function. The code verifies that the keypress works, but the dialog simply wont display. I have tried taking the returned IAsyncOperation and using 'get()' but that seems to freeze the application completely. What am I missing?

//#![windows_subsystem = "windows"]
use winit::{
    event::{Event, WindowEvent},
    event_loop::{ControlFlow, EventLoop},
    window::WindowBuilder,
};

use winrt::*;
import!(
    dependencies
        os
    modules
        "windows.data.xml.dom"
        "windows.foundation"
        "windows.ui"
        "windows.ui.popups"
);

fn main() {
    let event_loop = EventLoop::new();
    let window = WindowBuilder::new().build(&event_loop).unwrap();
    event_loop.run(move |event, _, control_flow| {
        *control_flow = ControlFlow::Wait;
        match event {
            Event::WindowEvent {
                event: WindowEvent::CloseRequested,
                window_id,
            } if window_id == window.id() => *control_flow = ControlFlow::Exit,
            Event::WindowEvent {
                event: WindowEvent::Resized (_size),
                ..
            } => (),
            Event::WindowEvent {
                event: WindowEvent::KeyboardInput {input,..},
                ..
            } if input.state == winit::event::ElementState::Pressed => {
                use windows::ui::popups::MessageDialog;
                let mymsg = MessageDialog::create("Test").unwrap().show_async();
                println!("KeyState-{}",input.scancode);
            },
            _ => (),
        }
    });
}

Body:
This highlights one of the differences in using some WinRT APIs in a Win32 application. In a UWP application, your app has a CoreWindow associated with its main thread. Normally, dialogs query for this window and display themselves as modal to it. However, in a Win32 application the system can't make an assumption about what window you want to use. In these instances, you need to QI for the IInitializeWithWindow interface and call the initialize function with your window handle.

Since the IInitializeWithWindow interface is a pure COM interface and not a WinRT one, winrt-rs doesn't have a projection for it. Instead you'll need to define it yourself (make sure you get the GUID right!):

#[repr(C)]
pub struct abi_IInitializeWithWindow {
    __base: [usize; 3],
    initialize: extern "system" fn(
        winrt::NonNullRawComPtr<InitializeWithWindowInterop>,
        *mut c_void,
    ) -> winrt::ErrorCode,
}

unsafe impl winrt::ComInterface for InitializeWithWindowInterop {
    type VTable = abi_IInitializeWithWindow;

    fn iid() -> winrt::Guid {
        winrt::Guid::from_values(1047057597, 28981, 19728, [128, 24, 159, 182, 217, 243, 63, 161])
    }
}

#[repr(transparent)]
#[derive(Default, Clone)]
pub struct InitializeWithWindowInterop {
    ptr: winrt::ComPtr<InitializeWithWindowInterop>,
}

impl InitializeWithWindowInterop {
    pub fn initialize(
        &self,
        window: *mut c_void,
    ) -> winrt::Result<()> {
        match self.ptr.abi() {
            None => panic!("The `this` pointer was null when calling method"),
            Some(this) => unsafe {
                (this.vtable().initialize)(
                    this,
                    window,
                )
                .ok()?;
                Ok(())
            },
        }
    }
}

To get the window handle from your winit Window, you'll need the raw-window-handle crate. From there you can create a helper trait for anything that implements HasRawWindowHandle:

trait InitializeWithWindow {
    fn initialize_with_window<O: RuntimeType + ComInterface>(&self, object: &O) -> winrt::Result<()>;
}

impl<T> InitializeWithWindow for T
where
    T: HasRawWindowHandle,
{
    fn initialize_with_window<O: RuntimeType + ComInterface>(
        &self,
        object: &O,
    ) -> winrt::Result<()> {
        // Get the window handle
        let window_handle = self.raw_window_handle();
        let window_handle = match window_handle {
            raw_window_handle::RawWindowHandle::Windows(window_handle) => window_handle.hwnd,
            _ => panic!("Unsupported platform!"),
        };

        let init: InitializeWithWindowInterop = object.try_into()?;
        init.initialize(window_handle)?;
        Ok(())
    }
}

Now in your event loop you can call it using the following:

let dialog = MessageDialog::create("Test").unwrap();
window.initialize_with_window(&dialog).unwrap();
dialog.show_async().unwrap();
println!("KeyState-{}",input.scancode);

Note that I'm not waiting on the result of the IAsyncOperation that is retunred by show_async. The reason is because only synchronous waiting it supported by the projection right now, and that would tie up your message pump and cause the window to hang. This means that the print statement will run before the dialog returns. This should improve once broader async support is up and running in the projection.

You can now use your initialize_with_window method on dialogs and pickers (e.g. FileSavePicker, GraphicsCapturePicker).


问:
Open a new tab with javascript but stay on current tab
Is it possible to open a new tab in Firefox (in background) using window.open("http://www.google.com") function, and remain the current tab?

Thanks for any help

答:
Here's an idea:</p>

```<code><script>
function open_in_bg(c_url, n_url)
{
 window.open (n_url, "mywindow" );
 window.open (c_url+"#maintain_focus","_self");
}
</script>

<input type="button" onclick="open_in_bg('current_page_url', 'url_to_be_opened')" />
</code>```

Body:
Here's an idea:

<script>
function open_in_bg(c_url, n_url)
{
 window.open (n_url, "mywindow" );
 window.open (c_url+"#maintain_focus","_self");
}
</script>

<input type="button" onclick="open_in_bg('current_page_url', 'url_to_be_opened')" />


问:
Could someone explain where BatchNorm is performed in ResNeXT https://github.com/facebookresearch/ResNeXt neural network?
I was reading the original paper that described ResNeXT   (variation of Resnet) at https://arxiv.org/pdf/1611.05431.pdf.

On Page-5 top right column, it says:

ReLU is performed right after eachBN, expect for the output of the
  block where ReLU is per-formed after the adding to the shortcut,
  following [14].

This sentence doesn't make sense, esp the part after comma "expect for the output of....".

Could someone explain what this sentence means?

Where is BN performed?

答:
ResNeXt uses the same conv-bn-relu policy as ResNet. Scheme is following:

You can check scheme for ResNet in official ResNet repo.

Probably you were confused by the typo in the paper: the word "expect" you should read as "except".


问:
Stripe Checkout webhook not passing customer email?
I'm using Stripe's Checkout in test mode. I'm trying to grab the customer's id in Stripe as well as the email they provided during checkout to update my database.

I set up a webhook for checkout.session.completed. If I send a test webhook, the id is filled in, but the customer_email is not.

I thought maybe the test webhook wouldn't pass that info,  so I filled out the checkout form. I get the id just fine, but customer_email is null.

I'm guessing I just don't understand the right way  to interact with Stripe.

```<code>
// straight from Stripe's documentation
try {
  $event = \Stripe\Webhook::constructEvent(
    $payload, $sig_header, $endpoint_secret
  );
} catch(\UnexpectedValueException $e) {
  // Invalid payload
  http_response_code(400);
  exit();
} catch(\Stripe\Exception\SignatureVerificationException $e) {
  // Invalid signature
  http_response_code(400);
  exit();
}

// Handle the checkout.session.completed event
if ($event->type == 'checkout.session.completed') {
  $session = $event->data->object;

  // Fulfill the purchase...
  handle_checkout_session($session);
}

http_response_code(200);

// my simple function
function handle_checkout_session($session){
  $stripeID=$session['id'];
  $userEmail=$session['customer_email'];
  print 'Email: ' . $userEmail . '\n'; // works
  print 'Stripe ID: ' . $stripeID . '\n'; // empty
}
</code>```

答:
It took me quite awhile to figure this out as well.

The customer_email field in the checkout.session.completed object is only there for passing through an email to the Stripe-generated checkout form if you already know the user's email before checkout.

To pull the user's email out via your webhook after the transaction, set your webhook to send the customer.created event as well (which you can select from the webhook event options). The user's email, as they entered it in the Checkout payment form, will be accessible on that object. However, note that it's called email, not customer_email, on the customer.created event.

Body:
I'm using Stripe's Checkout in test mode. I'm trying to grab the customer's id in Stripe as well as the email they provided during checkout to update my database.

I set up a webhook for checkout.session.completed. If I send a test webhook, the id is filled in, but the customer_email is not.

I thought maybe the test webhook wouldn't pass that info,  so I filled out the checkout form. I get the id just fine, but customer_email is null.

I'm guessing I just don't understand the right way  to interact with Stripe.

// straight from Stripe's documentation
try {
  $event = \Stripe\Webhook::constructEvent(
    $payload, $sig_header, $endpoint_secret
  );
} catch(\UnexpectedValueException $e) {
  // Invalid payload
  http_response_code(400);
  exit();
} catch(\Stripe\Exception\SignatureVerificationException $e) {
  // Invalid signature
  http_response_code(400);
  exit();
}

// Handle the checkout.session.completed event
if ($event->type == 'checkout.session.completed') {
  $session = $event->data->object;

  // Fulfill the purchase...
  handle_checkout_session($session);
}

http_response_code(200);

// my simple function
function handle_checkout_session($session){
  $stripeID=$session['id'];
  $userEmail=$session['customer_email'];
  print 'Email: ' . $userEmail . '\n'; // works
  print 'Stripe ID: ' . $stripeID . '\n'; // empty
}


问:
Cocoapods cannot install Trunk
I'm trying to develop a React Native mobile app for iOS on Windows 10. Using the react native cli, I've generated a RN iOS project with the standard file structure, including a "Podfile" file with the default RN pods.

However, when I try to use "pod install" in order to add other pods of my own, I get the following error code:

[!] CDN: trunk URL couldn't be downloaded: https://cdn.cocoapods.org/CocoaPods-version.yml Response: SSL peer certificate or SSH remote key was not OK

I've been googling this error but I've run into a dead end. I've tried using pod update, I've changed my cURL version, I've gone over the setup instructions for Ruby, curl, and others, and I'm at a loss. What can I do?

Note: I haven't run the app yet, and am trying to install the react-native-mapbox-gl pod first, but I can't even properly install Trunk.

cURL Version:7.70.0

CocoaPods Version: 1.9.3

答:
You won't be able to develop for iOS on Windows – because the iOS SDK and build tools are only available on macOS. No way to legally do it without an access to an Apple computer.

You can try Expo though – it doesn't require macOS for development, but keep in mind that you will be limited to the APIs Expo provides.

As for the actual error – it seems that the CocoaPods rubygem has not been tested on Windows at all, and is likely invoking curl in a way that doesn't account for Windows's SSL certificate management system.

Title: Cocoapods cannot install Trunk


问:
is there any similar way in meson as `cmake -LAH`?
I am debugging my meson build. I want to see all the cached variables as we do in cmake. Is there any way to do this? currently I have to go into the meson.build and add all the message() calls which is very inefficient. The python tricks vars() does not work either, but this is no surprising since meson.build is not python.

答:
Before building I always check meson_options.txt for possible options.

I noticed there is a file meson-info/intro-buildoptions.json under the build
directory after configuring with meson.

The options from meson_options.txt reappear in meson-info/intro-buildoptions.json with their configured values.

Since that file is in json format you will need to make it more readable if needed. This is a quick and dirty way that seems to work:

```<code>sed -e 's/},/&\n/g' meson-info/intro-buildoptions.json|sed -ne 's/^.*{"name": "\([^"]*\)", "value": \(\[[^]]*\]\|"[^"]*"\|[^,]*\).*$/\1 = \2/p'
</code>```

Body:
Before building I always check meson_options.txt for possible options.

I noticed there is a file meson-info/intro-buildoptions.json under the build
directory after configuring with meson.

The options from meson_options.txt reappear in meson-info/intro-buildoptions.json with their configured values.

Since that file is in json format you will need to make it more readable if needed. This is a quick and dirty way that seems to work:

sed -e 's/},/&\n/g' meson-info/intro-buildoptions.json|sed -ne 's/^.*{"name": "\([^"]*\)", "value": \(\[[^]]*\]\|"[^"]*"\|[^,]*\).*$/\1 = \2/p'


问:
android webview displaying blank page specific url only
My webview only showing white screen son specific url. (It's working with for ex. google.com)

```<code>package com.cemcebi.beyanname;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {

    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView = findViewById(R.id.webview);
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl("https://*****/");
    }
}

</code>```

Does anyone have any idea that why it's not opening.

答:
I ran your code in my app and voila it worked.

First add the following line in your manifest file.

```<code>android:cleartextTrafficPermitted="true"
</code>```

Now change the link from https to http and it works perfectly.

Let me know you why I did this..!!
When the original link is compiled I got a error like handshake failed SSL certificate returned -1. So I guess it mean the website has some issues. So try using this.

Hope it helps.

Body:
My webview only showing white screen son specific url. (It's working with for ex. google.com)

package com.cemcebi.beyanname;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {

    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView = findViewById(R.id.webview);
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl("https://*****/");
    }
}

Does anyone have any idea that why it's not opening.

Body:
I ran your code in my app and voila it worked.

First add the following line in your manifest file.

android:cleartextTrafficPermitted="true"

Now change the link from https to http and it works perfectly.

Let me know you why I did this..!!
When the original link is compiled I got a error like handshake failed SSL certificate returned -1. So I guess it mean the website has some issues. So try using this.

Hope it helps.


问:
Filter data for last 24 hours using c#?
Here i am calculating the server restart count.

i need the server restart count for last 24 hours.

```<code>string logType = "System";
EventLog ev = new EventLog(logType, System.Environment.MachineName);
int count=0;
for (int i = ev.Entries.Count - 1; i >= 0; i--)
{
EventLogEntry CurrentEntry = ev.Entries[i];
if (CurrentEntry.Source.ToUpper() == "USER32")
{
count = count + 1;
}
}
ev.Close();
</code>```

and i have tried like

```<code>DateTime dt = DateTime.Now;
TimeSpan ts = dt.Subtract(CurrentEntry.TimeGenerated);
int hours = (ts.Days * 24) + ts.Hours;
</code>```

Any suggestion?

答:
This code will give you the count of events, in tha last day, that have a source of USER32 in the System event log.

```<code>int count; //your result

//When yesterday became today
DateTime yesterday = DateTime.Now.Subtract(new TimeSpan(24, 0, 0));

using (EventLog appLog = new EventLog("System"))
{
    count = appLog.Entries.OfType<EventLogEntry>().Where(
        e => (e.Source.ToUpperInvariant == "USER32") &&
             (e.TimeGenerated > yesterday)).Count();
}
</code>```

EDIT: Or Even better, taking good bits from Mangus's answer

```<code>DateTime yesterday = DateTime.Now.AddDays(-1);
int count = 0;

using (Eventlog appLog = new EventLog("System"))
{
    count = appLog.Entries.OfType<EventLogEntry>().Count(
        e.Source.Equals("USER32", StringComparison.CurrentCultureIgnoreCase) &&
        e.TimeGenerated > yesterday
    )

}
</code>```

If "USER32" events do not have a direct correllation with system restart events, this will not give you a count of system restarts.

Title: Filter data for last 24 hours using c#?

Body:
Here i am calculating the server restart count.

i need the server restart count for last 24 hours.

string logType = "System";
EventLog ev = new EventLog(logType, System.Environment.MachineName);
int count=0;
for (int i = ev.Entries.Count - 1; i >= 0; i--)
{
EventLogEntry CurrentEntry = ev.Entries[i];
if (CurrentEntry.Source.ToUpper() == "USER32")
{
count = count + 1;
}
}
ev.Close();

and i have tried like

DateTime dt = DateTime.Now;
TimeSpan ts = dt.Subtract(CurrentEntry.TimeGenerated);
int hours = (ts.Days * 24) + ts.Hours;

Any suggestion?

Body:
This code will give you the count of events, in tha last day, that have a source of USER32 in the System event log.

int count; //your result

//When yesterday became today
DateTime yesterday = DateTime.Now.Subtract(new TimeSpan(24, 0, 0));

using (EventLog appLog = new EventLog("System"))
{
    count = appLog.Entries.OfType<EventLogEntry>().Where(
        e => (e.Source.ToUpperInvariant == "USER32") &&
             (e.TimeGenerated > yesterday)).Count();
}

EDIT: Or Even better, taking good bits from Mangus's answer

DateTime yesterday = DateTime.Now.AddDays(-1);
int count = 0;

using (Eventlog appLog = new EventLog("System"))
{
    count = appLog.Entries.OfType<EventLogEntry>().Count(
        e.Source.Equals("USER32", StringComparison.CurrentCultureIgnoreCase) &&
        e.TimeGenerated > yesterday
    )

}

If "USER32" events do not have a direct correllation with system restart events, this will not give you a count of system restarts.


问:
Why do I get a type error when I attempt to update the value attribute of Progressbar in Tkinter?
I am using Python 3.8.2
I have the following code that has 3 main loops. I need a simple UI that shows the progress for each loop.

```<code>import tkinter as tk
from tkinter import filedialog, ttk
from tkinter.ttk import Progressbar
import json
class App(tk.Tk):

    def __init__(self):
        tk.Tk.__init__(self)
        self.filename = ''
        tk.Button(self, text = 'Upload File', command = self.get_file).grid(row = 0, column = 0)
        tk.Button(self, text = 'Verify', command = self.verify).grid(row = 1, column = 0)
        # tk.Label(self, text = 'some name').grid(row = 0, column = 1)
        self.mainloop()

    def get_file(self):
        self.filename = tk.filedialog.askopenfilename(title = "Select File", filetypes = [("JSON", "*.json")])
        tk.Label(self, text = self.filename).grid(row = 0, column = 1)
    def verify(self):
        tk.Label(self, text = 'Verifying Trustee Public Keys').grid(row = 2, column = 0)
        ttk.Progressbar(self,
                   length = 100,
                   orient = "horizontal",
                   maximum = len(self.data["trustee_public_keys"]),
                   value = 0).grid(row = 3, column = 0)
        i = 1
        for trustee_key_list in self.data['trustee_public_keys']:
            print('Trustee :', i)
            //some code
            i = i+1
            ttk.Progressbar['value'] =  i
</code>```

Everytime I run it I get the error:

```<code> File "C:/Users/Student User/AppData/Roaming/JetBrains/PyCharmCE2020.1/scratches/scratch_17.py", line 81, in verify
ttk.Progressbar['value'] =  i
TypeError: 'type' object does not support item assignment
</code>```

What am I doing wrong and how do I get the intended result?

答:
Your code tries to assign a value to the progressbar type while you should assign the value to the instance of the progressbar.</p>

```<code>def verify(self):
        tk.Label(self, text = 'Verifying Trustee Public Keys').grid(row = 2, column = 0)
        progress = ttk.Progressbar(self,
                   length = 100,
                   orient = "horizontal",
                   maximum = len(self.data["trustee_public_keys"]),
                   value = 0)
        progress.grid(row = 3, column = 0)
        i = 1
        for trustee_key_list in self.data['trustee_public_keys']:
            print('Trustee :', i)
            //some code
            i = i+1
            progress['value'] =  i
</code>```

Body:
I am using Python 3.8.2
I have the following code that has 3 main loops. I need a simple UI that shows the progress for each loop.

import tkinter as tk
from tkinter import filedialog, ttk
from tkinter.ttk import Progressbar
import json
class App(tk.Tk):

    def __init__(self):
        tk.Tk.__init__(self)
        self.filename = ''
        tk.Button(self, text = 'Upload File', command = self.get_file).grid(row = 0, column = 0)
        tk.Button(self, text = 'Verify', command = self.verify).grid(row = 1, column = 0)
        # tk.Label(self, text = 'some name').grid(row = 0, column = 1)
        self.mainloop()

    def get_file(self):
        self.filename = tk.filedialog.askopenfilename(title = "Select File", filetypes = [("JSON", "*.json")])
        tk.Label(self, text = self.filename).grid(row = 0, column = 1)
    def verify(self):
        tk.Label(self, text = 'Verifying Trustee Public Keys').grid(row = 2, column = 0)
        ttk.Progressbar(self,
                   length = 100,
                   orient = "horizontal",
                   maximum = len(self.data["trustee_public_keys"]),
                   value = 0).grid(row = 3, column = 0)
        i = 1
        for trustee_key_list in self.data['trustee_public_keys']:
            print('Trustee :', i)
            //some code
            i = i+1
            ttk.Progressbar['value'] =  i

Everytime I run it I get the error:

 File "C:/Users/Student User/AppData/Roaming/JetBrains/PyCharmCE2020.1/scratches/scratch_17.py", line 81, in verify
ttk.Progressbar['value'] =  i
TypeError: 'type' object does not support item assignment

What am I doing wrong and how do I get the intended result?

Body:
Your code tries to assign a value to the progressbar type while you should assign the value to the instance of the progressbar.

def verify(self):
        tk.Label(self, text = 'Verifying Trustee Public Keys').grid(row = 2, column = 0)
        progress = ttk.Progressbar(self,
                   length = 100,
                   orient = "horizontal",
                   maximum = len(self.data["trustee_public_keys"]),
                   value = 0)
        progress.grid(row = 3, column = 0)
        i = 1
        for trustee_key_list in self.data['trustee_public_keys']:
            print('Trustee :', i)
            //some code
            i = i+1
            progress['value'] =  i


问:
How do I prevent more than one occurence of a specific character using regular expressions
I have a regular expression that uses numbered capture groups:

\\b${JOB_SEARCH_RESULTS_RANGE_KEY}\\s+((\\d+)-(\\d+)|\\*)/(\\d+|\\*)

That will parse a Content-Header:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range

Currently, this regular expression will allow a * on either side of range or size.  I want to catch if there is a * on both sides.

How can I do this?

I'm very new to regex.  Any help is greatly appreciated.

答:
I think you're trying to change the regular expression in such a way that it won't match the header containing*/*. The problem, however, is that your current expression matches all of these situations:

Content-Range: <unit> <range-start>-<range-end>/<size>

Content-Range: <unit> <range-start>-<range-end>/*

Content-Range: <unit> */<size>

Content-Range: <unit> */*

I can think of 5 ways to expand your regular expression that will only match the first three cases.

1. Positive lookahead (?=)

```<code>\\b${JOB_SEARCH_RESULTS_RANGE_KEY}\\s+((\\d+)-(\\d+)|\*(?=/\\d))/(\\d+|\\*)
</code>```

It only matches * if it's followed by / and a number

2. Negative lookahead (?!)

```<code>\\b${JOB_SEARCH_RESULTS_RANGE_KEY}\\s+((\\d+)-(\\d+)|\\*(?!/\\*))/(\\d+|\\*)
</code>```

It only matches * if it's not followed by /*

3. Positive lookbehind (?<=)

```<code>\\b${JOB_SEARCH_RESULTS_RANGE_KEY}\\s+((\\d+)-(\\d+)|\\*)/(\\d+|(?<=\\d/)\\*)
</code>```

It only matches * if it's preceded by a number and /

4. Negative lookbehind (?<!)

```<code>\\b${JOB_SEARCH_RESULTS_RANGE_KEY}\\s+((\\d+)-(\\d+)|\\*)/(\\d+|(?<!\\*/)\\*)
</code>```

It only matches * if it's not preceded by */

This page explains the so-called lookaround assertions in more detail: https://www.regular-expressions.info/lookaround.html

5. Using "or" (|)

```<code>\\b${JOB_SEARCH_RESULTS_RANGE_KEY}\\s+(((\\d+)-(\\d+)|\\*)/(\\d+)|((\\d+)-(\\d+))/(\\d+|\\*))
</code>```

To make this explanation more readable, let's take r for range and s for size where none of them are *. It takes the form of ((r or *)/s or (r/(s or *)) and it simply takes out the possibility to match */*.

Which one?

My lookaround examples (1-4) are pretty similar and you can choose any one of them. However, they are not fool-proof. They just check the nearest character on the other side of the slash (/) and therefore make the assumption that there is no malicious input such as Content-Range: bytes *1/*. You can expand the expression to catch these situations as well, but then you would be better of with the "or" example that I gave as it will be shorter, easier to read, and perhaps even faster in execution. The "or" example is just one of many and perhaps someone else can come up with an even shorter expression. My advice would be to choose the expression that looks the easiest to understand.

One more alternative that I did not list is to keep the original regular expression and make sure the string does not contain */* using a simple equals statement. It's perhaps the easiest solution to read.

Body:
I think you're trying to change the regular expression in such a way that it won't match the header containing*/*. The problem, however, is that your current expression matches all of these situations:

Content-Range: <unit> <range-start>-<range-end>/<size>

Content-Range: <unit> <range-start>-<range-end>/*

Content-Range: <unit> */<size>

Content-Range: <unit> */*

I can think of 5 ways to expand your regular expression that will only match the first three cases.

1. Positive lookahead (?=)

\\b${JOB_SEARCH_RESULTS_RANGE_KEY}\\s+((\\d+)-(\\d+)|\*(?=/\\d))/(\\d+|\\*)

It only matches * if it's followed by / and a number

2. Negative lookahead (?!)

\\b${JOB_SEARCH_RESULTS_RANGE_KEY}\\s+((\\d+)-(\\d+)|\\*(?!/\\*))/(\\d+|\\*)

It only matches * if it's not followed by /*

3. Positive lookbehind (?<=)

\\b${JOB_SEARCH_RESULTS_RANGE_KEY}\\s+((\\d+)-(\\d+)|\\*)/(\\d+|(?<=\\d/)\\*)

It only matches * if it's preceded by a number and /

4. Negative lookbehind (?<!)

\\b${JOB_SEARCH_RESULTS_RANGE_KEY}\\s+((\\d+)-(\\d+)|\\*)/(\\d+|(?<!\\*/)\\*)

It only matches * if it's not preceded by */

This page explains the so-called lookaround assertions in more detail: https://www.regular-expressions.info/lookaround.html

5. Using "or" (|)

\\b${JOB_SEARCH_RESULTS_RANGE_KEY}\\s+(((\\d+)-(\\d+)|\\*)/(\\d+)|((\\d+)-(\\d+))/(\\d+|\\*))

To make this explanation more readable, let's take r for range and s for size where none of them are *. It takes the form of ((r or *)/s or (r/(s or *)) and it simply takes out the possibility to match */*.

Which one?

My lookaround examples (1-4) are pretty similar and you can choose any one of them. However, they are not fool-proof. They just check the nearest character on the other side of the slash (/) and therefore make the assumption that there is no malicious input such as Content-Range: bytes *1/*. You can expand the expression to catch these situations as well, but then you would be better of with the "or" example that I gave as it will be shorter, easier to read, and perhaps even faster in execution. The "or" example is just one of many and perhaps someone else can come up with an even shorter expression. My advice would be to choose the expression that looks the easiest to understand.

One more alternative that I did not list is to keep the original regular expression and make sure the string does not contain */* using a simple equals statement. It's perhaps the easiest solution to read.


问:
Pytorch / device problem(cpu, gpu) when load state dict for optimizer
Hi i`m student who studies pytorch since last summer.

```<code>state = torch.load('drive/My Drive/MODEL/4 CBAM classifier55')

model = MyResNet()
model.load_state_dict(state['state_dict'])

criterion = nn.CrossEntropyLoss()

optimizer = optim.Adam(model.parameters(), lr=0.0003,betas=(0.5,0.999))
optimizer.load_state_dict(state['optimizer'])

model.to(device)
</code>```

i wrote code like above.

```<code>RuntimeError                              Traceback (most recent call last)
<ipython-input-26-507493db387a> in <module>()
     56     new_loss.backward()
     57
---> 58     optimizer.step()
     59
     60     running_loss += loss.item()

/usr/local/lib/python3.6/dist-packages/torch/autograd/grad_mode.py in decorate_context(*args, **kwargs)
     13         def decorate_context(*args, **kwargs):
     14             with self:
---> 15                 return func(*args, **kwargs)
     16         return decorate_context
     17

/usr/local/lib/python3.6/dist-packages/torch/optim/adam.py in step(self, closure)
     97
     98                 # Decay the first and second moment running average coefficient
---> 99                 exp_avg.mul_(beta1).add_(grad, alpha=1 - beta1)
    100                 exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=1 - beta2)
    101                 if amsgrad:

RuntimeError: expected device cpu but got device cuda:0
</code>```

And when i implement training code, then i got this kind of error. When i comment out 'optimizer.load_state_dict', it works well. How can i solve this problem? Thank you for your answer. :)

答:
Seems like the state was on cuda when you saved and now trying to use it on cpu or vice-versa. To avoid this error, a simple way is to pass the map_location argument to load.

Just pass map_location=<device you want to use> in torch.load and it should work fine. Also, see https://pytorch.org/tutorials/beginner/saving_loading_models.html#saving-loading-model-across-devices

Body:
Hi i`m student who studies pytorch since last summer.

state = torch.load('drive/My Drive/MODEL/4 CBAM classifier55')

model = MyResNet()
model.load_state_dict(state['state_dict'])

criterion = nn.CrossEntropyLoss()

optimizer = optim.Adam(model.parameters(), lr=0.0003,betas=(0.5,0.999))
optimizer.load_state_dict(state['optimizer'])

model.to(device)

i wrote code like above.

RuntimeError                              Traceback (most recent call last)
<ipython-input-26-507493db387a> in <module>()
     56     new_loss.backward()
     57
---> 58     optimizer.step()
     59
     60     running_loss += loss.item()

/usr/local/lib/python3.6/dist-packages/torch/autograd/grad_mode.py in decorate_context(*args, **kwargs)
     13         def decorate_context(*args, **kwargs):
     14             with self:
---> 15                 return func(*args, **kwargs)
     16         return decorate_context
     17

/usr/local/lib/python3.6/dist-packages/torch/optim/adam.py in step(self, closure)
     97
     98                 # Decay the first and second moment running average coefficient
---> 99                 exp_avg.mul_(beta1).add_(grad, alpha=1 - beta1)
    100                 exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=1 - beta2)
    101                 if amsgrad:

RuntimeError: expected device cpu but got device cuda:0

And when i implement training code, then i got this kind of error. When i comment out 'optimizer.load_state_dict', it works well. How can i solve this problem? Thank you for your answer. :)


问:
Why is ONE basic arithmetic operation in for loop body executed SLOWER THAN TWO arithmetic operations?
While I experimented with measuring time of execution of arithmetic operations, I came across very strange behavior. A code block containing a for loop with one arithmetic operation in the loop body was always executed slower than an identical code block, but with two arithmetic operations in the for loop body. Here is the code I ended up testing:

```<code>#include <iostream>
#include <chrono>

#define NUM_ITERATIONS 100000000

int main()
{
    // Block 1: one operation in loop body
    {
        int64_t x = 0, y = 0;
        auto start = std::chrono::high_resolution_clock::now();

        for (long i = 0; i < NUM_ITERATIONS; i++) {x+=31;}

        auto end = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double> diff = end-start;
        std::cout << diff.count() << " seconds. x,y = " << x << "," << y << std::endl;
    }

    // Block 2: two operations in loop body
    {
        int64_t x = 0, y = 0;
        auto start = std::chrono::high_resolution_clock::now();

        for (long i = 0; i < NUM_ITERATIONS; i++) {x+=17; y-=37;}

        auto end = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double> diff = end-start;
        std::cout << diff.count() << " seconds. x,y = " << x << "," << y << std::endl;
    }

    return 0;
}
</code>```

I tested this with different levels of code optimization (-O0,-O1,-O2,-O3), with different online compilers (for example onlinegdb.com), on my work machine, on my hame PC and laptop, on RaspberryPi and on my colleague's computer. I rearranged these two code blocks, repeated them, changed constants, changed operations (+, -, <<, =, etc.), changed integer types. But I always got similar result: the block with one line in loop is SLOWER than block with two lines:

1.05681 seconds. x,y = 3100000000,0

  0.90414 seconds. x,y = 1700000000,-3700000000

I checked the assembly output on https://godbolt.org/ but everything looked like I expected: second block just had one more operation in assembly output.

Three operations always behaved as expected: they are slower than one and faster than four. So why two operations produce such an anomaly?

Edit:

Let me repeat: I have such behaviour on all of my Windows and Unix machines with code not optimized. I looked at assembly I execute (Visual Studio, Windows) and I see the instructions I want to test there. Anyway if the loop is optimized away, there is nothing I ask about in the code which left. I added that optimizations notice in the question to avoid "do not measure not optimized code" answers because optimizations is not what I ask about. The question is actually why my computers execute two operations faster than one, first of all in code where these operations are not optimized away. The difference in time of execution is 5-25% on my tests (quite noticeable).

答:
I split up the code into C++ and assembly. I just wanted to test the loops, so I didn't return the sum(s). I'm running on Windows, the calling convention is rcx, rdx, r8, r9, the loop count is in rcx. The code is adding immediate values to 64 bit integers on the stack.

I'm getting similar times for both loops, less than 1% variation, same or either one up to 1% faster than the other.

There is an apparent dependency factor here: each add to memory has to wait for the prior add to memory to the same location to complete, so two add to memories can be performed essentially in parallel.

Changing test2 to do 3 add to memories, ends up about 6% slower, 4 add to memories, 7.5% slower.

My system is Intel 3770K 3.5 GHz CPU, Intel DP67BG motherboard, DDR3 1600 9-9-9-27 memory, Win 7 Pro 64 bit, Visual Studio 2015.

```<code>        .code
        public  test1
        align   16
test1   proc
        sub     rsp,16
        mov     qword ptr[rsp+0],0
        mov     qword ptr[rsp+8],0
tst10:  add     qword ptr[rsp+8],17
        dec     rcx
        jnz     tst10
        add     rsp,16
        ret
test1   endp

        public  test2
        align 16
test2   proc
        sub     rsp,16
        mov     qword ptr[rsp+0],0
        mov     qword ptr[rsp+8],0
tst20:  add     qword ptr[rsp+0],17
        add     qword ptr[rsp+8],-37
        dec     rcx
        jnz     tst20
        add     rsp,16
        ret
test2   endp

        end
</code>```

I also tested with add immediate to register, 1 or 2 registers within 1% (either could be faster, but we'd expect them both to execute at 1 iteration / clock on Ivy Bridge, given its 3 integer ALU ports; What considerations go into predicting latency for operations on modern superscalar processors and how can I calculate them by hand?).

3 registers 1.5 times as long, somewhat worse than the ideal 1.333 cycles / iterations from 4 uops (including the loop counter macro-fused dec/jnz) for 3 back-end ALU ports with perfect scheduling.

4 registers, 2.0 times as long, bottlenecked on the front-end: Is performance reduced when executing loops whose uop count is not a multiple of processor width?.  Haswell and later microarchitectures would handle this better.

```<code>        .code
        public  test1
        align   16
test1   proc
        xor     rdx,rdx
        xor     r8,r8
        xor     r9,r9
        xor     r10,r10
        xor     r11,r11
tst10:  add     rdx,17
        dec     rcx
        jnz     tst10
        ret
test1   endp

        public  test2
        align 16
test2   proc
        xor     rdx,rdx
        xor     r8,r8
        xor     r9,r9
        xor     r10,r10
        xor     r11,r11
tst20:  add     rdx,17
        add     r8,-37
        dec     rcx
        jnz     tst20
        ret
test2   endp

        public  test3
        align 16
test3   proc
        xor     rdx,rdx
        xor     r8,r8
        xor     r9,r9
        xor     r10,r10
        xor     r11,r11
tst30:  add     rdx,17
        add     r8,-37
        add     r9,47
        dec     rcx
        jnz     tst30
        ret
test3   endp

        public  test4
        align 16
test4   proc
        xor     rdx,rdx
        xor     r8,r8
        xor     r9,r9
        xor     r10,r10
        xor     r11,r11
tst40:  add     rdx,17
        add     r8,-37
        add     r9,47
        add     r10,-17
        dec     rcx
        jnz     tst40
        ret
test4   endp

        end
</code>```

Body:
While I experimented with measuring time of execution of arithmetic operations, I came across very strange behavior. A code block containing a for loop with one arithmetic operation in the loop body was always executed slower than an identical code block, but with two arithmetic operations in the for loop body. Here is the code I ended up testing:

#include <iostream>
#include <chrono>

#define NUM_ITERATIONS 100000000

int main()
{
    // Block 1: one operation in loop body
    {
        int64_t x = 0, y = 0;
        auto start = std::chrono::high_resolution_clock::now();

        for (long i = 0; i < NUM_ITERATIONS; i++) {x+=31;}

        auto end = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double> diff = end-start;
        std::cout << diff.count() << " seconds. x,y = " << x << "," << y << std::endl;
    }

    // Block 2: two operations in loop body
    {
        int64_t x = 0, y = 0;
        auto start = std::chrono::high_resolution_clock::now();

        for (long i = 0; i < NUM_ITERATIONS; i++) {x+=17; y-=37;}

        auto end = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double> diff = end-start;
        std::cout << diff.count() << " seconds. x,y = " << x << "," << y << std::endl;
    }

    return 0;
}

I tested this with different levels of code optimization (-O0,-O1,-O2,-O3), with different online compilers (for example onlinegdb.com), on my work machine, on my hame PC and laptop, on RaspberryPi and on my colleague's computer. I rearranged these two code blocks, repeated them, changed constants, changed operations (+, -, <<, =, etc.), changed integer types. But I always got similar result: the block with one line in loop is SLOWER than block with two lines:

1.05681 seconds. x,y = 3100000000,0

  0.90414 seconds. x,y = 1700000000,-3700000000

I checked the assembly output on https://godbolt.org/ but everything looked like I expected: second block just had one more operation in assembly output.

Three operations always behaved as expected: they are slower than one and faster than four. So why two operations produce such an anomaly?

Edit:

Let me repeat: I have such behaviour on all of my Windows and Unix machines with code not optimized. I looked at assembly I execute (Visual Studio, Windows) and I see the instructions I want to test there. Anyway if the loop is optimized away, there is nothing I ask about in the code which left. I added that optimizations notice in the question to avoid "do not measure not optimized code" answers because optimizations is not what I ask about. The question is actually why my computers execute two operations faster than one, first of all in code where these operations are not optimized away. The difference in time of execution is 5-25% on my tests (quite noticeable).

Body:
I split up the code into C++ and assembly. I just wanted to test the loops, so I didn't return the sum(s). I'm running on Windows, the calling convention is rcx, rdx, r8, r9, the loop count is in rcx. The code is adding immediate values to 64 bit integers on the stack.

I'm getting similar times for both loops, less than 1% variation, same or either one up to 1% faster than the other.

There is an apparent dependency factor here: each add to memory has to wait for the prior add to memory to the same location to complete, so two add to memories can be performed essentially in parallel.

Changing test2 to do 3 add to memories, ends up about 6% slower, 4 add to memories, 7.5% slower.

My system is Intel 3770K 3.5 GHz CPU, Intel DP67BG motherboard, DDR3 1600 9-9-9-27 memory, Win 7 Pro 64 bit, Visual Studio 2015.

        .code
        public  test1
        align   16
test1   proc
        sub     rsp,16
        mov     qword ptr[rsp+0],0
        mov     qword ptr[rsp+8],0
tst10:  add     qword ptr[rsp+8],17
        dec     rcx
        jnz     tst10
        add     rsp,16
        ret
test1   endp

        public  test2
        align 16
test2   proc
        sub     rsp,16
        mov     qword ptr[rsp+0],0
        mov     qword ptr[rsp+8],0
tst20:  add     qword ptr[rsp+0],17
        add     qword ptr[rsp+8],-37
        dec     rcx
        jnz     tst20
        add     rsp,16
        ret
test2   endp

        end

I also tested with add immediate to register, 1 or 2 registers within 1% (either could be faster, but we'd expect them both to execute at 1 iteration / clock on Ivy Bridge, given its 3 integer ALU ports; What considerations go into predicting latency for operations on modern superscalar processors and how can I calculate them by hand?).

3 registers 1.5 times as long, somewhat worse than the ideal 1.333 cycles / iterations from 4 uops (including the loop counter macro-fused dec/jnz) for 3 back-end ALU ports with perfect scheduling.

4 registers, 2.0 times as long, bottlenecked on the front-end: Is performance reduced when executing loops whose uop count is not a multiple of processor width?.  Haswell and later microarchitectures would handle this better.

        .code
        public  test1
        align   16
test1   proc
        xor     rdx,rdx
        xor     r8,r8
        xor     r9,r9
        xor     r10,r10
        xor     r11,r11
tst10:  add     rdx,17
        dec     rcx
        jnz     tst10
        ret
test1   endp

        public  test2
        align 16
test2   proc
        xor     rdx,rdx
        xor     r8,r8
        xor     r9,r9
        xor     r10,r10
        xor     r11,r11
tst20:  add     rdx,17
        add     r8,-37
        dec     rcx
        jnz     tst20
        ret
test2   endp

        public  test3
        align 16
test3   proc
        xor     rdx,rdx
        xor     r8,r8
        xor     r9,r9
        xor     r10,r10
        xor     r11,r11
tst30:  add     rdx,17
        add     r8,-37
        add     r9,47
        dec     rcx
        jnz     tst30
        ret
test3   endp

        public  test4
        align 16
test4   proc
        xor     rdx,rdx
        xor     r8,r8
        xor     r9,r9
        xor     r10,r10
        xor     r11,r11
tst40:  add     rdx,17
        add     r8,-37
        add     r9,47
        add     r10,-17
        dec     rcx
        jnz     tst40
        ret
test4   endp

        end


问:
Cut transparent hole in UIView using UIImageView
I'm trying to create the image below for my QR camera view.

I have an image for the camera overlay (which is the square in the middle of the screen).

Ive looked at similar topics on stackoverflow and found out how to cut out the camera overlay image from the black background (0.75% transparent) so that it leaves the empty space in the middle, however I'm having some real issues with its placement, and I cant find out what is behaving so weirdly.

Here is the code that I use to create the background black image and also to cut out the square in the center:

```<code>            // Create a view filling the screen.
        let backgroundView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))

        // Set a semi-transparent, black background.
        backgroundView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.75)

        // Create the initial layer from the view bounds.
        let maskLayer = CAShapeLayer()
        maskLayer.frame = backgroundView.bounds
        maskLayer.fillColor = UIColor.black.cgColor

        // Create the path.
        let path = UIBezierPath(rect: backgroundView.bounds)
        maskLayer.fillRule = CAShapeLayerFillRule.evenOdd

        // Append the overlay image to the path so that it is subtracted.
        path.append(UIBezierPath(rect: camOverlayImageView.frame))
        maskLayer.path = path.cgPath

        // Set the mask of the view.
        backgroundView.layer.mask = maskLayer

        // Add the view so it is visible.
        self.view.addSubview(backgroundView)
</code>```

The camOverlayImageView is created in storyboard and all I'm using on it are constraints to center it both vertically and horizontally to the superview like this:

However, when I do this, this is what I'm getting on the device:

If anyone might know what might be causing this or how to fix it, it would be greatly appreciated as I can't seem to find it.

I can of course manually move the frame and offset it like this but that isn't the correct way to do this:

```<code>            let overlayFrame = camOverlayImageView.frame
        // Append the overlay image to the path so that it is subtracted.
        path.append(UIBezierPath(rect: CGRect(
            x: overlayFrame.origin.x + 18,
            y: overlayFrame.origin.y - 6,
            width: overlayFrame.size.width,
            height: overlayFrame.size.height))
        )
        maskLayer.path = path.cgPath
</code>```

Instead of doing what I was previously doing:

```<code>path.append(UIBezierPath(rect: camOverlayImageView.frame))
maskLayer.path = path.cgPath
</code>```

答:
Most likely...

You are creating your mask too early - before auto-layout has sized / positioned the views.

Try it like this:

```<code>class HoleInViewController: UIViewController {

    @IBOutlet var camOverlayImageView: UIView!

    let backgroundView: UIView = {
        let v = UIView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = UIColor.black.withAlphaComponent(0.75)
        return v
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(backgroundView)
        NSLayoutConstraint.activate([
            backgroundView.topAnchor.constraint(equalTo: view.topAnchor),
            backgroundView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            backgroundView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            backgroundView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
        ])

    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        // Create the initial layer from the view bounds.
        let maskLayer = CAShapeLayer()
        maskLayer.frame = backgroundView.bounds
        maskLayer.fillColor = UIColor.black.cgColor

        // Create the path.
        let path = UIBezierPath(rect: backgroundView.bounds)
        maskLayer.fillRule = CAShapeLayerFillRule.evenOdd

        // Append the overlay image to the path so that it is subtracted.
        path.append(UIBezierPath(rect: camOverlayImageView.frame))
        maskLayer.path = path.cgPath

        // Set the mask of the view.
        backgroundView.layer.mask = maskLayer

    }

}
</code>```

Body:
I'm trying to create the image below for my QR camera view.

I have an image for the camera overlay (which is the square in the middle of the screen).

Ive looked at similar topics on stackoverflow and found out how to cut out the camera overlay image from the black background (0.75% transparent) so that it leaves the empty space in the middle, however I'm having some real issues with its placement, and I cant find out what is behaving so weirdly.

Here is the code that I use to create the background black image and also to cut out the square in the center:

            // Create a view filling the screen.
        let backgroundView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))

        // Set a semi-transparent, black background.
        backgroundView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.75)

        // Create the initial layer from the view bounds.
        let maskLayer = CAShapeLayer()
        maskLayer.frame = backgroundView.bounds
        maskLayer.fillColor = UIColor.black.cgColor

        // Create the path.
        let path = UIBezierPath(rect: backgroundView.bounds)
        maskLayer.fillRule = CAShapeLayerFillRule.evenOdd

        // Append the overlay image to the path so that it is subtracted.
        path.append(UIBezierPath(rect: camOverlayImageView.frame))
        maskLayer.path = path.cgPath

        // Set the mask of the view.
        backgroundView.layer.mask = maskLayer

        // Add the view so it is visible.
        self.view.addSubview(backgroundView)

The camOverlayImageView is created in storyboard and all I'm using on it are constraints to center it both vertically and horizontally to the superview like this:

However, when I do this, this is what I'm getting on the device:

If anyone might know what might be causing this or how to fix it, it would be greatly appreciated as I can't seem to find it.

I can of course manually move the frame and offset it like this but that isn't the correct way to do this:

            let overlayFrame = camOverlayImageView.frame
        // Append the overlay image to the path so that it is subtracted.
        path.append(UIBezierPath(rect: CGRect(
            x: overlayFrame.origin.x + 18,
            y: overlayFrame.origin.y - 6,
            width: overlayFrame.size.width,
            height: overlayFrame.size.height))
        )
        maskLayer.path = path.cgPath

Instead of doing what I was previously doing:

path.append(UIBezierPath(rect: camOverlayImageView.frame))
maskLayer.path = path.cgPath

Body:
Most likely...

You are creating your mask too early - before auto-layout has sized / positioned the views.

Try it like this:

class HoleInViewController: UIViewController {

    @IBOutlet var camOverlayImageView: UIView!

    let backgroundView: UIView = {
        let v = UIView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = UIColor.black.withAlphaComponent(0.75)
        return v
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(backgroundView)
        NSLayoutConstraint.activate([
            backgroundView.topAnchor.constraint(equalTo: view.topAnchor),
            backgroundView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            backgroundView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            backgroundView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
        ])

    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        // Create the initial layer from the view bounds.
        let maskLayer = CAShapeLayer()
        maskLayer.frame = backgroundView.bounds
        maskLayer.fillColor = UIColor.black.cgColor

        // Create the path.
        let path = UIBezierPath(rect: backgroundView.bounds)
        maskLayer.fillRule = CAShapeLayerFillRule.evenOdd

        // Append the overlay image to the path so that it is subtracted.
        path.append(UIBezierPath(rect: camOverlayImageView.frame))
        maskLayer.path = path.cgPath

        // Set the mask of the view.
        backgroundView.layer.mask = maskLayer

    }

}


问:
How to split a list which contains sentences into a list with words using Python?
I have a list with sentences in Python:

```<code>list1 = ["This is the first sentence", "This is the second", "This is the third"]
</code>```

I tried using split(" "):

```<code>sth = []
for i in list1:
    sth.append(i.split(" "))
</code>```

But this way I get a 2D array, which contains regular lists from the sentences with their words, so something like this:

```<code>[["This", "is", "the", "first", "sentence"], ["This", "is", "the", "second"], ["This", "is", "the", "third"]]
</code>```

I would like the outcome to be a regular list, this way:

```<code>["This", "is", "the", "first", "sentence", "This", "is", "the", "second", "This", "is", "the", "third"]
</code>```

How can I achieve this?

答:
try using extend instead of append.
full code:

```<code>list1 = ["This is the first sentence", "This is the second", "This is the third"]
sth = []
for i in list1:
    sth.extend(i.split(" "))
</code>```

Output:

```<code>['This', 'is', 'the', 'first', 'sentence', 'This', 'is', 'the', 'second', 'This', 'is', 'the', 'third']

</code>```

Body:
I have a list with sentences in Python:

list1 = ["This is the first sentence", "This is the second", "This is the third"]

I tried using split(" "):

sth = []
for i in list1:
    sth.append(i.split(" "))

But this way I get a 2D array, which contains regular lists from the sentences with their words, so something like this:

[["This", "is", "the", "first", "sentence"], ["This", "is", "the", "second"], ["This", "is", "the", "third"]]

I would like the outcome to be a regular list, this way:

["This", "is", "the", "first", "sentence", "This", "is", "the", "second", "This", "is", "the", "third"]

How can I achieve this?

Body:
try using extend instead of append.
full code:

list1 = ["This is the first sentence", "This is the second", "This is the third"]
sth = []
for i in list1:
    sth.extend(i.split(" "))

Output:

['This', 'is', 'the', 'first', 'sentence', 'This', 'is', 'the', 'second', 'This', 'is', 'the', 'third']


问:
How to solve "The directory is not empty" error when running rmdir command in a batch script?
I am making a batch script and part of the script is trying to remove a directory and all of its sub-directories. I am getting an intermittent error about a sub-directory not being empty. I read one article about indexing being the culprit. I disabled WSearch but I eventually got the error again. Here's the command:</p>
```<code>rmdir /S /Q "C:\<dir>\"
</code>```

答:
Windows sometimes is "broken by design", so you need to create an empty folder, and then mirror the "broken folder" with an "empty folder" with backup mode.

```<code>robocopy - cmd copy utility

/copyall - copies everything
/mir deletes item if there is no such item in source a.k.a mirrors source with
destination
/b works around premissions shenanigans
</code>```

Create en empty dir like this:

```<code>mkdir empty
</code>```

overwrite broken folder with empty like this:

```<code>robocopy /copyall /mir /b empty broken
</code>```

and then delete that folder

```<code>rd broken /s
rd empty /s
</code>```

If this does not help, try restarting in "recovery mode with command prompt" by holding shift when clicking restart and trying to run these command again in recovery mode

Body:
I am making a batch script and part of the script is trying to remove a directory and all of its sub-directories. I am getting an intermittent error about a sub-directory not being empty. I read one article about indexing being the culprit. I disabled WSearch but I eventually got the error again. Here's the command:

rmdir /S /Q "C:\<dir>\"

Body:
Windows sometimes is "broken by design", so you need to create an empty folder, and then mirror the "broken folder" with an "empty folder" with backup mode.

robocopy - cmd copy utility

/copyall - copies everything
/mir deletes item if there is no such item in source a.k.a mirrors source with
destination
/b works around premissions shenanigans

Create en empty dir like this:

mkdir empty

overwrite broken folder with empty like this:

robocopy /copyall /mir /b empty broken

and then delete that folder

rd broken /s
rd empty /s

If this does not help, try restarting in "recovery mode with command prompt" by holding shift when clicking restart and trying to run these command again in recovery mode


问:
Problem with #ifndef and #pragma once
I want write the program with next struct

stdafx.h - contains some #define defenitions of program constants and #include of headers wich uses in all project.

frmMain.h - contatins code of Form1 also can Show form2 and uses some code from BckHeadr.h and some functions call that headers included in stdafx.h.

frmIniPrgs.h - contatins code of Form2 and uses some code from BckHeadr.h and some functions call that headers included in stdafx.h.

BckHeadr.h - contatins some definitions of functions and some functions call that headers included in stdafx.h.

I know what i must use #ifndef or #pragma once directives. But i can not decided this problem. I included in stdafx.h: frmIniPrgs.H, BckHeadr.h, frmMain.h. And use #ifndef in all modules. I uset it like this:

```<code>#ifndef MYMODULE_H
#define MYMODULE_H
//module code
#endif
</code>```

There is next errors in my project (i have russian visual studio and text of errors is translate by google translate and may contain the errors, ScnIniPackages is my function in BckHeadr.h ):

```<code>BckHeadr.h (96): error C3861: PtrToStringChars: identifier not found
BckHeadr.h (141): error C2065: vector: undeclared identifier
BckHeadr.h (141): error C2062: type "int" is not required
BckHeadr.h (141): error C2143: syntax error: no ";" before "("
BckHeadr.h (141): error C2447: (: missing function header (possibly using a formal list of old type)
BckHeadr.h (169): error C2065: vector: undeclared identifier
frmIniPrgs.h (119): error C2065: vector: undeclared identifier
frmIniPrgs.h (122): error C3861: ScnIniPackages: identifier not found
frmIniPrgs.h (121): error C2065: vector: undeclared identifier
C: \ Program Files \ Microsoft SDKs \ Windows \ v6.0A \ include \ Wininet.h (381): error C2872: FILETIME: ambiguous symbol
    be 'C: \ Program Files \ Microsoft SDKs \ Windows \ v6.0A \ include \ windef.h (377): _FILETIME FILETIME'
    or 'c: \ windows \ microsoft.net \ framework \ v2.0.50727 \ mscorlib.dll: System:: Runtime:: InteropServices:: FILETIME'
</code>```

答:
Try

```<code>#include <vector>
using namespace std;
</code>```

This may solve some of the errors (if not all).

ContentLicense: CC BY-SA 2.5

Title: Problem with #ifndef and #pragma once

Body:
I want write the program with next struct

stdafx.h - contains some #define defenitions of program constants and #include of headers wich uses in all project.

frmMain.h - contatins code of Form1 also can Show form2 and uses some code from BckHeadr.h and some functions call that headers included in stdafx.h.

frmIniPrgs.h - contatins code of Form2 and uses some code from BckHeadr.h and some functions call that headers included in stdafx.h.

BckHeadr.h - contatins some definitions of functions and some functions call that headers included in stdafx.h.

I know what i must use #ifndef or #pragma once directives. But i can not decided this problem. I included in stdafx.h: frmIniPrgs.H, BckHeadr.h, frmMain.h. And use #ifndef in all modules. I uset it like this:

#ifndef MYMODULE_H
#define MYMODULE_H
//module code
#endif

There is next errors in my project (i have russian visual studio and text of errors is translate by google translate and may contain the errors, ScnIniPackages is my function in BckHeadr.h ):

BckHeadr.h (96): error C3861: PtrToStringChars: identifier not found
BckHeadr.h (141): error C2065: vector: undeclared identifier
BckHeadr.h (141): error C2062: type "int" is not required
BckHeadr.h (141): error C2143: syntax error: no ";" before "("
BckHeadr.h (141): error C2447: (: missing function header (possibly using a formal list of old type)
BckHeadr.h (169): error C2065: vector: undeclared identifier
frmIniPrgs.h (119): error C2065: vector: undeclared identifier
frmIniPrgs.h (122): error C3861: ScnIniPackages: identifier not found
frmIniPrgs.h (121): error C2065: vector: undeclared identifier
C: \ Program Files \ Microsoft SDKs \ Windows \ v6.0A \ include \ Wininet.h (381): error C2872: FILETIME: ambiguous symbol
    be 'C: \ Program Files \ Microsoft SDKs \ Windows \ v6.0A \ include \ windef.h (377): _FILETIME FILETIME'
    or 'c: \ windows \ microsoft.net \ framework \ v2.0.50727 \ mscorlib.dll: System:: Runtime:: InteropServices:: FILETIME'

Body:
Try

#include <vector>
using namespace std;

This may solve some of the errors (if not all).