问:
View is re-initialized after DragGesture onChanged
The following code shows an orange screen with a green circle in the lower right. The circle can be dragged.

```<code>import SwiftUI

struct DraggableCircle: View {
    @Binding var offset: CGSize
    @State private var previousOffset: CGSize

    var body: some View {
        Circle().fill(Color.green)
            .frame(width: 100)
            .offset(self.offset)
            .gesture(
                DragGesture(minimumDistance: 0, coordinateSpace: .local)
                    .onChanged { event in
                        print("\nDragGesture onChanged")
                        self.offset = CGSize(width: event.location.x - (event.startLocation.x - self.previousOffset.width),
                                             height: event.location.y - (event.startLocation.y - self.previousOffset.height))
                    }
            )
    }

    init(offset: Binding<CGSize>) {
        print("Init with offset \(offset.wrappedValue)")
        self._offset = offset
        self._previousOffset = State(initialValue: offset.wrappedValue)
        print("offset = \(self.offset), previousOffset=\(self.previousOffset)")
    }
}

struct ContentView: View {
    @State var circleOffset = CGSize()

    var body: some View {
        GeometryReader { reader in
            Rectangle().fill(Color.orange)
                .overlay(
                    DraggableCircle(offset: self.$circleOffset)
                )
                .onAppear {
                    self.circleOffset = CGSize(width: reader.size.width / 2,
                                               height: reader.size.height / 2)
                    print("size: \(reader)\n")
                }
        }
    }
}
</code>```

If you run and tap the green circle (to begin a drag gesture), the following appears in the console:

```<code>Init with offset (0.0, 0.0)
offset = (0.0, 0.0), previousOffset=(0.0, 0.0)
size: GeometryProxy(base: SwiftUI._PositionAwareLayoutContext(base: SwiftUI.LayoutTraitsContext(context: AttributeGraph.AttributeContext<SwiftUI.VoidAttribute>(graph: __C.AGGraphRef(p: 0x00007f84b6a05ff0), attribute: AttributeGraph.Attribute<()>(identifier: __C.AGAttribute(id: 42))), environmentIndex: 4), dimensionsIndex: 1, transformIndex: 3, positionIndex: 2), seed: 1, viewGraph: Optional(SwiftUI.ViewGraph))

Init with offset (187.5, 323.5)
offset = (187.5, 323.5), previousOffset=(187.5, 323.5)

DragGesture onChanged
Init with offset (0.0, 0.0)
offset = (0.0, 0.0), previousOffset=(0.0, 0.0)
</code>```

What I expected to happen, is that when you drag the circle, it can be smoothly dragged somewhere else on the screen.

What actually happens, is when dragging starts, DraggableCircle.init is called again, which resets the offset and places the circle right in the middle. Why is this?

Note: when you move the @State previousOffset into the ContentView, the issue disappears. But I don't understand why.

答:
I changed my code based on your comment. In my code this drag gesture workes fine. The only bug right now I see is in the first time drag gesture is activated. Maybe this will lead you to your desired solution. </p>

```<code>        struct DraggableCircle: View {
    @Binding var circleOffset: CGSize
    @State private var previousOffset: CGSize

    var body: some View {
        Circle().fill(Color.green)
            .frame(width: 100)
            .offset(self.circleOffset)
            .gesture(
                DragGesture()
                    .onChanged { event in
                        print("\nDragGesture onChanged")
                            self.circleOffset = CGSize(width: event.location.x - (event.startLocation.x - self.previousOffset.width),
                                                       height: event.location.y - (event.startLocation.y - self.previousOffset.height))
                }
                .onEnded { event in
                    self.circleOffset = CGSize(width: event.location.x - (event.startLocation.x - self.previousOffset.width),
                                               height: event.location.y - (event.startLocation.y - self.previousOffset.height))

                    self.previousOffset = self.circleOffset
                }
        )
    }

    init(offset: Binding<CGSize>) {
        print("Init with offset \(offset.wrappedValue)")
        self._circleOffset = offset
        self._previousOffset = State(initialValue: offset.wrappedValue)
        print("offset = \(self.offset), previousOffset=\(self.previousOffset)")
    }
}

struct ContentView: View {
    @State var circleOffset = CGSize()

    var body: some View {
        GeometryReader { reader in
            Rectangle().fill(Color.orange)
                .overlay(
                    DraggableCircle(offset: self.$circleOffset)
                )
                .onAppear {
                    self.circleOffset = CGSize(width: reader.size.width / 2,
                                               height: reader.size.height / 2)
                    print("size: \(reader)\n")
                }
        }
    }
}
</code>```

Body:
The following code shows an orange screen with a green circle in the lower right. The circle can be dragged.

import SwiftUI

struct DraggableCircle: View {
    @Binding var offset: CGSize
    @State private var previousOffset: CGSize

    var body: some View {
        Circle().fill(Color.green)
            .frame(width: 100)
            .offset(self.offset)
            .gesture(
                DragGesture(minimumDistance: 0, coordinateSpace: .local)
                    .onChanged { event in
                        print("\nDragGesture onChanged")
                        self.offset = CGSize(width: event.location.x - (event.startLocation.x - self.previousOffset.width),
                                             height: event.location.y - (event.startLocation.y - self.previousOffset.height))
                    }
            )
    }

    init(offset: Binding<CGSize>) {
        print("Init with offset \(offset.wrappedValue)")
        self._offset = offset
        self._previousOffset = State(initialValue: offset.wrappedValue)
        print("offset = \(self.offset), previousOffset=\(self.previousOffset)")
    }
}

struct ContentView: View {
    @State var circleOffset = CGSize()

    var body: some View {
        GeometryReader { reader in
            Rectangle().fill(Color.orange)
                .overlay(
                    DraggableCircle(offset: self.$circleOffset)
                )
                .onAppear {
                    self.circleOffset = CGSize(width: reader.size.width / 2,
                                               height: reader.size.height / 2)
                    print("size: \(reader)\n")
                }
        }
    }
}

If you run and tap the green circle (to begin a drag gesture), the following appears in the console:

Init with offset (0.0, 0.0)
offset = (0.0, 0.0), previousOffset=(0.0, 0.0)
size: GeometryProxy(base: SwiftUI._PositionAwareLayoutContext(base: SwiftUI.LayoutTraitsContext(context: AttributeGraph.AttributeContext<SwiftUI.VoidAttribute>(graph: __C.AGGraphRef(p: 0x00007f84b6a05ff0), attribute: AttributeGraph.Attribute<()>(identifier: __C.AGAttribute(id: 42))), environmentIndex: 4), dimensionsIndex: 1, transformIndex: 3, positionIndex: 2), seed: 1, viewGraph: Optional(SwiftUI.ViewGraph))

Init with offset (187.5, 323.5)
offset = (187.5, 323.5), previousOffset=(187.5, 323.5)

DragGesture onChanged
Init with offset (0.0, 0.0)
offset = (0.0, 0.0), previousOffset=(0.0, 0.0)

What I expected to happen, is that when you drag the circle, it can be smoothly dragged somewhere else on the screen.

What actually happens, is when dragging starts, DraggableCircle.init is called again, which resets the offset and places the circle right in the middle. Why is this?

Note: when you move the @State previousOffset into the ContentView, the issue disappears. But I don't understand why.

Body:
I changed my code based on your comment. In my code this drag gesture workes fine. The only bug right now I see is in the first time drag gesture is activated. Maybe this will lead you to your desired solution.

        struct DraggableCircle: View {
    @Binding var circleOffset: CGSize
    @State private var previousOffset: CGSize

    var body: some View {
        Circle().fill(Color.green)
            .frame(width: 100)
            .offset(self.circleOffset)
            .gesture(
                DragGesture()
                    .onChanged { event in
                        print("\nDragGesture onChanged")
                            self.circleOffset = CGSize(width: event.location.x - (event.startLocation.x - self.previousOffset.width),
                                                       height: event.location.y - (event.startLocation.y - self.previousOffset.height))
                }
                .onEnded { event in
                    self.circleOffset = CGSize(width: event.location.x - (event.startLocation.x - self.previousOffset.width),
                                               height: event.location.y - (event.startLocation.y - self.previousOffset.height))

                    self.previousOffset = self.circleOffset
                }
        )
    }

    init(offset: Binding<CGSize>) {
        print("Init with offset \(offset.wrappedValue)")
        self._circleOffset = offset
        self._previousOffset = State(initialValue: offset.wrappedValue)
        print("offset = \(self.offset), previousOffset=\(self.previousOffset)")
    }
}

struct ContentView: View {
    @State var circleOffset = CGSize()

    var body: some View {
        GeometryReader { reader in
            Rectangle().fill(Color.orange)
                .overlay(
                    DraggableCircle(offset: self.$circleOffset)
                )
                .onAppear {
                    self.circleOffset = CGSize(width: reader.size.width / 2,
                                               height: reader.size.height / 2)
                    print("size: \(reader)\n")
                }
        }
    }
}


来源: stackexchange

问:
TypeError: Unexpected keyword argument passed to optimizer: learning_rate
I am trying to load a Keras model which was trained on an Azure VM (NC promo). But I am getting the following error.

TypeError: Unexpected keyword argument passed to optimizer:learning_rate

EDIT:

Here is the code snippet that I am using to load my model:

```<code>from keras.models import load_model
model = load_model('my_model_name.h5')
</code>```

答:
It was a simple fix for me. Check your tensorflow version.
I trained my model on 1.14 and was predicting it on 2.0

I used 1.14 again and it worked

ContentLicense: CC BY-SA 4.0

Body:
I am trying to load a Keras model which was trained on an Azure VM (NC promo). But I am getting the following error.

TypeError: Unexpected keyword argument passed to optimizer:learning_rate

EDIT:

Here is the code snippet that I am using to load my model:

from keras.models import load_model
model = load_model('my_model_name.h5')


问:
How to select default item in detail view for iPad? (in Split View Controller)
I'm using a split-view controller. For iPad, when the app starts, I want to selected in the first item in master-view controller. So how can I do that in Swift? Thanks!</p>

答:
Converted to Swift 5 after fixing automatic errors

let initialIndexPath = NSIndexPath(row: 0, section: 0)
self.tableView.selectRow(at: initialIndexPath as IndexPath, animated: true, scrollPosition:UITableView.ScrollPosition.none)

if UIDevice.current.userInterfaceIdiom == .pad {
    self.performSegue(withIdentifier: "ShowDetail", sender: initialIndexPath)
}
```

ContentLicense: CC BY-SA 3.0


问:
Going through a JSON file and displaying all elements
So I have a JSON file that I am fetching from github. And I have certain problems. My JSON file:

```<code>{    "Data" :
[
{"Name": "Widget", "Price": "25.00", "Quantity": "5" },
{"Name": "Thing", "Price": "15.00", "Quantity": "5" },
{"Name": "Doodad", "Price": "5.00", "Quantity": "10" }
] }
</code>```

Now, I am writing in a .html file and have a script section in which I want to write a JavaScript function that will allow me to go through Data from JSON and for example display the names of all the products that are there:

```<code> <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
    <body>
        <div>
            <form id="form1">
                What product do you want? <input name="name" type="text" size="20">
            </form>
            <button onclick="outputprodus()">Submit
            </button>
            <button id="fetchUserDataBtn">Cauta</button>
        </div>
        <hr>
        <div id="response"></div>
        <script>
            document.getElementById('fetchUserDataBtn').addEventListener('click', fetchUserData);

            function fetchUserData(){
                fetch('Vlad.json')
                    .then(response => response.json())
                    .then(Data => {
                        console.log("salut");
                        let output = "Lista produselor din stoc"
                        output += '<ul>';
                        Data.forEach(function(Data) {
                            output += `
                                <li>
                                    ${Data.Name}
                                </li>
                            `;
                        });
                        output += '</ul>'
                        document.getElementById("response").innerHTML = output;
                    });
            }
    </script>
    </body>
</html>
</code>```

When I run it, I get the error "Data.forEach is not a function". Funny enough is that when I write my JSON file without the initial "{"Data:" and just begin immediately writing the name for all objects, this problem does not occur and I can get a list of all the names of the products using the script above. However I want to use a loop to identify certain objects using a user input I will later add. Can anyone elucidate this for me?

答:
You are trying to iterate an object which is not possible. You need to iterate the array which is the Data property. So you need to do it like this:
Data.Data.forEach(function(Data) { or Data['Data'].forEach(function(Data) {

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors

Body:
So I have a JSON file that I am fetching from github. And I have certain problems. My JSON file:

{    "Data" :
[
{"Name": "Widget", "Price": "25.00", "Quantity": "5" },
{"Name": "Thing", "Price": "15.00", "Quantity": "5" },
{"Name": "Doodad", "Price": "5.00", "Quantity": "10" }
] }

Now, I am writing in a .html file and have a script section in which I want to write a JavaScript function that will allow me to go through Data from JSON and for example display the names of all the products that are there:

 <!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

            <form id="form1">
                What product do you want? <input name="name" type="text" size="20">
            </form>
            <button onclick="outputprodus()">Submit
            </button>
            <button id="fetchUserDataBtn">Cauta</button>

When I run it, I get the error "Data.forEach is not a function". Funny enough is that when I write my JSON file without the initial "{"Data:" and just begin immediately writing the name for all objects, this problem does not occur and I can get a list of all the names of the products using the script above. However I want to use a loop to identify certain objects using a user input I will later add. Can anyone elucidate this for me?


问:
Code Generators or T4 Templates, are they really evil?
I have heard people state that Code Generators and T4 templates should not be used. The logic behind that is that if you are generating code with a generator then there is a better more efficient way to build the code through generics and templating.

While I slightly agree with this statement above, I have not really found effective ways to build templates that can say for instance instantiate themselves. In otherwords I can never do :

```<code>return new T();
</code>```

Additionally, if I want to generate code based on database values I have found that using Microsoft.SqlServer.Management.SMO in conjunction with T4 templates have been wonderful at generating mass amounts of code without having to copy / paste or use resharper.

Many of the problems I have found with Generics too is that to my shock there are a lot of developers who do not understand them. When I do examine generics for a solution, there are times where it gets complicated because C# states that you cannot do something that may seem logical in my mind.

What are your thoughts? Do you prefer to build a generator, or do you prefer to use generics? Also, how far can generics go? I know a decent amount about generics, but there are traps and pitfalls that I always run into that cause me to resort to a T4 template.

What is the more proper way to handle scenarios where you need a large amount of flexibility? Oh and as a bonus to this question, what are good resources on C# and Generics?

答:
Code generation is for me a workaround for many problems found in language, frameworks, etc. They are not evil by themselves, I would say it is very very bad (i.e. evil) to release a language (C#) and framework which forces you to copy&paste (swap on properties, events triggering, lack of macros) or use magical numbers (wpf binding).

So, I cry, but I use them, because I have to.

OwnerDisplayName: jwendl

Body:
I have heard people state that Code Generators and T4 templates should not be used. The logic behind that is that if you are generating code with a generator then there is a better more efficient way to build the code through generics and templating.

While I slightly agree with this statement above, I have not really found effective ways to build templates that can say for instance instantiate themselves. In otherwords I can never do :

return new T();

Additionally, if I want to generate code based on database values I have found that using Microsoft.SqlServer.Management.SMO in conjunction with T4 templates have been wonderful at generating mass amounts of code without having to copy / paste or use resharper.

Many of the problems I have found with Generics too is that to my shock there are a lot of developers who do not understand them. When I do examine generics for a solution, there are times where it gets complicated because C# states that you cannot do something that may seem logical in my mind.

What are your thoughts? Do you prefer to build a generator, or do you prefer to use generics? Also, how far can generics go? I know a decent amount about generics, but there are traps and pitfalls that I always run into that cause me to resort to a T4 template.

What is the more proper way to handle scenarios where you need a large amount of flexibility? Oh and as a bonus to this question, what are good resources on C# and Generics?

LastEditorDisplayName: Morendil


问:
TypeScript creating a type based on number of parameters
Why does the extends clause succeed when checking whether a 0-arity function extends a 1-arity type?

Is there any way to make the first form work?

The same check on tuples works as I'd expect, so I can use Parameters instead, but I'm curious as to why.

function foo(bar: number) {
  // ...
}

function baz() {
  // ...
}

type Foo = typeof foo extends (bar: infer T) => void ? T : never; // number - expected number
type Baz = typeof baz extends (bar: infer T) => void ? T : never; // unknown - expected never

type Foo2 = Parameters<typeof foo> extends [infer T] ? T : never; // number - ok
type Baz2 = Parameters<typeof baz> extends [infer T] ? T : never; // never - ok
```

Playground Link

答:
I find this behavior strange myself, but the issue is that TypeScript says that less parameters is a subtype of more parameters. What this means is that () => void extends (x: number) => void, but not vice versa. TypeScript doesn't know the value of the parameter in type Baz (since there are no parameters in typeof baz) so it says the extends clause is true and sets T to unknown.

On the other hand, tuple types can't really extend each other unless the type in each index of the subtype tuple extend the value of the corresponding index in the supertype tuple (i.e. it's true that [number & string, number] extends [number, number]). That means when there are a different number of parameters, the extends clause always returns false and makes your second example work.

This is definitely pretty confusing, so here's a playground showing the difference.

Body:
Why does the extends clause succeed when checking whether a 0-arity function extends a 1-arity type?

Is there any way to make the first form work?

The same check on tuples works as I'd expect, so I can use Parameters instead, but I'm curious as to why.

function foo(bar: number) {
  // ...
}

function baz() {
  // ...
}

type Foo = typeof foo extends (bar: infer T) => void ? T : never; // number - expected number
type Baz = typeof baz extends (bar: infer T) => void ? T : never; // unknown - expected never

type Foo2 = Parameters<typeof foo> extends [infer T] ? T : never; // number - ok
type Baz2 = Parameters<typeof baz> extends [infer T] ? T : never; // never - ok

Playground Link


问:
Python script to create a backup file of a SQL Server database (with pyodbc)
I am trying to write a python script to do a backup of a SQL Server database and then restore it into a new database.

The SQL script itself seems to work fine when run in SQL Server:

```<code>BACKUP DATABASE TEST_DB
TO DISK = 'D:/test/test_db.BAK';
</code>```

However, when I try to run it from a python script it fails:

```<code>con = pyodbc.connect('UID=xx; PWD=xxxxxx, driver='{SQL Server}', server=r'xxxxxx', database='TEST_DB')
sql_cursor = con.cursor()
query = ("""BACKUP DATABASE TEST_DB
            TO DISK = 'D:/test/test_db.BAK';""")
con.autocommit = True
sql_cursor.execute(query1)
con.commit()
</code>```

First of all, if I don't add the line "con.autocommit = True", it will fail with the message:

```<code>Cannot perform a backup or restore operation within a transaction. (3021)
</code>```

No idea what a transaction is. I read in another post that the line "con.autocommit = True" removes the error, and indeed it does. I have no clue why though.

Finally, when I run the python script with con.autocommit set to True, no errors are thrown, the BAK file can be seen temporarily in the expected location ('D:/test/test_db.BAK'), but when the script finishes running, the BAK file disappears (????). Does anyone know why this is happening?

答:
The solution, as described in this GitHub issue, is to call .nextset() repeatedly after executing the BACKUP statement ...

crsr.execute(backup_statement)
while (crsr.nextset()):
    pass
```

... to "consume" the progress messages issued by the BACKUP. If those messages are not consumed before the connection is closed then SQL Server figures that something went wrong and cancels the backup.

SSMS can apparently capture those messages directly, but an ODBC connection must issue calls to the ODBC SQLMoreResults function to retrieve each message, and that's what happens when we call the pyodbc .nextset() method.

Body:
I am trying to write a python script to do a backup of a SQL Server database and then restore it into a new database.

The SQL script itself seems to work fine when run in SQL Server:

BACKUP DATABASE TEST_DB
TO DISK = 'D:/test/test_db.BAK';

However, when I try to run it from a python script it fails:

con = pyodbc.connect('UID=xx; PWD=xxxxxx, driver='{SQL Server}', server=r'xxxxxx', database='TEST_DB')
sql_cursor = con.cursor()
query = ("""BACKUP DATABASE TEST_DB
            TO DISK = 'D:/test/test_db.BAK';""")
con.autocommit = True
sql_cursor.execute(query1)
con.commit()

First of all, if I don't add the line "con.autocommit = True", it will fail with the message:

Cannot perform a backup or restore operation within a transaction. (3021)

No idea what a transaction is. I read in another post that the line "con.autocommit = True" removes the error, and indeed it does. I have no clue why though.

Finally, when I run the python script with con.autocommit set to True, no errors are thrown, the BAK file can be seen temporarily in the expected location ('D:/test/test_db.BAK'), but when the script finishes running, the BAK file disappears (????). Does anyone know why this is happening?

Body:
The solution, as described in this GitHub issue, is to call .nextset() repeatedly after executing the BACKUP statement ...

crsr.execute(backup_statement)
while (crsr.nextset()):
    pass

... to "consume" the progress messages issued by the BACKUP. If those messages are not consumed before the connection is closed then SQL Server figures that something went wrong and cancels the backup.

SSMS can apparently capture those messages directly, but an ODBC connection must issue calls to the ODBC SQLMoreResults function to retrieve each message, and that's what happens when we call the pyodbc .nextset() method.


问:
What are the definitions for LPARAM and WPARAM?
I know I'm being lazy here and I should trawl the header files for myself, but what are the actual types for LPARAM and WPARAM parameters? Are they pointers, or four byte ints? I'm doing some C# interop code and want to be sure I get it working on x64 systems.</p>

答:
c++ in linux and windows 64bit tested, the most simple solution I found:</p>

```<code>#define WPARAM long long unsigned int
#define LPARAM long long int
</code>```

Body:
c++ in linux and windows 64bit tested, the most simple solution I found:

#define WPARAM long long unsigned int
#define LPARAM long long int


问:
Qnx-neutrino can't format my partitions with fdisc, process freezes
I'm trying to format my HDD 250Gb in QNX-neutrino OS running on Oracle VM in Windows 10. I mounted my HDD and everything looks fine. I run command

```<code>fdisk /dev/hd1
</code>```

And create 4 partitions with next sizes:

```<code>1325, 124684, 17265, 47496 MB
</code>```

After that I run command:

```<code>mount -e /dev/hd1
</code>```

And when I tried to format created partitions with commands:

```<code>mkqnx6fs –q –b4096 /dev/hd1t177

mkqnx6fs –q –b4096 /dev/hd1t178

mkqnx6fs –q –b4096 /dev/hd1t179

mkqnx6fs –q –b4096 /dev/hd1t180
</code>```

the process starts and never end. Terminal is just frezees. What can I do to fix it? Or there is another way to format my partitions in this system?

答:
VM Ware didn't suit me, because it counted cylinders incorrectly.

I find the solution. The problem was due to poor contact of the USB cable with my hard drive. I tried changing the usb cable and usb port and it worked fine.

Body:
I'm trying to format my HDD 250Gb in QNX-neutrino OS running on Oracle VM in Windows 10. I mounted my HDD and everything looks fine. I run command

fdisk /dev/hd1

And create 4 partitions with next sizes:

1325, 124684, 17265, 47496 MB

After that I run command:

mount -e /dev/hd1

And when I tried to format created partitions with commands:

mkqnx6fs –q –b4096 /dev/hd1t177

mkqnx6fs –q –b4096 /dev/hd1t178

mkqnx6fs –q –b4096 /dev/hd1t179

mkqnx6fs –q –b4096 /dev/hd1t180

the process starts and never end. Terminal is just frezees. What can I do to fix it? Or there is another way to format my partitions in this system?


问:
Filter based on master and detail how to?
I want a Linq query like this:

```<code>var q = from order in Order
join detail in Detail on order.OrderId equals detail.OrderId
</code>```

That permits me to do the following optional filtering, based on user choice :

```<code>if (cbxCustomer.Text != string.Empty)
{
  q = q.Where(x=>x.CustomerId = (int)cbxCustomer.SelectedItem) // filter based on master
}

if (cbxItem.Text != string.Empty)
{
  q = q.Where(x=>x.ItemId = (int)cbxItem.SelectedItem) // filter based on detail
}
</code>```

the result should be a list of orders with no duplicates that answers the above optional filter.

Thanks

答: After applying the filter, you need to select just Orders and than use Distinct LINQ extension method.</p>

Body:
I want a Linq query like this:

var q = from order in Order
join detail in Detail on order.OrderId equals detail.OrderId

That permits me to do the following optional filtering, based on user choice :

if (cbxCustomer.Text != string.Empty)
{
  q = q.Where(x=>x.CustomerId = (int)cbxCustomer.SelectedItem) // filter based on master
}

if (cbxItem.Text != string.Empty)
{
  q = q.Where(x=>x.ItemId = (int)cbxItem.SelectedItem) // filter based on detail
}

the result should be a list of orders with no duplicates that answers the above optional filter.

Thanks


问:
how use media queries with iframes ? to show different iframe source based on media query
I am new to HTML.

My question is, how do I show different iframes, based on the sizes of media queries?

Example:
for @media (max-width:400px) load iframe01 and for the rest of the sizes, load iframe02.

Any ideas, please?

My code is as follows:

.container {
  position: relative;
  width: 100%;
  overflow: hidden;
  padding-top: 75%; /* 4:3 Aspect Ratio */
}

.responsive-iframe {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  width: 100%;
  height: 100%;
  border: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <title>Document</title>
  </head>
  <body>
    <div class="container">
      <iframe class="responsive-iframe" src="iframe_sample"></iframe>
    </div>
  </body>
</html></code>```

答:
It is possible to achieve this.

Here is an example:

html {
  background: blue;
}

.container {
  position: relative;
  width: 100%;
  overflow: hidden;
  /* padding-top: 75%; */
  /* 4: 3 Aspect Ratio; */
}

.responsive-iframe,
.responsive-iframe2 {
  /* position: absolute; */
  top: 0;
  left: 0;
  /* bottom: 0; */
  right: 0;
  width: 100%;
  height: 100%;
  border: none;
}

@media only screen and (max-width: 400px) {
  html {
    background: red;
  }
  .responsive-iframe {
    /* position: absolute; */
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    width: 100%;
    height: 100%;
    border: none;
  }
  .responsive-iframe2 {
    display: none;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <title>Document</title>
  </head>
  <body>
    <div class="container">
      <iframe class="responsive-iframe" src="https://www.facebook.com/"></iframe>
      <iframe class="responsive-iframe2" src="https://twitter.com/home"></iframe>
    </div>
  </body>
</html></code>```

The iframes are broken links. However, you can give a separate ID or class to each iframe and then use the display: none property on the ID or class that you do not want visible.

The code I presented shows two iframes on desktop format. However, once you scale the page to 400px or less, it shows only one. I also altered the background colour for reference.

Hope this answers your question.

Body:
I am new to HTML.

My question is, how do I show different iframes, based on the sizes of media queries?

Example:
for @media (max-width:400px) load iframe01 and for the rest of the sizes, load iframe02.

Any ideas, please?

My code is as follows:

.container {
  position: relative;
  width: 100%;
  overflow: hidden;
  padding-top: 75%; /* 4:3 Aspect Ratio */
}

.responsive-iframe {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  width: 100%;
  height: 100%;
  border: none;
}

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <title>Document</title>

Body:
It is possible to achieve this.

Here is an example:

html {
  background: blue;
}

.container {
  position: relative;
  width: 100%;
  overflow: hidden;
  /* padding-top: 75%; */
  /* 4: 3 Aspect Ratio; */
}

.responsive-iframe,
.responsive-iframe2 {
  /* position: absolute; */
  top: 0;
  left: 0;
  /* bottom: 0; */
  right: 0;
  width: 100%;
  height: 100%;
  border: none;
}

@media only screen and (max-width: 400px) {
  html {
    background: red;
  }
  .responsive-iframe {
    /* position: absolute; */
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    width: 100%;
    height: 100%;
    border: none;
  }
  .responsive-iframe2 {
    display: none;
  }
}

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <title>Document</title>
  </head>
  <body>
    <div class="container">
      <iframe class="responsive-iframe" src="https://www.facebook.com/"></iframe>
      <iframe class="responsive-iframe2" src="https://twitter.com/home"></iframe>
    </div>
  </body>
</html>

The iframes are broken links. However, you can give a separate ID or class to each iframe and then use the display: none property on the ID or class that you do not want visible.

The code I presented shows two iframes on desktop format. However, once you scale the page to 400px or less, it shows only one. I also altered the background colour for reference.

Hope this answers your question.


问:
Win32 WM_CTLCOLORSTATIC background not completely filled
I am working on a dialog box that is created and controlled by a host program. The host creates the window and then sends me all the messages, but this means I don't have full access to everything it's doing. (I mention this because it could be contributing to my issue.)

I would like to change the color of an LTEXT to red. I am handling the WM_CTLCOLORSTATIC message and it is working where the text is drawn. The problem I'm having is that the rectangle for the LTEXT is slightly wider than the length of the text. For the part of the control that does not contain text it is leaving the background white instead of COLOR_BTNFACE as I have specified.

Here is the code for my handler. I call it by way of HANDLE_WM_CTLCOLORSTATIC.

```<code>// color message handler
HBRUSH OnControlColor ( HWND hDlg, twobyte dlgItem, HDC hdcCtrl, int type ) override
{
    if ( (dlgItem == ID_MANUAL_EDIT_WARNING) && (type == CTLCOLOR_STATIC) )
    {
        SetTextColor(hdcCtrl, RGB(204, 0, 0));
        SetBkColor(hdcCtrl, GetSysColor(COLOR_BTNFACE));
        return (HBRUSH)GetSysColorBrush(COLOR_BTNFACE);
    }
    return NO;
}
</code>```

It seems like maybe I need to invalidate the entire client rect some way, but I am not sure how to do this. Obviously I could carefully make the rectangle the exact right size in the dialog designer, but this doesn't seem like the safest approach.

答:
What you could do is to explicitly select your desired background brush into the control's device context; thus, when its rectangle is drawn, that brush will be used. You can do it with one additional line of code in your handler:

HBRUSH OnControlColor ( HWND hDlg, twobyte dlgItem, HDC hdcCtrl, int type ) override
{
    if ( (dlgItem == ID_MANUAL_EDIT_WARNING) && (type == CTLCOLOR_STATIC) )
    {
        SetTextColor(hdcCtrl, RGB(204, 0, 0));
        SetBkColor(hdcCtrl, GetSysColor(COLOR_BTNFACE));
        SelectObject(hdcCtrl, GetSysColorBrush(COLOR_BTNFACE)); // Select the B/G brush
        return (HBRUSH)GetSysColorBrush(COLOR_BTNFACE);
    }
    return NO;
}
```

My one concern here is that you're manipulating object selection in a device context that is 'owned' by another process; this could cause issues if the replaced object in that DC is user-created (but that doesn't seem to be so in this case).

Body:
I am working on a dialog box that is created and controlled by a host program. The host creates the window and then sends me all the messages, but this means I don't have full access to everything it's doing. (I mention this because it could be contributing to my issue.)

I would like to change the color of an LTEXT to red. I am handling the WM_CTLCOLORSTATIC message and it is working where the text is drawn. The problem I'm having is that the rectangle for the LTEXT is slightly wider than the length of the text. For the part of the control that does not contain text it is leaving the background white instead of COLOR_BTNFACE as I have specified.

Here is the code for my handler. I call it by way of HANDLE_WM_CTLCOLORSTATIC.

// color message handler
HBRUSH OnControlColor ( HWND hDlg, twobyte dlgItem, HDC hdcCtrl, int type ) override
{
    if ( (dlgItem == ID_MANUAL_EDIT_WARNING) && (type == CTLCOLOR_STATIC) )
    {
        SetTextColor(hdcCtrl, RGB(204, 0, 0));
        SetBkColor(hdcCtrl, GetSysColor(COLOR_BTNFACE));
        return (HBRUSH)GetSysColorBrush(COLOR_BTNFACE);
    }
    return NO;
}

It seems like maybe I need to invalidate the entire client rect some way, but I am not sure how to do this. Obviously I could carefully make the rectangle the exact right size in the dialog designer, but this doesn't seem like the safest approach.

Body:
What you could do is to explicitly select your desired background brush into the control's device context; thus, when its rectangle is drawn, that brush will be used. You can do it with one additional line of code in your handler:

HBRUSH OnControlColor ( HWND hDlg, twobyte dlgItem, HDC hdcCtrl, int type ) override
{
    if ( (dlgItem == ID_MANUAL_EDIT_WARNING) && (type == CTLCOLOR_STATIC) )
    {
        SetTextColor(hdcCtrl, RGB(204, 0, 0));
        SetBkColor(hdcCtrl, GetSysColor(COLOR_BTNFACE));
        SelectObject(hdcCtrl, GetSysColorBrush(COLOR_BTNFACE)); // Select the B/G brush
        return (HBRUSH)GetSysColorBrush(COLOR_BTNFACE);
    }
    return NO;
}

My one concern here is that you're manipulating object selection in a device context that is 'owned' by another process; this could cause issues if the replaced object in that DC is user-created (but that doesn't seem to be so in this case).


问:
python 3.73 (Windows, urllib3) ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED]
After executing simple code:

```<code>from urllib3 import ProxyManager

def GET(url):
    http = ProxyManager("https://91.208.39.70:8080")
    response = http.urlopen('GET', url)
    print(response.data)
    return ''

if __name__ == '__main__':
    result = GET("https://example.com")
    print(result)
</code>```

I have next errors:

Traceback (most recent call last):
    File "F:\Run\Lprogr\Phyton\lib\site-packages\urllib3\connectionpool.py", line 597, in urlopen
      self._prepare_proxy(conn)
    File "F:\Run\Lprogr\Phyton\lib\site-packages\urllib3\connectionpool.py", line 807, in _prepare_proxy
      conn.connect()
    File "F:\Run\Lprogr\Phyton\lib\site-packages\urllib3\connection.py", line 350, in connect
      ssl_context=context)
    File "F:\Run\Lprogr\Phyton\lib\site-packages\urllib3\util\ssl_.py", line 355, in ssl_wrap_socket
      return context.wrap_socket(sock, server_hostname=server_hostname)
    File "F:\Run\Lprogr\Phyton\lib\ssl.py", line 412, in wrap_socket
      session=session
    File "F:\Run\Lprogr\Phyton\lib\ssl.py", line 853, in _create
      self.do_handshake()
    File "F:\Run\Lprogr\Phyton\lib\ssl.py", line 1117, in do_handshake
      self._sslobj.do_handshake()
  ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1056)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
    File "F:/My/Documents/PycharmProjects/proxyTester/proxy.py", line 17, in
      result = GET("https://example.com")
    File "F:/My/Documents/PycharmProjects/proxyTester/proxy.py", line 11, in GET
      response = http.urlopen('GET', url)
    File "F:\Run\Lprogr\Phyton\lib\site-packages\urllib3\poolmanager.py", line 451, in urlopen
      return super(ProxyManager, self).urlopen(method, url, redirect=redirect, **kw)
    File "F:\Run\Lprogr\Phyton\lib\site-packages\urllib3\poolmanager.py", line 326, in urlopen
      response = conn.urlopen(method, u.request_uri, **kw)
    File "F:\Run\Lprogr\Phyton\lib\site-packages\urllib3\connectionpool.py", line 670, in urlopen
      **response_kw)
    File "F:\Run\Lprogr\Phyton\lib\site-packages\urllib3\connectionpool.py", line 670, in urlopen
      **response_kw)
    File "F:\Run\Lprogr\Phyton\lib\site-packages\urllib3\connectionpool.py", line 670, in urlopen
      **response_kw)
    File "F:\Run\Lprogr\Phyton\lib\site-packages\urllib3\connectionpool.py", line 641, in urlopen
      _stacktrace=sys.exc_info()[2])
    File "F:\Run\Lprogr\Phyton\lib\site-packages\urllib3\util\retry.py", line 399, in increment
      raise MaxRetryError(_pool, url, error or ResponseError(cause))
  urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='example.com', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1056)')))

UPDATE: I don't want ignore certificate validation.

答:
If you are on windows server 2018/2019 (I tried it on a personal Datacenter Server.) you can issue the command below to allow your programs to connect. This is a system wide fix for what I can tell. I had to run it off of an administrative terminal to get it to work but this command fixed all of my problems.

```<code>certutil -generateSSTFromWU roots.sst && certutil -addstore -f root roots.sst && del roots.sst
</code>```

Best of luck to you!

Body:
After executing simple code:

from urllib3 import ProxyManager

def GET(url):
    http = ProxyManager("https://91.208.39.70:8080")
    response = http.urlopen('GET', url)
    print(response.data)
    return ''

if __name__ == '__main__':
    result = GET("https://example.com")
    print(result)

I have next errors:

Traceback (most recent call last):
    File "F:\Run\Lprogr\Phyton\lib\site-packages\urllib3\connectionpool.py", line 597, in urlopen
      self._prepare_proxy(conn)
    File "F:\Run\Lprogr\Phyton\lib\site-packages\urllib3\connectionpool.py", line 807, in _prepare_proxy
      conn.connect()
    File "F:\Run\Lprogr\Phyton\lib\site-packages\urllib3\connection.py", line 350, in connect
      ssl_context=context)
    File "F:\Run\Lprogr\Phyton\lib\site-packages\urllib3\util\ssl_.py", line 355, in ssl_wrap_socket
      return context.wrap_socket(sock, server_hostname=server_hostname)
    File "F:\Run\Lprogr\Phyton\lib\ssl.py", line 412, in wrap_socket
      session=session
    File "F:\Run\Lprogr\Phyton\lib\ssl.py", line 853, in _create
      self.do_handshake()
    File "F:\Run\Lprogr\Phyton\lib\ssl.py", line 1117, in do_handshake
      self._sslobj.do_handshake()
  ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1056)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
    File "F:/My/Documents/PycharmProjects/proxyTester/proxy.py", line 17, in
      result = GET("https://example.com")
    File "F:/My/Documents/PycharmProjects/proxyTester/proxy.py", line 11, in GET
      response = http.urlopen('GET', url)
    File "F:\Run\Lprogr\Phyton\lib\site-packages\urllib3\poolmanager.py", line 451, in urlopen
      return super(ProxyManager, self).urlopen(method, url, redirect=redirect, **kw)
    File "F:\Run\Lprogr\Phyton\lib\site-packages\urllib3\poolmanager.py", line 326, in urlopen
      response = conn.urlopen(method, u.request_uri, **kw)
    File "F:\Run\Lprogr\Phyton\lib\site-packages\urllib3\connectionpool.py", line 670, in urlopen
      **response_kw)
    File "F:\Run\Lprogr\Phyton\lib\site-packages\urllib3\connectionpool.py", line 670, in urlopen
      **response_kw)
    File "F:\Run\Lprogr\Phyton\lib\site-packages\urllib3\connectionpool.py", line 670, in urlopen
      **response_kw)
    File "F:\Run\Lprogr\Phyton\lib\site-packages\urllib3\connectionpool.py", line 641, in urlopen
      _stacktrace=sys.exc_info()[2])
    File "F:\Run\Lprogr\Phyton\lib\site-packages\urllib3\util\retry.py", line 399, in increment
      raise MaxRetryError(_pool, url, error or ResponseError(cause))
  urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='example.com', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1056)')))

UPDATE: I don't want ignore certificate validation.

Body:
If you are on windows server 2018/2019 (I tried it on a personal Datacenter Server.) you can issue the command below to allow your programs to connect. This is a system wide fix for what I can tell. I had to run it off of an administrative terminal to get it to work but this command fixed all of my problems.

certutil -generateSSTFromWU roots.sst && certutil -addstore -f root roots.sst && del roots.sst

Best of luck to you!


问:
How do I make python read a value after a string, then comparing and outputting the value?
For example, say I have a set of data.txt:

```<code>Name1 | Points:100
Name2 | Points:150
Name3 | Points:200
</code>```

I want python to read the value after "Points:", compare it to a variable "j" and output the line only if the value is less than the variable "j".

I'm a complete beginner to Python, so apologies if this seems very easy. Thanks for any replies :)

答:
```<code>    import re
    text = open('data.txt')
    line = text.readline()
    while line:
        out = re.findall('\d+', )
        line = text.readline()
        if out < j:
            print(out)
    text.close()
</code>```

Hope this helps.

Body:
For example, say I have a set of data.txt:

Name1 | Points:100
Name2 | Points:150
Name3 | Points:200

I want python to read the value after "Points:", compare it to a variable "j" and output the line only if the value is less than the variable "j".

I'm a complete beginner to Python, so apologies if this seems very easy. Thanks for any replies :)

Body:
    import re
    text = open('data.txt')
    line = text.readline()
    while line:
        out = re.findall('\d+', )
        line = text.readline()
        if out < j:
            print(out)
    text.close()

Hope this helps.


问:
What is Firestore recommended data structure in terms of nesting? Go deeper or keep it flat?
I guess firebase is not a big fan of nesting but they also say (if I understood correctly) that one-level nesting is okay.

Let's have an example of a restaurant and 2 diff scenarios:

Flat: No Nesting (no subcollections)

```<code>/restaurants
    -mealCategoriesID: List<DocumentReference>
    -mealsID: List<DocumentReference>

/meal_categories

/meals
    -mealCategoryID: DocumentReference
</code>```

Deep: Nesting

```<code>/restaurants/meal_categories/meals
</code>```

So, what would be the best approach in this restaurant example?

答:
When it comes to NoSQL data modeling there is no singular "best" model. It all depends on how you want to use that data.

Before Firestore supported collection group queries it often made sense to store items in a few top-level list, so that you could query over them. That would've been your first model, which would've always allowed you to query all meals, no matter what restaurant or category.

But with collection group queries, you can now always query all meals, since they're in collections of the same name. And at this stage, spreading them out across multiple subcollections actually helps write throughput, since those subcollections are more likely to be spread out across the disks.

One thing that sets your models apart is the ability to query across meals of a certain category.

Say you want a query across all restaurants for meals of a specific category. In your last model that is only possible if you also store the category ID in each meal document.

Similarly, say that you want to query across the meals for a specific restaurant, or a subset of restaurants, for meals of a certain category. To allow such queries, each meal needs to have a category ID and a restaurant ID field.

In both the cases above you're duplicating data, to allow certain queries. But it's still usually better to perform some nesting, since it allows for better write concurrency/throughput if you ever reach usage volume where this matter.

Note that the read and query performance is the same for each data model, since Firestore only allows use-cases where it can guarantee that performance.

Body:
I guess firebase is not a big fan of nesting but they also say (if I understood correctly) that one-level nesting is okay.

Let's have an example of a restaurant and 2 diff scenarios:

Flat: No Nesting (no subcollections)

/restaurants
    -mealCategoriesID: List<DocumentReference>
    -mealsID: List<DocumentReference>

/meal_categories

/meals
    -mealCategoryID: DocumentReference

Deep: Nesting

/restaurants/meal_categories/meals

So, what would be the best approach in this restaurant example?


问:
laravel Javascript and Render sections
Hi I did a webapp with laravel, with various forms that add datas to database and then refresh only some sections (for example insert an order, then insert some products...etc), but when section render javascript doesn't work anymore.
I have some Jquery that catch some events...for example some click buttons.
EXAMPLE

PART of script in the HEAD

```<code>    <script src="{{ asset('public/js/jquery-3.5.1.min.js') }}"></script>
    <script src="{{ asset('public/js/vendor/popper.min.js') }}"></script>
    <script src="{{ asset('public/js/bootstrap.min.js') }}"></script>
    <script src="{{ asset('public/js/vendor/holder.min.js') }}"></script>
    <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
    <script>
        $(document).ready(function(){

            $(document).ajaxSend(function() {
            $("#overlay").fadeIn(300);
            });

            $('#searchPolizza').keydown(function (e) {
              if (e.keyCode == 13) {
              e.preventDefault();
              $value=$(this).val();
                $.ajax({
                    type : 'get',
                    url : "{{ url("/trova") }}",
                    data:{'numero':$value},
                    success:function(data){
                    $('#RefreshContent').replaceWith(data);
                    //initRefundsFunctions();
                    //initDossierListClick();
                    }
                });
              }
            });

$( "#addDossier" ).click(function( event ) {
          event.preventDefault();

          //$("#addDossierForm")[0].reset();
          var r = confirm("Vuoi veramente creare un nuovo dossier?");
            if (r == true) {
                       ....continue.......</script>
</code>```

After i found a "polizza" calling ajax '#searchPolizza' Then i refresh content section

Part of RefreshContent section where i have a form with button #addDossier that i can press after refresh section related to first search

```<code><div class="" style="zoom:90%">
  <form class="form-inline" id="addDossierForm">
    <input type="text" class="form-control mb-2 mr-sm-2" placeholder="dossier" id="dossier">
    <input type="date" class="form-control mb-2 mr-sm-2" placeholder="data sinitro" id="date_cla">
  <button type="submit" class="btn btn-primary mb-2" data-customer_id="@isset($customer_id){{$customer_id}}@endisset" id="addDossier"><i class="fa fa-plus" aria-hidden="true"></i></button>
  </form>
</div>
</code>```

But jquery cannot catch anymore the click event

I tried to put all script in the head or also to create function to recall but it doesn't work well.
Is there another solution?
Thx

答:
Here, $(dom).click() binds events statically, You should try registering you click event function like this:

$( '#addDossier' ).on( 'click', function (event) { your code});

which binds event handler dynamically, check that out here and you could use shorthand (function(){..})(); instead of $(document).ready(function(){...}); and you should consider using something modern like Vue/React. Jquery is primitive and getting older.

Title: laravel Javascript and Render sections

Body:
Hi I did a webapp with laravel, with various forms that add datas to database and then refresh only some sections (for example insert an order, then insert some products...etc), but when section render javascript doesn't work anymore.
I have some Jquery that catch some events...for example some click buttons.
EXAMPLE

PART of script in the HEAD

After i found a "polizza" calling ajax '#searchPolizza' Then i refresh content section

Part of RefreshContent section where i have a form with button #addDossier that i can press after refresh section related to first search

  <form class="form-inline" id="addDossierForm">
    <input type="text" class="form-control mb-2 mr-sm-2" placeholder="dossier" id="dossier">
    <input type="date" class="form-control mb-2 mr-sm-2" placeholder="data sinitro" id="date_cla">
  <button type="submit" class="btn btn-primary mb-2" data-customer_id="@isset($customer_id){{$customer_id}}@endisset" id="addDossier"></button>
  </form>

But jquery cannot catch anymore the click event

I tried to put all script in the head or also to create function to recall but it doesn't work well.
Is there another solution?
Thx


问:
Logger.LogDebug vs Debug.WriteLine
I have this program

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace debuglogtest
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddHostedService<Worker>();
                });
    }
}
```

<p>With this worker</p>

<pre class="lang-cs prettyprint-override"><code>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace debuglogtest
{
    public class Worker : BackgroundService
    {
        private readonly ILogger<Worker> _logger;

        public Worker(ILogger<Worker> logger)
        {
            _logger = logger;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogDebug("_logger.LogDebug");
            _logger.LogTrace("_logger.LogTrace");
            Debug.WriteLine("Debug.WriteLine");
        }
    }
}
</code>```

and this configuration

```<code>{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  }
}
</code>```

When I run this in debug dotnet run -c Debug i get this in the console

dbug: debuglogtest.Worker[0]
       _logger.LogDebug

And this in DebugView

This is expected, because as i understand it, when we compile our program, we get get debug logging. But when i compile this in release with dotnet run -c Release I still get this in the console

dbug: debuglogtest.Worker[0]
       _logger.LogDebug

But nothing in DebugView:

What i expect:

_logger.LogDebug is written both in console and in DebugView when compiling in debug, and no places when compiling in Release

Debug.WriteLine is written in DebugView when compiling in debug

What is actually happening:

_logger.LogDebug is only written to console, and not DebugView in debug mode

Debug.WriteLine is correctly written only when compiling in debug mode.

I thought that LogDebug was calling Debug.WriteLine under the hood, but maybe Debug.WriteLineand Logger.LogDebug is two different things? I surely looks like it. I think this is confusing because, we need to control Debug logging in two different places (when compiling and filtering). If i read the docs: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-3.1#debug it says that it calls the same Debug.WriteLine:

The Debug provider writes log output by using the System.Diagnostics.Debug class. Calls to System.Diagnostics.Debug.WriteLine write to the Debug provider.

Am I doing something wrong? I must be misunderstanding something. I want to be able to control Logger.Debug when compiling in Debug mode. Is that not possible?

UPDATE

If i check the source (even though it is kind of old (does anybody know an updated reference, please specify)): https://github.com/aspnet/Logging/blob/master/src/Microsoft.Extensions.Logging.Debug/DebugLogger.debug.cs I can see that it defines #define DEBUG, and calls the Debug.WriteLine, but it doesn't add up in my head. It should be showing up in DebugView, but it doesn't in both debug and release mode.

答: ILogger.LogDebug, ILogger.LogTrace and so on is about LogLevel of message and not about where it is written and is basically equivalent to calling Log(..) with corresponding value of logLevel parameter. The write destination of log message is determined by which logger you are using (console, file, ETW, I'm sure that you can even create one which writes to the debug view see the logging providers section of docs). LogLevel allows you to filter which log level is actually written to the log destination and is regulated by appsettings and not directly by build configuration (though you can have different settings for different configurations).

Title: Logger.LogDebug vs Debug.WriteLine

Body:
I have this program

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace debuglogtest
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddHostedService<Worker>();
                });
    }
}

With this worker

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace debuglogtest
{
    public class Worker : BackgroundService
    {
        private readonly ILogger<Worker> _logger;

        public Worker(ILogger<Worker> logger)
        {
            _logger = logger;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogDebug("_logger.LogDebug");
            _logger.LogTrace("_logger.LogTrace");
            Debug.WriteLine("Debug.WriteLine");
        }
    }
}

and this configuration

{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  }
}

When I run this in debug dotnet run -c Debug i get this in the console

dbug: debuglogtest.Worker[0]
       _logger.LogDebug

And this in DebugView

This is expected, because as i understand it, when we compile our program, we get get debug logging. But when i compile this in release with dotnet run -c Release I still get this in the console

dbug: debuglogtest.Worker[0]
       _logger.LogDebug

But nothing in DebugView:

What i expect:

_logger.LogDebug is written both in console and in DebugView when compiling in debug, and no places when compiling in Release

Debug.WriteLine is written in DebugView when compiling in debug

What is actually happening:

_logger.LogDebug is only written to console, and not DebugView in debug mode

Debug.WriteLine is correctly written only when compiling in debug mode.

I thought that LogDebug was calling Debug.WriteLine under the hood, but maybe Debug.WriteLineand Logger.LogDebug is two different things? I surely looks like it. I think this is confusing because, we need to control Debug logging in two different places (when compiling and filtering). If i read the docs: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-3.1#debug it says that it calls the same Debug.WriteLine:

The Debug provider writes log output by using the System.Diagnostics.Debug class. Calls to System.Diagnostics.Debug.WriteLine write to the Debug provider.

Am I doing something wrong? I must be misunderstanding something. I want to be able to control Logger.Debug when compiling in Debug mode. Is that not possible?

UPDATE

If i check the source (even though it is kind of old (does anybody know an updated reference, please specify)): https://github.com/aspnet/Logging/blob/master/src/Microsoft.Extensions.Logging.Debug/DebugLogger.debug.cs I can see that it defines #define DEBUG, and calls the Debug.WriteLine, but it doesn't add up in my head. It should be showing up in DebugView, but it doesn't in both debug and release mode.


问:
Python Flask - Request object doesn't exist even though it's imported
I have an extremely bare bones python REST application:

main.py

```<code>from app import app

def main():

    parser = ArgumentParser(description="Character information hosting server!")
    parser.add_argument('--parse-word-doc', dest="parse_doc", required=False, action='store_true',
                        help='Parses a word document for characters and then serializes them with pickle to a file')
    parser.add_argument('--source-file', dest="source_file", type=str, required=False,
                        help='Path and name of the source word document you want to read from. Defaults to source.docx.',
                        default="source.docx")
    parser.add_argument('--port', dest="port", required=False, type=int, default=5000,
                        help='Specify the port you want Flask to run on')
    parser.add_argument('--log-level', metavar='LOG_LEVEL', dest="log_level", required=False, type=str, default="info",
                        choices=['debug', 'info', 'warning', 'error', 'critical'],
                        help='The log level at which you want to run.')

    args = parser.parse_args()  # type: argparse.Namespace

    if not Path(args.source_file).is_file():
        logging.error("Could not find " + args.source_file + ". Are you sure you got the path right?")
        exit(1)

    logging.info("Reading data from the file \"database\" from disk")
    with open('database', 'rb') as database:
        characters = pickle.load(database)
        app.config['DATABASE'] = characters

    if args.log_level:
        if args.log_level == "debug":
            logging.basicConfig(level=logging.DEBUG)
            app.config['DEBUG'] = True
        elif args.log_level == "info":
            logging.basicConfig(level=logging.INFO)
        elif args.log_level == "warning":
            logging.basicConfig(level=logging.WARNING)
        elif args.log_level == "error":
            logging.basicConfig(level=logging.ERROR)
        elif args.log_level == "critical":
            logging.basicConfig(level=logging.CRITICAL)
    else:
        logging.basicConfig(level=logging.INFO)

    app.run(host='0.0.0.0', port=args.port)

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

app/init.py

```<code>from flask import Flask

# Initialize the app
app = Flask(__name__)

# Load the views
from app import views
</code>```

app/config.py

```<code>import os

class Config(object):

    # Enable Flask's debugging features. Should be False in production
    DEBUG = os.environ.get('DEBUG') or True
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'default-secret-just-for-csrf-attacks-nbd'
</code>```

app/views.py

```<code>from flask import request
from app import app

@app.route('/api/lookup', methods=['GET'])
def lookup():

    input_text = request.args.get('character_to_lookup')

    if input_text in app.config['DATABASE']:
        return app.config['DATABASE'][input_text]
    else:
        return {}
</code>```

Problem

If I send a simple curl command: curl -X GET -d '{"character_to_lookup": "test"}' http://127.0.01:5000/api/lookup -H 'Content-Type: application/json'

and check in PyCharm for debugging - request simply doesn't exist at all. It isn't set to none, it just doesn't exist. There must be something about the app context I'm missing, but it isn't clear.

The only thing I've been able to find online is that you need to import request, which I've done and I can't think of another reason that request simply wouldn't exist.

答:
The problem was that request.args in flask refers specifically to data passed via the url. Flask uses different values in request for different types of data. In my case, I wanted JSON so I had to use request.get_json().

See this answer for a great explanation.

Body:
I have an extremely bare bones python REST application:

main.py

from app import app

def main():

    parser = ArgumentParser(description="Character information hosting server!")
    parser.add_argument('--parse-word-doc', dest="parse_doc", required=False, action='store_true',
                        help='Parses a word document for characters and then serializes them with pickle to a file')
    parser.add_argument('--source-file', dest="source_file", type=str, required=False,
                        help='Path and name of the source word document you want to read from. Defaults to source.docx.',
                        default="source.docx")
    parser.add_argument('--port', dest="port", required=False, type=int, default=5000,
                        help='Specify the port you want Flask to run on')
    parser.add_argument('--log-level', metavar='LOG_LEVEL', dest="log_level", required=False, type=str, default="info",
                        choices=['debug', 'info', 'warning', 'error', 'critical'],
                        help='The log level at which you want to run.')

    args = parser.parse_args()  # type: argparse.Namespace

    if not Path(args.source_file).is_file():
        logging.error("Could not find " + args.source_file + ". Are you sure you got the path right?")
        exit(1)

    logging.info("Reading data from the file \"database\" from disk")
    with open('database', 'rb') as database:
        characters = pickle.load(database)
        app.config['DATABASE'] = characters

    if args.log_level:
        if args.log_level == "debug":
            logging.basicConfig(level=logging.DEBUG)
            app.config['DEBUG'] = True
        elif args.log_level == "info":
            logging.basicConfig(level=logging.INFO)
        elif args.log_level == "warning":
            logging.basicConfig(level=logging.WARNING)
        elif args.log_level == "error":
            logging.basicConfig(level=logging.ERROR)
        elif args.log_level == "critical":
            logging.basicConfig(level=logging.CRITICAL)
    else:
        logging.basicConfig(level=logging.INFO)

    app.run(host='0.0.0.0', port=args.port)

if __name__ == '__main__':
    main()

app/init.py

from flask import Flask

# Initialize the app
app = Flask(__name__)

# Load the views
from app import views

app/config.py

import os

class Config(object):

    # Enable Flask's debugging features. Should be False in production
    DEBUG = os.environ.get('DEBUG') or True
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'default-secret-just-for-csrf-attacks-nbd'

app/views.py

from flask import request
from app import app

@app.route('/api/lookup', methods=['GET'])
def lookup():

    input_text = request.args.get('character_to_lookup')

    if input_text in app.config['DATABASE']:
        return app.config['DATABASE'][input_text]
    else:
        return {}

Problem

If I send a simple curl command: curl -X GET -d '{"character_to_lookup": "test"}' http://127.0.01:5000/api/lookup -H 'Content-Type: application/json'

and check in PyCharm for debugging - request simply doesn't exist at all. It isn't set to none, it just doesn't exist. There must be something about the app context I'm missing, but it isn't clear.

The only thing I've been able to find online is that you need to import request, which I've done and I can't think of another reason that request simply wouldn't exist.


问:
Cannot use .place for a label frame in tkinter
I've been working on adding label frames to my window but for some reason whenever I use .place it never places the frame. Grid and pack work though. I'm trying to get the label frame right in the middle of the screen through coordinates. Heres my code (the error is somewhere in the createstock functiom):</p>

```<code>import tkinter as tk
import yfinance

class StockWindow:
    def __init__(self,master,number):

        self.master = master
        self.frame=tk.Frame(self.master)
        self.frame.pack()
        w, h = master.winfo_screenwidth(), master.winfo_screenheight()
        self.master.overrideredirect(1)
        self.master.geometry("%dx%d+0+0" % (w, h))
        self.master.focus_set() # <-- move focus to this widget
        self.master.bind("<Escape>", lambda e: e.widget.quit())
        #################################################
        ## Labels
        self.amountChanged = tk.Label(self.master,text = "$1000")
        self.amountChanged.place(x=w/2,y=h/2)
        self.highestChangedStock = tk.Label(self.master,text = "Amzn")
        self.highestChangedStock.place(x=w/2+10,y=h/2+40)
        self.lowestChangedStock = tk.Label(self.master,text = "this one")
        self.stockTips = tk.Label(self.master,text = "Buy some")
        self.stockTips.place(x=2,y=777)
        self.marketChange = tk.Label(self.master,text = "Alot!")
        self.marketChange.place(x=23,y=66)
        self.stockNews = tk.Label(self.master,text = "News Here!")
        self.stockNews.place(x=23,y=234)
        self.stockNewds = tk.Label(self.master,text = "News Hewewere!")
        self.stockNewds.place(x=300,y=300)
        ## Buttons
        self.seeAllStocks = tk.Button(self.master,text ="do you wanna see more stocks?")
        self.seeAllStocks.place(x=0,y=0)
        self.goBack =tk.Button(self.master,text = "Go back",command=self.close_windows)
        self.goBack.place(x=100,y=100)
        self.createStock("afdhsfdhsfhsfghsgfhsdg",3,30)
        #########
    def createStock(self,name,pricechange,placement):
        stockframe = tk.LabelFrame(self.frame,text='')
        #stockframe.size(200)
        stockframe.place(x=400,y=400,height=10,width=10)
        #stockframe.pack(expand='yes',fill='both')
        #stockframe.grid(column=5,row=5)
        tempLabel = tk.Label(stockframe,text=name)

        tempLabel.pack()
    def close_windows(self):
        self.master.destroy()
</code>```

答:
The problem is that self.frame is used as the parent of the label frame, but it has a height of 1x1 since there's nothing in it. Thus, any widget placed inside it will also be invisible.

If you want to use place to center a widget, the simplest solution is to use relative coordinates with a relative x and y coordinate of .5 (ie: 50% of the width and height of the window).

For example, you don't need to place the labelframe inside a label inside the root window. Just remove self.frame and use relative coordinates for the label frame:

```<code>    stockframe = tk.LabelFrame(self.master,text='')
    stockframe.place(relx=.5, rely=.5)
</code>```

Body:
I've been working on adding label frames to my window but for some reason whenever I use .place it never places the frame. Grid and pack work though. I'm trying to get the label frame right in the middle of the screen through coordinates. Heres my code (the error is somewhere in the createstock functiom):

import tkinter as tk
import yfinance

class StockWindow:
    def __init__(self,master,number):

        self.master = master
        self.frame=tk.Frame(self.master)
        self.frame.pack()
        w, h = master.winfo_screenwidth(), master.winfo_screenheight()
        self.master.overrideredirect(1)
        self.master.geometry("%dx%d+0+0" % (w, h))
        self.master.focus_set() # <-- move focus to this widget
        self.master.bind("<Escape>", lambda e: e.widget.quit())
        #################################################
        ## Labels
        self.amountChanged = tk.Label(self.master,text = "$1000")
        self.amountChanged.place(x=w/2,y=h/2)
        self.highestChangedStock = tk.Label(self.master,text = "Amzn")
        self.highestChangedStock.place(x=w/2+10,y=h/2+40)
        self.lowestChangedStock = tk.Label(self.master,text = "this one")
        self.stockTips = tk.Label(self.master,text = "Buy some")
        self.stockTips.place(x=2,y=777)
        self.marketChange = tk.Label(self.master,text = "Alot!")
        self.marketChange.place(x=23,y=66)
        self.stockNews = tk.Label(self.master,text = "News Here!")
        self.stockNews.place(x=23,y=234)
        self.stockNewds = tk.Label(self.master,text = "News Hewewere!")
        self.stockNewds.place(x=300,y=300)
        ## Buttons
        self.seeAllStocks = tk.Button(self.master,text ="do you wanna see more stocks?")
        self.seeAllStocks.place(x=0,y=0)
        self.goBack =tk.Button(self.master,text = "Go back",command=self.close_windows)
        self.goBack.place(x=100,y=100)
        self.createStock("afdhsfdhsfhsfghsgfhsdg",3,30)
        #########
    def createStock(self,name,pricechange,placement):
        stockframe = tk.LabelFrame(self.frame,text='')
        #stockframe.size(200)
        stockframe.place(x=400,y=400,height=10,width=10)
        #stockframe.pack(expand='yes',fill='both')
        #stockframe.grid(column=5,row=5)
        tempLabel = tk.Label(stockframe,text=name)

        tempLabel.pack()
    def close_windows(self):
        self.master.destroy()

Body:
The problem is that self.frame is used as the parent of the label frame, but it has a height of 1x1 since there's nothing in it. Thus, any widget placed inside it will also be invisible.

If you want to use place to center a widget, the simplest solution is to use relative coordinates with a relative x and y coordinate of .5 (ie: 50% of the width and height of the window).

For example, you don't need to place the labelframe inside a label inside the root window. Just remove self.frame and use relative coordinates for the label frame:

    stockframe = tk.LabelFrame(self.master,text='')
    stockframe.place(relx=.5, rely=.5)


问:
Unable to get the first bar to show up in python matplotlib
For some reason my plot at 50 is not showing up and I can't figure out why. any help would be much appreciated.

```<code>import matplotlib.pyplot as plt
num = [50, 100, 150, 300, 400]
prob = [0.08, .03, .013,.0033,0]
plt.bar(num,prob)
plt.xlabel("Number of Flaws")
plt.ylabel ("probability")
plt.show()
</code>```

答:
```<code>import matplotlib.pyplot as plt

plt.style.use('fivethirtyeight')

num = [50, 100, 150, 300, 400]
prob = [0.08, .03, .013,.0033,0]
plt.bar(num,prob)
plt.xlabel("Number of Flaws")
plt.ylabel ("probability")
</code>```

plt.tight_layout()

```<code>plt.show()
</code>```

Body:
For some reason my plot at 50 is not showing up and I can't figure out why. any help would be much appreciated.

import matplotlib.pyplot as plt
num = [50, 100, 150, 300, 400]
prob = [0.08, .03, .013,.0033,0]
plt.bar(num,prob)
plt.xlabel("Number of Flaws")
plt.ylabel ("probability")
plt.show()

Body:
import matplotlib.pyplot as plt

plt.style.use('fivethirtyeight')

num = [50, 100, 150, 300, 400]
prob = [0.08, .03, .013,.0033,0]
plt.bar(num,prob)
plt.xlabel("Number of Flaws")
plt.ylabel ("probability")

plt.tight_layout()

plt.show()


问:
How to wait for asynchronous operation to complete before rendering every time state changes
I'm working on an app that displays images that are dynamically generated by the backend in response to changes in the current state.

I only want a component to re-render after a state change after the asynchronous call to the backend has returned with the new image.

Then I want to atomically update the image (in a canvas, say) and other UI based on the state - e.g. some HTML.

If I was generating a new image synchronously on the client I could use a (Layout) Effect hook to update the canvas.

I could only change the state after the network request to the backend returns - but I'm not sure of the cleanest way of doing this. I have to copy a whole bunch of state (into a "pending" state) and then mutate a bit of it, send it to server and only apply it when the call returns? It could get a little complicated if there are multiple state changes in-flight at once. Then I need to continue to mutate "pending" state in response to subsequent actions.

I wonder - is there something in React (or Redux?) that can help with this? Or should I try code it up myself?

BTW I'm new to React.

答:
You're basically looking for async actions you can learn to do it natively here or use a middleware like redux-thunk (or redux-saga but its a bit complicated to be honest).

The basics are for every async requests you need to make 3 actions

A action to start the request.

A action when the action completes.

A action if the request fails.

and the code will look something like

function async makeRequest() {
  dispatch({type: 'START'})
  try {
    const res = await myRequest()
    dispatch({type: 'SUCCESS', payload: res})
  } catch (e) {
    dispatch({type: 'FAILURE', payload: e})
  }
}
```


问:
ZeroMQ: Waiting for a message without consuming thread
I have some simple python code which waits for messages for a topic.

However...when running this, the python process will hog CPU. I know with other languages, such as with sockets, there is a way to wait for messages without eating the entire processing power. Essentially the thread just remains halted waiting for a response. Is that possible with ZeroMQ?

```<code>import zmq
import sys

port = "5556"
if len(sys.argv) > 1:
    port =  sys.argv[1]
    int(port)

# Socket to talk to server
context = zmq.Context()
socket = context.socket(zmq.SUB)

print "Collecting updates from weather server..."
socket.connect ("tcp://localhost:%s" % port)

# Subscribe to zipcode, default is NYC, 10001
topicfilter = "10001"
socket.setsockopt(zmq.SUBSCRIBE, topicfilter)

# Process 5 updates
total_value = 0
for update_nbr in range (5):
    string = socket.recv()
    topic, messagedata = string.split()
    total_value += int(messagedata)
    print ('{} {}'.format(topic, message)
</code>```

答:
Yes, this is possible.

The code above is not a reproducible MCVE/MWE-representation of the claimed problem.

First : the code explicitly blocks. Using a .recv()-method is blocking until any new, matching message arrives ( if ever ).

That does not overload the CPU. It just keeps sitting on the SUB-side waiting, until a first such message ( if any ) arrives.

If interested in a better scheme, do not use .recv()-method this way, but rather detect any such POSACK-acknowledgement with a .poll()-method & read a POSACK-ed case with .recv( zmq.NOBLOCK )-method.

Body:
I have some simple python code which waits for messages for a topic.

However...when running this, the python process will hog CPU. I know with other languages, such as with sockets, there is a way to wait for messages without eating the entire processing power. Essentially the thread just remains halted waiting for a response. Is that possible with ZeroMQ?

import zmq
import sys

port = "5556"
if len(sys.argv) > 1:
    port =  sys.argv[1]
    int(port)

# Socket to talk to server
context = zmq.Context()
socket = context.socket(zmq.SUB)

print "Collecting updates from weather server..."
socket.connect ("tcp://localhost:%s" % port)

# Subscribe to zipcode, default is NYC, 10001
topicfilter = "10001"
socket.setsockopt(zmq.SUBSCRIBE, topicfilter)

# Process 5 updates
total_value = 0
for update_nbr in range (5):
    string = socket.recv()
    topic, messagedata = string.split()
    total_value += int(messagedata)
    print ('{} {}'.format(topic, message)


问:
ADO.NET Entity Framework tutorials
Does anyone know of any good tutorials on ADO.NET Entity Framework?

There are a few useful links here at Stack OverFlow, and I've found one tutorial at Jason's DotNet Architecture Blog, but can anyone recommend any other good tutorials?
Any tutorials available from Microsoft, either online or as part of any conference/course material?

答: Microsoft offers .NET 3.5 Enhancements Training Kit it contains documentation and sample code for ADO.NET EF</p>

OwnerDisplayName: Yngvar

ContentLicense: CC BY-SA 2.5

Title: ADO.NET Entity Framework tutorials

LastEditorDisplayName: aku

OwnerDisplayName: aku


问:
How can you get the server time from Firebase
I'm using angularjs with firebase and when I use

```<code>$scope.createdDate = new Date();
</code>```

it uses the time on the client, however I want to use Firebase Servers current time as client-side time may vary. How can I go about this in angular?

答:
2020: Now you can use firebase.firestore.Timestamp.now() to get the UNIX time from the server. It returns an object that looks like this:

{
    seconds: NUM_OF_SECONDS,
    nanoseconds: NUM_OF_NANOSECONDS
}
```

From this in the docs.

Body:
I'm using angularjs with firebase and when I use

$scope.createdDate = new Date();

it uses the time on the client, however I want to use Firebase Servers current time as client-side time may vary. How can I go about this in angular?

Body:
2020: Now you can use firebase.firestore.Timestamp.now() to get the UNIX time from the server. It returns an object that looks like this:

{
    seconds: NUM_OF_SECONDS,
    nanoseconds: NUM_OF_NANOSECONDS
}

From this in the docs.


问:
Remove empty folders (Python)
This is the folder tree:

```<code>FOLDER\\
       \\1\\file
       \\2\\file
       \\3\\
       \\4\\file
</code>```

The script should scan (loop) for each folder in FOLDER and check if the sub-folders are empty or not. If they are, they must be deleted.

My code, until now, is this:

```<code>folders = ([x[0] for x in os.walk(os.path.expanduser('~\\Desktop\\FOLDER\\DIGITS\\'))])
folders2= (folders[1:])
</code>```

This scan for folders and, using folders2 begin from the firs folder in DIGITS.
In DIGITS there are numbered directories: 1,2,3,4,etc

Now what? Tried using os.rmdir but it gives me an error, something about string. In fact, folders2 is a list, not a string, just saying...

答:
```<code>import os

directory = r'path-to-directory'

for entry in os.scandir(directory):
    if os.path.isdir(entry.path) and not os.listdir(entry.path) :
        os.rmdir(entry.path)
</code>```

Here you can find a good introduction/explanation to scandir

Title: Remove empty folders (Python)

Body:
This is the folder tree:

FOLDER\\
       \\1\\file
       \\2\\file
       \\3\\
       \\4\\file

The script should scan (loop) for each folder in FOLDER and check if the sub-folders are empty or not. If they are, they must be deleted.

My code, until now, is this:

folders = ([x[0] for x in os.walk(os.path.expanduser('~\\Desktop\\FOLDER\\DIGITS\\'))])
folders2= (folders[1:])

This scan for folders and, using folders2 begin from the firs folder in DIGITS.
In DIGITS there are numbered directories: 1,2,3,4,etc

Now what? Tried using os.rmdir but it gives me an error, something about string. In fact, folders2 is a list, not a string, just saying...

Body:
import os

directory = r'path-to-directory'

for entry in os.scandir(directory):
    if os.path.isdir(entry.path) and not os.listdir(entry.path) :
        os.rmdir(entry.path)

Here you can find a good introduction/explanation to scandir


问:
Get Json Output with two select query in SQL Server
I would like to output the results of a SELECT statement as a JSON object.

```<code>id    name        active  Status
1     Bob Jones   1       Active
2     John Smith  0       Inactive
</code>```

I need return result like this:

```<code>{"Active"  :[{"id":1,"name":"Bob Jones" ,"active":1}],
 "InActive":[{"id":2,"name":"John Smith","active":0}]}
</code>```

How to use the query?

I am using this code

```<code>DECLARE @JSONTierDetails AS TABLE (TierDetails VARCHAR(8000))

INSERT INTO @JSONTierDetails
    SELECT
        (SELECT id, name, active
         FROM MyTable
         WHERE Status = 'Active'
         FOR JSON PATH, INCLUDE_NULL_VALUES) TierDetails

SELECT TierDetails
FROM @JSONTierDetails
</code>```

Thanks in advance

答:
Array wrappers and the property names for each JSON expression are needed for your case. Adding Array wrappers is not so hard but the property names is. , ROOT(<property_name>) after FOR JSON PATH might be used but that might be applied once and in static manner.

So, a Dynamic Query might be preferred, such as

```<code>DECLARE @JSONTierDetails NVARCHAR(MAX) =
(
 SELECT 'SELECT ' +
    STUFF((
            SELECT  N',(SELECT id, name, active
                          FROM MyTable subT
                         WHERE subT.status = ''' + status + N'''
                           FOR JSON PATH
                       ) AS [' + status + N']' + CHAR(13) + '   '
              FROM MyTable t
            FOR XML PATH(''),TYPE).value('(./text())[1]','NVARCHAR(MAX)'),1,1,'')
        + 'FOR JSON PATH, WITHOUT_ARRAY_WRAPPER' );

EXEC (@JSONTierDetails);
</code>```

Demo

Body:
I would like to output the results of a SELECT statement as a JSON object.

id    name        active  Status
1     Bob Jones   1       Active
2     John Smith  0       Inactive

I need return result like this:

{"Active"  :[{"id":1,"name":"Bob Jones" ,"active":1}],
 "InActive":[{"id":2,"name":"John Smith","active":0}]}

How to use the query?

I am using this code

DECLARE @JSONTierDetails AS TABLE (TierDetails VARCHAR(8000))

INSERT INTO @JSONTierDetails
    SELECT
        (SELECT id, name, active
         FROM MyTable
         WHERE Status = 'Active'
         FOR JSON PATH, INCLUDE_NULL_VALUES) TierDetails

SELECT TierDetails
FROM @JSONTierDetails

Thanks in advance

Body:
Array wrappers and the property names for each JSON expression are needed for your case. Adding Array wrappers is not so hard but the property names is. , ROOT(<property_name>) after FOR JSON PATH might be used but that might be applied once and in static manner.

So, a Dynamic Query might be preferred, such as

DECLARE @JSONTierDetails NVARCHAR(MAX) =
(
 SELECT 'SELECT ' +
    STUFF((
            SELECT  N',(SELECT id, name, active
                          FROM MyTable subT
                         WHERE subT.status = ''' + status + N'''
                           FOR JSON PATH
                       ) AS [' + status + N']' + CHAR(13) + '   '
              FROM MyTable t
            FOR XML PATH(''),TYPE).value('(./text())[1]','NVARCHAR(MAX)'),1,1,'')
        + 'FOR JSON PATH, WITHOUT_ARRAY_WRAPPER' );

EXEC (@JSONTierDetails);

Demo


问:
How to store xml file on firebase hosting get url point to it?
I have a React app that is stored in google Firebase with my custom domain (not the one that is provided by google Firebase)
I have created an xml file and want to store it on google Firebase and get its URL.

for example if my website domain is:
www.mywebsite.com
I want to upload file sitemap.xml to Firebase and get it stored there,
and to be able to access it through:
www.mywebsite.com/sitemap.xml

How can I upload that file and have access to it through that URL?

答:
If you want to upload a sitemap.xml:

Place the sitemap.xml into the folder that you've configured as the public folder in your firebase.json, which is also the folder where you have your main index.html file.

Run firebase deploy --only hosting.

Now the sitemap.xml will be available on www.mywebsite.com/sitemap.xml.


问:
How to use inner join in Django query set
I have the following models in model.py

```<code>    class Jobs(models.Model):
     JobNumber=models.CharField()
    CustomerName = models.CharField()

class JobTime(models.Model):
    JobNumber = models.ForeignKey(Jobs, on_delete=models.PROTECT)
    WorkHrs = models.FloatField()
    LabourCost = models.FloatField()

class JobMaterial(models.Model):
    JobNumber = models.ForeignKey(Jobs, on_delete=models.PROTECT)
    MaterialCost = models.FloatField()
</code>```

I want to generate a queryset with JobNumber,CustomerName, LabourCost, MaterialCost for all the JobNumbers in Jobs model. Please help, I use Django Version:    3.0.6 and Python Version:   3.8.2

答:
Honestly, I think your models should be modified so the foreign keys reside inside the Jobs class. A job should have a JobTime, and a JobMaterial, rather than the other way around. Then, you could do something like:

```<code>class Jobs(models.Model):
    JobNumber=models.CharField()
    CustomerName = models.CharField()
    job_time = models.ForeignKey(JobTime, on_delete=models.PROTECT)
    job_material = models.ForeignKey(JobMaterial, on_delete=models.PROTECT)

Jobs.objects.all().select_related('job_time', 'job_material')
</code>```

If you wanted job_material to be a one-to-many field on Jobs, then you would use prefetch_related instead of select_related.

Hope that helps, happy coding!

Body:
I have the following models in model.py

    class Jobs(models.Model):
     JobNumber=models.CharField()
    CustomerName = models.CharField()

class JobTime(models.Model):
    JobNumber = models.ForeignKey(Jobs, on_delete=models.PROTECT)
    WorkHrs = models.FloatField()
    LabourCost = models.FloatField()

class JobMaterial(models.Model):
    JobNumber = models.ForeignKey(Jobs, on_delete=models.PROTECT)
    MaterialCost = models.FloatField()

I want to generate a queryset with JobNumber,CustomerName, LabourCost, MaterialCost for all the JobNumbers in Jobs model. Please help, I use Django Version:    3.0.6 and Python Version:   3.8.2

Body:
Honestly, I think your models should be modified so the foreign keys reside inside the Jobs class. A job should have a JobTime, and a JobMaterial, rather than the other way around. Then, you could do something like:

class Jobs(models.Model):
    JobNumber=models.CharField()
    CustomerName = models.CharField()
    job_time = models.ForeignKey(JobTime, on_delete=models.PROTECT)
    job_material = models.ForeignKey(JobMaterial, on_delete=models.PROTECT)

Jobs.objects.all().select_related('job_time', 'job_material')

If you wanted job_material to be a one-to-many field on Jobs, then you would use prefetch_related instead of select_related.

Hope that helps, happy coding!


问:
boost::interprocess message_queue performance - rather slow?
I need an ultra-fast MQ mechanism, where both sender and receiver are written in C++, on Windows platform.

My current implementation using RCF-C++ for IPC is clocking at around 20,000 msg/sec over Windows Named Pipes.

I am testing the perf of boost::interprocess Message Queues according to the demo app, and am measuring around 48,000 messages/sec, which is surprisingly slow, considering that when I cooked up a simple Memory Mapped File communication on the same machine (in C# using code from this blog post), I got around 150,000 messages/sec.

Any idea about why I'm getting such slow performance out of boost message_queue, and what I can try to improve it?

答:
As Boost document states, boost::interprocess::shared_memory_object is implemented using memory mapped file in Win32. And, boost's message queue is using that simulated shared memory object as well. (For native Win32 shared memory, boost provides windows_shared_memory class separately.)

For better performance of message queue, therefore, you have to implement your own version of message queue using native Win32 shared memory object. In my experiments, after replacing it, performance increased noticeably.

Note that, if you change to Win32 native shared memory, you must take care of 'deletion' of the shared memory. POSIX shared memory and Win32 shared memory has different policy of deletion.


问:
Possible to determine if a stream is a string?
Is it possible to somehow (without a huge performance loss) determine if a Stream (just a normal System.IO.Stream) "contains" a string or not? I have tried to google this, but I havent found a good solution that doesnt involve try and catching.</p>

答:
Any stream can be a string as a string is just a series of bytes.  If you're asking if a stream contains a specific sequence of bytes -- i.e. you want to confirm that a stream contains a $MY_TOKEN$ somewhere then you'll have to read up until that point or to the end of the stream.

Depending on the nature of your stream, there might be an efficient way to do this and then reset the cursor back to the beginning of the stream.


问:
Apply a condition using any() or all() to multiple columns
I have dataframe with a few columns and I want to check if atleast 3 of the columns meet a condition. I will prefer to not directly iterate over columns but if that is the only way, I will go with it.

```<code>df = pd.DataFrame(np.random.randint(10, size=(5, 6)),
                  columns=list('ABCDEF'),
                  index=['R{}'.format(i) for i in range(5)])
df.head()

Out:
    A   B   C   D   E   F
R0  4   6   4   9   8   7
R1  0   7   5   0   6   4
R2  6   3   4   2   0   2
R3  9   4   7   2   5   7
R4  8   6   1   9   6   1
</code>```

For one column, say column A, I can do this: if any(df['A'] > 7) but I want to check all the columns and return True only if at least 3 columns out of the 6 meet the condition. In the dataframe above, columns A, D, E individually meet the condition (i.e. have at least one element > 7), so the if statement will return True.

答:
We can do gt then sum

```<code>df[df.gt(75).sum(axis=1).ge(3)]
</code>```

Body:
I have dataframe with a few columns and I want to check if atleast 3 of the columns meet a condition. I will prefer to not directly iterate over columns but if that is the only way, I will go with it.

df = pd.DataFrame(np.random.randint(10, size=(5, 6)),
                  columns=list('ABCDEF'),
                  index=['R{}'.format(i) for i in range(5)])
df.head()

Out:
    A   B   C   D   E   F
R0  4   6   4   9   8   7
R1  0   7   5   0   6   4
R2  6   3   4   2   0   2
R3  9   4   7   2   5   7
R4  8   6   1   9   6   1

For one column, say column A, I can do this: if any(df['A'] > 7) but I want to check all the columns and return True only if at least 3 columns out of the 6 meet the condition. In the dataframe above, columns A, D, E individually meet the condition (i.e. have at least one element > 7), so the if statement will return True.

Body:
We can do gt then sum

df[df.gt(75).sum(axis=1).ge(3)]