问:
Why doesn't Python see my file, even though it can connect to the server via smb?
I am trying to rename the file, I can see it when I print out the shared file.filename, but it gives an error saying its not there

```<code>import os, datetime
from smb.SMBConnection import SMBConnection
from datetime import date, datetime

userID = 'username'
password = 'mypsswrd$'
client_machine_name = 'localpcname'
server_name = 'hostname'
server_ip = '10.28.7.249'

domain_name = 'domain name'
now = datetime.now()
date_time = now.strftime("%d/%m/%y")

conn = SMBConnection(userID, password, client_machine_name, server_name, domain=domain_name, use_ntlm_v2=True,
                     is_direct_tcp=True)
conn.connect(server_ip, 445)

shares = conn.listShares()

for share in shares:
    if not share.isSpecial and share.name not in ['NETLOGON', 'SYSVOL']:
        sharedfiles = conn.listPath(share.name, '/')
        for sharedfile in sharedfiles:
            print(sharedfile.filename)

#change name
newname = 'CS_Out_Of_Country' + date_time +'.csv'
os.rename('CS_Out_Of_Country.csv', newname)

#Copy to archive

#close the connection
conn.close()
</code>```

the connection works fine and I can see my csv file but it says it doesn't exist, how come?

答:
os.rename operates in the current working directory. It doesn't know about the smb connection you created before. To fix this, you should either

Mount the smb share into the local filesystem, then os.chdir() to said mountpoint and then run os.rename() OR

use SMBConnection.rename (disclaimer: I've never used pysmb before, but that's what I found in 5 seconds using google.)

Body:
I am trying to rename the file, I can see it when I print out the shared file.filename, but it gives an error saying its not there

import os, datetime
from smb.SMBConnection import SMBConnection
from datetime import date, datetime

userID = 'username'
password = 'mypsswrd$'
client_machine_name = 'localpcname'
server_name = 'hostname'
server_ip = '10.28.7.249'

domain_name = 'domain name'
now = datetime.now()
date_time = now.strftime("%d/%m/%y")

conn = SMBConnection(userID, password, client_machine_name, server_name, domain=domain_name, use_ntlm_v2=True,
                     is_direct_tcp=True)
conn.connect(server_ip, 445)

shares = conn.listShares()

for share in shares:
    if not share.isSpecial and share.name not in ['NETLOGON', 'SYSVOL']:
        sharedfiles = conn.listPath(share.name, '/')
        for sharedfile in sharedfiles:
            print(sharedfile.filename)

#change name
newname = 'CS_Out_Of_Country' + date_time +'.csv'
os.rename('CS_Out_Of_Country.csv', newname)

#Copy to archive

#close the connection
conn.close()

the connection works fine and I can see my csv file but it says it doesn't exist, how come?


来源: stackexchange

问:
react-scrollmagic 'setPin()': Invalid pin element supplied. error
I'm using react-scrollmagic together with react-gasp and getting an error in the console: (ScrollMagic.Scene) -> ERROR calling method 'setPin()': Invalid pin element supplied. .

Everything seems to be working fine on the front end though, but in a more complex project these console errors add up very quickly. I can't get rid of the error no matter what I try. Is there any solution to this?

```<code>import "./styles.css";
import { Controller, Scene } from "react-scrollmagic";
import { Timeline, Tween } from "react-gsap";

export default function App() {
  return (
    <div className="App">
      <Controller>
        <Scene duration={500} triggerElement={"h1"} pin>
          {(progress) => (
            <Timeline
              totalProgress={progress}
              target={<h1>Hello CodeSandbox</h1>}
            >
              <Tween from={{ opacity: "0" }} to={{ opacity: "1" }} />
            </Timeline>
          )}
        </Scene>
      </Controller>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

</code>```

Here is the code and error in action at codesandbox.

答:
The solution would be to use the ScrollTrigger component instead of "react-scrollmagic". It's a modern version of ScrollMagic and plays better together with the Timeline or Tween components.

```<code>import "./styles.css";
import { Timeline, Tween, ScrollTrigger } from "react-gsap";

export default function App() {
  return (
    <div className="App">
      <ScrollTrigger start="top center" end="500px center" pin markers>
        <Timeline target={<h1>Hello CodeSandbox</h1>}>
          <Tween from={{ opacity: "0" }} to={{ opacity: "1" }} />
        </Timeline>
      </ScrollTrigger>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}
</code>```

Have a look at the react-gsap docs and official gsap docs:

https://bitworking.github.io/react-gsap/src-components-scroll-trigger
https://greensock.com/docs/v3/Plugins/ScrollTrigger

ContentLicense: CC BY-SA 4.0

Body:
I'm using react-scrollmagic together with react-gasp and getting an error in the console: (ScrollMagic.Scene) -> ERROR calling method 'setPin()': Invalid pin element supplied. .

Everything seems to be working fine on the front end though, but in a more complex project these console errors add up very quickly. I can't get rid of the error no matter what I try. Is there any solution to this?

import "./styles.css";
import { Controller, Scene } from "react-scrollmagic";
import { Timeline, Tween } from "react-gsap";

export default function App() {
  return (

      <Controller>
        <Scene duration={500} triggerElement={"h1"} pin>
          {(progress) => (
            <Timeline
              totalProgress={progress}
              target={
Hello CodeSandbox
}
            >
              <Tween from={{ opacity: "0" }} to={{ opacity: "1" }} />
            </Timeline>
          )}
        </Scene>
      </Controller>

Start editing to see some magic happen!

  );
}

Here is the code and error in action at codesandbox.

Body:
The solution would be to use the ScrollTrigger component instead of "react-scrollmagic". It's a modern version of ScrollMagic and plays better together with the Timeline or Tween components.

import "./styles.css";
import { Timeline, Tween, ScrollTrigger } from "react-gsap";

export default function App() {
  return (
    <div className="App">
      <ScrollTrigger start="top center" end="500px center" pin markers>
        <Timeline target={<h1>Hello CodeSandbox</h1>}>
          <Tween from={{ opacity: "0" }} to={{ opacity: "1" }} />
        </Timeline>
      </ScrollTrigger>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

Have a look at the react-gsap docs and official gsap docs:

https://bitworking.github.io/react-gsap/src-components-scroll-trigger
https://greensock.com/docs/v3/Plugins/ScrollTrigger


问:
How do I call extract_to_pathname function on a user uploaded zip file?
I have an instance of an activity and when I want to view it I want to extract the associated zip file to be extracted and set the index.html file inside to be the starting page inside view.php.

I found out that the filepath I passed in the extract function doesn't exist, but I can access its fields in the database.

How do I properly pass in the filepath parameter?

Edit:

```<code>    $fp = get_file_packer('application/zip');
    $fileinfo = array(
    'component' => 'mod_game',
    'filearea' => 'content',
    'itemid' => 0,
    'contextid' => 472,
    'filepath' => '/',
    'filename' => 'game.7z');

    $myfile = $fs->get_file($fileinfo['contextid'], $fileinfo['component'], $fileinfo['filearea'],
                      $fileinfo['itemid'], $fileinfo['filepath'], $fileinfo['filename']);

    $filepath = '/'.$context->id.'/mod_game/content/'.$game->revision.$myfile->get_filepath().$myfile->get_filename();
    $files = $fp->extract_to_pathname($filepath, $CFG->dirroot.'/mod/game/games'.$filepath.'_extracted');
</code>```

答:
I can see a number of issues here.

Firstly, the file ending (.7z) suggests that this is not a Zip file, but 7Zip file, which Moodle does not (as far as I am aware) support the unzipping of.

The next problem is that you don't appear to have created the folder into which you want to extract the files - you need to create the destination folder, before you try to extract files into it.

Finally, you appear to be trying to pass the (partial?) URL of the file to unzip, rather than either the path to it on the server (NOT recommended in this case) or the stored_file instance itself (strongly recommended).

Unless you need these long term, I would suggest a better solution would look like this:

```<code>// Make a temporary folder that will be automatically deleted at the end of the request.
$dest = make_request_directory();
// Extract the stored_file instance into this destination.
$files = $fp->extract_to_pathname($myfile, $dest);
</code>```

Body:
I have an instance of an activity and when I want to view it I want to extract the associated zip file to be extracted and set the index.html file inside to be the starting page inside view.php.

I found out that the filepath I passed in the extract function doesn't exist, but I can access its fields in the database.

How do I properly pass in the filepath parameter?

Edit:

    $fp = get_file_packer('application/zip');
    $fileinfo = array(
    'component' => 'mod_game',
    'filearea' => 'content',
    'itemid' => 0,
    'contextid' => 472,
    'filepath' => '/',
    'filename' => 'game.7z');

    $myfile = $fs->get_file($fileinfo['contextid'], $fileinfo['component'], $fileinfo['filearea'],
                      $fileinfo['itemid'], $fileinfo['filepath'], $fileinfo['filename']);

    $filepath = '/'.$context->id.'/mod_game/content/'.$game->revision.$myfile->get_filepath().$myfile->get_filename();
    $files = $fp->extract_to_pathname($filepath, $CFG->dirroot.'/mod/game/games'.$filepath.'_extracted');

Body:
I can see a number of issues here.

Firstly, the file ending (.7z) suggests that this is not a Zip file, but 7Zip file, which Moodle does not (as far as I am aware) support the unzipping of.

The next problem is that you don't appear to have created the folder into which you want to extract the files - you need to create the destination folder, before you try to extract files into it.

Finally, you appear to be trying to pass the (partial?) URL of the file to unzip, rather than either the path to it on the server (NOT recommended in this case) or the stored_file instance itself (strongly recommended).

Unless you need these long term, I would suggest a better solution would look like this:

// Make a temporary folder that will be automatically deleted at the end of the request.
$dest = make_request_directory();
// Extract the stored_file instance into this destination.
$files = $fp->extract_to_pathname($myfile, $dest);


问:
How can I clone a CDK resource?
Let's say I'm using the AWS CDK with TypeScript. Is there a way to define a function that takes a resource as a parameter and creates a clone with tweaked parameters?

Alternatively, do CDK constructs allow extracting all their attributes so I can use them in a new constructor?

Perhaps there's a TypeScript trick to achieve this? I'm not that familiar with the language.

More specifically, I want to do this with IAM roles.

(Following is very pseudocode-y)

```<code>const role = new iam.Role(this, 'CloudWatchLogsLoggingRole', {
    ...
});
makeRoleVariant(role)

makeRoleVariant(role: iam.Role) {
    // newAttributes = <attributes from role, but edited>
    new iam.Role(
        ...newAttributes
    );
}
</code>```

答:
The recommended way here is to use simple extends from Object Oriented Programming.

E.g. if you want to have a reusable IAM role with some tweaks, that you want to pass to other constructs that expect an IRole object, you can do this:

```<code>export class RoleWithSNSPermissions extends iam.Role{
   construct(scope: Construct, id:string){
       super(scope, id);
       this.addToRolePolicy(new PolicyStatement({
           actions: ['sns:*'], resources: ['*'],
       }));
   }

}
</code>```

Then you can start using it:

```<code>const role = new RoleWithSNSPermissions(this, 'Role');
new lambda.Function(this, 'fn', {
    ...
    role,
</code>```

Alternatively, since MOST built-in CDK constructs are strongly typed to accept an Interface, rather than a concrete implementation (e.g. lambda.Function() construct expects an IRole object rather than a Role object), you are also free to create a completely custom class that conforms to the IRole interface.

```<code>class MyCustomRole implements IRole{
   // Implement all methods of IRole here
}
</code>```

The disadvantage of this approach is that you need to reimplement all methods defined in the parent Interface, so pick the option that works best for your use case.

The general rule of thumb is:

If you want to apply only small changes like apply meaningful defaults or invoke methods under the hood - extend the base class.

If you want a completely custom behavior and flexibility to override code flow - implement the interface.

There's also a combined option for certain use cases

Title: How can I clone a CDK resource?

Body:
Let's say I'm using the AWS CDK with TypeScript. Is there a way to define a function that takes a resource as a parameter and creates a clone with tweaked parameters?

Alternatively, do CDK constructs allow extracting all their attributes so I can use them in a new constructor?

Perhaps there's a TypeScript trick to achieve this? I'm not that familiar with the language.

More specifically, I want to do this with IAM roles.

(Following is very pseudocode-y)

const role = new iam.Role(this, 'CloudWatchLogsLoggingRole', {
    ...
});
makeRoleVariant(role)

makeRoleVariant(role: iam.Role) {
    // newAttributes = <attributes from role, but edited>
    new iam.Role(
        ...newAttributes
    );
}

Body:
The recommended way here is to use simple extends from Object Oriented Programming.

E.g. if you want to have a reusable IAM role with some tweaks, that you want to pass to other constructs that expect an IRole object, you can do this:

export class RoleWithSNSPermissions extends iam.Role{
   construct(scope: Construct, id:string){
       super(scope, id);
       this.addToRolePolicy(new PolicyStatement({
           actions: ['sns:*'], resources: ['*'],
       }));
   }

}

Then you can start using it:

const role = new RoleWithSNSPermissions(this, 'Role');
new lambda.Function(this, 'fn', {
    ...
    role,

Alternatively, since MOST built-in CDK constructs are strongly typed to accept an Interface, rather than a concrete implementation (e.g. lambda.Function() construct expects an IRole object rather than a Role object), you are also free to create a completely custom class that conforms to the IRole interface.

class MyCustomRole implements IRole{
   // Implement all methods of IRole here
}

The disadvantage of this approach is that you need to reimplement all methods defined in the parent Interface, so pick the option that works best for your use case.

The general rule of thumb is:

If you want to apply only small changes like apply meaningful defaults or invoke methods under the hood - extend the base class.

If you want a completely custom behavior and flexibility to override code flow - implement the interface.

There's also a combined option for certain use cases


问:
Linkage of alias that requires decltype
I have a class member that is std::unique_ptr with a custom deleter. The custom deleter is a lambda function around a c function from an external library I do not control. I want to alias the unique_ptr type so that clients don't have to be exposed to the full signature. That is, I want :

```<code>struct {
   mytype_ptr foo;
}
</code>```

instead of:

```<code>struct {
   std::unique_ptr<mytype, lambda<blah>> foo;
}
</code>```

I tried doing this in the class header file:

```<code>auto x = [](mytype* t){ mytype_destroy(t); };
using mytype_ptr = std::unique_ptr<mytype, decltype(x)>;
</code>```

but of course the linker complains about multiple definitions.

I have tried various permutations, including inlining the lambda definition in decltype() and others, without success.

Is there a clean way to do this?

答:
No, you cannot. lambda<blah> is not an implementation detail of the object; it is part of the object. The deleter of a unique_ptr is part of its type. And this type is a member of the object. So any external users of that type will have to know about all of its members.

Unless you use PIMPL or type erasure (via std::shared_ptr, for example) or something similar, external users will need to access the type.

If all you want to do is keep users from having to know about the C API, you can write a simple function declaration or functor in the header, and put the implementation of its deletion operation in a source file:

```<code>//In header
struct my_deleter
{
  void operator()(mytype*) const;
};
</code>```

Title: Linkage of alias that requires decltype

Body:
I have a class member that is std::unique_ptr with a custom deleter. The custom deleter is a lambda function around a c function from an external library I do not control. I want to alias the unique_ptr type so that clients don't have to be exposed to the full signature. That is, I want :

struct {
   mytype_ptr foo;
}

instead of:

struct {
   std::unique_ptr<mytype, lambda<blah>> foo;
}

I tried doing this in the class header file:

auto x = [](mytype* t){ mytype_destroy(t); };
using mytype_ptr = std::unique_ptr<mytype, decltype(x)>;

but of course the linker complains about multiple definitions.

I have tried various permutations, including inlining the lambda definition in decltype() and others, without success.

Is there a clean way to do this?

Body:
No, you cannot. lambda<blah> is not an implementation detail of the object; it is part of the object. The deleter of a unique_ptr is part of its type. And this type is a member of the object. So any external users of that type will have to know about all of its members.

Unless you use PIMPL or type erasure (via std::shared_ptr, for example) or something similar, external users will need to access the type.

If all you want to do is keep users from having to know about the C API, you can write a simple function declaration or functor in the header, and put the implementation of its deletion operation in a source file:

//In header
struct my_deleter
{
  void operator()(mytype*) const;
};


问:
How to run a single XCTest case using gcloud for Firebase TestLab
I am trying to run my UI tests using gcloud for Firebase TestLab.

In Android TestLab documentation it says you can use --test-targets to run the specific test class and optionally add the # sign for a specific, single test case.

Does anyone know if it is possible to run a single test class/test case on iOS side?

This command would run all of my test cases in all classes:

```<code>gcloud firebase test ios run --test /Users/.../Desktop/Archive.zip\
--device model=iphone8,version=14.7,locale=en,orientation=portrait
</code>```

答:
XCTest sharding is not currently supported in Test Lab, but it's on our radar.
You can monitor #ftl-announcements to get an update when this feature becomes available.</p>

Body:
I am trying to run my UI tests using gcloud for Firebase TestLab.

In Android TestLab documentation it says you can use --test-targets to run the specific test class and optionally add the # sign for a specific, single test case.

Does anyone know if it is possible to run a single test class/test case on iOS side?

This command would run all of my test cases in all classes:

gcloud firebase test ios run --test /Users/.../Desktop/Archive.zip\
--device model=iphone8,version=14.7,locale=en,orientation=portrait


问:
Layout problems on Wagtail
I installing Wagtail on shared hosting. Instead of normal main and admin page there is view like that

答:
It looks like your static assets are not correctly built (CSS/JS).

If you are running locally you may need to run the Django management command collectstatic.

./manage.py collectstatic
```

If you are encountering this on the server, here are some relevant questions that may help.

django collectstatic on server

Django: CSS Is not not working

Title: Layout problems on Wagtail

Body:
It looks like your static assets are not correctly built (CSS/JS).

If you are running locally you may need to run the Django management command collectstatic.

./manage.py collectstatic

If you are encountering this on the server, here are some relevant questions that may help.

django collectstatic on server

Django: CSS Is not not working


问:
usage of string tokenizer
i have a string like this..

/home/Abcd/Pradeep/Jack.sh

/home/Abcd/Pradeep/Paul/Kill.sh

I need to take Jack.sh and Kill.sh alone from these strings. there can be many / in the string.

How to do this using strtok ?

答:
From the path name style, it looks like it is a *nix system.
You can use the command basename which does the same thing.
If you want to use it in a c program, try man 3 basename in your system to get the documentation.

ContentLicense: CC BY-SA 3.0

Title: usage of string tokenizer


问:
How do I make Neo4J continue after conditional create
After having created a collection of nodes, some of the nodes should also have a relation attached based on a condition. In the example below the condition is simulated with WHERE n.number > 3 and the nodes are simple numbers:

```<code>WITH [2, 3, 4] as numbers
UNWIND numbers AS num
CREATE(n:Number {number: num})
WITH collect(n) AS nodes
UNWIND nodes AS n
WITH nodes, n WHERE n.number > 3
CREATE (n)-[:IM_SPECIAL]->(n)
RETURN nodes
</code>```

Which returns:

```<code>╒════════════════════════════════════════╕
│"nodes"                                 │
╞════════════════════════════════════════╡
│[{"number":2},{"number":3},{"number":4}]│
└────────────────────────────────────────┘
Added 3 labels, created 3 nodes, set 3 properties, created 1 relationship, started streaming 1 records in less than 1 ms and completed after 1 ms.
</code>```

My problem is that nothing is returned unless I have at least one of these "special" nodes that is caught by the filter. The problem can be simulated by changing the input numbers to [1, 2, 3] which returns an empty result (no nodes) even though the nodes are created (as they should):

```<code><empty result>
Added 3 labels, created 3 nodes, set 3 properties, completed after 2 ms.
</code>```

I might be approaching the problem totally wrong but I've exhausted my Google skills... what Neo4J Cypher magic am I missing?

答:
The documentation about Conditional Cypher Execution - Using correlated subqueries in 4.1+ describes how to solve this without the need for Apoc:

```<code>WITH [2, 3, 4] AS numbers
UNWIND numbers AS num
CREATE(n:Number {number: num})
WITH n
CALL {
    WITH n
    WITH n WHERE n.number > 3
    CREATE (n)-[:IM_SPECIAL]->(n)
    RETURN count(n)
}
RETURN collect(n) AS nodes
</code>```

Thanks to Sanjay Singh and Jose Bacoy for putting me on the right track.

Body:
After having created a collection of nodes, some of the nodes should also have a relation attached based on a condition. In the example below the condition is simulated with WHERE n.number > 3 and the nodes are simple numbers:

WITH [2, 3, 4] as numbers
UNWIND numbers AS num
CREATE(n:Number {number: num})
WITH collect(n) AS nodes
UNWIND nodes AS n
WITH nodes, n WHERE n.number > 3
CREATE (n)-[:IM_SPECIAL]->(n)
RETURN nodes

Which returns:

╒════════════════════════════════════════╕
│"nodes"                                 │
╞════════════════════════════════════════╡
│[{"number":2},{"number":3},{"number":4}]│
└────────────────────────────────────────┘
Added 3 labels, created 3 nodes, set 3 properties, created 1 relationship, started streaming 1 records in less than 1 ms and completed after 1 ms.

My problem is that nothing is returned unless I have at least one of these "special" nodes that is caught by the filter. The problem can be simulated by changing the input numbers to [1, 2, 3] which returns an empty result (no nodes) even though the nodes are created (as they should):

<empty result>
Added 3 labels, created 3 nodes, set 3 properties, completed after 2 ms.

I might be approaching the problem totally wrong but I've exhausted my Google skills... what Neo4J Cypher magic am I missing?

Body:
The documentation about Conditional Cypher Execution - Using correlated subqueries in 4.1+ describes how to solve this without the need for Apoc:

WITH [2, 3, 4] AS numbers
UNWIND numbers AS num
CREATE(n:Number {number: num})
WITH n
CALL {
    WITH n
    WITH n WHERE n.number > 3
    CREATE (n)-[:IM_SPECIAL]->(n)
    RETURN count(n)
}
RETURN collect(n) AS nodes

Thanks to Sanjay Singh and Jose Bacoy for putting me on the right track.


问:
SwiftUI receiving "Editor placeholder in source file" and "Protocol 'Equatable' as a type cannot conform to the protocol itself" errors
I'm taking a SwiftUI course and am trying to get this animation method figured out and for some reason it's not compiling.

Haven't coded in a while with swift, could someone please point me in the right direction?

Thank you

```<code> struct ContentView: View {
private let imageURL: String = "https://credo.academy/credo-academy@3x.png"

var body: some View {

    AsyncImage(url: URL(string: imageURL), transaction: Transaction(animation: .interactiveSpring(response: 0.5, dampingFraction: 0.6, blendDuration: 0.25))) {
        phase in
        switch phase {
        case .success(let image):
            image
                .imageModifier()
                .transition(.move(edge: .bottom))
        case .failure(_):
            Image(systemName: "ant.circle.fill").iconModifier()
        case.empty:
            Image(systemName: "photo.circle.fill").iconModifier()
        @unknown default:
           ProgressView()
        }
    }
    .padding(40)
}
  }
</code>```

答: Sadly, the issue was fixed by restarting xcode</p>

Body:
I'm taking a SwiftUI course and am trying to get this animation method figured out and for some reason it's not compiling.

Haven't coded in a while with swift, could someone please point me in the right direction?

Thank you

 struct ContentView: View {
private let imageURL: String = "https://credo.academy/credo-academy@3x.png"

var body: some View {

    AsyncImage(url: URL(string: imageURL), transaction: Transaction(animation: .interactiveSpring(response: 0.5, dampingFraction: 0.6, blendDuration: 0.25))) {
        phase in
        switch phase {
        case .success(let image):
            image
                .imageModifier()
                .transition(.move(edge: .bottom))
        case .failure(_):
            Image(systemName: "ant.circle.fill").iconModifier()
        case.empty:
            Image(systemName: "photo.circle.fill").iconModifier()
        @unknown default:
           ProgressView()
        }
    }
    .padding(40)
}
  }


问:
Windows Python (<=3.10.2) fails to run `python -m venv .venv`
This issue has been solved, resulted in a bug report to Python.org. See the my self-answer below for the workaround until it's fixed in a future release of Python

One of my PCs got bitten by this bug which no longer allows me to create venv with the error:

```<code>Error: Command '['C:\\Users\\kesh\\test\\.venv\\Scripts\\python.exe', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 101.
</code>```

This issue has been known, chronologically: v3.7.2, v3.8, v3.?, & v3.10.1

The only known solution is to give up per-user install and use global install by checking "Install for all users" option

I'm trying to figure out what exactly is happening, but quickly running out of ideas. Here are what I've tried so far:

On my PC, "Install for all users" works as well as per-user install on a dummy account (all using the same v3.10.2 installer). This singles out the issue to be on my Windows account. Changing the install location does not help.

Went into venv source by running Python with venv.main(args=('.venv',)), debugging line-by-line and noted that it copies Lib\venv\scripts\nt\python.exe from the python install dir to the local .venv\Scripts folder using shutil.copyfile().

If I run the original Lib\venv\scripts\nt\python.exe in command prompt, it runs with a message No pyvenv.cfg file (which makes sense as the .cfg file is in .venv folder which it couldn't see)

If I call the copied .venv\Scripts\python.exe then it returns an error Unable to create process using 'C:\Users\kesh\AppData\Local\Programs\Python\Python310\python.exe' (note that the python.exe path for the process is that of the installed Python exe)

If .venv is installed successfully (on the dummy Windows account), the above run starts a Python session as you'd expect.

venv\scripts\nt\python.exe is different from the standard python binary and verified that this file and its source in venv\Scripts\nt are identical.

All this points to that something in my account configuration is bothering the .venv\Scripts\python.exe to do the right thing, but my environmental variables are pretty clean and python paths are at the top of the user PATH variable.

Currently trying to locate the source code of .venv\Scripts\python.exe but not found it yet.

Can it be something in registry?

If you have any other ideas to try, please share.

Update #1:

Found the source of the error message PC/launcher.c Line 814

Possibility: CreateProcessW(NULL, cmdline,... where cmdline is the original python path in the error message, without quote. CreateProcessW documentation states executable name is deduced from the first white space–delimited token in the cmdline string. Though I replaced my actual account name with kesh it actually comprises two words and a space...

Update #2:

Solution found as posted below

答:
Bingo, the finding in the update #1 was the cause. The space in my username was the culprit. Although I have no idea what triggered this behavior change on my account... (anybody with an answer, please follow up.)

Let's say the per-user python is installed at

```<code>C:\Users\User Name\AppData\Local\Programs\Python\Python310
</code>```

In my case, "Microsoft Visual C++ 2015-2022 Redistributable" installer (VC_redist.x64.exe) left a log file C:\Users\User (a text file with the first part of my account name as its file name). This caused python venv to use C:\Users\User as the python executable and promptly failed (see the issue tracker link below for the full explanation).

You can fix the issue in 2 ways until Python patches the problem.

Easy Fix

Simply delete the file C:\Users\User

Note: This will work until next time another installer leaves this nasty log file.

More Involved Fix

In command console, run

```<code>DIR /X C:\Users
</code>```

which lists something like:

```<code>02/08/2022  11:44 AM    <DIR>                       .
02/08/2022  11:44 AM    <DIR>                       ..
11/19/2020  01:48 AM    <DIR>                       Public
02/08/2022  02:47 PM    <DIR>          USERNA~1     User Name
</code>```

Open the Environmental Variables dialog and edit Path user variable's Python entries from

```<code>C:\Users\User Name\AppData\Local\Programs\Python\Python310\Scripts
C:\Users\User Name\AppData\Local\Programs\Python\Python310
</code>```

to

```<code>C:\Users\USERNA~1\AppData\Local\Programs\Python\Python310\Scripts
C:\Users\USERNA~1\AppData\Local\Programs\Python\Python310
</code>```

Re-open python console window or app so the path change is applied to your dev environment.

Note: This fix will work as long as you don't update python version. When you do, you need to delete the old path entries manually and update the new path entries.

Eventual Fix

I reported this bug to python bug tracker: Issue 46686. They've acknowledged the bug and have it labeled as critical with a proposed fix. So, hopefully it will get fixed in a near future release. (>3.10.2)

Body:
This issue has been solved, resulted in a bug report to Python.org. See the my self-answer below for the workaround until it's fixed in a future release of Python

One of my PCs got bitten by this bug which no longer allows me to create venv with the error:

Error: Command '['C:\\Users\\kesh\\test\\.venv\\Scripts\\python.exe', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 101.

This issue has been known, chronologically: v3.7.2, v3.8, v3.?, & v3.10.1

The only known solution is to give up per-user install and use global install by checking "Install for all users" option

I'm trying to figure out what exactly is happening, but quickly running out of ideas. Here are what I've tried so far:

On my PC, "Install for all users" works as well as per-user install on a dummy account (all using the same v3.10.2 installer). This singles out the issue to be on my Windows account. Changing the install location does not help.

Went into venv source by running Python with venv.main(args=('.venv',)), debugging line-by-line and noted that it copies Lib\venv\scripts\nt\python.exe from the python install dir to the local .venv\Scripts folder using shutil.copyfile().

If I run the original Lib\venv\scripts\nt\python.exe in command prompt, it runs with a message No pyvenv.cfg file (which makes sense as the .cfg file is in .venv folder which it couldn't see)

If I call the copied .venv\Scripts\python.exe then it returns an error Unable to create process using 'C:\Users\kesh\AppData\Local\Programs\Python\Python310\python.exe' (note that the python.exe path for the process is that of the installed Python exe)

If .venv is installed successfully (on the dummy Windows account), the above run starts a Python session as you'd expect.

venv\scripts\nt\python.exe is different from the standard python binary and verified that this file and its source in venv\Scripts\nt are identical.

All this points to that something in my account configuration is bothering the .venv\Scripts\python.exe to do the right thing, but my environmental variables are pretty clean and python paths are at the top of the user PATH variable.

Currently trying to locate the source code of .venv\Scripts\python.exe but not found it yet.

Can it be something in registry?

If you have any other ideas to try, please share.

Update #1:

Found the source of the error message PC/launcher.c Line 814

Possibility: CreateProcessW(NULL, cmdline,... where cmdline is the original python path in the error message, without quote. CreateProcessW documentation states executable name is deduced from the first white space–delimited token in the cmdline string. Though I replaced my actual account name with kesh it actually comprises two words and a space...

Update #2:

Solution found as posted below

Body:
Bingo, the finding in the update #1 was the cause. The space in my username was the culprit. Although I have no idea what triggered this behavior change on my account... (anybody with an answer, please follow up.)

Let's say the per-user python is installed at

C:\Users\User Name\AppData\Local\Programs\Python\Python310

In my case, "Microsoft Visual C++ 2015-2022 Redistributable" installer (VC_redist.x64.exe) left a log file C:\Users\User (a text file with the first part of my account name as its file name). This caused python venv to use C:\Users\User as the python executable and promptly failed (see the issue tracker link below for the full explanation).

You can fix the issue in 2 ways until Python patches the problem.

Easy Fix

Simply delete the file C:\Users\User

Note: This will work until next time another installer leaves this nasty log file.

More Involved Fix

In command console, run

DIR /X C:\Users

which lists something like:

02/08/2022  11:44 AM    <DIR>                       .
02/08/2022  11:44 AM    <DIR>                       ..
11/19/2020  01:48 AM    <DIR>                       Public
02/08/2022  02:47 PM    <DIR>          USERNA~1     User Name

Open the Environmental Variables dialog and edit Path user variable's Python entries from

C:\Users\User Name\AppData\Local\Programs\Python\Python310\Scripts
C:\Users\User Name\AppData\Local\Programs\Python\Python310

to

C:\Users\USERNA~1\AppData\Local\Programs\Python\Python310\Scripts
C:\Users\USERNA~1\AppData\Local\Programs\Python\Python310

Re-open python console window or app so the path change is applied to your dev environment.

Note: This fix will work as long as you don't update python version. When you do, you need to delete the old path entries manually and update the new path entries.

Eventual Fix

I reported this bug to python bug tracker: Issue 46686. They've acknowledged the bug and have it labeled as critical with a proposed fix. So, hopefully it will get fixed in a near future release. (>3.10.2)


问:
Easiest way to check if Tailwind is installed
I am playing around with Tailwind and Next.js, but I am having trouble figuring out if it's installed or not. Even when I go to https://play.tailwindcss.com/ and try the following HTML element styled with Tailwind.

```<code><h1 className="text-3xl font-bold underline">
      Hello world!
</h1>
</code>```

It doesn't render it underlined or even an h1 element. I follow the instructions at  https://tailwindcss.com/docs/guides/nextjs verbatim. Any ideas?

答:
The reason it's not working for you is that you are using className instead of class.

```<code><h1 class="text-3xl font-bold underline">
      Hello world!
</h1>
</code>```

Using NPM, you can see if a specific package is installed.

```<code>npm view tailwindcss version
</code>```

Or

```<code>npm info tailwindcss version
</code>```

If you're using NPX, you can do the following.

```<code>npx gvi tailwindcss
</code>```

Body:
I am playing around with Tailwind and Next.js, but I am having trouble figuring out if it's installed or not. Even when I go to https://play.tailwindcss.com/ and try the following HTML element styled with Tailwind.

      Hello world!

It doesn't render it underlined or even an h1 element. I follow the instructions at  https://tailwindcss.com/docs/guides/nextjs verbatim. Any ideas?

Body:
The reason it's not working for you is that you are using className instead of class.

<h1 class="text-3xl font-bold underline">
      Hello world!
</h1>

Using NPM, you can see if a specific package is installed.

npm view tailwindcss version

Or

npm info tailwindcss version

If you're using NPX, you can do the following.

npx gvi tailwindcss


问:
Putting a background on the linear layout and takes almost 3/4 of the screen
I have tried all kinds of help from other posts (setting widths to 0dp etc.) but nothing seems to work.

I have 2 layouts and the first one still seems to dominate. If I put background colors on the textviews, they are behaving themselves and end correctly. However put a background on the linear layout and it is almost 3/4 of the screen!?

```<code><?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:id="@+id/rowkRow"
    android:background="@color/RowBkgColor" android:gravity="center_vertical"
    android:minHeight="60dp">
    <ImageView android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:id="@+id/rowleftImage"
        android:padding="3dip" android:gravity="left" android:layout_weight="0" />

    <LinearLayout android:orientation="vertical"
        android:layout_weight="0" android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:id="@+id/rowtext1"
            android:padding="3dip" android:gravity="left" android:typeface="sans"
            android:textStyle="bold" android:text="First Text" android:textSize="40dp"
            android:textColor="#FF333344" android:visibility="visible"
             />
        <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:id="@+id/rowtext3"
            android:padding="3dip" android:gravity="center" android:typeface="sans"
            android:textStyle="bold" android:text="First Text" android:textSize="10dp"
            android:textColor="#FF333344" android:visibility="visible"
            android:background="#606060"
             />
    </LinearLayout>

    <LinearLayout android:orientation="vertical"
        android:layout_weight="1" android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content" android:id="@+id/rowtext4"
            android:padding="3dip" android:gravity="right" android:text="Fourth Text"
            android:textSize="10dp" android:textStyle="bold" android:textColor="@color/RowTextColor"
            android:visibility="visible" />
        <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content" android:id="@+id/rowtext2"
            android:padding="3dip" android:gravity="left" android:text="Second Text"
            android:textSize="17dp" android:textStyle="bold" android:textColor="@color/RowTextColor"
            />
    </LinearLayout>

    <ImageView android:id="@+id/rowrightImage"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:padding="3dip" android:layout_weight="0" android:gravity="right" />
</TableRow>
</code>```

答:
Do the following things. U can solve your problem.

set the android:layout_width of the children to "0dp"

set the android:weightSum of the parent

set the android:layout_weight of each child proportionally (e.g. weightSum = "5", three children: layout_weight="1", layout_weight="3", layout_weight="1")

Body:
I have tried all kinds of help from other posts (setting widths to 0dp etc.) but nothing seems to work.

I have 2 layouts and the first one still seems to dominate. If I put background colors on the textviews, they are behaving themselves and end correctly. However put a background on the linear layout and it is almost 3/4 of the screen!?

<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:id="@+id/rowkRow"
    android:background="@color/RowBkgColor" android:gravity="center_vertical"
    android:minHeight="60dp">
    <ImageView android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:id="@+id/rowleftImage"
        android:padding="3dip" android:gravity="left" android:layout_weight="0" />

    <LinearLayout android:orientation="vertical"
        android:layout_weight="0" android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:id="@+id/rowtext1"
            android:padding="3dip" android:gravity="left" android:typeface="sans"
            android:textStyle="bold" android:text="First Text" android:textSize="40dp"
            android:textColor="#FF333344" android:visibility="visible"
             />
        <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:id="@+id/rowtext3"
            android:padding="3dip" android:gravity="center" android:typeface="sans"
            android:textStyle="bold" android:text="First Text" android:textSize="10dp"
            android:textColor="#FF333344" android:visibility="visible"
            android:background="#606060"
             />
    </LinearLayout>

    <LinearLayout android:orientation="vertical"
        android:layout_weight="1" android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content" android:id="@+id/rowtext4"
            android:padding="3dip" android:gravity="right" android:text="Fourth Text"
            android:textSize="10dp" android:textStyle="bold" android:textColor="@color/RowTextColor"
            android:visibility="visible" />
        <TextView android:layout_width="fill_parent"
            android:layout_height="wrap_content" android:id="@+id/rowtext2"
            android:padding="3dip" android:gravity="left" android:text="Second Text"
            android:textSize="17dp" android:textStyle="bold" android:textColor="@color/RowTextColor"
            />
    </LinearLayout>

    <ImageView android:id="@+id/rowrightImage"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:padding="3dip" android:layout_weight="0" android:gravity="right" />
</TableRow>


答:
The button is drawn at the location stored in the `rect attribute:

screen.blit(self.image,self.rect)
```
</blockquote>
<p>Therefore you need to set the position of the <code>rect</code> attribute:</p>
<pre class="lang-py prettyprint-override"><code>class Button():
    def __init__(self,x,y,image):
        self.image = image
        self.rect = self.image.get_rect(center = (x, y))
        # [...]
</code>```

You don't need the x and y attributes at all. You can delete them. The top left position of the button is (self.rect.x, self.rect.y). See also pygame.Rect.

Title: inserting image in middle of pygame scene

Body:
i have one problem which i can't understand  and please help me(sorry for big code), but you should be able to see whole picture

import numpy as np
import matplotlib.pyplot as plt
from pygame.locals import  *
import pygame
pygame.init()
screen_width =800
screen_height =800
screen =pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption("Platformer")
sky_img =pygame.image.load("sky.png")
sun_img =pygame.image.load("sun.png")
restart_img =pygame.image.load("restart_btn.png")
start_image =pygame.image.load("start_btn.png")
exit_image =pygame.image.load("exit_btn.png")
clock =pygame.time.Clock()
fps =60
tile_size =40

world_data = [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 1],
[1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 2, 2, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 0, 7, 0, 5, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 1],
[1, 7, 0, 0, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 7, 0, 0, 0, 0, 1],
[1, 0, 2, 0, 0, 7, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 2, 0, 0, 4, 0, 0, 0, 0, 3, 0, 0, 3, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 7, 0, 0, 0, 0, 2, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 0, 2, 2, 2, 2, 2, 1],
[1, 0, 0, 0, 0, 0, 2, 2, 2, 6, 6, 6, 6, 6, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
]
blob_group = pygame.sprite.Group()
lava_group =pygame.sprite.Group()
game_over =0

class World():
    def __init__(self,data):
        self.tile_list =[]
        wall_imag =pygame.image.load("dirt.png")
        grass_img =pygame.image.load("grass.png")
        row_count =0
        for row in data:
            col_count =0
            for tile in row:
                if tile ==1:
                    img =pygame.transform.scale(wall_imag,(tile_size,tile_size))
                    img_rect =img.get_rect()
                    img_rect.x =col_count*tile_size
                    img_rect.y =row_count*tile_size
                    tile =(img,img_rect)
                    self.tile_list.append(tile)
                if tile == 2:
                    img = pygame.transform.scale(grass_img, (tile_size, tile_size))
                    img_rect = img.get_rect()
                    img_rect.x = col_count * tile_size
                    img_rect.y = row_count * tile_size
                    tile = (img, img_rect)
                    self.tile_list.append(tile)
                if tile ==3:
                    blob =Enemy(col_count*tile_size,row_count*tile_size+15)
                    blob_group.add(blob)
                if tile ==6:
                    lava =Lava(col_count*tile_size,row_count*tile_size+(tile_size)//2)
                    lava_group.add(lava)
                col_count+=1
            row_count+=1
    def draw(self):
        for tile in self.tile_list:
            screen.blit(tile[0],tile[1])
class Button():
    def __init__(self,x,y,image):
        self.image =image
        self.rect =self.image.get_rect()
        self.x =x
        self.y =y
        self.clicked =False

    def draw(self):
        action =False
        pos =pygame.mouse.get_pos()
        if self.rect.collidepoint(pos):
            if pygame.mouse.get_pressed()[0]==1 and self.clicked==False:
                action =True
                self.clicked =True
        if pygame.mouse.get_pressed()[0] ==0:
            self.clicked =False
        screen.blit(self.image,self.rect)
        return action
class Player():
    def __init__(self,x,y):
        self.reset(x,y)
    def reset(self,x,y):
        self.images_right = []
        self.images_left = []
        self.index = 0
        self.counter = 0
        for num in range(1, 5):
            player_img = pygame.image.load(f'guy{num}.png')
            player_img = pygame.transform.scale(player_img, (40, 80))
            player_imag_Left = pygame.transform.flip(player_img, True, False)
            self.images_right.append(player_img)
            self.images_left.append(player_imag_Left)

        self.dead_image = pygame.image.load('ghost.png')
        self.image = self.images_right[self.index]
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.vel_y = 0
        self.width = self.image.get_width()
        self.height = self.image.get_height()
        self.jumped = False
        self.direction = 0
        self.in_air =True
    def update(self,game_over):

        dx = 0
        dy =0
        walk_cooldown =5
        if game_over==0:
            key =pygame.key.get_pressed()
            if key[pygame.K_SPACE] and self.jumped ==False and self.in_air==False:
                self.vel_y =-15
                self.jumped =True
            if key[pygame.K_SPACE] == False:
                self.jumped = False
            if key[pygame.K_LEFT] ==True:
                dx -=5
                self.counter+=1
                self.direction =-1
            if key[pygame.K_RIGHT] ==True:
                dx +=5
                self.counter += 1
                self.direction=1
            if key[pygame.K_LEFT]==False and  key[pygame.K_RIGHT]==False:
                self.counter =0
                self.index =0
            if self.direction==1:
                    self.image =self.images_right[self.index]
            if self.direction==-1:
                self.image = self.images_left[self.index]
            if self.counter >walk_cooldown:
                self.counter =0
                self.index+=1
                if self.index>=len(self.images_right):
                    self.index =0
                if self.direction==1:
                    self.image =self.images_right[self.index]
                if self.direction==-1:
                    self.image = self.images_left[self.index]
            self.vel_y +=1
            if self.vel_y >10:
                self.vel_y =10
            dy +=self.vel_y
            self.in_air =True
            for tile in world.tile_list:
                if tile[1].colliderect(self.rect.x+dx,self.rect.y,self.width,self.rect.height):
                    dx =0
                if tile[1].colliderect(self.rect.x,self.rect.y+dy,self.width,self.height):
                    if self.vel_y <0:
                        dy =tile[1].bottom -self.rect.top
                        self.vel_y =0
                    elif self.vel_y>=0:
                        dy =tile[1].top -self.rect.bottom
                        self.vel_y=0
                        self.in_air =False
            if pygame.sprite.spritecollide(self,blob_group,False):
                game_over =-1

            if pygame.sprite.spritecollide(self,lava_group,False):
                game_over =-1
            self.rect.x +=dx
            self.rect.y +=dy
            if self.rect.bottom >screen_height:
                self.rect.bottom =screen_height
                dy =0
        elif game_over==-1:
            self.image =self.dead_image
            if self.rect.y >200:
                self.rect.y-=5

        screen.blit(self.image,self.rect)
        return game_over
class Enemy(pygame.sprite.Sprite):
    def __init__(self,x,y):
        pygame.sprite.Sprite.__init__(self)
        self.image =pygame.image.load("blob.png")
        self.rect =self.image.get_rect()
        self.rect.x =x
        self.rect.y =y
        self.move_direction =1
        self.move_counter =0
    def update(self):
        self.rect.x +=self.move_direction
        self.move_counter+=1
        if abs(self.move_counter)>50:
            self.move_direction *=-1
            self.move_counter *=-1
        pygame.draw.rect(screen,(255, 255, 255),self.rect)
class Lava(pygame.sprite.Sprite):
    def __init__(self,x,y):
        pygame.sprite.Sprite.__init__(self)
        lava_image =pygame.image.load("lava.png")
        self.image =pygame.transform.scale(lava_image,(tile_size,tile_size//2))
        self.rect =self.image.get_rect()
        self.rect.x =x
        self.rect.y =y

world =World(world_data)
player =Player(100,screen_height-120)
restart_button =Button(screen_width//2-50,screen_height //2+100,restart_img)
start_button =Button(screen_width//2,screen_height//2,start_image)
exit_button  =Button(280,280,exit_image)
def draw_grid():
    for line in range(0,tile_size+1):
        pygame.draw.line(screen,(255,255,255),(0,line*tile_size),(screen_width,line*tile_size))
        pygame.draw.line(screen, (255, 255, 255), (line * tile_size,0), (line * tile_size,screen_height))
run =True
while  run :
    clock.tick(fps)

    screen.blit(sky_img,(0,0))

    screen.blit(sun_img, (100, 100))

    #exit_button.draw()

    #draw_grid()

    world.draw()
    start_button.draw()

    if game_over == 0:
        blob_group.update()

    blob_group.draw(screen)
    lava_group.draw(screen)
    game_over = player.update(game_over)
    if game_over==-1:
        if restart_button.draw():
            player.reset(100,screen_height-130)
            game_over =0
    for event in pygame.event.get():
        if event.type ==pygame.QUIT:
            run =False
    pygame.display.update()
pygame.quit()

here is my result :

i want to put this image(start menu) in the middle of game, but  i could not it(i have changed coordinates, try several  experiments but  no result yet), here is main part of positioning picture on image :

start_button =Button(screen_width//2,screen_height//2,start_image)

i have  tried different numbers(starting from (0,0) and so on) but no result, i did not get what is the wrong? game is running without any problem

UPDATED
After updating  my code according answer, buttons coordinate are

start_button = Button(screen_width // 2 - 350, screen_height // 2, start_image)
exit_button = Button(screen_width // 2 + 150, screen_height // 2, exit_image)

and image is `

Body:
The button is drawn at the location stored in the `rect attribute:

screen.blit(self.image,self.rect)

Therefore you need to set the position of the rect attribute:

class Button():
    def __init__(self,x,y,image):
        self.image = image
        self.rect = self.image.get_rect(center = (x, y))
        # [...]

You don't need the x and y attributes at all. You can delete them. The top left position of the button is (self.rect.x, self.rect.y). See also pygame.Rect.


问:
Azurerm: KeyVault Nested Item should contain 2 or 3 segments, got 10
I get the error message below:

```<code>Error: parsing "/subscriptions/<subscription_id>/resourceGroups/<resource_group_name>/providers/Microsoft.Network/applicationGateways/<app_gateway_name>/sslCertificates/<cert_name>": KeyVault Nested Item should contain 2 or 3 segments, got 10 from "subscriptions/<subscription_id>/resourceGroups/<resource_group_name>/providers/Microsoft.Network/applicationGateways/<app_gateway_name>/sslCertificates/<cert_name>"
</code>```

I suppose the key error is "KeyVault Nested Item should contain 2 or 3 segments, got 10" but I have no idea what this means.

What I'm trying to do:

Via Terraform (azurerm), create an application gateway resource with a HTTPS(443) listener. I uploaded the certificate to the Azure Key (with Vault access policy) and created a managed identity to access that cert. In the portal, I can setup the listener with HTTPS using the managed identity and cert - no issues. Everything works as expected.

However, when I try to do the same in Terraform, I'm getting the error above.

Here's what I have:

```<code>data "azurerm_key_vault" "cert_store" {
  name                = "certstore"
  resource_group_name = local.resource_group.name
}

data "azurerm_key_vault_certificate" "tls_cert" {
  name         = "tls_cert"
  key_vault_id = data.azurerm_key_vault.cert_store.id
}

resource "azurerm_application_gateway" "app_gateway" {
  name                = "app_gateway1"
  resource_group_name = local.resource_group.name
  location            = local.resource_group.location
  sku {
    name     = var.gateway_vars.sku.name
    tier     = var.gateway_vars.sku.tier
    capacity = 2
  }

  gateway_ip_configuration {
    name      = "${var.gateway_vars.name}-ip-configuration"
    subnet_id = data.azurerm_subnet.gateway_subnet.id
  }

  frontend_port {
    name = "port_80"
    port = 80
  }

  frontend_port {
    name = "port_443"
    port = 443
  }

  identity {
    type = "UserAssigned"
    identity_ids = [
      azurerm_user_assigned_identity.app_gateway_managed_identity.id
    ]
  }

  ssl_certificate {
    key_vault_secret_id = data.azurerm_key_vault_certificate.cert_store.id
    name                = "tls_cert"
  }

  frontend_ip_configuration {
    name                 = "frontendIp"
    public_ip_address_id = azurerm_public_ip.app_gateway.id
  }

  backend_address_pool {
    name  = "frontend-pool"
    fqdns = ["fqdn.com"]
  }

  # https settings - used to connect to backend services via https
  backend_http_settings {
    name                                = "https"
    cookie_based_affinity               = "Disabled"
    port                                = 443
    protocol                            = "Https"
    request_timeout                     = 60
    path                                = "/"
    pick_host_name_from_backend_address = true
  }

  http_listener {
    name                           = "http80-listener"
    frontend_ip_configuration_name = "frontendIp"
    frontend_port_name             = "port_80"
    protocol                       = "Http"
  }

  http_listener {
    name                           = "https443-listener"
    frontend_ip_configuration_name = "frontendIp"
    frontend_port_name             = "port_443"
    protocol                       = "Https"
    ssl_certificate_name           = "tls_cert"
    require_sni                    = false
  }

  url_path_map {
    name                               = "path-map"
    default_backend_address_pool_name  = "frontend-pool"
    default_backend_http_settings_name = "https"
    path_rule {
      name                       = "xx"
      paths                      = ["/path"]
      backend_address_pool_name  = "frontend-pool"
      backend_http_settings_name = "https"
    }

  }

  request_routing_rule {
    name               = "tdr-routing-rule-443"
    rule_type          = "PathBasedRouting"
    http_listener_name = "https443-listener"
    url_path_map_name  = "path-map"
  }

}
</code>```

答:
So as I was making this post and about the publish it, a coworker reached out and figured he saw something similar a while back. Found it here:

https://github.com/hashicorp/terraform-provider-azurerm/issues/6188

The problem was the version of the cert being referenced. I think it didn't know which version of the cert to use, so I had to tell it which one. Within the app gateway resource block, in the ssl_certificate block, I used the trimsuffix function:

```<code>  ssl_certificate {
    name                = "tls_cert"
    key_vault_secret_id = trimsuffix(data.azurerm_key_vault_secret.certificate_secret.id, "${data.azurerm_key_vault_secret.certificate_secret.version}")
  }
</code>```

Second, I had to use azurerm_key_vault_secret instead of azurerm_key_vault_certificate, like below:

```<code>data "azurerm_key_vault_secret" "certificate_secret" {
  name         = "name_of_cert"
  key_vault_id = data.azurerm_key_vault.cert_store.id
}
</code>```

After that, it seems to be working. I still don't fully understand why using a keyvault secret works over keyvault certificate when trying to get a certificate but :shrug:.

Body:
I get the error message below:

Error: parsing "/subscriptions/<subscription_id>/resourceGroups/<resource_group_name>/providers/Microsoft.Network/applicationGateways/<app_gateway_name>/sslCertificates/<cert_name>": KeyVault Nested Item should contain 2 or 3 segments, got 10 from "subscriptions/<subscription_id>/resourceGroups/<resource_group_name>/providers/Microsoft.Network/applicationGateways/<app_gateway_name>/sslCertificates/<cert_name>"

I suppose the key error is "KeyVault Nested Item should contain 2 or 3 segments, got 10" but I have no idea what this means.

What I'm trying to do:

Via Terraform (azurerm), create an application gateway resource with a HTTPS(443) listener. I uploaded the certificate to the Azure Key (with Vault access policy) and created a managed identity to access that cert. In the portal, I can setup the listener with HTTPS using the managed identity and cert - no issues. Everything works as expected.

However, when I try to do the same in Terraform, I'm getting the error above.

Here's what I have:

data "azurerm_key_vault" "cert_store" {
  name                = "certstore"
  resource_group_name = local.resource_group.name
}

data "azurerm_key_vault_certificate" "tls_cert" {
  name         = "tls_cert"
  key_vault_id = data.azurerm_key_vault.cert_store.id
}

resource "azurerm_application_gateway" "app_gateway" {
  name                = "app_gateway1"
  resource_group_name = local.resource_group.name
  location            = local.resource_group.location
  sku {
    name     = var.gateway_vars.sku.name
    tier     = var.gateway_vars.sku.tier
    capacity = 2
  }

  gateway_ip_configuration {
    name      = "${var.gateway_vars.name}-ip-configuration"
    subnet_id = data.azurerm_subnet.gateway_subnet.id
  }

  frontend_port {
    name = "port_80"
    port = 80
  }

  frontend_port {
    name = "port_443"
    port = 443
  }

  identity {
    type = "UserAssigned"
    identity_ids = [
      azurerm_user_assigned_identity.app_gateway_managed_identity.id
    ]
  }

  ssl_certificate {
    key_vault_secret_id = data.azurerm_key_vault_certificate.cert_store.id
    name                = "tls_cert"
  }

  frontend_ip_configuration {
    name                 = "frontendIp"
    public_ip_address_id = azurerm_public_ip.app_gateway.id
  }

  backend_address_pool {
    name  = "frontend-pool"
    fqdns = ["fqdn.com"]
  }

  # https settings - used to connect to backend services via https
  backend_http_settings {
    name                                = "https"
    cookie_based_affinity               = "Disabled"
    port                                = 443
    protocol                            = "Https"
    request_timeout                     = 60
    path                                = "/"
    pick_host_name_from_backend_address = true
  }

  http_listener {
    name                           = "http80-listener"
    frontend_ip_configuration_name = "frontendIp"
    frontend_port_name             = "port_80"
    protocol                       = "Http"
  }

  http_listener {
    name                           = "https443-listener"
    frontend_ip_configuration_name = "frontendIp"
    frontend_port_name             = "port_443"
    protocol                       = "Https"
    ssl_certificate_name           = "tls_cert"
    require_sni                    = false
  }

  url_path_map {
    name                               = "path-map"
    default_backend_address_pool_name  = "frontend-pool"
    default_backend_http_settings_name = "https"
    path_rule {
      name                       = "xx"
      paths                      = ["/path"]
      backend_address_pool_name  = "frontend-pool"
      backend_http_settings_name = "https"
    }

  }

  request_routing_rule {
    name               = "tdr-routing-rule-443"
    rule_type          = "PathBasedRouting"
    http_listener_name = "https443-listener"
    url_path_map_name  = "path-map"
  }

}

Body:
So as I was making this post and about the publish it, a coworker reached out and figured he saw something similar a while back. Found it here:

https://github.com/hashicorp/terraform-provider-azurerm/issues/6188

The problem was the version of the cert being referenced. I think it didn't know which version of the cert to use, so I had to tell it which one. Within the app gateway resource block, in the ssl_certificate block, I used the trimsuffix function:

  ssl_certificate {
    name                = "tls_cert"
    key_vault_secret_id = trimsuffix(data.azurerm_key_vault_secret.certificate_secret.id, "${data.azurerm_key_vault_secret.certificate_secret.version}")
  }

Second, I had to use azurerm_key_vault_secret instead of azurerm_key_vault_certificate, like below:

data "azurerm_key_vault_secret" "certificate_secret" {
  name         = "name_of_cert"
  key_vault_id = data.azurerm_key_vault.cert_store.id
}

After that, it seems to be working. I still don't fully understand why using a keyvault secret works over keyvault certificate when trying to get a certificate but :shrug:.


问:
Azure Powershell (Az module) get public IP address
With the new Az module for Azure, does anyone have the syntax for getting the public IP address of an Azure VM using the name?
The commandlet Get-AzPublicIpAddress has no argument for the VM name, only the IP object name

This works, but I'm not using the machine name here, it's the name of the IP object itself:

```<code>$CurrentIp = (Get-AzPublicIpAddress -ResourceGroupName 'RG1' -Name 'MyVMname-ip').IpAddress
</code>```

I can't figure out how to just get it from the VM object i.e. this doesn't work:

```<code>Get-AzVM -ResourceGroupName 'RG1' -Name 'MyVMname' | Get-AzPublicIpAddress
</code>```

答:
This is a corrected version of the Mark Wragg's script earlier in this thread:

```<code>function Get-VmIP {
<#
.SYNOPSIS
    Returns the IP addresses for all VMs in the current subscription.
#>
[cmdletbinding()]
param()

$Interfaces = Get-AzNetworkInterface

foreach ($Interface in $Interfaces) {

    if ($Interface.VirtualMachine) {
        $VMName = $Interface.VirtualMachine.Id.split('/')[-1]

        $PrivateIP = $Interface.IpConfigurations.PrivateIpAddress
        $PublicIpAddressConfig = $Interface.IpConfigurations.publicIpAddress

        $PublicIP = $null
        $pconfigname = $null
        if ($PublicIpAddressConfig) {
            $pconfigname = $PublicIpAddressConfig.Id.Split('/')[-1]
            $PublicIP = (Get-AzPublicIpAddress -Name $pconfigname).IpAddress
        }

        [PSCustomObject]@{
            VMName    = $VMName
            RGName    = $Interface.ResourceGroupName
            PrivateIP = $PrivateIP
            PublicIP  = $PublicIP
        }
    }
}
</code>```

}

Body:
With the new Az module for Azure, does anyone have the syntax for getting the public IP address of an Azure VM using the name?
The commandlet Get-AzPublicIpAddress has no argument for the VM name, only the IP object name

This works, but I'm not using the machine name here, it's the name of the IP object itself:

$CurrentIp = (Get-AzPublicIpAddress -ResourceGroupName 'RG1' -Name 'MyVMname-ip').IpAddress

I can't figure out how to just get it from the VM object i.e. this doesn't work:

Get-AzVM -ResourceGroupName 'RG1' -Name 'MyVMname' | Get-AzPublicIpAddress

Body:
This is a corrected version of the Mark Wragg's script earlier in this thread:

function Get-VmIP {
<#
.SYNOPSIS
    Returns the IP addresses for all VMs in the current subscription.
#>
[cmdletbinding()]
param()

$Interfaces = Get-AzNetworkInterface

foreach ($Interface in $Interfaces) {

    if ($Interface.VirtualMachine) {
        $VMName = $Interface.VirtualMachine.Id.split('/')[-1]

        $PrivateIP = $Interface.IpConfigurations.PrivateIpAddress
        $PublicIpAddressConfig = $Interface.IpConfigurations.publicIpAddress

        $PublicIP = $null
        $pconfigname = $null
        if ($PublicIpAddressConfig) {
            $pconfigname = $PublicIpAddressConfig.Id.Split('/')[-1]
            $PublicIP = (Get-AzPublicIpAddress -Name $pconfigname).IpAddress
        }

        [PSCustomObject]@{
            VMName    = $VMName
            RGName    = $Interface.ResourceGroupName
            PrivateIP = $PrivateIP
            PublicIP  = $PublicIP
        }
    }
}

}


问:
How to set different font size for UIButton when it is pressed
I am trying to change font size of button itself after it was pressed.

```<code>class ViewController: UIViewController {
   @IBOutlet weak var buttonToResize: UIButton!

   @IBAction func buttonTapped(_ sender: UIButton) {
        buttonToResize.titleLabel!.font = UIFont(name: "Helvetica", size: 40)
// Also tried buttonToResize.titleLabel?.font = UIFont .systemFont(ofSize: 4)
}
</code>```

However the changes are not applied.

What is interesting, to me, that if I try to resize some other button (second one) after pressing on initial (first one), it works as expected.

Like this:

```<code>class ViewController: UIViewController {
@IBOutlet weak var buttonToResize: UIButton!
@IBOutlet weak var secondButtonToResize: UIButton!

@IBAction func buttonTapped(_ sender: UIButton) {
    secondButtonToResize.titleLabel!.font = UIFont(name: "Helvetica", size: 40)
}
</code>```

Other properties like backgroundColor seems to apply, however with font size I face problem.

答:
```<code>class ViewController: UIViewController {
     @IBOutlet weak var buttonToResize: UIButton!

    @IBAction func buttonTapped(_ sender: UIButton) {
    sender.titleLabel?.font = .systemFont(ofSize: 30)
    }
  }
</code>```

This should solve the problem. Use the sender tag instead of the IBOutlet.

Body:
I am trying to change font size of button itself after it was pressed.

class ViewController: UIViewController {
   @IBOutlet weak var buttonToResize: UIButton!

   @IBAction func buttonTapped(_ sender: UIButton) {
        buttonToResize.titleLabel!.font = UIFont(name: "Helvetica", size: 40)
// Also tried buttonToResize.titleLabel?.font = UIFont .systemFont(ofSize: 4)
}

However the changes are not applied.

What is interesting, to me, that if I try to resize some other button (second one) after pressing on initial (first one), it works as expected.

Like this:

class ViewController: UIViewController {
@IBOutlet weak var buttonToResize: UIButton!
@IBOutlet weak var secondButtonToResize: UIButton!

@IBAction func buttonTapped(_ sender: UIButton) {
    secondButtonToResize.titleLabel!.font = UIFont(name: "Helvetica", size: 40)
}

Other properties like backgroundColor seems to apply, however with font size I face problem.

Body:
class ViewController: UIViewController {
     @IBOutlet weak var buttonToResize: UIButton!

    @IBAction func buttonTapped(_ sender: UIButton) {
    sender.titleLabel?.font = .systemFont(ofSize: 30)
    }
  }

This should solve the problem. Use the sender tag instead of the IBOutlet.


问:
ncat: piping multiline request breaks HTTP
I just started using ncat, and playing around with simple HTTP requests, I came across the following:

Starting ncat and typing a two-line get request works fine:

```<code>$ ncat 192.168.56.20 80
GET / HTTP/1.1
Host: 192.168.56.20

HTTP/1.1 200 OK
</code>```

If however the request gets echoed to ncat, it apparently breaks somewhere:

```<code>$ echo 'GET / HTTP/1.1\nHost: 192.168.56.20' | ncat 192.168.56.20 80
HTTP/1.1 400 Bad Request
</code>```

I don't get it.

答:
The \n in the string is sent literally. Use echo -e to enable interpretation of backslash escapes. Also, the newline sequence for HTTP 1.1 is \r\n (CRLF). And the header section ends with an additional end-of-line.

Try:

```<code>echo -e 'GET / HTTP/1.1\r\nHost: 192.168.56.20\r\n\r\n' | ncat 192.168.56.20 80
</code>```

Alternatively, the ncat has the option to convert new lines to CRLF:

```<code>-C, --crlf                 Use CRLF for EOL sequence
</code>```

Hence, you can write:

```<code>echo -e 'GET / HTTP/1.1\nHost: 192.168.56.20\n\n' | ncat -C 192.168.56.20 80
</code>```

and you should get the same result.

Body:
I just started using ncat, and playing around with simple HTTP requests, I came across the following:

Starting ncat and typing a two-line get request works fine:

$ ncat 192.168.56.20 80
GET / HTTP/1.1
Host: 192.168.56.20

HTTP/1.1 200 OK

If however the request gets echoed to ncat, it apparently breaks somewhere:

$ echo 'GET / HTTP/1.1\nHost: 192.168.56.20' | ncat 192.168.56.20 80
HTTP/1.1 400 Bad Request

I don't get it.

Body:
The \n in the string is sent literally. Use echo -e to enable interpretation of backslash escapes. Also, the newline sequence for HTTP 1.1 is \r\n (CRLF). And the header section ends with an additional end-of-line.

Try:

echo -e 'GET / HTTP/1.1\r\nHost: 192.168.56.20\r\n\r\n' | ncat 192.168.56.20 80

Alternatively, the ncat has the option to convert new lines to CRLF:

-C, --crlf                 Use CRLF for EOL sequence

Hence, you can write:

echo -e 'GET / HTTP/1.1\nHost: 192.168.56.20\n\n' | ncat -C 192.168.56.20 80

and you should get the same result.


问:
Nested ternary operators
I have this code:

```<code>_viewModel.PhoneDefault = user == null ? "" :
    (string.IsNullOrEmpty(user.PhoneDay) ?
        (string.IsNullOrEmpty(user.PhoneEvening) ?
            (string.IsNullOrEmpty(user.Mobile) ? "" :
                user.Mobile) :
            user.PhoneEvening) :
         user.PhoneDay);
</code>```

Is there a better way to write this to make it more readable?

答:
Well, as long as the entries can be just null or valid:

    if (user == null)
    {
        _viewModel.PhoneDefault = string.Empty;
    }
    else
    {
        _viewModel.PhoneDefault = user.PhoneDay ?? user.PhoneEvening ?? user.Mobile ?? string.Empty;
    }
```

You can even define an  extension method on string to convert empty strings to null and use it here, but I am just crazy.

If they can be an empty string, just use the other people answers. Jason's method is nice and clean.

Title: Nested ternary operators

Body:
I have this code:

_viewModel.PhoneDefault = user == null ? "" :
    (string.IsNullOrEmpty(user.PhoneDay) ?
        (string.IsNullOrEmpty(user.PhoneEvening) ?
            (string.IsNullOrEmpty(user.Mobile) ? "" :
                user.Mobile) :
            user.PhoneEvening) :
         user.PhoneDay);

Is there a better way to write this to make it more readable?

Body:
Well, as long as the entries can be just null or valid:

    if (user == null)
    {
        _viewModel.PhoneDefault = string.Empty;
    }
    else
    {
        _viewModel.PhoneDefault = user.PhoneDay ?? user.PhoneEvening ?? user.Mobile ?? string.Empty;
    }

You can even define an  extension method on string to convert empty strings to null and use it here, but I am just crazy.

If they can be an empty string, just use the other people answers. Jason's method is nice and clean.


问:
Python Requests and SSLContext
I'm trying to figure out how to specify an SSLContext with Request.

I have two functions which in theory should do the same, however the one with Requests doesn't work.

```<code>def func_OK(token):
    ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH,cafile='myCA.crt.pem')
    ctx.load_cert_chain(certfile='myprivate.pem')
    url = 'https://my_url.com'
    hdr = {"Content-Type": "application/json","Authorization":"Bearer "+token}
    data = '{"filterList":[{}]}'
    bdata = data.encode('utf-8')
    req = urllib.request.Request(url, headers=hdr)
    resp = urllib.request.urlopen(req, data=bdata, context=ctx)
    content = resp.read()
    data = json.loads(content.decode('utf-8'))
</code>```
```<code>def func_NOK(token):
    import requests
    url = 'https://my_url.com'
    hdr = {"Content-Type": "application/json","Authorization":"Bearer "+token}
    data = '{"filterList":[{}]}'
    bdata = data.encode('utf-8')
    resp = requests.post(url,headers=hdr, data={"filterList":[{}]})
</code>```

The only the difference between the two functions are the sslContext.
In the func_NOK, I try :

resp = requests.post(url,headers=hdr, data={"filterList":[{}]}, verify=False) - it doesn't work

resp = requests.post(url,headers=hdr, data={"filterList":[{}]}, cert=('myCA.crt.pem','myprivate.pem')) - it doesn't work

resp = requests.post(url,headers=hdr, data={"filterList":[{}]}, verify="concat_file.crt") with "concat_file.crt" file a concatenation of 'myCA.crt.pem' and 'myprivate.pem'

In any cases I have an SSL error.
For example, on my last example the error msg is :

```<code>requests.exceptions.ConnectionError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1131)
</code>```

I'm just trying to use an SSLContext with Requests.

答:
I solved it using :
requests.post(url,headers=hdr,json={"filterList":[{}]}, cert='myprivate.pem')</p>

Title: Python Requests and SSLContext

Body:
I'm trying to figure out how to specify an SSLContext with Request.

I have two functions which in theory should do the same, however the one with Requests doesn't work.

def func_OK(token):
    ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH,cafile='myCA.crt.pem')
    ctx.load_cert_chain(certfile='myprivate.pem')
    url = 'https://my_url.com'
    hdr = {"Content-Type": "application/json","Authorization":"Bearer "+token}
    data = '{"filterList":[{}]}'
    bdata = data.encode('utf-8')
    req = urllib.request.Request(url, headers=hdr)
    resp = urllib.request.urlopen(req, data=bdata, context=ctx)
    content = resp.read()
    data = json.loads(content.decode('utf-8'))

def func_NOK(token):
    import requests
    url = 'https://my_url.com'
    hdr = {"Content-Type": "application/json","Authorization":"Bearer "+token}
    data = '{"filterList":[{}]}'
    bdata = data.encode('utf-8')
    resp = requests.post(url,headers=hdr, data={"filterList":[{}]})

The only the difference between the two functions are the sslContext.
In the func_NOK, I try :

resp = requests.post(url,headers=hdr, data={"filterList":[{}]}, verify=False) - it doesn't work

resp = requests.post(url,headers=hdr, data={"filterList":[{}]}, cert=('myCA.crt.pem','myprivate.pem')) - it doesn't work

resp = requests.post(url,headers=hdr, data={"filterList":[{}]}, verify="concat_file.crt") with "concat_file.crt" file a concatenation of 'myCA.crt.pem' and 'myprivate.pem'

In any cases I have an SSL error.
For example, on my last example the error msg is :

requests.exceptions.ConnectionError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1131)

I'm just trying to use an SSLContext with Requests.


问:
ASP.NET CORE, Web API: No route matches the supplied values
PLEASE NOTE: This question was asked in 2016. The original answer to this problem was to update the microsoft api versiong package. In the current days, the problem reoccurs, but for other reasons.

Original Question:

i have some problems with the routing in asp.net core (web api).

I have this Controller (simplified):

```<code>[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[Controller]")]
public class DocumentController : Controller
{

[HttpGet("{guid}", Name = "GetDocument")]
public IActionResult GetByGuid(string guid)
{
    var doc = DocumentDataProvider.Find(guid);
    if (doc == null)
        return NotFound();

    return new ObjectResult(doc) {StatusCode = 200};
}

[HttpPost]
public IActionResult Create([FromBody] Document doc)
{
    //... Creating Doc

    // Does not work
    var val = CreatedAtRoute("GetDocument", new {guid = doc.Guid.ToString("N")}, document);

    // or this:
    CreatedAtRoute("GetDocument", new { controller = "Document", guid = doc.Guid.ToString("N")}, document);
    // neither this
    var val = CreatedAtRoute("GetDocument", new { version = "1", controller = "Document", guid = doc.Guid.ToString("N")}, document);

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

If i call Create, the document is created and the routing object was created but i get the error "No route matches the supplied values" and get a 500 status.

I can call the GetByGuid directly, without any problems.

I couldn't find any debugging help for asp.net core (like any existing routing debugger).

I would appreciate any help!

EDIT
Looks like it would be a bug from microsoft's versioning package.. if i define the fix route /api/v1/[Controller] it's working.

But that's not a solution for me.

答:
If your route has parameters (for example GetbookById(int id)) then you need 3 parts to the CreatedAtRoute for example:

```<code>book b = new book(); // The Created new book.
var routeValues = new { id = book.Id}; // Represents the parameter(s) to GetbookById
return CreatedAtRoute( nameof(GetbookById), routeValues, b);
</code>```

More in: Created, CreatedAtAction, CreatedAtRoute Methods In ASP.NET Core Explained With Examples

Body:
PLEASE NOTE: This question was asked in 2016. The original answer to this problem was to update the microsoft api versiong package. In the current days, the problem reoccurs, but for other reasons.

Original Question:

i have some problems with the routing in asp.net core (web api).

I have this Controller (simplified):

[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[Controller]")]
public class DocumentController : Controller
{

[HttpGet("{guid}", Name = "GetDocument")]
public IActionResult GetByGuid(string guid)
{
    var doc = DocumentDataProvider.Find(guid);
    if (doc == null)
        return NotFound();

    return new ObjectResult(doc) {StatusCode = 200};
}

[HttpPost]
public IActionResult Create([FromBody] Document doc)
{
    //... Creating Doc

    // Does not work
    var val = CreatedAtRoute("GetDocument", new {guid = doc.Guid.ToString("N")}, document);

    // or this:
    CreatedAtRoute("GetDocument", new { controller = "Document", guid = doc.Guid.ToString("N")}, document);
    // neither this
    var val = CreatedAtRoute("GetDocument", new { version = "1", controller = "Document", guid = doc.Guid.ToString("N")}, document);

    return val;
}
}

If i call Create, the document is created and the routing object was created but i get the error "No route matches the supplied values" and get a 500 status.

I can call the GetByGuid directly, without any problems.

I couldn't find any debugging help for asp.net core (like any existing routing debugger).

I would appreciate any help!

EDIT
Looks like it would be a bug from microsoft's versioning package.. if i define the fix route /api/v1/[Controller] it's working.

But that's not a solution for me.

Body:
If your route has parameters (for example GetbookById(int id)) then you need 3 parts to the CreatedAtRoute for example:

book b = new book(); // The Created new book.
var routeValues = new { id = book.Id}; // Represents the parameter(s) to GetbookById
return CreatedAtRoute( nameof(GetbookById), routeValues, b);

More in: Created, CreatedAtAction, CreatedAtRoute Methods In ASP.NET Core Explained With Examples