问:
Implementing a drag-and-drop zone in Swift
I recently started using Swift to build OS X apps and I am wondering how I could implement a drag-and-drop zone.

More specifically, I built an app that processes images but, for the moment, the user has to manually enter the path to the input images or use a File Chooser (which is quite annoying). I would like to improve my app allowing the user to input the images by a simple drag-and-drop (I only need to retrieve a String representing the path to the images).

How can I do this?

答:
This implementation allows for multiple files.

Just set the view class to DragView in Interface Builder, implement DragViewDelegate in your controller, then hook up the delegate outlet in Interface Builder. This way you get a delegate callback with the file URLs.

func dragViewDidReceive(fileURLs: [URL])
{
    // Yay!
}
```

<p><strong><code>DragView.swift</code></strong></p>

<pre class="lang-swift prettyprint-override"><code>//
//  DragView.swift
//
//  Copyright (c) 2020 Geri Borbás http://www.twitter.com/_eppz
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import Cocoa

@objc protocol DragViewDelegate
{

    func dragViewDidReceive(fileURLs: [URL])
}

class DragView: NSView
{

    @IBOutlet weak var delegate: DragViewDelegate?
    let fileExtensions = ["pdf"]

    required init?(coder: NSCoder)
    {
        super.init(coder: coder)
        color(to: .clear)
        registerForDraggedTypes([.fileURL])
    }

    override func draggingEntered(_ draggingInfo: NSDraggingInfo) -> NSDragOperation
    {
        var containsMatchingFiles = false
        draggingInfo.draggingPasteboard.readObjects(forClasses: [NSURL.self], options: nil)?.forEach
        {
            eachObject in
            if let eachURL = eachObject as? URL
            {
                containsMatchingFiles = containsMatchingFiles || fileExtensions.contains(eachURL.pathExtension.lowercased())
                if containsMatchingFiles { print(eachURL.path) }
            }
        }

        switch (containsMatchingFiles)
        {
            case true:
                color(to: .secondaryLabelColor)
                return .copy
            case false:
                color(to: .disabledControlTextColor)
                return .init()
        }
    }

    override func performDragOperation(_ draggingInfo: NSDraggingInfo) -> Bool
    {
        // Collect URLs.
        var matchingFileURLs: [URL] = []
        draggingInfo.draggingPasteboard.readObjects(forClasses: [NSURL.self], options: nil)?.forEach
        {
            eachObject in
            if
                let eachURL = eachObject as? URL,
                fileExtensions.contains(eachURL.pathExtension.lowercased())
            { matchingFileURLs.append(eachURL) }
        }

        // Only if any,
        guard matchingFileURLs.count > 0
        else { return false }

        // Pass to delegate.
        delegate?.dragViewDidReceive(fileURLs: matchingFileURLs)
        return true
    }

    override func draggingExited(_ sender: NSDraggingInfo?)
    { color(to: .clear) }

    override func draggingEnded(_ sender: NSDraggingInfo)
    { color(to: .clear) }

}

extension DragView
{

    func color(to color: NSColor)
    {
        self.wantsLayer = true
        self.layer?.backgroundColor = color.cgColor
    }
}

</code>```

Body:
This implementation allows for multiple files.

Just set the view class to DragView in Interface Builder, implement DragViewDelegate in your controller, then hook up the delegate outlet in Interface Builder. This way you get a delegate callback with the file URLs.

func dragViewDidReceive(fileURLs: [URL])
{
    // Yay!
}

DragView.swift

//
//  DragView.swift
//
//  Copyright (c) 2020 Geri Borbás http://www.twitter.com/_eppz
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import Cocoa

@objc protocol DragViewDelegate
{

    func dragViewDidReceive(fileURLs: [URL])
}

class DragView: NSView
{

    @IBOutlet weak var delegate: DragViewDelegate?
    let fileExtensions = ["pdf"]

    required init?(coder: NSCoder)
    {
        super.init(coder: coder)
        color(to: .clear)
        registerForDraggedTypes([.fileURL])
    }

    override func draggingEntered(_ draggingInfo: NSDraggingInfo) -> NSDragOperation
    {
        var containsMatchingFiles = false
        draggingInfo.draggingPasteboard.readObjects(forClasses: [NSURL.self], options: nil)?.forEach
        {
            eachObject in
            if let eachURL = eachObject as? URL
            {
                containsMatchingFiles = containsMatchingFiles || fileExtensions.contains(eachURL.pathExtension.lowercased())
                if containsMatchingFiles { print(eachURL.path) }
            }
        }

        switch (containsMatchingFiles)
        {
            case true:
                color(to: .secondaryLabelColor)
                return .copy
            case false:
                color(to: .disabledControlTextColor)
                return .init()
        }
    }

    override func performDragOperation(_ draggingInfo: NSDraggingInfo) -> Bool
    {
        // Collect URLs.
        var matchingFileURLs: [URL] = []
        draggingInfo.draggingPasteboard.readObjects(forClasses: [NSURL.self], options: nil)?.forEach
        {
            eachObject in
            if
                let eachURL = eachObject as? URL,
                fileExtensions.contains(eachURL.pathExtension.lowercased())
            { matchingFileURLs.append(eachURL) }
        }

        // Only if any,
        guard matchingFileURLs.count > 0
        else { return false }

        // Pass to delegate.
        delegate?.dragViewDidReceive(fileURLs: matchingFileURLs)
        return true
    }

    override func draggingExited(_ sender: NSDraggingInfo?)
    { color(to: .clear) }

    override func draggingEnded(_ sender: NSDraggingInfo)
    { color(to: .clear) }

}

extension DragView
{

    func color(to color: NSColor)
    {
        self.wantsLayer = true
        self.layer?.backgroundColor = color.cgColor
    }
}


来源: stackexchange

问:
Upload file to SFTP using PowerShell
We were asked to set up an automated upload from one of our servers to an SFTP site. There will be a file that is exported from a database to a filer every Monday morning and they want the file to be uploaded to SFTP on Tuesday. The current authentication method we are using is username and password (I believe there was an option to have key file as well but username/password option was chosen).

The way I am envisioning this is to have a script sitting on a server that will be triggered by Windows Task scheduler to run at a specific time (Tuesday) that will grab the file in question upload it to the SFTP and then move it to a different location for backup purposes.

For example:

Local Directory: C:\FileDump

SFTP Directory: /Outbox/

Backup Directory: C:\Backup

I tried few things at this point WinSCP being one of them as well as SFTP PowerShell Snap-In but nothing has worked for me so far.

This will be running on Windows Server 2012R2.

When I run Get-Host my console host version is 4.0.

Thanks.

答:
I am able to sftp using PowerShell as below:

PS C:\Users\user\Desktop> sftp user@aa.bb.cc.dd
user@aa.bb.cc.dd's password:
Connected to user@aa.bb.cc.dd.
sftp> ls
testFolder
sftp> cd testFolder
sftp> ls
taj_mahal.jpeg
sftp> put taj_mahal_1.jpeg
Uploading taj_mahal_1.jpeg to /home/user/testFolder/taj_mahal_1.jpeg
taj_mahal_1.jpeg                                                                      100%   11KB  35.6KB/s   00:00
sftp> ls
taj_mahal.jpeg      taj_mahal_1.jpeg
sftp>
```

I do not have installed Posh-SSH or anything like that. I am using Windows 10 Pro PowerShell. No additional modules installed.

ContentLicense: CC BY-SA 3.0

Title: Upload file to SFTP using PowerShell

Body:
I am able to sftp using PowerShell as below:

PS C:\Users\user\Desktop> sftp user@aa.bb.cc.dd
user@aa.bb.cc.dd's password:
Connected to user@aa.bb.cc.dd.
sftp> ls
testFolder
sftp> cd testFolder
sftp> ls
taj_mahal.jpeg
sftp> put taj_mahal_1.jpeg
Uploading taj_mahal_1.jpeg to /home/user/testFolder/taj_mahal_1.jpeg
taj_mahal_1.jpeg                                                                      100%   11KB  35.6KB/s   00:00
sftp> ls
taj_mahal.jpeg      taj_mahal_1.jpeg
sftp>

I do not have installed Posh-SSH or anything like that. I am using Windows 10 Pro PowerShell. No additional modules installed.

ContentLicense: CC BY-SA 4.0


问:
How can I prevent subtraction from repeating?
I'm using vb.net
My condition is this:

Dim num1,num2  As Integer

num1 = TextBox1.Text

num2 = TextBox2.Text

TextBox3.Text = num1 - num2

The subtraction is working. My problem when I continuous clicking the button for result, its still subtracting. How can I prevent it if the value on the textbox is the same.. Or how can I make it subtracting once?

Example, MyStockTextBox minus ItemSoldTextBox. After I get the result by clicking the button, when I click the button again its still subtracting even if I'm done subtracting the two.

This is my code for subtraction.

```<code>Private Sub BtnResult_Click(sender As System.Object, e As System.EventArgs) Handles Subtract.Click
    Dim num1, num2 As Integer
    num1 = TextBox1.Text
    num2 = TextBox2.Text
    TextBox3.Text = num1 - num2
End Sub
</code>```

答:
First thing, add this to the top of your code:

```<code>Option Strict On
Option Explicit On
</code>```

Then you'll see a bunch of errors appear. That's a good thing. Currently, you're not managing your variable types, and at some point it's bound to be a problem, whether because you don't learn to manage them or just because the program is crashing because of it.

Textbox1.Text is a String type. You want to calculate numbers. You're bound to have a problem at some point.

Since you probably want Integers, here's a way you could safeguard this code snippet:

```<code>Dim num1, num2 As Integer

'If one of the textboxes contains something else than a number, your program won't crash. It returns 'True' when it's able to parse the String into an Integer and 'False' if it can't.
If Integer.TryParse(Number1TextBox.Text, num1) AndAlso Integer.TryParse(Number1TextBox.Text, num2) Then
    Number1TextBox.Text = (num1 - num2).ToString
Else
    MessageBox.Show("Use only integer numbers!")
End If
</code>```

This doesn't prevent your code from running the operation more than once, but the result should be the same, so there will be no visible change on the screen.

There are several ways to prevent your user from repeating the same operation more than once, although I doubt that it would change much since the result won't change. Let me know if there's something I don't get.

Body:
I'm using vb.net
My condition is this:

Dim num1,num2  As Integer

num1 = TextBox1.Text

num2 = TextBox2.Text

TextBox3.Text = num1 - num2

The subtraction is working. My problem when I continuous clicking the button for result, its still subtracting. How can I prevent it if the value on the textbox is the same.. Or how can I make it subtracting once?

Example, MyStockTextBox minus ItemSoldTextBox. After I get the result by clicking the button, when I click the button again its still subtracting even if I'm done subtracting the two.

This is my code for subtraction.

Private Sub BtnResult_Click(sender As System.Object, e As System.EventArgs) Handles Subtract.Click
    Dim num1, num2 As Integer
    num1 = TextBox1.Text
    num2 = TextBox2.Text
    TextBox3.Text = num1 - num2
End Sub

Body:
First thing, add this to the top of your code:

Option Strict On
Option Explicit On

Then you'll see a bunch of errors appear. That's a good thing. Currently, you're not managing your variable types, and at some point it's bound to be a problem, whether because you don't learn to manage them or just because the program is crashing because of it.

Textbox1.Text is a String type. You want to calculate numbers. You're bound to have a problem at some point.

Since you probably want Integers, here's a way you could safeguard this code snippet:

Dim num1, num2 As Integer

'If one of the textboxes contains something else than a number, your program won't crash. It returns 'True' when it's able to parse the String into an Integer and 'False' if it can't.
If Integer.TryParse(Number1TextBox.Text, num1) AndAlso Integer.TryParse(Number1TextBox.Text, num2) Then
    Number1TextBox.Text = (num1 - num2).ToString
Else
    MessageBox.Show("Use only integer numbers!")
End If

This doesn't prevent your code from running the operation more than once, but the result should be the same, so there will be no visible change on the screen.

There are several ways to prevent your user from repeating the same operation more than once, although I doubt that it would change much since the result won't change. Let me know if there's something I don't get.


问:
<Lists> emptying themselves
Good evening,

I am having a weird issue with a method I am trying to implement on Java.
I will try and describe it as well as possible:

Basically what it does is checks for the next states an Epsilon-Non Deterministic State Machine would reach, given a state and an array of possible transitions.
The method "loadEpsilon(List)" loads up the possible epsilon transitions for the given list of states.

```<code>      if (transitionList.isEmpty()){
          return new HashSet<State>(stateEntryList);
      }
      else{
          for (int i=0; i <= transitionList.size()-1; i++){
              for (int j=0; j <= stateEntryList.size()-1; j++){
                  for (Transition tr : this.transitions()){
                      if ((tr.fromState() == stateEntryList.get(j)) && (tr.label() == transitionList.get(i))){
                          if (!stateExitList.contains(tr.toState())){
                              stateExitList.add(tr.toState());
                          }
                      }
                  }
              }
              stateEntryList.clear();
              stateEntryList = loadEpsilon(stateExitList);
              stateExitList.clear();
          }
          return new HashSet<State>(stateEntryList);
              }
</code>```

So, filling up the whole code with tracing "System.out.print"s right to the very end, just before the

```<code>    stateExitList.clear();
</code>```

everything is OK. However, past that line, I print BOTH lists RIGHT after that sentence (StateExitList and StateEntryList) and they are both GONE.

I just can't figure out why they are emptying themselves.

Any chance for help?

Thanks a lot in advanced.

EDIT: This here would be the code for loadEpsilon:

```<code>  public List<State> loadEpsilon(List<State> states) throws NoInitialStateException{
      State stateRead;
      if (states.isEmpty()){
          if (this.getInitialState() == null){
              throw new NoInitialStateException();
          }
          states.add(this.getInitialState());
          return loadEpsilon(states);
      }
      else{
          for (int i=0; i <= states.size()-1;i++){
              stateRead = states.get(i);
              for (Transition tr : this.transitions()){
                  if ((tr.fromState() == stateRead) && (tr.label().isEpsilon()) && (!states.contains(tr.toState()))){
                      states.add(tr.toState());
                      System.out.print(states.size());
                  }
              }
          }
      }
      return states;
  }
</code>```

The declaration of the lists are the following:

```<code>      List<State> stateEntryList = new ArrayList<State>();
      stateEntryList = loadEpsilon(stateEntryList);
      List<State> stateExitList = new ArrayList<State>();
      List<Label> listaLabels = new ArrayList<Label>();
      listaLabels.addAll(Arrays.asList(labels));
</code>```

答:
If stateEntryList is empty after you call stateExitList.clear() after you call loadEpsilon, that points toward the List that loadEpsilon returns being somehow tied to the stateExitList being passed to it.  Perhaps the list that loadEpsilon is returning is using the list passed to it as a backing store or something like that?  You really need to  post the code to loadEpsilon.

Edited:

Well that explains it.  your loadEpsilon is returning the List that was passed to it.  It is returning the exact same object it was given.  So you're ending up with the same object being referred to by two names.  But since it's the same object underneath, when you clear it, it's cleared.

You're basically doing this:

```<code>List<String> list1 = new ArrayList<String>();
list1.add("foo");
list1.add("bar");

List<String> sameList = list1;
sameList.add("quux");

list1.clear();
</code>```

Does that make it clearer why clearing one list clears them "both"?  (Again, there's only one object there that is being referred to by two reference variables).

Title: <Lists> emptying themselves

Body:
Good evening,

I am having a weird issue with a method I am trying to implement on Java.
I will try and describe it as well as possible:

Basically what it does is checks for the next states an Epsilon-Non Deterministic State Machine would reach, given a state and an array of possible transitions.
The method "loadEpsilon(List)" loads up the possible epsilon transitions for the given list of states.

      if (transitionList.isEmpty()){
          return new HashSet<State>(stateEntryList);
      }
      else{
          for (int i=0; i <= transitionList.size()-1; i++){
              for (int j=0; j <= stateEntryList.size()-1; j++){
                  for (Transition tr : this.transitions()){
                      if ((tr.fromState() == stateEntryList.get(j)) && (tr.label() == transitionList.get(i))){
                          if (!stateExitList.contains(tr.toState())){
                              stateExitList.add(tr.toState());
                          }
                      }
                  }
              }
              stateEntryList.clear();
              stateEntryList = loadEpsilon(stateExitList);
              stateExitList.clear();
          }
          return new HashSet<State>(stateEntryList);
              }

So, filling up the whole code with tracing "System.out.print"s right to the very end, just before the

    stateExitList.clear();

everything is OK. However, past that line, I print BOTH lists RIGHT after that sentence (StateExitList and StateEntryList) and they are both GONE.

I just can't figure out why they are emptying themselves.

Any chance for help?

Thanks a lot in advanced.

EDIT: This here would be the code for loadEpsilon:

  public List<State> loadEpsilon(List<State> states) throws NoInitialStateException{
      State stateRead;
      if (states.isEmpty()){
          if (this.getInitialState() == null){
              throw new NoInitialStateException();
          }
          states.add(this.getInitialState());
          return loadEpsilon(states);
      }
      else{
          for (int i=0; i <= states.size()-1;i++){
              stateRead = states.get(i);
              for (Transition tr : this.transitions()){
                  if ((tr.fromState() == stateRead) && (tr.label().isEpsilon()) && (!states.contains(tr.toState()))){
                      states.add(tr.toState());
                      System.out.print(states.size());
                  }
              }
          }
      }
      return states;
  }

The declaration of the lists are the following:

      List<State> stateEntryList = new ArrayList<State>();
      stateEntryList = loadEpsilon(stateEntryList);
      List<State> stateExitList = new ArrayList<State>();
      List listaLabels = new ArrayList();
      listaLabels.addAll(Arrays.asList(labels));

Body:
If stateEntryList is empty after you call stateExitList.clear() after you call loadEpsilon, that points toward the List that loadEpsilon returns being somehow tied to the stateExitList being passed to it.  Perhaps the list that loadEpsilon is returning is using the list passed to it as a backing store or something like that?  You really need to  post the code to loadEpsilon.

Edited:

Well that explains it.  your loadEpsilon is returning the List that was passed to it.  It is returning the exact same object it was given.  So you're ending up with the same object being referred to by two names.  But since it's the same object underneath, when you clear it, it's cleared.

You're basically doing this:

List<String> list1 = new ArrayList<String>();
list1.add("foo");
list1.add("bar");

List<String> sameList = list1;
sameList.add("quux");

list1.clear();

Does that make it clearer why clearing one list clears them "both"?  (Again, there's only one object there that is being referred to by two reference variables).


问:
Updating CosmosDb indexing policy through ARM templates
I am trying to use ARM templates to update the indexing policy for cosmos container. I tried 2 methods, one to simply declare the indexing policy in while declaring the container in ARM.

{
      "apiVersion": "[variables('cosmosDbApiVersion')]",
      "type": "Microsoft.DocumentDB/databaseAccounts/apis/databases/containers",
      "dependsOn": [ /* resourceId */ ],
      "name": "/* containerName */",
      "properties": {
        "resource": {
          "id": "/* id */",
          "partitionKey": {
            "paths": [
              "/partitionKey"
            ],
            "kind": "Hash"
          },
          "indexes": [
            {
              "indexingMode": "consistent",
              "automatic": true,
              "includedPaths": [
                {
                  "path": "/*",
                  "indexes": [
                    {
                      "kind": "Range",
                      "dataType": "Number",
                      "precision": -1
                    },
                    {
                      "kind": "Hash",
                      "dataType": "String",
                      "precision": 3
                    }
                  ]
                }
              ]
            }
          ],
          "defaultTtl": "[variables('defaultTtlValueToEnableTtl')]"
        }
      }
    },```
</div>
</div>
</p>

<p>The second was to use to use ARM to deploy container setting as such: </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>{
      "apiVersion": "[variables('cosmosDbApiVersion')]",
      "type": "Microsoft.DocumentDB/databaseAccounts/apis/databases/containers/settings",
      "name": "[/* name */",
      "dependsOn": [ " /* container name */" ],
      "properties": {
        "resource": {
          "throughput": "/* some throughput */",
          "indexes": [
            {
              "indexingMode": "consistent",
              "automatic": true,
              "includedPaths": [
                {
                  "path": "/*",
                  "indexes": [
                    {
                      "kind": "Range",
                      "dataType": "Number",
                      "precision": -1
                    },
                    {
                      "kind": "Hash",
                      "dataType": "String",
                      "precision": 3
                    }
                  ]
                }
              ]
            }
          ]
        }
      }
    },</code>```

Both techniques do not fail deployment but the indexing policy does not change.

Would appreciate some help.

答:
Range and hash index types are ignored by the Cosmos resource provider now for new containers or containers that were created within the past year or so. ARM does not validate the index policy which is why the template will deploy successfully.

Hash index was deprecated for these newer container because the performance of the range index in the new indexer is surpasses what hash index provided so was no longer necessary.

To create/modify index policy refer to this article below. There are multiple examples of index policies that implement everything from very simple to more complex policies that include composite indexes, spatial indexes and unique keys.

https://learn.microsoft.com/en-us/azure/cosmos-db/manage-sql-with-resource-manager#create-resource

Body:
I am trying to use ARM templates to update the indexing policy for cosmos container. I tried 2 methods, one to simply declare the indexing policy in while declaring the container in ARM.

{
      "apiVersion": "[variables('cosmosDbApiVersion')]",
      "type": "Microsoft.DocumentDB/databaseAccounts/apis/databases/containers",
      "dependsOn": [ /* resourceId */ ],
      "name": "/* containerName */",
      "properties": {
        "resource": {
          "id": "/* id */",
          "partitionKey": {
            "paths": [
              "/partitionKey"
            ],
            "kind": "Hash"
          },
          "indexes": [
            {
              "indexingMode": "consistent",
              "automatic": true,
              "includedPaths": [
                {
                  "path": "/*",
                  "indexes": [
                    {
                      "kind": "Range",
                      "dataType": "Number",
                      "precision": -1
                    },
                    {
                      "kind": "Hash",
                      "dataType": "String",
                      "precision": 3
                    }
                  ]
                }
              ]
            }
          ],
          "defaultTtl": "[variables('defaultTtlValueToEnableTtl')]"
        }
      }
    },

The second was to use to use ARM to deploy container setting as such:

{
      "apiVersion": "[variables('cosmosDbApiVersion')]",
      "type": "Microsoft.DocumentDB/databaseAccounts/apis/databases/containers/settings",
      "name": "[/* name */",
      "dependsOn": [ " /* container name */" ],
      "properties": {
        "resource": {
          "throughput": "/* some throughput */",
          "indexes": [
            {
              "indexingMode": "consistent",
              "automatic": true,
              "includedPaths": [
                {
                  "path": "/*",
                  "indexes": [
                    {
                      "kind": "Range",
                      "dataType": "Number",
                      "precision": -1
                    },
                    {
                      "kind": "Hash",
                      "dataType": "String",
                      "precision": 3
                    }
                  ]
                }
              ]
            }
          ]
        }
      }
    },

Both techniques do not fail deployment but the indexing policy does not change.

Would appreciate some help.


问:
dropDatabase() Error db does not exist but it Shows up on show dbs
I am trying to drop a database from mongos shell but I get an error the database does not exist. But the database is listed in show dbs and I am able to switch to the database.

答: Ok. I was able to delete the db from mongod shell. I still don't know why it didn't work. If mongos shell doesn't allow dropping db or since I had mongod shell open in another terminal that prevented mongos shell from dropping the db. Either way the error message is completely wrong.


问:
undefined variable Posts
I am trying to complete a search filter feature for my website however i am recieving the following error:

Undefined variable: posts (View:

```<code>@foreach($posts as $distance)

 <option value="{{$distance->distance}}">{{ $distance->distance}}</option>

 @endforeach
</code>```

Here is my search.blade.php (error occuring:

```<code>   @foreach($posts as $distance)
 <option value="{{$distance->distance}}">{{ $distance->distance}}</option>
 @endforeach
</select>
</code>```

SearchController.php

```<code>    function index()
{
 $posts = DB::table('posts')
     ->groupBy('title')
     ->get();
 return view('posts.search')->with('posts', $posts);
}
</code>```

Does anyone know why i am receiving the error even thoough my posts have been defined.

答:
In your Controller

```<code>public function index()
{
 $posts = DB::table('posts')
     ->groupBy('title')
     ->get();
 return view('posts.search',compact('posts'));
}
</code>```

In your model

```<code> @foreach($posts as $distance)

 <option value="{{$distance->id}}">{{ $distance->distance}}</option>

 @endforeach
</code>```

Title: undefined variable Posts

Body:
I am trying to complete a search filter feature for my website however i am recieving the following error:

Undefined variable: posts (View:

@foreach($posts as $distance)

 <option value="{{$distance->distance}}">{{ $distance->distance}}</option>

 @endforeach

Here is my search.blade.php (error occuring:

   @foreach($posts as $distance)
 <option value="{{$distance->distance}}">{{ $distance->distance}}</option>
 @endforeach
</select>

SearchController.php

    function index()
{
 $posts = DB::table('posts')
     ->groupBy('title')
     ->get();
 return view('posts.search')->with('posts', $posts);
}

Does anyone know why i am receiving the error even thoough my posts have been defined.

Body:
In your Controller

public function index()
{
 $posts = DB::table('posts')
     ->groupBy('title')
     ->get();
 return view('posts.search',compact('posts'));
}

In your model

 @foreach($posts as $distance)

 <option value="{{$distance->id}}">{{ $distance->distance}}</option>

 @endforeach


答:
Lists do not spontaneously empty themselves in Java.  Trust me.  It doesn't happen.

This means that there must be a different explanation:

Maybe the two lists are actually the same object, or views on the same object.  So clearing one list clears the second one.

Maybe clear is being called on the second list somewhere else, and you haven't spotted it.  Or maybe it is happening as a result of remove / removeAll calls.

Maybe the second list was already empty.  For instance, where you thought you were adding to the second list you were actually adding to an entirely different list object.

Maybe you are using a custom list implementation that has broken behaviour; e.g. some other operation is effectively deleting things as a mistaken side-effect.

Maybe it is something else ...

We are not going to help you with this without all of the relevant code (with the traceprint code included) and the output from the traceprints.

Title: <Lists> emptying themselves


问:
what is the purpose of spring boot autowired annotation on a constructor?
what is the purpose of @Autowired annotation on a constructor? What is the difference between non-annotated and annotated constructor? Thank you.</p>

答:
Autowiring feature enables you to inject the object dependency implicitly.

Without autowiring you have to initiate the object like:

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

        private CarService carService;

        public SomeOperation() {

            carService = new CarServiceImpl();
        }
    }
</code>```

But if you annotate with @Autowired you don't have to initiate the object. The framework will bring the class which implements the carService and initiate your object with it.

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

        private CarService carService;

        @Autowired
        public SomeOperation(CarService carService) {

            this.carService = carService;
        }
    }
</code>```

Body:
Autowiring feature enables you to inject the object dependency implicitly.

Without autowiring you have to initiate the object like:

    public class SomeOperation() {

        private CarService carService;

        public SomeOperation() {

            carService = new CarServiceImpl();
        }
    }

But if you annotate with @Autowired you don't have to initiate the object. The framework will bring the class which implements the carService and initiate your object with it.

    public class SomeOperation() {

        private CarService carService;

        @Autowired
        public SomeOperation(CarService carService) {

            this.carService = carService;
        }
    }


问:
How do I reverse words in a string with Python
I am trying to reverse words of a string, but having difficulty, any assistance will be appreciated:

```<code>S = " what is my name"

def reversStr(S):
    for x in range(len(S)):
        return S[::-1]
        break
</code>```

What I get now is: eman ym si tahw

However, I am trying to get: tahw is ym eman (individual words reversed)

答:
```<code>s1 = input("Enter a string with multiple words:")

print(f'Original:{s1}')
print(f'Reverse is:{s1[::-1]}')

each_word_new_list = []

s1_split = s1.split()

for i in range(0,len(s1_split)):
    each_word_new_list.append(s1_split[i][::-1])

print(f'New Reverse as List:{each_word_new_list}')

each_word_new_string=' '.join(each_word_new_list)

print(f'New Reverse as String:{each_word_new_string}')
</code>```

Body:
I am trying to reverse words of a string, but having difficulty, any assistance will be appreciated:

S = " what is my name"

def reversStr(S):
    for x in range(len(S)):
        return S[::-1]
        break

What I get now is: eman ym si tahw

However, I am trying to get: tahw is ym eman (individual words reversed)


问:
Solidity Function Signature - question about part of signature
I'm looking at examples of Smart Contracts written in Solidity and I found a constructor with the signature:

```<code>constructor() ERC721Full("<Token name>", "<Token Symbol>") public {

}
</code>```

what is the ERC721Full("", "") part of the signature? And how am I able to pass arguments into it?

答:
Found answer here:
https://solidity.readthedocs.io/en/develop/contracts.html#arguments-for-base-constructors

You can pass arguments to parent's constructors through a child constructor's "modifier"

Body:
I'm looking at examples of Smart Contracts written in Solidity and I found a constructor with the signature:

constructor() ERC721Full("<Token name>", "<Token Symbol>") public {

}

what is the ERC721Full("", "") part of the signature? And how am I able to pass arguments into it?


问:
RayCastAll from Camera to Player Not Working
Trying to run a raycast from my camera to Z = 0 that will hit objects on the TransparentFX layer and temporarily make them transparent as they are likely blocking the view of the player.  But the raycast never hits anything.

Camera
https://imgur.com/lyTo8OZ

Tree
https://imgur.com/bgNiMWR

ClearSight.cs

```<code>[RequireComponent(typeof(Camera))]
public class ClearSight : MonoBehaviour
{
    [SerializeField]
    private LayerMask raycastLayers;

    // Update is called once per frame
    void Update()
    {
        Vector3 forward = transform.TransformDirection(Vector3.forward) * 10;
        Debug.DrawRay(transform.position, forward, Color.green);
        RaycastHit2D[] hits = Physics2D.RaycastAll(transform.position, transform.TransformDirection(Vector3.forward), 10f, raycastLayers);
        if(hits != null && hits.Length > 0)
        {
            Debug.Log("Found objects blocking player!");
            foreach(RaycastHit2D hit in hits)
            {
                Debug.Log("Making " + hit.transform.gameObject.name + " transparent!");
                AutoTransparent at = hit.transform.GetComponent<AutoTransparent>();
                if(at == null)
                {
                    at = hit.transform.gameObject.AddComponent<AutoTransparent>();
                }

                at.MakeTransparent();
            }
        }
    }
}
</code>```

AutoTransparent.cs

```<code>[RequireComponent(typeof(SpriteRenderer))]
public class AutoTransparent : MonoBehaviour
{
    [SerializeField]
    private SpriteRenderer[] renderTargets;
    [SerializeField]
    private float transparentRecoveryTime = 0.1f;

    private bool isTransparent = false;
    private float transparencyTimer = 0;

    private void Update()
    {
        if (isTransparent)
        {
            UpdateTransparencyTimer();
        }
    }

    private void UpdateTransparencyTimer()
    {
        transparencyTimer += Time.deltaTime / transparentRecoveryTime;
        if(transparencyTimer >= 1)
        {
            MakeOpaque();
        }
    }

    public void MakeTransparent()
    {
        transparencyTimer = 0;
        if (!isTransparent)
        {
            isTransparent = true;
            foreach (SpriteRenderer renderer in renderTargets)
            {
                Color c = renderer.color;
                renderer.color = new Color(c.r, c.g, c.b, 0.3f);
            }
        }
    }

    public void MakeOpaque()
    {
        isTransparent = false;
        foreach(SpriteRenderer renderer in renderTargets)
        {
            Color c = renderer.color;
            renderer.color = new Color(c.r, c.g, c.b, 1);
        }
    }
}
</code>```

答: Figured it out.  I was using RaycastHit2D and Physics2D.RaycastAll, which uses Vector2 parameters so the Z forward variable was being taken out of the equation.  Switched up to Box Collider and Physics.RaycastAll and it works great.</p>

Body:
Trying to run a raycast from my camera to Z = 0 that will hit objects on the TransparentFX layer and temporarily make them transparent as they are likely blocking the view of the player.  But the raycast never hits anything.

Camera
https://imgur.com/lyTo8OZ

Tree
https://imgur.com/bgNiMWR

ClearSight.cs

[RequireComponent(typeof(Camera))]
public class ClearSight : MonoBehaviour
{
    [SerializeField]
    private LayerMask raycastLayers;

    // Update is called once per frame
    void Update()
    {
        Vector3 forward = transform.TransformDirection(Vector3.forward) * 10;
        Debug.DrawRay(transform.position, forward, Color.green);
        RaycastHit2D[] hits = Physics2D.RaycastAll(transform.position, transform.TransformDirection(Vector3.forward), 10f, raycastLayers);
        if(hits != null && hits.Length > 0)
        {
            Debug.Log("Found objects blocking player!");
            foreach(RaycastHit2D hit in hits)
            {
                Debug.Log("Making " + hit.transform.gameObject.name + " transparent!");
                AutoTransparent at = hit.transform.GetComponent<AutoTransparent>();
                if(at == null)
                {
                    at = hit.transform.gameObject.AddComponent<AutoTransparent>();
                }

                at.MakeTransparent();
            }
        }
    }
}

AutoTransparent.cs

[RequireComponent(typeof(SpriteRenderer))]
public class AutoTransparent : MonoBehaviour
{
    [SerializeField]
    private SpriteRenderer[] renderTargets;
    [SerializeField]
    private float transparentRecoveryTime = 0.1f;

    private bool isTransparent = false;
    private float transparencyTimer = 0;

    private void Update()
    {
        if (isTransparent)
        {
            UpdateTransparencyTimer();
        }
    }

    private void UpdateTransparencyTimer()
    {
        transparencyTimer += Time.deltaTime / transparentRecoveryTime;
        if(transparencyTimer >= 1)
        {
            MakeOpaque();
        }
    }

    public void MakeTransparent()
    {
        transparencyTimer = 0;
        if (!isTransparent)
        {
            isTransparent = true;
            foreach (SpriteRenderer renderer in renderTargets)
            {
                Color c = renderer.color;
                renderer.color = new Color(c.r, c.g, c.b, 0.3f);
            }
        }
    }

    public void MakeOpaque()
    {
        isTransparent = false;
        foreach(SpriteRenderer renderer in renderTargets)
        {
            Color c = renderer.color;
            renderer.color = new Color(c.r, c.g, c.b, 1);
        }
    }
}


问:
How to display PIL Image dynamically
I want to crop my image file using PIL library and display it using Flask and Jinja.

I have tried this code:

```<code>@bp.route('/media/<fname>')
def fetch_media(fname):
...
    image = Image.open(path)
    cropped_image = image.crop(box)
    return cropped_image
</code>```

This gives a TypeError:

The view function did not return a valid response. The return type
  must be a string, dict, tuple, Response instance, or WSGI callable,
  but it was a Image.

How can I return the Image to html page?

答:
Untested, but certainly pretty close to this:</p>

```<code>import io
from PIL import Image
from flask import Response

....
....
buffer = io.BytesIO()
cropped_image.save(buffer, format="PNG")
return Response(buffer.getvalue(), mimetype='image/png')
</code>```

Title: How to display PIL Image dynamically

Body:
I want to crop my image file using PIL library and display it using Flask and Jinja.

I have tried this code:

@bp.route('/media/<fname>')
def fetch_media(fname):
...
    image = Image.open(path)
    cropped_image = image.crop(box)
    return cropped_image

This gives a TypeError:

The view function did not return a valid response. The return type
  must be a string, dict, tuple, Response instance, or WSGI callable,
  but it was a Image.

How can I return the Image to html page?

Body:
Untested, but certainly pretty close to this:

import io
from PIL import Image
from flask import Response

....
....
buffer = io.BytesIO()
cropped_image.save(buffer, format="PNG")
return Response(buffer.getvalue(), mimetype='image/png')


问:
wpf combobox - bind custom isselected property
I want to bind a list of items with properties 'ID', 'Description' and 'IsSelected' to a combobox. The display value is set using DisplayMemberPath to 'Description' which works fine. However i want that 'IsSelected' property to be set when that item is selected. I've tried Setting SelectedValuePath and SelectedValue to 'IsSelected' but it doesn't work.</p>

答:
Nothing like re-answering a five year old question... I disagree with Mike in that you should keep track of both states as the ComboBox can give you the IsSelected state of the SelectedValue. Matrix was on the right lines but you can't use IsSelected with DisplayMemberPath.

With the code below my Fruits Selected property is bound to IsSelected.

View Code

```<code><ComboBox ItemsSource="{Binding Fruit}"
          SelectedValue="{Binding SelectedFruitViewModel}"
          DisplayMemberPath="Name">
    <ComboBox.ItemContainerStyle>
        <Style TargetType="ComboBoxItem">
            <Setter Property="IsSelected" Value="{Binding Selected}" />
        </Style>
    </ComboBox.ItemContainerStyle>
</ComboBox>
</code>```

MainWindowViewModel

```<code>public class MainWindowViewModel : BaseViewModel
{
    private FruitViewModel _selectedFruitViewModel;

    public MainWindowViewModel()
    {
        this.Fruit = new ObservableCollection<FruitViewModel>
        {
            new FruitViewModel { Name = "Pineapple", Selected = false },
            new FruitViewModel { Name = "Apple", Selected = false },
            new FruitViewModel { Name = "Orange", Selected = false },
            new FruitViewModel { Name = "Kiwi", Selected = false }
        };
    }

    public ObservableCollection<FruitViewModel> Fruit { get; }

    public FruitViewModel SelectedFruitViewModel
    {
        get => _selectedFruitViewModel;
        set => SetProperty(ref _selectedFruitViewModel, value);
    }
}
</code>```

FruitViewModel

```<code>public class FruitViewModel : BaseViewModel
{
    private bool _selected;
    private string _name;

    public bool Selected
    {
        get => _selected;
        set => SetProperty(ref _selected, value);
    }

    public string Name
    {
        get => _name;
        set => SetProperty(ref _name, value);
    }
}
</code>```

BaseViewModel

```<code>public class BaseViewModel : INotifyPropertyChanged
{
    public virtual event PropertyChangedEventHandler PropertyChanged;

    protected virtual bool SetProperty<T>(ref T storage,
                                          T value,
                                          [CallerMemberName] string propertyName = null)
    {
        if (EqualityComparer<T>.Default.Equals(storage, value))
        {
            return false;
        }

        storage = value;

        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

        return true;
    }
}
</code>```

Body:
Nothing like re-answering a five year old question... I disagree with Mike in that you should keep track of both states as the ComboBox can give you the IsSelected state of the SelectedValue. Matrix was on the right lines but you can't use IsSelected with DisplayMemberPath.

With the code below my Fruits Selected property is bound to IsSelected.

View Code

<ComboBox ItemsSource="{Binding Fruit}"
          SelectedValue="{Binding SelectedFruitViewModel}"
          DisplayMemberPath="Name">
    <ComboBox.ItemContainerStyle>
        <Style TargetType="ComboBoxItem">
            <Setter Property="IsSelected" Value="{Binding Selected}" />
        </Style>
    </ComboBox.ItemContainerStyle>
</ComboBox>

MainWindowViewModel

public class MainWindowViewModel : BaseViewModel
{
    private FruitViewModel _selectedFruitViewModel;

    public MainWindowViewModel()
    {
        this.Fruit = new ObservableCollection<FruitViewModel>
        {
            new FruitViewModel { Name = "Pineapple", Selected = false },
            new FruitViewModel { Name = "Apple", Selected = false },
            new FruitViewModel { Name = "Orange", Selected = false },
            new FruitViewModel { Name = "Kiwi", Selected = false }
        };
    }

    public ObservableCollection<FruitViewModel> Fruit { get; }

    public FruitViewModel SelectedFruitViewModel
    {
        get => _selectedFruitViewModel;
        set => SetProperty(ref _selectedFruitViewModel, value);
    }
}

FruitViewModel

public class FruitViewModel : BaseViewModel
{
    private bool _selected;
    private string _name;

    public bool Selected
    {
        get => _selected;
        set => SetProperty(ref _selected, value);
    }

    public string Name
    {
        get => _name;
        set => SetProperty(ref _name, value);
    }
}

BaseViewModel

public class BaseViewModel : INotifyPropertyChanged
{
    public virtual event PropertyChangedEventHandler PropertyChanged;

    protected virtual bool SetProperty<T>(ref T storage,
                                          T value,
                                          [CallerMemberName] string propertyName = null)
    {
        if (EqualityComparer<T>.Default.Equals(storage, value))
        {
            return false;
        }

        storage = value;

        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

        return true;
    }
}


问:
Java, How does the compiler know which constructor to call in this lambda expression
I have a question, I'm learning java with a Book, and as I've copied some code in there (and made some changes) and made some investigations, I noticed something odd..., here is the code

```<code>public static void main(String[] args)
{
    Timer timer = new Timer(1000, (event) ->
    {
        System.out.println("At the Tone, the time is" + Instant.ofEpochMilli(event.getWhen()));
        Toolkit.getDefaultToolkit().beep();
    });

    timer.start();
    JOptionPane.showMessageDialog(null, "Quit?");
    System.exit(0);

}
</code>```

It's just a code that notifies you if a second passes. (this code compiles and runs smoothly)

as you can see Timer Constructor requires 2 pars (int, ActionListener)

```<code>public Timer(int delay, ActionListener listener)
</code>```

and the ActionListener Interface has one method that is actionPerformed and requires ActionEvent parameter

```<code>public void actionPerformed(ActionEvent e);
</code>```

Now here is my question, when calling this actionPerformed Method in that lambda expression above
How does the compiler know which constructor to call to instantiate ActionEvent without feeding him any clues about the parameters, ActionEvent has no "No argument Constructor" and the method getWhen() is not static (obj must be instantiated)

Here are all the constructors of ActionEvent:

```<code>public ActionEvent(Object source, int id, String command)

public ActionEvent(Object source, int id, String command, int modifiers)

public ActionEvent(Object source, int id, String command, long when,
                   int modifiers)
</code>```

I really hope I made myself clear!, Thank you

答:
The compiler does not know! ;-)

It is the Timer instance that will create the ActionEvent instance at runtime every delay and the Timer instance will call the ActionListener method actionPerformed with the ActionEvent it created.

You can have a look at one of the implementation here:

http://developer.classpath.org/doc/javax/swing/Timer-source.html

```<code>/**
 * Fire the action event, named "Timer" and having the numeric
 * identifier, equal to the numer of events that have been
 * already fired before.
 */
void fireActionPerformed()
{
  fireActionPerformed(new ActionEvent(this, ticks++, "Timer"));
}
</code>```

Body:
I have a question, I'm learning java with a Book, and as I've copied some code in there (and made some changes) and made some investigations, I noticed something odd..., here is the code

public static void main(String[] args)
{
    Timer timer = new Timer(1000, (event) ->
    {
        System.out.println("At the Tone, the time is" + Instant.ofEpochMilli(event.getWhen()));
        Toolkit.getDefaultToolkit().beep();
    });

    timer.start();
    JOptionPane.showMessageDialog(null, "Quit?");
    System.exit(0);

}

It's just a code that notifies you if a second passes. (this code compiles and runs smoothly)

as you can see Timer Constructor requires 2 pars (int, ActionListener)

public Timer(int delay, ActionListener listener)

and the ActionListener Interface has one method that is actionPerformed and requires ActionEvent parameter

public void actionPerformed(ActionEvent e);

Now here is my question, when calling this actionPerformed Method in that lambda expression above
How does the compiler know which constructor to call to instantiate ActionEvent without feeding him any clues about the parameters, ActionEvent has no "No argument Constructor" and the method getWhen() is not static (obj must be instantiated)

Here are all the constructors of ActionEvent:

public ActionEvent(Object source, int id, String command)

public ActionEvent(Object source, int id, String command, int modifiers)

public ActionEvent(Object source, int id, String command, long when,
                   int modifiers)

I really hope I made myself clear!, Thank you

Body:
The compiler does not know! ;-)

It is the Timer instance that will create the ActionEvent instance at runtime every delay and the Timer instance will call the ActionListener method actionPerformed with the ActionEvent it created.

You can have a look at one of the implementation here:

http://developer.classpath.org/doc/javax/swing/Timer-source.html

/**
 * Fire the action event, named "Timer" and having the numeric
 * identifier, equal to the numer of events that have been
 * already fired before.
 */
void fireActionPerformed()
{
  fireActionPerformed(new ActionEvent(this, ticks++, "Timer"));
}


答:
```<code>SELECT COUNT(DISTINCT column_name)
FROM table_name
WHERE ( DateTime > (GetDate()-30) )
</code>```

something along those lines

Title: How do I create an array of data for 30 days from database table where some dates are not entered?

Body:
Let's say you have a simple table with:

ID  IP                  CREATED_DATE
-------------------------------------------------------
1   111.111.111.111     2011-03-28 14:12:31
2   111.111.111.111     2011-03-29 03:38:12
3   222.222.222.222     2011-04-02 12:04:45
4   111.111.111.111     2011-04-02 22:13:23
5   333.333.333.333     2011-04-03 05:53:15
6   222.222.222.222     2011-04-05 02:13:51
7   111.111.111.111     2011-04-07 11:45:34

I need to query the last 30 days and get a count of unique ips and total rows per day even if there are no entries for that day. So days that are not entered would obviously just be 0 as the array value for both unique and total rows.

Body:
SELECT COUNT(DISTINCT column_name)
FROM table_name
WHERE ( DateTime > (GetDate()-30) )

something along those lines


问:
In tkinter application development, why does my code not give any output?
I am trying to develop a widget using Tkinter Python. It should take the data as input from user in two stages and then proceed further based on given inputs. My code does not give any output at all. I am new to Python.

Here is my code:

```<code>
from tkinter import *

def f_step():
    global txt_1
    global txt_2
    global v0

    window=Tk()

    txt_1=StringVar()
    Label(window,text="DB/rst name (without extension)").place(x=10,y=75)
    Entry(window,textvariable=txt_1,width=40).place(x=225,y=75)

    txt_2=StringVar()
    Label(window,text="DB/rst folder path").place(x=10,y=100)
    Entry(window,textvariable=txt_2,width=40).place(x=225,y=100)

    v0=StringVar()
    #v0.set(1)
    Label(window,text="Do you have first node number").place(x=10,y=150)
    Radiobutton(window,text="yes",variable=v0,value="a").place(x=225,y=150)
    Radiobutton(window,text="no",variable=v0,value="b").place(x=350,y=150)

    Button(window,text="Next",command=clicked).place(x=250,y=250)
    window.title('Path operation application')
    window.geometry("500x300+10+10")
    window.mainloop()

def clicked():
    global db_name
    global fpath
    global aa

    db_name = txt_1.get()
    fpath = txt_2.get()
    aa=v0.get()
    window.destroy()
    Initiaterun()

def Initiaterun():
    if aa == "a": # Checks to see if you entered the correct data.
        r = Tk() # Opens new window
        r.title(':D')
        r.geometry('150x50') # Makes the window a certain size
        rlbl = Label(r, text='\n[+] with node number operation') # "logged in" label
        rlbl.pack() # Pack is like .grid(), just different
        r.mainloop()
    elif aa == "b":
        r = Tk()
        r.title('D:')
        r.geometry('150x50')
        rlbl = Label(r, text='\n[!] With component file operation')
        rlbl.pack()
        r.mainloop()

def DelUser():
    r.destroy() # Destroys the login window
    f_step() # And goes back to the start!
'''

</code>```

答:
Your code doesn't give any output because you have not called any functions yet.
You have only defined the functions.

Try calling f_step() at the end of the code.

Hope this helps

Body:
I am trying to develop a widget using Tkinter Python. It should take the data as input from user in two stages and then proceed further based on given inputs. My code does not give any output at all. I am new to Python.

Here is my code:

from tkinter import *

def f_step():
    global txt_1
    global txt_2
    global v0

    window=Tk()

    txt_1=StringVar()
    Label(window,text="DB/rst name (without extension)").place(x=10,y=75)
    Entry(window,textvariable=txt_1,width=40).place(x=225,y=75)

    txt_2=StringVar()
    Label(window,text="DB/rst folder path").place(x=10,y=100)
    Entry(window,textvariable=txt_2,width=40).place(x=225,y=100)

    v0=StringVar()
    #v0.set(1)
    Label(window,text="Do you have first node number").place(x=10,y=150)
    Radiobutton(window,text="yes",variable=v0,value="a").place(x=225,y=150)
    Radiobutton(window,text="no",variable=v0,value="b").place(x=350,y=150)

    Button(window,text="Next",command=clicked).place(x=250,y=250)
    window.title('Path operation application')
    window.geometry("500x300+10+10")
    window.mainloop()

def clicked():
    global db_name
    global fpath
    global aa

    db_name = txt_1.get()
    fpath = txt_2.get()
    aa=v0.get()
    window.destroy()
    Initiaterun()

def Initiaterun():
    if aa == "a": # Checks to see if you entered the correct data.
        r = Tk() # Opens new window
        r.title(':D')
        r.geometry('150x50') # Makes the window a certain size
        rlbl = Label(r, text='\n[+] with node number operation') # "logged in" label
        rlbl.pack() # Pack is like .grid(), just different
        r.mainloop()
    elif aa == "b":
        r = Tk()
        r.title('D:')
        r.geometry('150x50')
        rlbl = Label(r, text='\n[!] With component file operation')
        rlbl.pack()
        r.mainloop()

def DelUser():
    r.destroy() # Destroys the login window
    f_step() # And goes back to the start!
'''


问:
Search for multiple possible param values
At the moment I have a form in which the user can input price per person and/or duration and/or team_size. What I would like to accomplish is to retrieve all records from a table that match the user input and for this I set scope in the model:

```<code>scope :filter_by_team_size, -> (team_size) { where("team_size = ?", team_size) }
scope :filter_by_duration, -> (duration) { where("duration = ?", duration) }
scope :filter_by_price, -> (price) { where("price = ?", price) }
</code>```

And then in the controller use that again to retrieve the records by doing so:

```<code>@experiences = policy_scope(Experience).order(team_size: :desc).geocoded.filter_by_team_size(params[:team_size]) if params[:team_size].present?
@experiences = policy_scope(Experience).order(duration: :desc).geocoded.filter_by_duration(params[:duration]) if params[:duration].present?
@experiences = policy_scope(Experience).order(price: :desc).geocoded.filter_by_price(params[:price]) if params[:price].present?
</code>```

However, this only gives me only the records for which the first input value matches but ignores all other values. Additionally, when you are viewing the search results and use the filter again it should apply the filter only for the records it found already.

Any suggestion on how to solve this would be much appreciated!

答:
One way to handle this is to use a virtual model that handles binding parameters to and from the form:

```<code>class SearchQuery
  include ActiveModel::Model
  include ActiveModel::Attributes
  attribute :team_size, :integer
  attribute :duration
  attribute :price
end
</code>```

You can then setup the form:

```<code><%= form_with(model: (@search_query || SearchQuery.new), url: '/experiences', method: :get) %>
  <div>
    <%= f.label :team_size %>
    <%= f.number_field :team_size %>
  </div>
  # ..
<% end %>
</code>```

And then you can just bind the params to the model with ActionController::Parameters#permit just like you would with a normal ActiveRecord model:

```<code>class ExperiencesController
  before_action :set_search_query, only: :index, if: ->{ params[:search_query].present? }
  # ...

  def index
    @experiences = if @search_query
      @search_query.build_scope(policy_scope(Experience))
    else
      policy_scope(Experience)
    end.geocoded
  end

  private
  def set_search_query
     @search_query = SearchQuery.new(search_query_params)
  end

  def search_query_params
     params.fetch(:search_query).permit(:team_size, :duration, :price)
  end
end
</code>```

This loopback will make the form stateful just like your normal CRUD forms. We have not actually implemented #build_scope yes so lets do so:

```<code>class SearchQuery
  include ActiveModel::Model
  include ActiveModel::Attributes
  attribute :team_size, :integer
  attribute :duration
  attribute :price

  def build_scope(base_scope)
    compacted_attributes = attributes.reject { value.nil? || value.empty? }
    compacted_attributes.each_with_object(base_scope) do |(k,v), base|
      if base.respond_to? "filter_by_#{k}"
        # lets you customize the logic with a scope
        base.send("filter_by_#{k}", v) # the scope is responsible for ordering
      else
        # convention over configuration!
        base.where(Hash[k,v]).order(Hash[k,:desc])
      end
    end
  end
end
</code>```

Since this uses convention over configuration you can get rid of those pointless scopes in your model.

Body:
At the moment I have a form in which the user can input price per person and/or duration and/or team_size. What I would like to accomplish is to retrieve all records from a table that match the user input and for this I set scope in the model:

scope :filter_by_team_size, -> (team_size) { where("team_size = ?", team_size) }
scope :filter_by_duration, -> (duration) { where("duration = ?", duration) }
scope :filter_by_price, -> (price) { where("price = ?", price) }

And then in the controller use that again to retrieve the records by doing so:

@experiences = policy_scope(Experience).order(team_size: :desc).geocoded.filter_by_team_size(params[:team_size]) if params[:team_size].present?
@experiences = policy_scope(Experience).order(duration: :desc).geocoded.filter_by_duration(params[:duration]) if params[:duration].present?
@experiences = policy_scope(Experience).order(price: :desc).geocoded.filter_by_price(params[:price]) if params[:price].present?

However, this only gives me only the records for which the first input value matches but ignores all other values. Additionally, when you are viewing the search results and use the filter again it should apply the filter only for the records it found already.

Any suggestion on how to solve this would be much appreciated!

Body:
One way to handle this is to use a virtual model that handles binding parameters to and from the form:

class SearchQuery
  include ActiveModel::Model
  include ActiveModel::Attributes
  attribute :team_size, :integer
  attribute :duration
  attribute :price
end

You can then setup the form:

<%= form_with(model: (@search_query || SearchQuery.new), url: '/experiences', method: :get) %>
  <div>
    <%= f.label :team_size %>
    <%= f.number_field :team_size %>
  </div>
  # ..
<% end %>

And then you can just bind the params to the model with ActionController::Parameters#permit just like you would with a normal ActiveRecord model:

class ExperiencesController
  before_action :set_search_query, only: :index, if: ->{ params[:search_query].present? }
  # ...

  def index
    @experiences = if @search_query
      @search_query.build_scope(policy_scope(Experience))
    else
      policy_scope(Experience)
    end.geocoded
  end

  private
  def set_search_query
     @search_query = SearchQuery.new(search_query_params)
  end

  def search_query_params
     params.fetch(:search_query).permit(:team_size, :duration, :price)
  end
end

This loopback will make the form stateful just like your normal CRUD forms. We have not actually implemented #build_scope yes so lets do so:

class SearchQuery
  include ActiveModel::Model
  include ActiveModel::Attributes
  attribute :team_size, :integer
  attribute :duration
  attribute :price

  def build_scope(base_scope)
    compacted_attributes = attributes.reject { value.nil? || value.empty? }
    compacted_attributes.each_with_object(base_scope) do |(k,v), base|
      if base.respond_to? "filter_by_#{k}"
        # lets you customize the logic with a scope
        base.send("filter_by_#{k}", v) # the scope is responsible for ordering
      else
        # convention over configuration!
        base.where(Hash[k,v]).order(Hash[k,:desc])
      end
    end
  end
end

Since this uses convention over configuration you can get rid of those pointless scopes in your model.


问:
Can I assign custom name for path converters in Django?
I want to assign custom name for slug path converter in urlpatterns of my
Now it looks like this:

```<code>urlpatterns = [
    ...
    path(
        route="<slug:category>/",
        view=views.Category.as_view(),
        name="shop_category"
    ),
    ...
]
</code>```

In this view I'm using DetailListView. The slug contains only ASCII characters, but anyway it doesn't let me in. After some manipulations with passed value, I return from get with return super().get(request, *args, **kwargs) line.

Then it throws me an error:

AttributeError: Generic detail view Category must be called with either an object pk or a slug in the URLconf.

But if I change in category name in urlpatterns to slug, error disappears.

Now, the question: can I assign custom name for path converters in Django?

答:
You can define custom name using slug_url_kwarg attribute in your view class:

```<code>class Category(DetailView):
    slug_url_kwarg = "category"
</code>```

Body:
I want to assign custom name for slug path converter in urlpatterns of my
Now it looks like this:

urlpatterns = [
    ...
    path(
        route="<slug:category>/",
        view=views.Category.as_view(),
        name="shop_category"
    ),
    ...
]

In this view I'm using DetailListView. The slug contains only ASCII characters, but anyway it doesn't let me in. After some manipulations with passed value, I return from get with return super().get(request, *args, **kwargs) line.

Then it throws me an error:

AttributeError: Generic detail view Category must be called with either an object pk or a slug in the URLconf.

But if I change in category name in urlpatterns to slug, error disappears.

Now, the question: can I assign custom name for path converters in Django?

Body:
You can define custom name using slug_url_kwarg attribute in your view class:

class Category(DetailView):
    slug_url_kwarg = "category"


答:
What is the difference between non-annotated and annotated
  constructor?

In Spring 3 or below, the annotation on the constructor is mandatory to make Spring consider the constructor as the way to instantiate the bean and inject dependencies provided in parameters.

Spring 4 and above versions don't require the annotation to do that.
You just need to declare the constructor with any parameter to achieve that.

So in recent Spring versions, don't clutter the code with the annotation :

```<code>public Foo(Bar bar){
  this.bar = bar;
}
</code>```

Title: what is the purpose of spring boot autowired annotation on a constructor?

Body: what is the purpose of @Autowired annotation on a constructor? What is the difference between non-annotated and annotated constructor? Thank you.

Body:
What is the difference between non-annotated and annotated
  constructor?

In Spring 3 or below, the annotation on the constructor is mandatory to make Spring consider the constructor as the way to instantiate the bean and inject dependencies provided in parameters.

Spring 4 and above versions don't require the annotation to do that.
You just need to declare the constructor with any parameter to achieve that.

So in recent Spring versions, don't clutter the code with the annotation :

public Foo(Bar bar){
  this.bar = bar;
}


问:
Cache has been closed exception
I am getting "Cache has been closed" exception when accessing Ignite Cache for querying. What I'm doing is simply,

```<code>CacheConfiguration cfg = new CacheConfiguration();
cacheConfiguration.setCacheMode(CacheMode.REPLICATED);
cacheConfiguration.setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL_SNAPSHOT);        cacheConfiguration.setWriteSynchronizationMode(CacheWriteSynchronizationMode.PRIMARY_SYNC);
IgniteCache cache = ignite.getOrCreateCache(cfg);
</code>```

After initializing this, in other place in my code I am calling cache.get("key"); But it's throwing exception.

Cache variable is member of some class's object. Why can't the cache be kept open till it is closed manually.

I AM NOT CLOSING IT ANYWHERE

答: Usually it happens when client is disconnected, servers go down, or client rejoins with new ID since you're not calling .close() or .destory() anywhere in your code.

Title: Cache has been closed exception

Body:
I am getting "Cache has been closed" exception when accessing Ignite Cache for querying. What I'm doing is simply,

CacheConfiguration cfg = new CacheConfiguration();
cacheConfiguration.setCacheMode(CacheMode.REPLICATED);
cacheConfiguration.setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL_SNAPSHOT);        cacheConfiguration.setWriteSynchronizationMode(CacheWriteSynchronizationMode.PRIMARY_SYNC);
IgniteCache cache = ignite.getOrCreateCache(cfg);

After initializing this, in other place in my code I am calling cache.get("key"); But it's throwing exception.

Cache variable is member of some class's object. Why can't the cache be kept open till it is closed manually.

I AM NOT CLOSING IT ANYWHERE


问:
How to make this image effect, any library that can help with it
Do you know if an emboss effect like this can be done with a programming package. Can someone suggest something

答: This may help: http://www.imagemagick.org/Usage/fonts/</p>


问:
Robocopy not functioning in Powershell script
I'm having some trouble using RoboCopy.exe through a Powershell script. The function is as follows...

```<code>function copyFiles{
    Start-Process "RoboCopy.exe" -ArgumentList "'C:\Test' 'C:\test2' /copyall"
    Write-Host 'Test'
}
</code>```

"Test" is output to console but the copy does not run. I was initially attempting to copy with variables as the directories, but I've boiled it down to this since that was not working. In the directory 'test1' there is a single .txt file and 'test2' exists but is empty. I have tried it without that directory existing as well.

It is called in another file via:

```<code>. .\rCopy.ps1
copyFiles
</code>```

Now, I tried outputting the log to a file with the code below, but it gives me a permissions error. "Out-File : Access to the path 'C:\Users\Me\Desktop' is denied". I also tried outputting direct to C:\ but that gives the same error. Powershell IS running as administrator.

```<code>$testCopy = Start-Process "RoboCopy.exe" -ArgumentList "'C:\Test' 'C:\test2' /copyall"
$testCopy | Out-File -LiteralPath "C:\Users\Me\
</code>```

And to close, I have also tried running "Start-Process 'RoboCopy.exe' -ArgumentList 'C:\test' 'C:\test2' /copyall" in the main script, without calling the function from another.

Any help would be greatly appreciated.

答:
I was able to get it working by using the following syntax:

```<code>Start-Process "RoboCopy.exe" -argumentlist "`"$localDir`" `"$networkDir`"  "
</code>```

I cannot copy from the directory I've been trying to from the get-go, but I'm assuming that's a permissions issue.

Body:
I'm having some trouble using RoboCopy.exe through a Powershell script. The function is as follows...

function copyFiles{
    Start-Process "RoboCopy.exe" -ArgumentList "'C:\Test' 'C:\test2' /copyall"
    Write-Host 'Test'
}

"Test" is output to console but the copy does not run. I was initially attempting to copy with variables as the directories, but I've boiled it down to this since that was not working. In the directory 'test1' there is a single .txt file and 'test2' exists but is empty. I have tried it without that directory existing as well.

It is called in another file via:

. .\rCopy.ps1
copyFiles

Now, I tried outputting the log to a file with the code below, but it gives me a permissions error. "Out-File : Access to the path 'C:\Users\Me\Desktop' is denied". I also tried outputting direct to C:\ but that gives the same error. Powershell IS running as administrator.

$testCopy = Start-Process "RoboCopy.exe" -ArgumentList "'C:\Test' 'C:\test2' /copyall"
$testCopy | Out-File -LiteralPath "C:\Users\Me\

And to close, I have also tried running "Start-Process 'RoboCopy.exe' -ArgumentList 'C:\test' 'C:\test2' /copyall" in the main script, without calling the function from another.

Any help would be greatly appreciated.

Body:
I was able to get it working by using the following syntax:

Start-Process "RoboCopy.exe" -argumentlist "`"$localDir`" `"$networkDir`"  "

I cannot copy from the directory I've been trying to from the get-go, but I'm assuming that's a permissions issue.


问:
How to add and pull submodules specified in the .gitmodules file even if they weren’t added to the current repo
I know I can call git submodule update --init --recursive if modules were already added to the repo.

However, Is there way to add and pull submodules specified in the .gitmodules file even if they weren’t added to the current repo with git submodule add command?

答: I think you've got a bad notion of the difference between "add" and "update".  The submodule helper command is a housekeeping tool.  The .gitmodules file is its notes on where to find things. When you first git submodule add a repo it updates its notes and then does an ordinary gitsubmodule init to load the local config and git submodule update to clone/fetch for you. You only need to add a submodule to your modules notes once, after that you init once per clone to load the tweakable settings from those notes, after that you do any tweaking (usually not needed) and update as needed.


答:
Looks like the tags figured it out for you...  This looks like something that'd be right up ImageMagick's alley.

Check out here for some good PHP ImageMagick watermark examples.

Title: How to make this image effect, any library that can help with it

Body: Do you know if an emboss effect like this can be done with a programming package. Can someone suggest something


问:
How to create Dynamic Buttons in Pyqt5
How can I handle each button separately? when clicking the assign button then the name will be assigned, what I have tried was trying to put each button and the name in a list but how can I keep track if the buttons were clicked?

Here is part of the code

```<code> ## repeated for every worker
    for i in range(2):

        self.Vl_name_location = QtWidgets.QVBoxLayout()
        self.Vl_name_location.setObjectName("Vl_name_location")
        self.worker_name = QtWidgets.QLabel(self.groupBox)
        self.worker_name.setAlignment(QtCore.Qt.AlignCenter)

        ## from db
        self.worker_name.setText("worker_name")
        self.worker_name.setObjectName("worker_name")
        self.Vl_name_location.addWidget(self.worker_name)
        self.worker_location = QtWidgets.QLabel(self.groupBox)
        self.worker_location.setAlignment(QtCore.Qt.AlignCenter)
        self.worker_location.setObjectName("worker_location")
        # from db
        self.worker_location.setText("Eng,Zone B")
        self.Vl_name_location.addWidget(self.worker_location)
        self.Hl_worker.addLayout(self.Vl_name_location)
        #####
        ### assign button to connect the name of the worker to the image       on the db
        #####

        self.assign_button = QtWidgets.QPushButton(self.groupBox)
        self.assign_button.setMinimumSize(QtCore.QSize(50, 25))
          self.assign_button.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.assign_button.setStyleSheet("")
        self.assign_button.setObjectName("assign_button")
        self.assign_button.setText( "Assign" )
        btns.append(self.assign_button)
        self.Hl_worker.addWidget(self.assign_button)
</code>```

preview of GUI

答:
I'm not sure if I understood your question correctly, but I assume that when one of the two buttons is pressed, you want to set the text of the corresponding worker_name label. If this is the case, then one way to achieve this is to add the buttons and labels as keys and values to a dictionary, and use self.dct[self.sender()] to extract the label when the button is pressed, e.g.

```<code>class MyWidget(QtWidgets.QWidget):
    def __init__(self, ...):
        ...

        # dictionary for storing button-label pairs
        self.label_dct = {}
        self.add_workers()

    def add_workers(self):
        for i in range(10):
            worker_label = QtWidgets.QLabel('worker name')
            assign_button = QtWidgets.QPushButton('Assign')
            self.label_dct[assign_button] = worker_label

            # rest of setup

            assign_button.clicked.connect(self.set_label)

    @pyqtSlot()
    def set_label(self):
        button = self.sender()
        label = self.label_dct[button]
        label.setText("John Doe")

</code>```

Title: How to create Dynamic Buttons in Pyqt5

Body:
How can I handle each button separately? when clicking the assign button then the name will be assigned, what I have tried was trying to put each button and the name in a list but how can I keep track if the buttons were clicked?

Here is part of the code

 ## repeated for every worker
    for i in range(2):

        self.Vl_name_location = QtWidgets.QVBoxLayout()
        self.Vl_name_location.setObjectName("Vl_name_location")
        self.worker_name = QtWidgets.QLabel(self.groupBox)
        self.worker_name.setAlignment(QtCore.Qt.AlignCenter)

        ## from db
        self.worker_name.setText("worker_name")
        self.worker_name.setObjectName("worker_name")
        self.Vl_name_location.addWidget(self.worker_name)
        self.worker_location = QtWidgets.QLabel(self.groupBox)
        self.worker_location.setAlignment(QtCore.Qt.AlignCenter)
        self.worker_location.setObjectName("worker_location")
        # from db
        self.worker_location.setText("Eng,Zone B")
        self.Vl_name_location.addWidget(self.worker_location)
        self.Hl_worker.addLayout(self.Vl_name_location)
        #####
        ### assign button to connect the name of the worker to the image       on the db
        #####

        self.assign_button = QtWidgets.QPushButton(self.groupBox)
        self.assign_button.setMinimumSize(QtCore.QSize(50, 25))
          self.assign_button.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.assign_button.setStyleSheet("")
        self.assign_button.setObjectName("assign_button")
        self.assign_button.setText( "Assign" )
        btns.append(self.assign_button)
        self.Hl_worker.addWidget(self.assign_button)

preview of GUI

Body:
I'm not sure if I understood your question correctly, but I assume that when one of the two buttons is pressed, you want to set the text of the corresponding worker_name label. If this is the case, then one way to achieve this is to add the buttons and labels as keys and values to a dictionary, and use self.dct[self.sender()] to extract the label when the button is pressed, e.g.

class MyWidget(QtWidgets.QWidget):
    def __init__(self, ...):
        ...

        # dictionary for storing button-label pairs
        self.label_dct = {}
        self.add_workers()

    def add_workers(self):
        for i in range(10):
            worker_label = QtWidgets.QLabel('worker name')
            assign_button = QtWidgets.QPushButton('Assign')
            self.label_dct[assign_button] = worker_label

            # rest of setup

            assign_button.clicked.connect(self.set_label)

    @pyqtSlot()
    def set_label(self):
        button = self.sender()
        label = self.label_dct[button]
        label.setText("John Doe")


问:
How to skip headers in csv file when headers exists
I am using apache-common-csv to import data from the CSV file and I would like to skip headers in the first line. What is important, the file sometimes can contain headers but sometimes not.
I have an implementation like below but the result not satisfying me, because when the file is without headers the first line is cutting.</p>

```<code>CSVFormat.DEFAULT
        .withDelimiter(';')
        .withHeader(HEADERS)
        .withSkipHeaderRecord()
        .parse(InputStreamReadersource.inputStream)
</code>```

答:
I think this could help you.

```<code>CSVFormat.RFC4180
         .withFirstRecordAsHeader()
         .withDelimiter(';').parse(InputStreamReadersource.inputStream);
</code>```

Here is the reference on Commons CSV user guide https://commons.apache.org/proper/commons-csv/user-guide.html

Body:
I am using apache-common-csv to import data from the CSV file and I would like to skip headers in the first line. What is important, the file sometimes can contain headers but sometimes not.
I have an implementation like below but the result not satisfying me, because when the file is without headers the first line is cutting.

CSVFormat.DEFAULT
        .withDelimiter(';')
        .withHeader(HEADERS)
        .withSkipHeaderRecord()
        .parse(InputStreamReadersource.inputStream)

Body:
I think this could help you.

CSVFormat.RFC4180
         .withFirstRecordAsHeader()
         .withDelimiter(';').parse(InputStreamReadersource.inputStream);

Here is the reference on Commons CSV user guide https://commons.apache.org/proper/commons-csv/user-guide.html


问:
This application failed to start because no Qt platform plugin could be initialized
I am stuck trying to run a very simple Python script, getting this error:

```<code>qt.qpa.plugin: Could not find the Qt platform plugin "cocoa" in ""
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.

zsh: abort      python3 mypuppy1.py
</code>```

The script code is:

```<code>import cv2
img = cv2.imread('00-puppy.jpg')
while True:
    cv2.imshow('Puppy',img)
    if cv2.waitKey(1) & 0xFF == 27:
        break
cv2.destroyAllWindows()
</code>```

However this Notebook code works in JupyterLab:

```<code>import cv2
img = cv2.imread('00-puppy.jpg')
cv2.imshow('Puppy', img)
cv2.waitKey()
</code>```

I am on macOS, using Anaconda and JupyterLab. I would appreciate any help with this issue. Thanks!

答:
I met the same issue. I agree with Simran Singh. This issue comes from the recent update.

Quote from pacjin79 on Github:"If you are on a mac, make sure you install opencv-python-headless instead of opencv-python to avoid these errors."
link

I personally solved the issue by doing so. Hope this works for you.

Body:
I am stuck trying to run a very simple Python script, getting this error:

qt.qpa.plugin: Could not find the Qt platform plugin "cocoa" in ""
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.

zsh: abort      python3 mypuppy1.py

The script code is:

import cv2
img = cv2.imread('00-puppy.jpg')
while True:
    cv2.imshow('Puppy',img)
    if cv2.waitKey(1) & 0xFF == 27:
        break
cv2.destroyAllWindows()

However this Notebook code works in JupyterLab:

import cv2
img = cv2.imread('00-puppy.jpg')
cv2.imshow('Puppy', img)
cv2.waitKey()

I am on macOS, using Anaconda and JupyterLab. I would appreciate any help with this issue. Thanks!


问:
show success message after form submit
i want to show a message when i update the statement but the button type is submit when i do that it refresh the page and the message wont show when i change the button type to button it shows the message but don't do the update action this is my codes
html code

```<code><div class="alert alert-success hidden" id="success-alert">

    <span class="glyphicon glyphicon-ok"></span> User Name Changed Succsefully
  </div>
 <div class="row">

  <div class="col-md-6">
    New username:  <input type="text" class="form-control" name="user" placeholder="New username">
    </div>
  </div>
  <div class="col-auto my-1">

       <button type="submit" name="changeuser" id="user" class="btn btn-primary">change username</button>
        </div>
    </fieldset>
    </form>
</code>```

java code

```<code><script type="text/javascript">
$(document).ready(function() {
  $("#user").click(function() {
    $('#success-alert').removeClass('hidden');
    $('#success-alert').delay(5000).fadeOut('slow');
  });
      $("button.close").click(function() {
    $('#success-alert').addClass('hidden');
  });

});
</code>```

php code

```<code>if (isset($_POST['changeuser']))
{

  $username=$_POST['user'];
  $sql="SELECT * from user_account where username='$username'";
            $result=mysqli_query($conn,$sql);

            if(mysqli_num_rows($result)==1)
            {
              echo '<script language="javascript">';
                  echo 'alert("User name already exits Please Chose Another One")';
                 echo '</script>';
            }
            else
            {
               $up = mysqli_query($conn, "UPDATE user_account SET username='$username' WHERE id='$id'");

            }

}
</code>```

答:
Change your php code as this:

```<code>$up = '';
if (isset($_POST['changeuser']))
{

  $username=$_POST['user'];
  $sql="SELECT * from user_account where username='$username'";
            $result=mysqli_query($conn,$sql);

            if(mysqli_num_rows($result)==1)
            {
              echo '<script language="javascript">';
                  echo 'alert("User name already exits Please Chose Another One")';
                 echo '</script>';
            }
            else
            {
               $up = mysqli_query($conn, "UPDATE user_account SET username='$username' WHERE id='$id'");

            }

}
</code>```

And change your html section like this:

```<code><?php
if($up) {
?>
<div class="alert alert-success" id="success-alert">

    <span class="glyphicon glyphicon-ok"></span> User Name Changed Succsefully
  </div>
<?php
}
?>
</code>```

Title: show success message after form submit

Body:
i want to show a message when i update the statement but the button type is submit when i do that it refresh the page and the message wont show when i change the button type to button it shows the message but don't do the update action this is my codes
html code

     User Name Changed Succsefully

    New username:  <input type="text" class="form-control" name="user" placeholder="New username">

       <button type="submit" name="changeuser" id="user" class="btn btn-primary">change username</button>

    </fieldset>
    </form>

java code

';
            }
            else
            {
               $up = mysqli_query($conn, "UPDATE user_account SET username='$username' WHERE id='$id'");

            }

}

Body:
Change your php code as this:

$up = '';
if (isset($_POST['changeuser']))
{

  $username=$_POST['user'];
  $sql="SELECT * from user_account where username='$username'";
            $result=mysqli_query($conn,$sql);

            if(mysqli_num_rows($result)==1)
            {
              echo '<script language="javascript">';
                  echo 'alert("User name already exits Please Chose Another One")';
                 echo '</script>';
            }
            else
            {
               $up = mysqli_query($conn, "UPDATE user_account SET username='$username' WHERE id='$id'");

            }

}

And change your html section like this:

<?php
if($up) {
?>
<div class="alert alert-success" id="success-alert">

    <span class="glyphicon glyphicon-ok"></span> User Name Changed Succsefully
  </div>
<?php
}
?>


问:
display grid empty div as spacer?
Building out a navbar that will look something like this:

```<code>|----------------------------------------------------------|
|                  link     Logo     link            link  |
|----------------------------------------------------------|
</code>```

My thought process for creating this layout is to have a html structure that looks like:

```<code><nav>
  <div></div>
  <div>
    link
    logo
    link
  </div>
  <div>
    link
  </div>
</nav>
</code>```

and then with CSS, I would do something like:

```<code>display: grid;
grid-template-columns: 200px auto 200px;
...
</code>```

My question here is: is there a better way to recreate this layout? I don't like how I use an empty div to create the space.

I know I can remove the empty div and put something like margin-left: 200px on the 2nd div but that seems kinda hacky as well.

Appreciate the input.

答:
This is a tricky design. You have to use multiple concept of CSS to achieve this design for example pseudo and position absolute will help you. You can check with other framework but again as per your design you need to write custom CSS as per limitation. I have written optimized CSS & markup of this design for you using pseudo elements and "position:absolute" for the fourth div. Please try code (you can change width of nav as per your requirement) and let me know if you need any more information or have any queries. Thanks in advance.

nav {
        width: 100%;
        max-width: 600px;
        margin: 0 auto;
        display: flex;
        flex-direction: row;
        justify-content: center;
        align-items: center;
        position: relative;
        border-top: .05em #000 dashed;
        border-bottom: .05em #000 dashed;
      }

      nav .lft-rgt-seperator {
        position: absolute;
        width: 103%;
        height: 14px;
        border-top:4px solid #fff;
        border-bottom:4px solid #fff;
        top: 50%;
        -webkit-transform: translateY(-50%);
        transform: translateY(-50%);
        z-index: 2;
      }

      nav:before {
        content:"";
        width:.05em;
        height: 49px;
        position: absolute;
        top: -6px;
        left: -4px;
        background: #000;
      }

      nav:after {
        content:"";
        width:.05em;
        height: 49px;
        position: absolute;
        top:-6px;
        right:-4px;
        background: #000;
      }

      nav ul {
        list-style: none;
        margin: 0;
        padding: 0;
        display: flex;
        flex-direction: row;
        justify-content: center;
        align-items: center;
        width: 100%;
        z-index: 4;
      }

      nav ul li {
        margin: 8px 15px;
      }

      nav ul li a, nav .lftlink a {
        color: #000;
        text-decoration: none;
        font-size:18px;
        cursor: pointer
      }

      nav ul li a:hover, nav .lftlink a:hover {
        text-decoration: underline;
      }

      nav .lftlink {
        position: absolute;
        right:20px;
        top: 50%;
        -webkit-transform: translateY(-50%);
        transform: translateY(-50%);
        z-index: 5;
      }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
      <div class="lft-rgt-seperator">
      </div>

        <ul>
          <li>
            Link
          </li>
          <li>
            Logo
          </li>
          <li>
            Link
          </li>
        </ul>

        <div class="lftlink">
            Link
        </div>
    </nav></code>```

Title: display grid empty div as spacer?

Body:
Building out a navbar that will look something like this:

|----------------------------------------------------------|
|                  link     Logo     link            link  |
|----------------------------------------------------------|

My thought process for creating this layout is to have a html structure that looks like:

    link
    logo
    link

    link

and then with CSS, I would do something like:

display: grid;
grid-template-columns: 200px auto 200px;
...

My question here is: is there a better way to recreate this layout? I don't like how I use an empty div to create the space.

I know I can remove the empty div and put something like margin-left: 200px on the 2nd div but that seems kinda hacky as well.

Appreciate the input.

Body:
This is a tricky design. You have to use multiple concept of CSS to achieve this design for example pseudo and position absolute will help you. You can check with other framework but again as per your design you need to write custom CSS as per limitation. I have written optimized CSS & markup of this design for you using pseudo elements and "position:absolute" for the fourth div. Please try code (you can change width of nav as per your requirement) and let me know if you need any more information or have any queries. Thanks in advance.

nav {
        width: 100%;
        max-width: 600px;
        margin: 0 auto;
        display: flex;
        flex-direction: row;
        justify-content: center;
        align-items: center;
        position: relative;
        border-top: .05em #000 dashed;
        border-bottom: .05em #000 dashed;
      }

      nav .lft-rgt-seperator {
        position: absolute;
        width: 103%;
        height: 14px;
        border-top:4px solid #fff;
        border-bottom:4px solid #fff;
        top: 50%;
        -webkit-transform: translateY(-50%);
        transform: translateY(-50%);
        z-index: 2;
      }

      nav:before {
        content:"";
        width:.05em;
        height: 49px;
        position: absolute;
        top: -6px;
        left: -4px;
        background: #000;
      }

      nav:after {
        content:"";
        width:.05em;
        height: 49px;
        position: absolute;
        top:-6px;
        right:-4px;
        background: #000;
      }

      nav ul {
        list-style: none;
        margin: 0;
        padding: 0;
        display: flex;
        flex-direction: row;
        justify-content: center;
        align-items: center;
        width: 100%;
        z-index: 4;
      }

      nav ul li {
        margin: 8px 15px;
      }

      nav ul li a, nav .lftlink a {
        color: #000;
        text-decoration: none;
        font-size:18px;
        cursor: pointer
      }

      nav ul li a:hover, nav .lftlink a:hover {
        text-decoration: underline;
      }

      nav .lftlink {
        position: absolute;
        right:20px;
        top: 50%;
        -webkit-transform: translateY(-50%);
        transform: translateY(-50%);
        z-index: 5;
      }

<nav>
      <div class="lft-rgt-seperator">
      </div>

        <ul>
          <li>
            <a href="#" title="Link">Link</a>
          </li>
          <li>
            <a href="#" title="Logo">Logo</a>
          </li>
          <li>
            <a href="#" title="Link">Link</a>
          </li>
        </ul>

        <div class="lftlink">
            <a href="#" title="Link">Link</a>
        </div>
    </nav>


问:
How to create a loop 1M with random numbers >100000
My teacher asked me to create a loop that will be executed 1M times.
I tried for(long i=0;i<1000000;i++), but the program is crashing. The maximum number that the program accepts is 10.000.

Any ideas? Is this possible?

Also he asked me to create a random number >100.000. I am using rand();. Should I use a different method?

this is the code:

```<code>start_time = clock();
for(long i=0;i<1000000;i++){
   num1 = rand();
   num2=rand();
   gcd1(num1,num2);
}

end_time = clock();

elapsed_time = (end_time - start_time) / CLOCKS_PER_SEC;

printf( "time is %.3f seconds\n", elapsed_time );
system("pause");
</code>```

This the gcd:

```<code>int gcd1(int x, int y){
    int z;
    if (x<y)
        z=x+1;
    else if (y<x)
        z=y+1;
    do{
        z=z-1;
    }
    while((x%z!=0) or (y%z!=0));
        return z;
    }
}
</code>```

答:
Try your loop as

```<code>for (i = 0; i < 1000000; i++) {
   do num1 = rand(); while (num1 == 0);
   do num2 = rand(); while (num2 == 0);
   gcd1(num1, num2);
}
</code>```

rand() can return 0. When it does that (after more than 10000 loops), your program will set z to 0 and attempt to divide by 0.

Body:
My teacher asked me to create a loop that will be executed 1M times.
I tried for(long i=0;i<1000000;i++), but the program is crashing. The maximum number that the program accepts is 10.000.

Any ideas? Is this possible?

Also he asked me to create a random number >100.000. I am using rand();. Should I use a different method?

this is the code:

start_time = clock();
for(long i=0;i<1000000;i++){
   num1 = rand();
   num2=rand();
   gcd1(num1,num2);
}

end_time = clock();

elapsed_time = (end_time - start_time) / CLOCKS_PER_SEC;

printf( "time is %.3f seconds\n", elapsed_time );
system("pause");

This the gcd:

int gcd1(int x, int y){
    int z;
    if (x<y)
        z=x+1;
    else if (y<x)
        z=y+1;
    do{
        z=z-1;
    }
    while((x%z!=0) or (y%z!=0));
        return z;
    }
}

Body:
Try your loop as

for (i = 0; i < 1000000; i++) {
   do num1 = rand(); while (num1 == 0);
   do num2 = rand(); while (num2 == 0);
   gcd1(num1, num2);
}

rand() can return 0. When it does that (after more than 10000 loops), your program will set z to 0 and attempt to divide by 0.


问:
How to calculate the average of class fields
Given that you have five input values and "average" method, calculate the average value for the five input values inside the average method and return it.
Note: average is the total summation of the values divided by its count</p>

```<code>public class MyCalculator {

    int input1 = 10;
    int input2 = 20;
    int input3 = 30;
    int input4 = 40;
    int input5 = 50;

    public float average() {

             return 0;
    }
}
</code>```

答:
Use this code to get average on using average function</p>

```<code>public class MyCalculator {
     int input1 = 10;
     int input2 = 20;
     int input3 = 30;
     int input4 = 40;
     int input5 = 50;

     public float average() {
              return (input1 + input2+input3+input4+input5)/5;
     }
}
</code>```

Body:
Given that you have five input values and "average" method, calculate the average value for the five input values inside the average method and return it.
Note: average is the total summation of the values divided by its count

public class MyCalculator {

    int input1 = 10;
    int input2 = 20;
    int input3 = 30;
    int input4 = 40;
    int input5 = 50;

    public float average() {

             return 0;
    }
}

Body:
Use this code to get average on using average function

public class MyCalculator {
     int input1 = 10;
     int input2 = 20;
     int input3 = 30;
     int input4 = 40;
     int input5 = 50;

     public float average() {
              return (input1 + input2+input3+input4+input5)/5;
     }
}