问:
Docker Plugin for Jenkins error: Scripts not permitted to use method
I'm trying to publish to Docker from my Jenkins Pipeline but most things I try result in an error. My latest try was this:

```<code>docker.withDockerRegistry('https://docker-registry.myco.com/lsacco/swagger-rest', 'docker-credential') {
    def image = docker.image(APPLICATION_NAME);
    image.tag("latest");
    image.push()
}
</code>```

When I run this, Jenkins outputs this error:

```<code>org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use method groovy.lang.GroovyObject invokeMethod java.lang.String java.lang.Object (org.jenkinsci.plugins.docker.workflow.Docker withDockerRegistry java.lang.String java.lang.String org.jenkinsci.plugins.workflow.cps.CpsClosure2)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.StaticWhitelist.rejectMethod(StaticWhitelist.java:163)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onMethodCall(SandboxInterceptor.java:78)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onMethodCall(SandboxInterceptor.java:69)
    at org.kohsuke.groovy.sandbox.impl.Checker$1.call(Checker.java:149)
    at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:146)
    at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.methodCall(SandboxInvoker.java:15)
    at WorkflowScript.dockerDeploy(WorkflowScript:290)
    at WorkflowScript.run(WorkflowScript:76)
    at ___cps.transform___(Native Method)
    at com.cloudbees.groovy.cps.impl.ContinuationGroup.methodCall(ContinuationGroup.java:55)
    at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.dispatchOrArg(FunctionCallBlock.java:106)
    at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.fixArg(FunctionCallBlock.java:79)
    at sun.reflect.GeneratedMethodAccessor317.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
    at com.cloudbees.groovy.cps.impl.ClosureBlock.eval(ClosureBlock.java:40)
    at com.cloudbees.groovy.cps.Next.step(Next.java:58)
    at com.cloudbees.groovy.cps.Continuable.run0(Continuable.java:154)
    at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.access$001(SandboxContinuable.java:19)
    at org.jenkinsci.plugins.workflow.cps.SandboxContinuable$1.call(SandboxContinuable.java:33)
    at org.jenkinsci.plugins.workflow.cps.SandboxContinuable$1.call(SandboxContinuable.java:30)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.GroovySandbox.runInSandbox(GroovySandbox.java:106)
    at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.run0(SandboxContinuable.java:30)
    at org.jenkinsci.plugins.workflow.cps.CpsThread.runNextChunk(CpsThread.java:164)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:277)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$000(CpsThreadGroup.java:77)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:186)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:184)
    at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:47)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at hudson.remoting.SingleLaneExecutorService$1.run(SingleLaneExecutorService.java:112)
    at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
</code>```

I'm running on the latest Jenkins with all the latest plugin updates. Any ideas?

1.642.2 Jenkins

```<code>Plugins.txt
ace-editor:1.1
ant:1.2
antisamy-markup-formatter:1.3
async-http-client:1.7.24
aws-credentials:1.12
aws-java-sdk:1.10.45
branch-api:1.3
build-token-root:1.3
cloudbees-folder:5.3
conditional-buildstep:1.3.3
config-file-provider:2.10.0
copy-to-slave:1.4.4
copyartifact:1.37
credentials-binding:1.7
credentials:1.25
cvs:2.12
docker-build-publish:1.1
docker-commons:1.3.1
docker-custom-build-environment:1.6.4
docker-traceability:1.1
docker-workflow:1.4
dockerhub-notification:1.0.2
durable-task:1.8
envinject:1.92.1
external-monitor-job:1.4
git-client:1.19.6
git-server:1.6
git:2.4.2
github-api:1.72.1
github:1.17.1
handlebars:1.1.1
jackson2-api:2.5.4
javadoc:1.3
jenkins-jira-issue-updater:1.18
jira:2.2
job-dsl:1.44
jquery:1.11.2-0
jquery-detached:1.2.1
junit:1.11
ldap:1.11
mailer:1.16
managed-scripts:1.2.1
mapdb-api:1.0.6.0
mask-passwords:2.8
matrix-auth:1.3.2
matrix-project:1.6
maven-plugin:2.12.1
momentjs:1.1.1
multi-branch-project-plugin:0.4.1
node-iterator-api:1.5
nodelabelparameter:1.7.1
pam-auth:1.2
Parameterized-Remote-Trigger:2.2.2
parameterized-trigger:2.30
pipeline-rest-api:1.0
pipeline-stage-view:1.0
plain-credentials:1.1
promoted-builds:2.25
rebuild:1.25
run-condition:1.0
scm-api:1.1
script-security:1.17
skip-certificate-check:1.0
ssh-credentials:1.11
ssh-slaves:1.10
subversion:2.5.7
swarm:2.0
timestamper:1.7.4
token-macro:1.12.1
translation:1.12
vsphere-cloud:2.11
workflow-aggregator:1.15
workflow-api:1.15
workflow-basic-steps:1.15
workflow-cps-global-lib:1.15
workflow-cps:1.15
workflow-durable-task-step:1.15
workflow-job:1.15
workflow-multibranch:1.15
workflow-scm-step:1.15
workflow-step-api:1.15
workflow-support:1.15
</code>```

答:
This is an ancient question, but I'd like to point out for the benefit of people googling the phrase at the top:

When you get a "Scripts not permitted to use method" error that is specifically about groovy.lang.GroovyObject invokeMethod, the reason is almost always that you have invoked a method on an object that does not have that method.

In this case, you tried to invoke docker.withDockerRegistry. There is no method on docker named withDockerRegistry.

The method is called simply withRegistry.

Note that "Scripts not permitted..." errors that are not about GroovyObject invokeMethod are actual permission issues, but such errors involving GroovyObject invokeMethod are generally the security system masking a "no such method" error

Body:
I'm trying to publish to Docker from my Jenkins Pipeline but most things I try result in an error. My latest try was this:

docker.withDockerRegistry('https://docker-registry.myco.com/lsacco/swagger-rest', 'docker-credential') {
    def image = docker.image(APPLICATION_NAME);
    image.tag("latest");
    image.push()
}

When I run this, Jenkins outputs this error:

org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use method groovy.lang.GroovyObject invokeMethod java.lang.String java.lang.Object (org.jenkinsci.plugins.docker.workflow.Docker withDockerRegistry java.lang.String java.lang.String org.jenkinsci.plugins.workflow.cps.CpsClosure2)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.StaticWhitelist.rejectMethod(StaticWhitelist.java:163)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onMethodCall(SandboxInterceptor.java:78)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onMethodCall(SandboxInterceptor.java:69)
    at org.kohsuke.groovy.sandbox.impl.Checker$1.call(Checker.java:149)
    at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:146)
    at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.methodCall(SandboxInvoker.java:15)
    at WorkflowScript.dockerDeploy(WorkflowScript:290)
    at WorkflowScript.run(WorkflowScript:76)
    at ___cps.transform___(Native Method)
    at com.cloudbees.groovy.cps.impl.ContinuationGroup.methodCall(ContinuationGroup.java:55)
    at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.dispatchOrArg(FunctionCallBlock.java:106)
    at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.fixArg(FunctionCallBlock.java:79)
    at sun.reflect.GeneratedMethodAccessor317.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
    at com.cloudbees.groovy.cps.impl.ClosureBlock.eval(ClosureBlock.java:40)
    at com.cloudbees.groovy.cps.Next.step(Next.java:58)
    at com.cloudbees.groovy.cps.Continuable.run0(Continuable.java:154)
    at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.access$001(SandboxContinuable.java:19)
    at org.jenkinsci.plugins.workflow.cps.SandboxContinuable$1.call(SandboxContinuable.java:33)
    at org.jenkinsci.plugins.workflow.cps.SandboxContinuable$1.call(SandboxContinuable.java:30)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.GroovySandbox.runInSandbox(GroovySandbox.java:106)
    at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.run0(SandboxContinuable.java:30)
    at org.jenkinsci.plugins.workflow.cps.CpsThread.runNextChunk(CpsThread.java:164)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:277)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$000(CpsThreadGroup.java:77)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:186)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:184)
    at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:47)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at hudson.remoting.SingleLaneExecutorService$1.run(SingleLaneExecutorService.java:112)
    at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

I'm running on the latest Jenkins with all the latest plugin updates. Any ideas?

1.642.2 Jenkins

Plugins.txt
ace-editor:1.1
ant:1.2
antisamy-markup-formatter:1.3
async-http-client:1.7.24
aws-credentials:1.12
aws-java-sdk:1.10.45
branch-api:1.3
build-token-root:1.3
cloudbees-folder:5.3
conditional-buildstep:1.3.3
config-file-provider:2.10.0
copy-to-slave:1.4.4
copyartifact:1.37
credentials-binding:1.7
credentials:1.25
cvs:2.12
docker-build-publish:1.1
docker-commons:1.3.1
docker-custom-build-environment:1.6.4
docker-traceability:1.1
docker-workflow:1.4
dockerhub-notification:1.0.2
durable-task:1.8
envinject:1.92.1
external-monitor-job:1.4
git-client:1.19.6
git-server:1.6
git:2.4.2
github-api:1.72.1
github:1.17.1
handlebars:1.1.1
jackson2-api:2.5.4
javadoc:1.3
jenkins-jira-issue-updater:1.18
jira:2.2
job-dsl:1.44
jquery:1.11.2-0
jquery-detached:1.2.1
junit:1.11
ldap:1.11
mailer:1.16
managed-scripts:1.2.1
mapdb-api:1.0.6.0
mask-passwords:2.8
matrix-auth:1.3.2
matrix-project:1.6
maven-plugin:2.12.1
momentjs:1.1.1
multi-branch-project-plugin:0.4.1
node-iterator-api:1.5
nodelabelparameter:1.7.1
pam-auth:1.2
Parameterized-Remote-Trigger:2.2.2
parameterized-trigger:2.30
pipeline-rest-api:1.0
pipeline-stage-view:1.0
plain-credentials:1.1
promoted-builds:2.25
rebuild:1.25
run-condition:1.0
scm-api:1.1
script-security:1.17
skip-certificate-check:1.0
ssh-credentials:1.11
ssh-slaves:1.10
subversion:2.5.7
swarm:2.0
timestamper:1.7.4
token-macro:1.12.1
translation:1.12
vsphere-cloud:2.11
workflow-aggregator:1.15
workflow-api:1.15
workflow-basic-steps:1.15
workflow-cps-global-lib:1.15
workflow-cps:1.15
workflow-durable-task-step:1.15
workflow-job:1.15
workflow-multibranch:1.15
workflow-scm-step:1.15
workflow-step-api:1.15
workflow-support:1.15


来源: stackexchange

问:
Functional programming: How to model relationships?
I wonder how to model relationships in functional programming.

Let's take employees, for example:
Employees can have friendships with 0..n colleagues.
Friendships are always mutual: if A is a friend of B then B is a friend of A.

How can I model this? I had 3 ideas (listed below). Each of them has downsides.

First try:

```<code>type Employee =
  { name : string
    friendships : Employee list
  }

// My list is mutable because I want to be able to update employees.
// I suppose the same problems would occur with e. g. Elmish.
let mutable employees : Employee list = [ (* ... *) ]

(* Downsides:
   Friendships are copies. Changes to an employee would have to be propagated manually.
*)
</code>```

Second try:

```<code>type EmployeeId = int

type Employee =
  { id : EmployeeId
    name : string
    friendships : EmployeeId list
  }

let mutable employees : Employee list = [ (* ... *) ]

(* Downsides:
   Friendships are not modeled as mutual.
   When the friendship of an employee changes,
   the friend's friendships don't change accordingly.
*)
</code>```

Third try:

```<code>type EmployeeId = int

type Friendships = list<EmployeeId * EmployeeId>

type Employee =
  { id : EmployeeId
    name : string
  }

let mutable employees : Employee list = [ (* ... *) ]

(* Downsides:
   After deleting an employee from the list,
   employeeFriendships contain invalid "references"
   to the deleted Employee.
*)
</code>```

Can this be done better? Thank you.

答:
Using let rec/and might be the most direct way. You would need to introduce laziness by changing friendships to an IEnumerable.

type Employee =
    {
        name : string
        friendships : seq<Employee>
    }

let rec peter = {name="Peter"; friendships=seq {yield paul; yield mary}}
and paul = {name="Paul"; friendships=seq {yield peter; yield mary}}
and mary = {name="Mary"; friendships=seq {yield peter; yield paul}}
```

<p>However, the compiler gives the following warning:</p>

<blockquote>
  <p>This and other recursive references to the object(s) being defined
  will be checked for initialization-soundness at runtime through the
  use of a delayed reference. This is because you are defining one or
  more recursive objects, rather than recursive functions. This warning
  may be suppressed by using '#nowarn "40"' or '--nowarn:40'.</p>
</blockquote>

<p>...which points to an arguably better solution:</p>

<pre class="lang-ml prettyprint-override"><code>type Employee =
    {
        name : string
        friendships : unit -> Employee list
    }

let rec peter = {name="Peter"; friendships=fun () -> [paul; mary]}
and paul = {name="Paul"; friendships=fun () -> [peter; mary]}
and mary = {name="Mary"; friendships=fun () -> [peter; paul]}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I wonder how to model relationships in functional programming.

Let's take employees, for example:
Employees can have friendships with 0..n colleagues.
Friendships are always mutual: if A is a friend of B then B is a friend of A.

How can I model this? I had 3 ideas (listed below). Each of them has downsides.

First try:

type Employee =
  { name : string
    friendships : Employee list
  }

// My list is mutable because I want to be able to update employees.
// I suppose the same problems would occur with e. g. Elmish.
let mutable employees : Employee list = [ (* ... *) ]

(* Downsides:
   Friendships are copies. Changes to an employee would have to be propagated manually.
*)

Second try:

type EmployeeId = int

type Employee =
  { id : EmployeeId
    name : string
    friendships : EmployeeId list
  }

let mutable employees : Employee list = [ (* ... *) ]

(* Downsides:
   Friendships are not modeled as mutual.
   When the friendship of an employee changes,
   the friend's friendships don't change accordingly.
*)

Third try:

type EmployeeId = int

type Friendships = list<EmployeeId * EmployeeId>

type Employee =
  { id : EmployeeId
    name : string
  }

let mutable employees : Employee list = [ (* ... *) ]

(* Downsides:
   After deleting an employee from the list,
   employeeFriendships contain invalid "references"
   to the deleted Employee.
*)

Can this be done better? Thank you.

Body:
Using let rec/and might be the most direct way. You would need to introduce laziness by changing friendships to an IEnumerable.

type Employee =
    {
        name : string
        friendships : seq<Employee>
    }

let rec peter = {name="Peter"; friendships=seq {yield paul; yield mary}}
and paul = {name="Paul"; friendships=seq {yield peter; yield mary}}
and mary = {name="Mary"; friendships=seq {yield peter; yield paul}}

However, the compiler gives the following warning:

This and other recursive references to the object(s) being defined
  will be checked for initialization-soundness at runtime through the
  use of a delayed reference. This is because you are defining one or
  more recursive objects, rather than recursive functions. This warning
  may be suppressed by using '#nowarn "40"' or '--nowarn:40'.

...which points to an arguably better solution:

type Employee =
    {
        name : string
        friendships : unit -> Employee list
    }

let rec peter = {name="Peter"; friendships=fun () -> [paul; mary]}
and paul = {name="Paul"; friendships=fun () -> [peter; mary]}
and mary = {name="Mary"; friendships=fun () -> [peter; paul]}


问:
Is a shadow launch in AWS Lambda possible?

What is a shadow launch?

Shadow launch means that you launch the new version but it not yet gets live traffic. The traffic of the old version gets 1:1 copied into the the new one and so you can measure the performance and results of the new function against the old one without influencing the live system.

Tried approach

I already tried building something like that myself with a "Proxy" function that async calls the new function and dumps the results and sync calls the old one returning its results.

The problem are side effects: If both functions do something e.g. in DynamoDB there could be an invalid state in the DB because of the shadow launch.

Goal

I want to test new code versions of a particular lambda function.

Intended usage Example

I have a function that calculates Fibbonacci recursive and stores the result with a timestamp in DynamoDB in my live system.

This function is called via AWS Step Functions as one in a chain of many.

As it should be more efficient to calculate it iterative I implement the function with this new algorithm.

Now I want to test the assumption that the new function is more performant than the old one.
So I shadow deploy it AWS lambda to get the actually live traffic as testing data.

Problem

With the current tooling I found it is only possible to execute the function twice and thereby create two entries in DynamoDB which I consider an unwanted side effect as my data in the DynamoDB is in an unintended invalid state.

If I mock the external services in the new function, it may always be more performant than the old one as the time-expensive external services are not access and thereby my result would be incorrect.

Question

Is it possible to shadow launch a new version of an AWS lambda function without these side effects?

答:
You mentioned that you use CloudFront, so a good option might be to use a Lambda@Edge function on the CloudFront request.

https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-at-the-edge.html

https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-examples.html#lambda-examples-a-b-testing

Basically, you can execute some code every time you get a CloudFront request. The link I have sent is about A/B testing, meaning you choose to send a request to instance A OR B. But there is nothing stopping you sending the request to A AND B.

This would be completely transparent to the user. You could deploy both versions, have both versions executed (or in some proportion), and the user experience would be the same.


问:
Is there a way to omit a subproject when I am targeting multiple frameworks?
I've inherited a project for a library that targets .NET framework 4.6.1. I'm going away for the weekend and I'd like to do work on my mac laptop using VS Code (which, obviously, means I'd need to target .NET core).

The project is structured into a bunch of sub-projects -- e.g.

```<code>MyProject/
   MyProject.SubProj1/
   MyProject.SubProj2/
</code>```

Complicating things is the fact that some pieces of the subprojects can't be ported to .NET core (they depend on Speech and Windows Forms), but I can extract all the framework-specific bits into a separate subproject (e.g MyProject.Windows).

How would I edit the .csproj files to target both frameworks, to be able to build JUST the shared projects that use .net core on my mac (so I can test it) but then all the projects (targeting .net framework) on my PC?

Edit: I only have two classes that have framework dependencies, and I’m totally fine omitting them when I target core. I’m just confused on how to set up the build tasks so that the rest of the project is “shared”.

答:
This would require you to port over the code to .NET Core. You can't just switch the framework and have it magically work. Migrations from .NET Framework to .NET Core usually require heavy lifting and refactoring.

I've migrated tons of apps to core and a lot of the time I had to find new libraries to replace the old ones and rewrite a lot of code.

I don't think you're going to get off easy on this one

Body:
I've inherited a project for a library that targets .NET framework 4.6.1. I'm going away for the weekend and I'd like to do work on my mac laptop using VS Code (which, obviously, means I'd need to target .NET core).

The project is structured into a bunch of sub-projects -- e.g.

MyProject/
   MyProject.SubProj1/
   MyProject.SubProj2/

Complicating things is the fact that some pieces of the subprojects can't be ported to .NET core (they depend on Speech and Windows Forms), but I can extract all the framework-specific bits into a separate subproject (e.g MyProject.Windows).

How would I edit the .csproj files to target both frameworks, to be able to build JUST the shared projects that use .net core on my mac (so I can test it) but then all the projects (targeting .net framework) on my PC?

Edit: I only have two classes that have framework dependencies, and I’m totally fine omitting them when I target core. I’m just confused on how to set up the build tasks so that the rest of the project is “shared”.


问:
How to reduce duplicate nested dictionary levels while serializing python object
I have an example python script below where, Market object has fruits object  which contains dictionary of different type of fruit objects.
While serializing the market object as shown below,

```<code>import json

class Fruit:
    def __init__(self, name, color):
        self.name = name
        self.color = color

    def __str__(self):
        return f"name:{self.name}, color:{self.color} \n"

    def as_dict(self):
        return self

class Fruits:
    def __init__(self):
        self.fruits = {}

    def add(self, name, color):
        fruit = Fruit(name, color)
        self.fruits[fruit.name] = fruit

    def __str__(self):
        text = ["Fruits: \n"]
        for exp_id in self.fruits:
            text.append(str(self.fruits[exp_id]))
        sep = ""
        return sep.join(text)

    def as_dict(self):
        return self.fruits

class Market:
    def __init__(self, name):
        self.name = name
        self.fruits = Fruits()

    def __str__(self):
        return f"Market name: {self.name}, \n Fruits: {str(self.fruits)}"

    def as_dict(self):
        return self

m= Market("Grocery market")
m.fruits.add("apple", "red")
m.fruits.add("banana", "yellow")
m.fruits.add("mango", "green")
js = (lambda x: x.__dict__)(m)
s = json.dumps(js, default=lambda x: x.__dict__)

print(s)
</code>```

the output json comes out as:

```<code>{
  "name": "Grocery market",
  "fruits": {
    "fruits": {
      "apple": { "name": "apple", "color": "red" },
      "banana": { "name": "banana", "color": "yellow" },
      "mango": { "name": "mango", "color": "green" }
    }
  }
}
</code>```

I am trying to reduce the 2 Fruits level to just 1 as shown below:

```<code>{
  "name": "Grocery market",
  "fruits": {
    "apple": { "name": "apple", "color": "red" },
    "banana": { "name": "banana", "color": "yellow" },
    "mango": { "name": "mango", "color": "green" }
  }
}
</code>```

I need help in understanding what would be the best way to go about it?
I tried overloading dict for fruits class, but realized it couldn't be overloaded.

Any help is appreciated.

答:
Try to be more explicit and avoid too much magic. Method to_dict() should return dict, not the object itself. Something like this works ok.</p>

```<code>import json

class Fruit:
    def __init__(self, name, color):
        self.name = name
        self.color = color

    def __str__(self):
        return f"name:{self.name}, color:{self.color} \n"

    def as_dict(self):
        return {
            'name': self.name,
            'color': self.color,
        }

class Fruits:
    def __init__(self):
        self.fruits = {}

    def add(self, name, color):
        fruit = Fruit(name, color)
        self.fruits[fruit.name] = fruit

    def __str__(self):
        text = ["Fruits: \n"]
        for exp_id in self.fruits:
            text.append(str(self.fruits[exp_id]))
        sep = ""
        return sep.join(text)

    def as_dict(self):
        return {k: v.as_dict() for k, v in self.fruits.items()}

class Market:
    def __init__(self, name):
        self.name = name
        self.fruits = Fruits()

    def __str__(self):
        return f"Market name: {self.name}, \n Fruits: {str(self.fruits)}"

    def as_dict(self):
        return {
            'name': self.name,
            'fruits': self.fruits.as_dict(),
        }

m= Market("Grocery market")
m.fruits.add("apple", "red")
m.fruits.add("banana", "yellow")
m.fruits.add("mango", "green")
s = json.dumps(m.as_dict())

print(s)
</code>```

Body:
I have an example python script below where, Market object has fruits object  which contains dictionary of different type of fruit objects.
While serializing the market object as shown below,

import json

class Fruit:
    def __init__(self, name, color):
        self.name = name
        self.color = color

    def __str__(self):
        return f"name:{self.name}, color:{self.color} \n"

    def as_dict(self):
        return self

class Fruits:
    def __init__(self):
        self.fruits = {}

    def add(self, name, color):
        fruit = Fruit(name, color)
        self.fruits[fruit.name] = fruit

    def __str__(self):
        text = ["Fruits: \n"]
        for exp_id in self.fruits:
            text.append(str(self.fruits[exp_id]))
        sep = ""
        return sep.join(text)

    def as_dict(self):
        return self.fruits

class Market:
    def __init__(self, name):
        self.name = name
        self.fruits = Fruits()

    def __str__(self):
        return f"Market name: {self.name}, \n Fruits: {str(self.fruits)}"

    def as_dict(self):
        return self

m= Market("Grocery market")
m.fruits.add("apple", "red")
m.fruits.add("banana", "yellow")
m.fruits.add("mango", "green")
js = (lambda x: x.__dict__)(m)
s = json.dumps(js, default=lambda x: x.__dict__)

print(s)

the output json comes out as:

{
  "name": "Grocery market",
  "fruits": {
    "fruits": {
      "apple": { "name": "apple", "color": "red" },
      "banana": { "name": "banana", "color": "yellow" },
      "mango": { "name": "mango", "color": "green" }
    }
  }
}

I am trying to reduce the 2 Fruits level to just 1 as shown below:

{
  "name": "Grocery market",
  "fruits": {
    "apple": { "name": "apple", "color": "red" },
    "banana": { "name": "banana", "color": "yellow" },
    "mango": { "name": "mango", "color": "green" }
  }
}

I need help in understanding what would be the best way to go about it?
I tried overloading dict for fruits class, but realized it couldn't be overloaded.

Any help is appreciated.

Body:
Try to be more explicit and avoid too much magic. Method to_dict() should return dict, not the object itself. Something like this works ok.

import json

class Fruit:
    def __init__(self, name, color):
        self.name = name
        self.color = color

    def __str__(self):
        return f"name:{self.name}, color:{self.color} \n"

    def as_dict(self):
        return {
            'name': self.name,
            'color': self.color,
        }

class Fruits:
    def __init__(self):
        self.fruits = {}

    def add(self, name, color):
        fruit = Fruit(name, color)
        self.fruits[fruit.name] = fruit

    def __str__(self):
        text = ["Fruits: \n"]
        for exp_id in self.fruits:
            text.append(str(self.fruits[exp_id]))
        sep = ""
        return sep.join(text)

    def as_dict(self):
        return {k: v.as_dict() for k, v in self.fruits.items()}

class Market:
    def __init__(self, name):
        self.name = name
        self.fruits = Fruits()

    def __str__(self):
        return f"Market name: {self.name}, \n Fruits: {str(self.fruits)}"

    def as_dict(self):
        return {
            'name': self.name,
            'fruits': self.fruits.as_dict(),
        }

m= Market("Grocery market")
m.fruits.add("apple", "red")
m.fruits.add("banana", "yellow")
m.fruits.add("mango", "green")
s = json.dumps(m.as_dict())

print(s)


问:
Magento: edit quantity and update price of bundle option in quote item
I am working with Magento bundle products that contain hidden bundle options that need to have the quantity updated programmatically. A problem arises when the bundle quantity is edited from the shopping cart. I have a button set up to submit the bundle quote item to an updateLineItemAction() method in my own CartController to handle the update of the hidden bundle option.

The updateLineItemAction() method locates the hidden bundle option and assigns the updated quantity to the "selection_qty_X" and "product_qty_X" properties, where X is the ID of the bundle option. Values in the "info_buyRequest" are also updated. After saving the quote item, there's a redirect to the cart to show the updated cart values.

The updated quantity is displayed correctly in the cart, and the hidden bundle option has the correct quantity assigned. The problem is that the bundle item price has not updated to reflect the updated quantity on the hidden bundle option. I did something similar to this in Magento 1.1.x and it worked fine. Doing this now in 1.4.1.2, the price is not automatically updated when the quote item is saved. I've tried saving the quote and the cart again after updating the item, but that doesn't seem to have any effect.

What is the proper way to recalculate the price for a quote item when subitems have had the quantity changed? Is there a better way to change the quantity of a quote item bundle option so that the price of the bundle item is updated correctly?

答: The solution for my case was to update the quantity values of the selections as noted in my original post, and also to adjust the quantity assigned to the bundle item associated with the hidden bundle option. This last step was not necessary in versions prior to Magento 1.4. </p>

ContentLicense: CC BY-SA 3.0


问:
Python pandas explode (one to many relationship)
Suppose I have a the following dataframe with columns name, preference, fruits:

```<code>name   preference   fruits
adam    likes       apples
mike   dislikes     orange
</code>```

If the dataframe above had a one to many relationship like column name would have have multiple relationship with column preference, fruits. For example the output dataframe I am looking for is:

```<code>name   preference   fruits
adam    likes       apples
adam    likes       orange
adam    dislikes    apple
adam    dislikes    orange
mike    likes       apples
mike    likes       orange
mike    dislikes    apple
mike    dislikes    orange
</code>```

Wondering if it is possible. From my knowledge about pandas so far I believe I will have to use groupby?
Any help is appreciated!
Thanks!

答:
I'd use itertools.product

```<code>import pandas as pd
from itertools import product

df = pd.DataFrame({
    'name': ['adam', 'mike'],
    'preference': ['likes', 'dislikes'],
    'fruits': ['apples', 'oranges']
})

ndf = pd.DataFrame(
    product(*[df[c] for c in df.columns]),
    columns=df.columns
)

print(ndf)
#    name preference   fruits
# 0  adam      likes   apples
# 1  adam      likes  oranges
# 2  adam   dislikes   apples
# 3  adam   dislikes  oranges
# 4  mike      likes   apples
# 5  mike      likes  oranges
# 6  mike   dislikes   apples
# 7  mike   dislikes  oranges
</code>```

As for speed, this seems to be a bit faster as well.

```<code>%%timeit
ndf = pd.DataFrame(
    product(*[df[c] for c in df.columns]),
    columns=df.columns
)
# 624 µs ± 32.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%%timeit
(pd.MultiIndex.from_product([df[col] for col in df],
                           names=df.columns)
   .to_frame().reset_index(drop=True)
)
# 3.51 ms ± 176 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
</code>```

Body:
Suppose I have a the following dataframe with columns name, preference, fruits:

name   preference   fruits
adam    likes       apples
mike   dislikes     orange

If the dataframe above had a one to many relationship like column name would have have multiple relationship with column preference, fruits. For example the output dataframe I am looking for is:

name   preference   fruits
adam    likes       apples
adam    likes       orange
adam    dislikes    apple
adam    dislikes    orange
mike    likes       apples
mike    likes       orange
mike    dislikes    apple
mike    dislikes    orange

Wondering if it is possible. From my knowledge about pandas so far I believe I will have to use groupby?
Any help is appreciated!
Thanks!

Body:
I'd use itertools.product

import pandas as pd
from itertools import product

df = pd.DataFrame({
    'name': ['adam', 'mike'],
    'preference': ['likes', 'dislikes'],
    'fruits': ['apples', 'oranges']
})

ndf = pd.DataFrame(
    product(*[df[c] for c in df.columns]),
    columns=df.columns
)

print(ndf)
#    name preference   fruits
# 0  adam      likes   apples
# 1  adam      likes  oranges
# 2  adam   dislikes   apples
# 3  adam   dislikes  oranges
# 4  mike      likes   apples
# 5  mike      likes  oranges
# 6  mike   dislikes   apples
# 7  mike   dislikes  oranges

As for speed, this seems to be a bit faster as well.

%%timeit
ndf = pd.DataFrame(
    product(*[df[c] for c in df.columns]),
    columns=df.columns
)
# 624 µs ± 32.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%%timeit
(pd.MultiIndex.from_product([df[col] for col in df],
                           names=df.columns)
   .to_frame().reset_index(drop=True)
)
# 3.51 ms ± 176 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)


问:
Ansible fail task but continue running
I'm currently writing a bunch of checks for Ansible.

It involves contacting remote machines and performing a check.

Based on the result of this check, I make a decision whether it failed or not.

This is the important bit: the task itself never fails. It merely returns a message. I register the result and then analyze it. And based on that I decide if it's a failure or not.

The thing is, I want to add a flag that allows tests to keep running instead of failing.

So the code looks like this:

```<code>- name: Check fail.
  fail:
    msg: "Test failed"
  when: "failfast_flag and <the actual check>"
</code>```

The problem there is, if I make failfast_flag false, it doesn't output red anymore.

I want it to continue with the next tests, in that case, but I also want it to color red, indicating it's an error/fail.

How do I accomplish this?

EDIT: Thanks for the suggestions, I'll give them a try in a bit.

答:
Not sure i fully understood your question, but you could use a - block and rescue structure in order to treat the failures and continue the playbook in failure scenarios:

example:

```<code>- block:
    - name: Check fail.
      fail:
      msg: "Test failed"
      when: "failfast_flag and <the actual check>"
  rescue:
    - name: do somthing when the task above fails
      command: <do somthing>
</code>```

Title: Ansible fail task but continue running

Body:
I'm currently writing a bunch of checks for Ansible.

It involves contacting remote machines and performing a check.

Based on the result of this check, I make a decision whether it failed or not.

This is the important bit: the task itself never fails. It merely returns a message. I register the result and then analyze it. And based on that I decide if it's a failure or not.

The thing is, I want to add a flag that allows tests to keep running instead of failing.

So the code looks like this:

- name: Check fail.
  fail:
    msg: "Test failed"
  when: "failfast_flag and <the actual check>"

The problem there is, if I make failfast_flag false, it doesn't output red anymore.

I want it to continue with the next tests, in that case, but I also want it to color red, indicating it's an error/fail.

How do I accomplish this?

EDIT: Thanks for the suggestions, I'll give them a try in a bit.

Body:
Not sure i fully understood your question, but you could use a - block and rescue structure in order to treat the failures and continue the playbook in failure scenarios:

example:

- block:
    - name: Check fail.
      fail:
      msg: "Test failed"
      when: "failfast_flag and <the actual check>"
  rescue:
    - name: do somthing when the task above fails
      command: <do somthing>


问:
Download Data from JSON $ajax
I am trying to download data off a server and return the data but, the function I made does not seem to return the downloaded data. It keeps returning the promise, can someone help me out?

Here is the output on console:

```<code>part3-main.js:9 data {readyState: 1, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
part3-application.js:55 Downloading Data
part3-application.js:56 Downloaded Data
part3-application.js:58 parsee (994) [{…},...]
</code>```

```<code>var getAndParseData = function(){
  var download_data = $.ajax({
    url: "https://raw.githubusercontent.com/MUSA611-CPLN692-spring2020/datasets/master/json/philadelphia-crime-snippet.json"
  })
  .done(function(data){
    console.log('Downloading Data');
    console.log('Downloaded Data');
    parsed_data = JSON.parse(data);
    console.log('parsee', parsed_data);
    return parsed_data;
  });
  console.log(download_data);
  return download_data;
};
</code>```

答:
Since the ajax call returns a promise you need a way to resolve that. As an alternative to the callback approach provided above you can use the async/await. Not much you need to change from your code structure.

Note: you will need a way to handle errors

var getAndParseData = async function(){
  var download_data = await $.ajax({
    url: "https://raw.githubusercontent.com/MUSA611-CPLN692-spring2020/datasets/master/json/philadelphia-crime-snippet.json"
  })

  console.log(download_data)
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

Title: Download Data from JSON $ajax

Body:
I am trying to download data off a server and return the data but, the function I made does not seem to return the downloaded data. It keeps returning the promise, can someone help me out?

Here is the output on console:

part3-main.js:9 data {readyState: 1, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
part3-application.js:55 Downloading Data
part3-application.js:56 Downloaded Data
part3-application.js:58 parsee (994) [{…},...]

var getAndParseData = function(){
  var download_data = $.ajax({
    url: "https://raw.githubusercontent.com/MUSA611-CPLN692-spring2020/datasets/master/json/philadelphia-crime-snippet.json"
  })
  .done(function(data){
    console.log('Downloading Data');
    console.log('Downloaded Data');
    parsed_data = JSON.parse(data);
    console.log('parsee', parsed_data);
    return parsed_data;
  });
  console.log(download_data);
  return download_data;
};

Body:
Since the ajax call returns a promise you need a way to resolve that. As an alternative to the callback approach provided above you can use the async/await. Not much you need to change from your code structure.

Note: you will need a way to handle errors

var getAndParseData = async function(){
  var download_data = await $.ajax({
    url: "https://raw.githubusercontent.com/MUSA611-CPLN692-spring2020/datasets/master/json/philadelphia-crime-snippet.json"
  })

  console.log(download_data)
};

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


问:
How can I check which file is a function in?
I'm working with PHP and sometimes, I want to find where the function being used is located. How can I do this easily without tracing through everything?</p>

答:
Use the __FILE__ constant.

See here:
http://php.net/manual/en/language.constants.predefined.php


问:
How to properly add elements to an array in Python
I have two arrays as the code shows below (A and B). I would like to take as output C = [[1, 2, 3, 11], [4, 5, 6, 12], [7, 8, 9, 13]]

I'm trying to, but the only thing I could reach was this:

```<code>A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
B = [11, 12, 13]
C = [[x, y] for x, y in zip(A, B)]

print(C)
# Output: [[[1, 2, 3], 11], [[4, 5, 6], 12], [[7, 8, 9], 13]]
</code>```

答:
If it doesn't need to be a new list and modifying A suffices:

```<code>for a, b in zip(A, B):
    a.append(b)
</code>```

It's more efficient, at least for longer inner lists.

Body:
I have two arrays as the code shows below (A and B). I would like to take as output C = [[1, 2, 3, 11], [4, 5, 6, 12], [7, 8, 9, 13]]

I'm trying to, but the only thing I could reach was this:

A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
B = [11, 12, 13]
C = [[x, y] for x, y in zip(A, B)]

print(C)
# Output: [[[1, 2, 3], 11], [[4, 5, 6], 12], [[7, 8, 9], 13]]

Body:
If it doesn't need to be a new list and modifying A suffices:

for a, b in zip(A, B):
    a.append(b)

It's more efficient, at least for longer inner lists.


问:
Nativescript-Vue axios call error on local laravel API [Request failed with status code null]
I'm fairly new to Nativescript, in my project I'm trying to make an http request to my local laravel server I set up with php artisan serve on http://127.0.0.1:8000/, I'm using a connected android device, no emulator. After some reading I got my local IPv4 with ipconfig command.

In my App.vue component I fire a GET request to my local laravel API endpoint with axios:

This DOESN'T work:

```<code>console.log('Firing axios call');
axios.get('http://192.168.1.35:8000/api/posts')
.then((response) => {
    console.log('It worked! /////////////////////////////////////////');
}).catch((err)=>{
    console.log('God dammit',err);
});
</code>```

But I always get error:

```<code>'God dammit' [Error: Request failed with status code null]
</code>```

In laravel, this is my controller methos which responds to /api/posts

```<code>public function list(Request $request)
    {
        $posts = Post::with(['postcategory','author'])
            ->latest()
            ->paginate($request->input('paginate', 10));

        return response()->json([
            'data' => $posts,
            'pagination' => [
                'total' => $posts->total(),
                'per_page' =>$posts->perPage(),
                'current_page' => $posts->currentPage(),
                'last_page' => $posts->lastPage(),
                'from' => $posts->firstItem(),
                'to' => $posts->lastItem()
            ]
        ]);
    }
</code>```

I tried with httpbin endpoint and I get response back, it works but my laravel API never works...

This DOES work:

```<code>axios.get('https://httpbin.org/get')
.then((response) => {
   console.log('success');
   console.log(response.data);
}).catch((err)=>{
   console.log(err);
});
</code>```

And returns:

```<code>{ args: {},
JS:   headers:
JS:    { Accept: 'application/json, text/plain, */*',
JS:      'Accept-Encoding': 'gzip',
JS:      Host: 'httpbin.org',
JS:      'User-Agent': 'Dalvik/1.6.0 (Linux; U; Android 4.4.4; GT-I9060I Build/KTU84P)' },
JS:   origin: '79.152.179.88, 79.152.179.88',
JS:   url: 'https://httpbin.org/get' }
</code>```

Any idea what I'm doing wrong?

答:
Since you are using http, you need to add this to your app/App_Resources/Android/src/main/AndroidManifest.xml in the application tag:
android:usesCleartextTraffic="true"

like this:

```<code><application ...
    android:usesCleartextTraffic="true"
</code>```

Body:
I'm fairly new to Nativescript, in my project I'm trying to make an http request to my local laravel server I set up with php artisan serve on http://127.0.0.1:8000/, I'm using a connected android device, no emulator. After some reading I got my local IPv4 with ipconfig command.

In my App.vue component I fire a GET request to my local laravel API endpoint with axios:

This DOESN'T work:

console.log('Firing axios call');
axios.get('http://192.168.1.35:8000/api/posts')
.then((response) => {
    console.log('It worked! /////////////////////////////////////////');
}).catch((err)=>{
    console.log('God dammit',err);
});

But I always get error:

'God dammit' [Error: Request failed with status code null]

In laravel, this is my controller methos which responds to /api/posts

public function list(Request $request)
    {
        $posts = Post::with(['postcategory','author'])
            ->latest()
            ->paginate($request->input('paginate', 10));

        return response()->json([
            'data' => $posts,
            'pagination' => [
                'total' => $posts->total(),
                'per_page' =>$posts->perPage(),
                'current_page' => $posts->currentPage(),
                'last_page' => $posts->lastPage(),
                'from' => $posts->firstItem(),
                'to' => $posts->lastItem()
            ]
        ]);
    }

I tried with httpbin endpoint and I get response back, it works but my laravel API never works...

This DOES work:

axios.get('https://httpbin.org/get')
.then((response) => {
   console.log('success');
   console.log(response.data);
}).catch((err)=>{
   console.log(err);
});

And returns:

{ args: {},
JS:   headers:
JS:    { Accept: 'application/json, text/plain, */*',
JS:      'Accept-Encoding': 'gzip',
JS:      Host: 'httpbin.org',
JS:      'User-Agent': 'Dalvik/1.6.0 (Linux; U; Android 4.4.4; GT-I9060I Build/KTU84P)' },
JS:   origin: '79.152.179.88, 79.152.179.88',
JS:   url: 'https://httpbin.org/get' }

Any idea what I'm doing wrong?

Body:
Since you are using http, you need to add this to your app/App_Resources/Android/src/main/AndroidManifest.xml in the application tag:
android:usesCleartextTraffic="true"

like this:

<application ...
    android:usesCleartextTraffic="true"


问:
How can I add spacebar on Header Nav Bar
So I made a navigation bar and a section lists and I successfully done it but the only problem is that the lists are not spaced. How do I fix this?

How the Page looks like

header {
  width:    100%;
  height:    80px;
  position:   fixed;
  top:    0;
  left:    0;
  background:   white;
  box-shadow:   0 32px 55px rgba(0, 0, 0, 0.5);
  z-index:    999;
}

header nav {
  float:    none;
  margin:    30px;
}

header nav ul li {
  display:    inline-block;
}

header nav ul li a {
  font-size:   16px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <header>

  <nav id="nav-main">
   <ul>
    <li>Home</li>
    <li>Elektro One</li>
    <li>Über uns</li>
    <li>Kontakt</li>
    <li>Impressum</li>
   </ul>
  </nav>

 </header></code>```

答:
just add margin for li tags like following:

header {
 width: 100%;
 height: 80px;
 position: fixed;
 top: 0;
 left: 0;
 background: white;
 box-shadow: 0 32px 55px rgba(0, 0, 0, 0.5);
 z-index: 999;
}

header nav {
 float: none;
 margin: 30px;
}

header nav ul li {
 display: inline-block;
    margin: 0 16px;
}

header nav ul li a {
 font-size: 16px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <header>

  <nav id="nav-main">
   <ul>
    <li>Home</li>
    <li>Elektro One</li>
    <li>Über uns</li>
    <li>Kontakt</li>
    <li>Impressum</li>
   </ul>
  </nav>

 </header></code>```

Body:
So I made a navigation bar and a section lists and I successfully done it but the only problem is that the lists are not spaced. How do I fix this?

How the Page looks like

header {
  width:    100%;
  height:    80px;
  position:   fixed;
  top:    0;
  left:    0;
  background:   white;
  box-shadow:   0 32px 55px rgba(0, 0, 0, 0.5);
  z-index:    999;
}

header nav {
  float:    none;
  margin:    30px;
}

header nav ul li {
  display:    inline-block;
}

header nav ul li a {
  font-size:   16px;
}

Home

Elektro One

Über uns

Kontakt

Impressum

Body:
just add margin for li tags like following:

header {
 width: 100%;
 height: 80px;
 position: fixed;
 top: 0;
 left: 0;
 background: white;
 box-shadow: 0 32px 55px rgba(0, 0, 0, 0.5);
 z-index: 999;
}

header nav {
 float: none;
 margin: 30px;
}

header nav ul li {
 display: inline-block;
    margin: 0 16px;
}

header nav ul li a {
 font-size: 16px;
}

 <header>

  <nav id="nav-main">
   <ul>
    <li><a href="#home">Home</a></li>
    <li><a href="#elektro_One">Elektro One</a></li>
    <li><a href="#über_uns">Über uns</a></li>
    <li><a href="#kontakt">Kontakt</a></li>
    <li><a href="#impressum">Impressum</a></li>
   </ul>
  </nav>

 </header>


问:
Optimizing the backward solve for a sparse lower triangular linear system
I have the compressed sparse column (csc) representation of the n x n lower-triangular matrix A with zeros on the main diagonal, and would like to solve for b in

```<code>(A + I)' * x = b
</code>```

This is the routine I have for computing this:

```<code>void backsolve(const int*__restrict__ Lp,
               const int*__restrict__ Li,
               const double*__restrict__ Lx,
               const int n,
               double*__restrict__ x) {
  for (int i=n-1; i>=0; --i) {
      for (int j=Lp[i]; j<Lp[i+1]; ++j) {
          x[i] -= Lx[j] * x[Li[j]];
      }
  }
}
</code>```

Thus, b is passed in via the argument x, and is overwritten by the solution. Lp, Li, Lx are respectively the row, indices, and data pointers in the standard csc representation of sparse matrices. This function is the top hotspot in the program, with the line

```<code>x[i] -= Lx[j] * x[Li[j]];
</code>```

being the bulk of the time spent. Compiling with gcc-8.3 -O3 -mfma -mavx -mavx512f gives

```<code>backsolve(int const*, int const*, double const*, int, double*):
        lea     eax, [rcx-1]
        movsx   r11, eax
        lea     r9, [r8+r11*8]
        test    eax, eax
        js      .L9
.L5:
        movsx   rax, DWORD PTR [rdi+r11*4]
        mov     r10d, DWORD PTR [rdi+4+r11*4]
        cmp     eax, r10d
        jge     .L6
        vmovsd  xmm0, QWORD PTR [r9]
.L7:
        movsx   rcx, DWORD PTR [rsi+rax*4]
        vmovsd  xmm1, QWORD PTR [rdx+rax*8]
        add     rax, 1
        vfnmadd231sd    xmm0, xmm1, QWORD PTR [r8+rcx*8]
        vmovsd  QWORD PTR [r9], xmm0
        cmp     r10d, eax
        jg      .L7
.L6:
        sub     r11, 1
        sub     r9, 8
        test    r11d, r11d
        jns     .L5
        ret
.L9:
        ret
</code>```

According to vtune,

```<code>vmovsd  QWORD PTR [r9], xmm0
</code>```

is the slowest part. I have almost no experience with assembly, and am at a loss as to how to further diagnose or optimize this operation. I have tried compiling with different flags to enable/disable SSE, FMA, etc, but nothing has worked.

Processor: Xeon Skylake

Question What can I do to optimize this function?

答:
You might shave a few cycles by using unsigned instead of int for the index types, which must be >= 0 anyway:

```<code>void backsolve(const unsigned * __restrict__ Lp,
               const unsigned * __restrict__ Li,
               const double * __restrict__ Lx,
               const unsigned n,
               double * __restrict__ x) {
    for (unsigned i = n; i-- > 0; ) {
        for (unsigned j = Lp[i]; j < Lp[i + 1]; ++j) {
            x[i] -= Lx[j] * x[Li[j]];
        }
    }
}
</code>```

Compiling with Godbolt's compiler explorer shows slightly different code for the innerloop, potentially making better use of the CPU pipeline. I cannot test, but you could try.

Here is the generated code for the inner loop:

```<code>.L8:
        mov     rax, rcx
.L5:
        mov     ecx, DWORD PTR [r10+rax*4]
        vmovsd  xmm1, QWORD PTR [r11+rax*8]
        vfnmadd231sd    xmm0, xmm1, QWORD PTR [r8+rcx*8]
        lea     rcx, [rax+1]
        vmovsd  QWORD PTR [r9], xmm0
        cmp     rdi, rax
        jne     .L8

</code>```

Body:
I have the compressed sparse column (csc) representation of the n x n lower-triangular matrix A with zeros on the main diagonal, and would like to solve for b in

(A + I)' * x = b

This is the routine I have for computing this:

void backsolve(const int*__restrict__ Lp,
               const int*__restrict__ Li,
               const double*__restrict__ Lx,
               const int n,
               double*__restrict__ x) {
  for (int i=n-1; i>=0; --i) {
      for (int j=Lp[i]; j<Lp[i+1]; ++j) {
          x[i] -= Lx[j] * x[Li[j]];
      }
  }
}

Thus, b is passed in via the argument x, and is overwritten by the solution. Lp, Li, Lx are respectively the row, indices, and data pointers in the standard csc representation of sparse matrices. This function is the top hotspot in the program, with the line

x[i] -= Lx[j] * x[Li[j]];

being the bulk of the time spent. Compiling with gcc-8.3 -O3 -mfma -mavx -mavx512f gives

backsolve(int const*, int const*, double const*, int, double*):
        lea     eax, [rcx-1]
        movsx   r11, eax
        lea     r9, [r8+r11*8]
        test    eax, eax
        js      .L9
.L5:
        movsx   rax, DWORD PTR [rdi+r11*4]
        mov     r10d, DWORD PTR [rdi+4+r11*4]
        cmp     eax, r10d
        jge     .L6
        vmovsd  xmm0, QWORD PTR [r9]
.L7:
        movsx   rcx, DWORD PTR [rsi+rax*4]
        vmovsd  xmm1, QWORD PTR [rdx+rax*8]
        add     rax, 1
        vfnmadd231sd    xmm0, xmm1, QWORD PTR [r8+rcx*8]
        vmovsd  QWORD PTR [r9], xmm0
        cmp     r10d, eax
        jg      .L7
.L6:
        sub     r11, 1
        sub     r9, 8
        test    r11d, r11d
        jns     .L5
        ret
.L9:
        ret

According to vtune,

vmovsd  QWORD PTR [r9], xmm0

is the slowest part. I have almost no experience with assembly, and am at a loss as to how to further diagnose or optimize this operation. I have tried compiling with different flags to enable/disable SSE, FMA, etc, but nothing has worked.

Processor: Xeon Skylake

Question What can I do to optimize this function?

Body:
You might shave a few cycles by using unsigned instead of int for the index types, which must be >= 0 anyway:

void backsolve(const unsigned * __restrict__ Lp,
               const unsigned * __restrict__ Li,
               const double * __restrict__ Lx,
               const unsigned n,
               double * __restrict__ x) {
    for (unsigned i = n; i-- > 0; ) {
        for (unsigned j = Lp[i]; j < Lp[i + 1]; ++j) {
            x[i] -= Lx[j] * x[Li[j]];
        }
    }
}

Compiling with Godbolt's compiler explorer shows slightly different code for the innerloop, potentially making better use of the CPU pipeline. I cannot test, but you could try.

Here is the generated code for the inner loop:

.L8:
        mov     rax, rcx
.L5:
        mov     ecx, DWORD PTR [r10+rax*4]
        vmovsd  xmm1, QWORD PTR [r11+rax*8]
        vfnmadd231sd    xmm0, xmm1, QWORD PTR [r8+rcx*8]
        lea     rcx, [rax+1]
        vmovsd  QWORD PTR [r9], xmm0
        cmp     rdi, rax
        jne     .L8


问:
UTF-16 strings in COM
Please, somebody, explain Go pointers magic
I try to call COM function

```<code>func (p *IServer) Authorize(user, pass string) error {
  UserName := ole.SysAllocString(login.UserName)
  defer ole.SysFreeString(UserName)
  UserPsw := ole.SysAllocString(login.UserPsw)
  defer ole.SysFreeString(UserPsw)

  // HRESULT IServer::Authorize([in] BSTR UserName, [in] BSTR UserPsw, [out] VARIANT* SID, [out, retval] long* Result)
  hr, _, _ := Call(p.VTable().Authorize,
    uintptr(unsafe.Pointer(p)),
    uintptr(unsafe.Pointer(UserName)),
    uintptr(unsafe.Pointer(UserPsw)),
    uintptr(unsafe.Pointer(sid)),
    uintptr(unsafe.Pointer(&res)))

   ...
}
</code>```

This code works well, but when I replace convertion to

```<code>UserName := syscall.StringToUTF16Ptr(login.UserName)
UserPsw := syscall.StringToUTF16Ptr(login.UserPsw)
</code>```

It cause an ACCESS VIOLATION! Source from go-ole

```<code>func SysAllocString(v string) (ss *int16) {
  pss, _, _ := procSysAllocString.Call(uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(v))))
  ss = (*int16)(unsafe.Pointer(pss))
  return
}
</code>```

What am I doing wrong?

Update: In C/C++ wchar* pointer works corretly both 386/amd64

```<code>void Authorize(IServer* p wchar* user, wchar* pass) {
   p.Authorize(user, pass ....
}
</code>```

答:
SysAllocString returns BSTR type, the com type object.

 typedef struct {
 #ifdef _WIN64
     DWORD pad;
 #endif
     DWORD size;
     union {
         char ptr[1];
         WCHAR str[1];
         DWORD dwptr[1];
     } u; // take it as a starting point of the string
 } bstr_t;
```

<p>In other words, it's the same utf16 encoded string but with the prefix in the form of its size (length of the Unicode characters multiplied by the size of wchar_t (2-4 byte)). For the optimization reason, it also has padding.</p>

<p>Because of its floating size, it's better to use ole package rather than reinventing the wheel. If you want to implement it yourself, and wchar_t has the size of int16 (2 bytes), then you have to do the following: </p>

<p>(half-pseudocode, I didn't test it)</p>

<pre class="lang-golang prettyprint-override"><code>type BSTR *uint16

func SysAllocString(str string) (result BSTR) {
    // DWORD == int32 == rune
    const padf = "\x00" // only for 64 bit system
    const sizef = "\x00"

    // int32 == 4 byte
    // int16 == 2 byte
    const wordSize = unsafe.Sizeof(int16(0))

    utf16 := utf16.Encode([]rune(padf + sizef + str))

    /* pad is on index 0 and 1 */
    size :=  &utf16[2 /* 0 for 32 bit system */]

    // set "size" field as unicode charachers length multypled by size of wchar_t
    *(*rune)(unsafe.Pointer(size)) = rune((len(utf16)-2) * int(wordSize))

    result = BSTR(&utf16[0])

    return
}

// ...
bstr := SysAllocString(login.UserName)

uintptr(unsafe.Pointer(bstr))
</code>```

Title: UTF-16 strings in COM

Body:
Please, somebody, explain Go pointers magic
I try to call COM function

func (p *IServer) Authorize(user, pass string) error {
  UserName := ole.SysAllocString(login.UserName)
  defer ole.SysFreeString(UserName)
  UserPsw := ole.SysAllocString(login.UserPsw)
  defer ole.SysFreeString(UserPsw)

  // HRESULT IServer::Authorize([in] BSTR UserName, [in] BSTR UserPsw, [out] VARIANT* SID, [out, retval] long* Result)
  hr, _, _ := Call(p.VTable().Authorize,
    uintptr(unsafe.Pointer(p)),
    uintptr(unsafe.Pointer(UserName)),
    uintptr(unsafe.Pointer(UserPsw)),
    uintptr(unsafe.Pointer(sid)),
    uintptr(unsafe.Pointer(&res)))

   ...
}

This code works well, but when I replace convertion to

UserName := syscall.StringToUTF16Ptr(login.UserName)
UserPsw := syscall.StringToUTF16Ptr(login.UserPsw)

It cause an ACCESS VIOLATION! Source from go-ole

func SysAllocString(v string) (ss *int16) {
  pss, _, _ := procSysAllocString.Call(uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(v))))
  ss = (*int16)(unsafe.Pointer(pss))
  return
}

What am I doing wrong?

Update: In C/C++ wchar* pointer works corretly both 386/amd64

void Authorize(IServer* p wchar* user, wchar* pass) {
   p.Authorize(user, pass ....
}

Body:
SysAllocString returns BSTR type, the com type object.

 typedef struct {
 #ifdef _WIN64
     DWORD pad;
 #endif
     DWORD size;
     union {
         char ptr[1];
         WCHAR str[1];
         DWORD dwptr[1];
     } u; // take it as a starting point of the string
 } bstr_t;

In other words, it's the same utf16 encoded string but with the prefix in the form of its size (length of the Unicode characters multiplied by the size of wchar_t (2-4 byte)). For the optimization reason, it also has padding.

Because of its floating size, it's better to use ole package rather than reinventing the wheel. If you want to implement it yourself, and wchar_t has the size of int16 (2 bytes), then you have to do the following:

(half-pseudocode, I didn't test it)

type BSTR *uint16

func SysAllocString(str string) (result BSTR) {
    // DWORD == int32 == rune
    const padf = "\x00" // only for 64 bit system
    const sizef = "\x00"

    // int32 == 4 byte
    // int16 == 2 byte
    const wordSize = unsafe.Sizeof(int16(0))

    utf16 := utf16.Encode([]rune(padf + sizef + str))

    /* pad is on index 0 and 1 */
    size :=  &utf16[2 /* 0 for 32 bit system */]

    // set "size" field as unicode charachers length multypled by size of wchar_t
    *(*rune)(unsafe.Pointer(size)) = rune((len(utf16)-2) * int(wordSize))

    result = BSTR(&utf16[0])

    return
}

// ...
bstr := SysAllocString(login.UserName)

uintptr(unsafe.Pointer(bstr))


问:
Change tab color according to two different cells (if statement)
I've trying to change the tab color following a if logic, for cells C32 and C46. Even though the logic is working for most o the logic some does not bring me the right color. I'm not super familiar with VBA.

What is not working:

```<code>C32= Fail and C46= Not Complette (brings me green instead of red)
C32= Not applicable and C46= Not Applicable (brings me red instead of gray)
C32= Not applicable and C46= Not Complete (brings me green instead of gray)
C32= Not Complete and C46= Not Complete (brings me green instead of gray)
C32= Not Complete and C46= Not Applicable (brings me red instead of gray)
</code>```

Please help. It seems simple to fix but could find the solution

```<code>Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    If Range("$C$32").Value = "Pass" And Range("$C$46").Value = "Pass" Or Range("$C$46").Value = "Not Complete" Then
         Me.Tab.ColorIndex = 10
    ElseIf Range("$C$32").Value = "Pass" And Range("$C$46").Value = "Not Applicable" Then
        Me.Tab.ColorIndex = 48
    ElseIf Range("$C$32").Value = "Pass" And Range("$C$46").Value = "Fail" Then
        Me.Tab.Color = vbRed
    ElseIf Range("$C$32").Value = "Fail" And Range("$C$46").Value = "Fail" Or Range("$C$46").Value = "Not Complete" Or Range("$C$46").Value = "Not Applicable" Then
        Me.Tab.Color = vbRed
    ElseIf Range("$C$32").Value = "Fail" And Range("$C$46").Value = "Pass" Then
        Me.Tab.ColorIndex = 10
    ElseIf Range("$C$32").Value = "Not Applicable" And Range("$C$46").Value = "Not Applicable" Or Range("$C$46").Value = "Not Complete" Then
        Me.Tab.ColorIndex = 48
    ElseIf Range("$C$32").Value = "Not Applicable" And Range("$C$46").Value = "Fail" Then
        Me.Tab.Color = vbRed
    ElseIf Range("$C$32").Value = "Not Applicable" And Range("$C$46").Value = "Pass" Then
        Me.Tab.ColorIndex = 10
    ElseIf Range("$C$32").Value = "Not Complete" And Range("$C$46").Value = "Not Applicable" Or Range("$C$46").Value = "Not Complete" Then
         Me.Tab.ColorIndex = 48
    ElseIf Range("$C$32").Value = "Not Complete" And Range("$C$46").Value = "Pass" Then
       Me.Tab.ColorIndex = 10
    ElseIf Range("$C$32").Value = "Not Complete" And Range("$C$46").Value = "Fail" Then
        Me.Tab.Color = vbRed
    End If

End Sub
</code>```

答:
Some remarks:

You are using the SelectionChange event (is that the intention?) if it is, change my code to use it

I organized the code in Select Case Statement which (IMO) is easier to read

I added parenthesis to understand better the options related with C46

Code:

```<code>Option Explicit

Private Sub Worksheet_change(ByVal Target As Range)
    ' Suggest that you define a range to watch when changed for this (un comment and adjust next line if you consider it)
    ' If not intersect(Target, me.Range("c32:c46")) Then Exit sub

    changeColorTab Me, LCase$(Me.Range("c32").Value), LCase$(Me.Range("c46").Value)

End Sub

Private Sub changeColorTab(ByVal targetSheet As Worksheet, ByVal c32Value As String, ByVal c46Value As String)

    Dim targetcolor As Long

    Select Case True
    Case c32Value = "pass" And (c46Value = "pass" Or c46Value = "not complete")
        targetcolor = 10 ' Green
    Case c32Value = "pass" And c46Value = "not applicable"
        targetcolor = 48 ' Dark grey
    Case c32Value = "pass" And (c46Value = "fail")
        targetcolor = 3 ' Red
    Case c32Value = "fail" And (c46Value = "fail" Or c46Value = "not complete" Or c46Value = "not applicable")
        targetcolor = 3 ' Red
    Case c32Value = "fail" And c46Value = "pass"
        targetcolor = 10 ' Green
    Case c32Value = "not applicable" And (c46Value = "not applicable" Or c46Value = "not complete")
        targetcolor = 48 ' Dark grey
    Case c32Value = "not applicable" And c46Value = "fail"
        targetcolor = 3 ' Red
    Case c32Value = "not applicable" And c46Value = "pass"
        targetcolor = 10 ' Green
    Case c32Value = "not complete" And (c46Value = "not applicable" Or c46Value = "not complete")
        targetcolor = 48
    Case c32Value = "not complete" And c46Value = "pass"
        targetcolor = 10
    Case c32Value = "not complete" And c46Value = "fail"
        targetcolor = 3 ' Red
    Case Else
        targetcolor = -4142 ' Light grey
    End Select

    targetSheet.Tab.ColorIndex = targetcolor

End Sub
</code>```

Let me know if it works

Body:
I've trying to change the tab color following a if logic, for cells C32 and C46. Even though the logic is working for most o the logic some does not bring me the right color. I'm not super familiar with VBA.

What is not working:

C32= Fail and C46= Not Complette (brings me green instead of red)
C32= Not applicable and C46= Not Applicable (brings me red instead of gray)
C32= Not applicable and C46= Not Complete (brings me green instead of gray)
C32= Not Complete and C46= Not Complete (brings me green instead of gray)
C32= Not Complete and C46= Not Applicable (brings me red instead of gray)

Please help. It seems simple to fix but could find the solution

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    If Range("$C$32").Value = "Pass" And Range("$C$46").Value = "Pass" Or Range("$C$46").Value = "Not Complete" Then
         Me.Tab.ColorIndex = 10
    ElseIf Range("$C$32").Value = "Pass" And Range("$C$46").Value = "Not Applicable" Then
        Me.Tab.ColorIndex = 48
    ElseIf Range("$C$32").Value = "Pass" And Range("$C$46").Value = "Fail" Then
        Me.Tab.Color = vbRed
    ElseIf Range("$C$32").Value = "Fail" And Range("$C$46").Value = "Fail" Or Range("$C$46").Value = "Not Complete" Or Range("$C$46").Value = "Not Applicable" Then
        Me.Tab.Color = vbRed
    ElseIf Range("$C$32").Value = "Fail" And Range("$C$46").Value = "Pass" Then
        Me.Tab.ColorIndex = 10
    ElseIf Range("$C$32").Value = "Not Applicable" And Range("$C$46").Value = "Not Applicable" Or Range("$C$46").Value = "Not Complete" Then
        Me.Tab.ColorIndex = 48
    ElseIf Range("$C$32").Value = "Not Applicable" And Range("$C$46").Value = "Fail" Then
        Me.Tab.Color = vbRed
    ElseIf Range("$C$32").Value = "Not Applicable" And Range("$C$46").Value = "Pass" Then
        Me.Tab.ColorIndex = 10
    ElseIf Range("$C$32").Value = "Not Complete" And Range("$C$46").Value = "Not Applicable" Or Range("$C$46").Value = "Not Complete" Then
         Me.Tab.ColorIndex = 48
    ElseIf Range("$C$32").Value = "Not Complete" And Range("$C$46").Value = "Pass" Then
       Me.Tab.ColorIndex = 10
    ElseIf Range("$C$32").Value = "Not Complete" And Range("$C$46").Value = "Fail" Then
        Me.Tab.Color = vbRed
    End If

End Sub

Body:
Some remarks:

You are using the SelectionChange event (is that the intention?) if it is, change my code to use it

I organized the code in Select Case Statement which (IMO) is easier to read

I added parenthesis to understand better the options related with C46

Code:

Option Explicit

Private Sub Worksheet_change(ByVal Target As Range)
    ' Suggest that you define a range to watch when changed for this (un comment and adjust next line if you consider it)
    ' If not intersect(Target, me.Range("c32:c46")) Then Exit sub

    changeColorTab Me, LCase$(Me.Range("c32").Value), LCase$(Me.Range("c46").Value)

End Sub

Private Sub changeColorTab(ByVal targetSheet As Worksheet, ByVal c32Value As String, ByVal c46Value As String)

    Dim targetcolor As Long

    Select Case True
    Case c32Value = "pass" And (c46Value = "pass" Or c46Value = "not complete")
        targetcolor = 10 ' Green
    Case c32Value = "pass" And c46Value = "not applicable"
        targetcolor = 48 ' Dark grey
    Case c32Value = "pass" And (c46Value = "fail")
        targetcolor = 3 ' Red
    Case c32Value = "fail" And (c46Value = "fail" Or c46Value = "not complete" Or c46Value = "not applicable")
        targetcolor = 3 ' Red
    Case c32Value = "fail" And c46Value = "pass"
        targetcolor = 10 ' Green
    Case c32Value = "not applicable" And (c46Value = "not applicable" Or c46Value = "not complete")
        targetcolor = 48 ' Dark grey
    Case c32Value = "not applicable" And c46Value = "fail"
        targetcolor = 3 ' Red
    Case c32Value = "not applicable" And c46Value = "pass"
        targetcolor = 10 ' Green
    Case c32Value = "not complete" And (c46Value = "not applicable" Or c46Value = "not complete")
        targetcolor = 48
    Case c32Value = "not complete" And c46Value = "pass"
        targetcolor = 10
    Case c32Value = "not complete" And c46Value = "fail"
        targetcolor = 3 ' Red
    Case Else
        targetcolor = -4142 ' Light grey
    End Select

    targetSheet.Tab.ColorIndex = targetcolor

End Sub

Let me know if it works


问:
NHibernate code completion Visual Studio
I know there is a way to enable code completion for hibernate-mapping files.
But I can't remember how I have to do this.
Can someone help me out pls?</p>

答:
Try copying the following files into: C:\Program Files\Microsoft Visual Studio 9.0\Common7\Packages\schemas\xml, or into C:\Program Files\Microsoft Visual Studio 9.0\Xml\Schemas.

I'm not sure which is the right place and I put them into both of mine but it works for me.

nhibernate-configuration.xsd

nhibernate-generic.xsd

nhibernate-mapping.xsd

You can get the files from the source of nHibernate

OwnerDisplayName: Sem Dendoncker

OwnerDisplayName: Josh

ContentLicense: CC BY-SA 2.5


问:
How to transfer the item ID from the game [World of Warcraft 1.13.3] to my addon?
I want to get the item ID by clicking on it with the mouse pointer with the modifier key or the item ID below the mouse pointer by clicking on the keyboard key.

Or how else can I get the ID of the selected item in my addon?

I found the documentation:

https://wowwiki.fandom.com/wiki/Using_bindings.xml_to_create_key_bindings_for_your_addon

https://wow.gamepedia.com/API_Frame_SetPropagateKeyboardInput

But I don’t understand how to solve my problem.

答:
There are probably better ways to do this, such as displaying the information in a tooltip when you mouseover, but here is a simple solution that basically does what you asked for: displaying the item and its id in the chat window when you shift-click.

This solution creates a listener who checks for the first time you open your bags.  It then attaches code to every slot in your open bag telling it to print the information when shift-clicked.  When this code is printed to slots in your final bag, it also tells the listener to stop functioning so as to avoid wasting CPU resources.

```<code>local listener = CreateFrame("Frame");
listener:SetScript("OnEvent", function()
    for bag=1, 5 do
        for slot=1, GetContainerNumSlots(bag-1) do
            local frame = _G["ContainerFrame" .. bag .. "Item" .. slot];
            if (frame and not frame.isHooked) then
                frame.isHooked = true;
                frame:HookScript("PreClick", function()
                    if (IsShiftKeyDown()) then
                        local itemLink, __, __, itemID = select(7, GetContainerItemInfo(bag - 1, frame:GetID()));
                        if (itemID) then
                            print(itemLink .. " " .. itemID);
                        end
                    end
                end);
                if(bag == 5) then
                    -- stops this from continuing to execute after all bags have been openned at least once.
                    listener:UnregisterEvent("BAG_UPDATE");
                end
            end
        end
    end
end);
listener:RegisterEvent("BAG_UPDATE");
</code>```

References:

GetContainerNumSlots

GetContainerItemInfo

RegisterEvent

UnregisterEvent

Body:
There are probably better ways to do this, such as displaying the information in a tooltip when you mouseover, but here is a simple solution that basically does what you asked for: displaying the item and its id in the chat window when you shift-click.

This solution creates a listener who checks for the first time you open your bags.  It then attaches code to every slot in your open bag telling it to print the information when shift-clicked.  When this code is printed to slots in your final bag, it also tells the listener to stop functioning so as to avoid wasting CPU resources.

local listener = CreateFrame("Frame");
listener:SetScript("OnEvent", function()
    for bag=1, 5 do
        for slot=1, GetContainerNumSlots(bag-1) do
            local frame = _G["ContainerFrame" .. bag .. "Item" .. slot];
            if (frame and not frame.isHooked) then
                frame.isHooked = true;
                frame:HookScript("PreClick", function()
                    if (IsShiftKeyDown()) then
                        local itemLink, __, __, itemID = select(7, GetContainerItemInfo(bag - 1, frame:GetID()));
                        if (itemID) then
                            print(itemLink .. " " .. itemID);
                        end
                    end
                end);
                if(bag == 5) then
                    -- stops this from continuing to execute after all bags have been openned at least once.
                    listener:UnregisterEvent("BAG_UPDATE");
                end
            end
        end
    end
end);
listener:RegisterEvent("BAG_UPDATE");

References:

GetContainerNumSlots

GetContainerItemInfo

RegisterEvent

UnregisterEvent


问:
Routing problems in CakePHP 4.0.3 'A route matching X could not be found'
I'm making a web app that has a backend REST API written in CakePHP 4.0.3 and a frontend consumer written in Vue.js 2.6.11 using axios 0.19.2 to make requests.

The problem is that I can't call the DELETE method on any of my endpoints and I can't tell whether the problem is in the frontend or backend code.

In the server log it says:

```<code>2020-02-14 10:55:54 Error: [Cake\Routing\Exception\MissingRouteException] A route matching "/meal-plans/14042e24-fa12-49d3-9bbe-91e57847a1c7" could not be found. in /var/www/html/vendor/cakephp/cakephp/src/Routing/RouteCollection.php on line 211
Exception Attributes: array (
  'url' => '/meal-plans/14042e24-fa12-49d3-9bbe-91e57847a1c7',
)
Stack Trace:
- /var/www/html/vendor/cakephp/cakephp/src/Routing/Router.php:227
- /var/www/html/vendor/cakephp/cakephp/src/Routing/Middleware/RoutingMiddleware.php:140
- /var/www/html/vendor/cakephp/cakephp/src/Http/Runner.php:73
- /var/www/html/vendor/cakephp/cakephp/src/Http/Runner.php:58
- /var/www/html/vendor/cakephp/cakephp/src/Http/Server.php:90
- /var/www/html/webroot/index.php:40

Request URL: /meal-plans/14042e24-fa12-49d3-9bbe-91e57847a1c7
Referer URL: http://localhost:8080/
Client IP: 172.19.0.1
</code>```

Realising it's just a routing issue, I type bin/cake routes into the terminal:

```<code>+------------------+-----------------+------------------------------------------------------------------------------------+
| Route name       | URI template    | Defaults                                                                           |
+------------------+-----------------+------------------------------------------------------------------------------------+
| mealplans:index  | /meal-plans     | {"_method":"GET","action":"index","controller":"MealPlans","plugin":null}          |
| mealplans:add    | /meal-plans     | {"_method":"POST","action":"add","controller":"MealPlans","plugin":null}           |
| mealplans:view   | /meal-plans/:id | {"_method":"GET","action":"view","controller":"MealPlans","plugin":null}           |
| mealplans:edit   | /meal-plans/:id | {"_method":["PUT","PATCH"],"action":"edit","controller":"MealPlans","plugin":null} |
| mealplans:delete | /meal-plans/:id | {"_method":"DELETE","action":"delete","controller":"MealPlans","plugin":null}      |
| meals:index      | /meals          | {"_method":"GET","action":"index","controller":"Meals","plugin":null}              |
| meals:add        | /meals          | {"_method":"POST","action":"add","controller":"Meals","plugin":null}               |
| meals:view       | /meals/:id      | {"_method":"GET","action":"view","controller":"Meals","plugin":null}               |
| meals:edit       | /meals/:id      | {"_method":["PUT","PATCH"],"action":"edit","controller":"Meals","plugin":null}     |
| meals:delete     | /meals/:id      | {"_method":"DELETE","action":"delete","controller":"Meals","plugin":null}          |
+------------------+-----------------+------------------------------------------------------------------------------------+
</code>```

But as you can see, it says the routes are loaded.

I wrote a test to see if it could give me any clues. The test should've failed

class MealPlansControllerTest extends TestCase
{
    use IntegrationTestTrait;

    public $fixtures = [
        'app.MealPlans',
        'app.Meals'
    ];

    public function testDelete()
    {
        $this->assertCountRecords(1);

        $this->delete('/meal-plans/14042e24-fa12-49d3-9bbe-91e57847a1c7');
        $this->assertResponseCode(204);

        $this->assertCountRecords(0);
    }

    public function testDeleteInvalid()
    {
        $this->assertCountRecords(1);

        $this->delete('/meal-plans/14042f24-fa12-49d3-9bbe-91e57847a1c7');
        $this->assertResponseCode(404);

        $this->assertCountRecords(1);
    }

    private function assertCountRecords($expected)
    {
        $this->get('/meal-plans');
        $this->assertResponseCode(200);

        $body = json_decode((string) $this->_response->getBody(), true);
        $this->assertArrayHasKey('mealPlans', $body);
        $this->assertEquals($expected, count($body['mealPlans']));
    }

}
```

<p>But both tests passed so it wasn't really helpful at all.</p>

<p>So now I'm stuck. I have no clue whats going on. It's probably something simple but I can't see it.</p>

<p>These are the offending routes:</p>

<pre class="lang-php prettyprint-override"><code>/** @var RouteBuilder $routes */
$routes->setRouteClass(DashedRoute::class);
$routes->scope('/', function (RouteBuilder &$builder) {
    $builder->setExtensions(['json']);
    $builder->resources('MealPlans');
    $builder->resources('Meals');
});
</code>```

This is the controller I'm trying to use:

/**
 * Class MealPlansController
 * @package App\Controller
 *
 * @property MealPlansTable $MealPlans
 */
class MealPlansController extends AppController
{
    public $modelClass = 'MealPlans';

    public function delete($id)
    {
        try {
            $mealPlan = $this->MealPlans->get($id);
        } catch (RecordNotFoundException $e) {
            $this->response = $this->response->withStatus(404, __d('meal_plans', 'delete_404'));
            return $this->render();
        }
        if ($this->MealPlans->delete($mealPlan)) {
            $this->response = $this->response->withStatus(204, __d('meal_plans', 'delete_200'));
        } else {
            $this->response = $this->response->withStatus(500, __d('meal_plans', 'delete_500'));
        }
        return $this->render();
    }
}
```

<p>The frontend call looks like this:</p>

<pre class="lang-js prettyprint-override"><code>deleteMealPlan (mealPlan) {
    axios.delete('http://localhost:11000/meal-plans/' + mealPlan.id)
        .then((response) => {
            console.log(response.statusText);
            this.$store.dispatch('planner/syncMealPlans').then(() => this.$forceUpdate());
        });
}
</code>```

And the endpoint being called looks like http://localhost:11000/meal-plans/14042e24-fa12-49d3-9bbe-91e57847a1c7

I can GET the above endpoint just fine, I haven't tested PUT or PATCH yet.

The only other relevant piece of code is my middleware setup:

$middlewareQueue
    ->add(new ErrorHandlerMiddleware(Configure::read('Error')))
    ->add(new AssetMiddleware([
        'cacheTime' => Configure::read('Asset.cacheTime'),
    ]))
    ->add(new RoutingMiddleware($this))
    ->add(new BodyParserMiddleware(['json' => true]))
    ->add(function (ServerRequest $request, Response $response, $next) {
        // Allow CORS
        return $next($request, $response)
            ->withHeader('Access-Control-Allow-Origin', '*')
            ->withHeader('Access-Control-Allow-Headers', '*')
            ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE');
    });
```

答:
This was a problem with my middleware.

I was aware that web browsers send a pre-flight request and by enabling the CORS headers, I thought I had covered myself.

However

I was allowing all requests to go through regardless of the request method. This would let OPTIONS requests to go through to the router.

When the router tried to parse the request and get the correct route, it would fail to find any routes with OPTIONS defined in the _method option and producing the error.

And that explains why my tests were passing. Since an OPTIONS request was never made, the error never came up.

So the solution is to return early if the request is an OPTIONS request

function (ServerRequest $request, Response $response, $next) {
    if ($request->getMethod() === 'OPTIONS') {
        return $response
            ->withHeader('Access-Control-Allow-Origin', '*')
            ->withHeader('Access-Control-Allow-Headers', '*')
            ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE');
    } else {
        $response = $next($request, $response)
            ->withHeader('Access-Control-Allow-Origin', '*')
            ->withHeader('Access-Control-Allow-Headers', '*')
            ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE');

        return $response;
    }
}
```

Body:
I'm making a web app that has a backend REST API written in CakePHP 4.0.3 and a frontend consumer written in Vue.js 2.6.11 using axios 0.19.2 to make requests.

The problem is that I can't call the DELETE method on any of my endpoints and I can't tell whether the problem is in the frontend or backend code.

In the server log it says:

2020-02-14 10:55:54 Error: [Cake\Routing\Exception\MissingRouteException] A route matching "/meal-plans/14042e24-fa12-49d3-9bbe-91e57847a1c7" could not be found. in /var/www/html/vendor/cakephp/cakephp/src/Routing/RouteCollection.php on line 211
Exception Attributes: array (
  'url' => '/meal-plans/14042e24-fa12-49d3-9bbe-91e57847a1c7',
)
Stack Trace:
- /var/www/html/vendor/cakephp/cakephp/src/Routing/Router.php:227
- /var/www/html/vendor/cakephp/cakephp/src/Routing/Middleware/RoutingMiddleware.php:140
- /var/www/html/vendor/cakephp/cakephp/src/Http/Runner.php:73
- /var/www/html/vendor/cakephp/cakephp/src/Http/Runner.php:58
- /var/www/html/vendor/cakephp/cakephp/src/Http/Server.php:90
- /var/www/html/webroot/index.php:40

Request URL: /meal-plans/14042e24-fa12-49d3-9bbe-91e57847a1c7
Referer URL: http://localhost:8080/
Client IP: 172.19.0.1

Realising it's just a routing issue, I type bin/cake routes into the terminal:

+------------------+-----------------+------------------------------------------------------------------------------------+
| Route name       | URI template    | Defaults                                                                           |
+------------------+-----------------+------------------------------------------------------------------------------------+
| mealplans:index  | /meal-plans     | {"_method":"GET","action":"index","controller":"MealPlans","plugin":null}          |
| mealplans:add    | /meal-plans     | {"_method":"POST","action":"add","controller":"MealPlans","plugin":null}           |
| mealplans:view   | /meal-plans/:id | {"_method":"GET","action":"view","controller":"MealPlans","plugin":null}           |
| mealplans:edit   | /meal-plans/:id | {"_method":["PUT","PATCH"],"action":"edit","controller":"MealPlans","plugin":null} |
| mealplans:delete | /meal-plans/:id | {"_method":"DELETE","action":"delete","controller":"MealPlans","plugin":null}      |
| meals:index      | /meals          | {"_method":"GET","action":"index","controller":"Meals","plugin":null}              |
| meals:add        | /meals          | {"_method":"POST","action":"add","controller":"Meals","plugin":null}               |
| meals:view       | /meals/:id      | {"_method":"GET","action":"view","controller":"Meals","plugin":null}               |
| meals:edit       | /meals/:id      | {"_method":["PUT","PATCH"],"action":"edit","controller":"Meals","plugin":null}     |
| meals:delete     | /meals/:id      | {"_method":"DELETE","action":"delete","controller":"Meals","plugin":null}          |
+------------------+-----------------+------------------------------------------------------------------------------------+

But as you can see, it says the routes are loaded.

I wrote a test to see if it could give me any clues. The test should've failed

class MealPlansControllerTest extends TestCase
{
    use IntegrationTestTrait;

    public $fixtures = [
        'app.MealPlans',
        'app.Meals'
    ];

    public function testDelete()
    {
        $this->assertCountRecords(1);

        $this->delete('/meal-plans/14042e24-fa12-49d3-9bbe-91e57847a1c7');
        $this->assertResponseCode(204);

        $this->assertCountRecords(0);
    }

    public function testDeleteInvalid()
    {
        $this->assertCountRecords(1);

        $this->delete('/meal-plans/14042f24-fa12-49d3-9bbe-91e57847a1c7');
        $this->assertResponseCode(404);

        $this->assertCountRecords(1);
    }

    private function assertCountRecords($expected)
    {
        $this->get('/meal-plans');
        $this->assertResponseCode(200);

        $body = json_decode((string) $this->_response->getBody(), true);
        $this->assertArrayHasKey('mealPlans', $body);
        $this->assertEquals($expected, count($body['mealPlans']));
    }

}

But both tests passed so it wasn't really helpful at all.

So now I'm stuck. I have no clue whats going on. It's probably something simple but I can't see it.

These are the offending routes:

/** @var RouteBuilder $routes */
$routes->setRouteClass(DashedRoute::class);
$routes->scope('/', function (RouteBuilder &$builder) {
    $builder->setExtensions(['json']);
    $builder->resources('MealPlans');
    $builder->resources('Meals');
});

This is the controller I'm trying to use:

/**
 * Class MealPlansController
 * @package App\Controller
 *
 * @property MealPlansTable $MealPlans
 */
class MealPlansController extends AppController
{
    public $modelClass = 'MealPlans';

    public function delete($id)
    {
        try {
            $mealPlan = $this->MealPlans->get($id);
        } catch (RecordNotFoundException $e) {
            $this->response = $this->response->withStatus(404, __d('meal_plans', 'delete_404'));
            return $this->render();
        }
        if ($this->MealPlans->delete($mealPlan)) {
            $this->response = $this->response->withStatus(204, __d('meal_plans', 'delete_200'));
        } else {
            $this->response = $this->response->withStatus(500, __d('meal_plans', 'delete_500'));
        }
        return $this->render();
    }
}

The frontend call looks like this:

deleteMealPlan (mealPlan) {
    axios.delete('http://localhost:11000/meal-plans/' + mealPlan.id)
        .then((response) => {
            console.log(response.statusText);
            this.$store.dispatch('planner/syncMealPlans').then(() => this.$forceUpdate());
        });
}

And the endpoint being called looks like http://localhost:11000/meal-plans/14042e24-fa12-49d3-9bbe-91e57847a1c7

I can GET the above endpoint just fine, I haven't tested PUT or PATCH yet.

The only other relevant piece of code is my middleware setup:

$middlewareQueue
    ->add(new ErrorHandlerMiddleware(Configure::read('Error')))
    ->add(new AssetMiddleware([
        'cacheTime' => Configure::read('Asset.cacheTime'),
    ]))
    ->add(new RoutingMiddleware($this))
    ->add(new BodyParserMiddleware(['json' => true]))
    ->add(function (ServerRequest $request, Response $response, $next) {
        // Allow CORS
        return $next($request, $response)
            ->withHeader('Access-Control-Allow-Origin', '*')
            ->withHeader('Access-Control-Allow-Headers', '*')
            ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE');
    });


问:
General way of ensuring implicit definition always has higher/lower priority
I have a somewhat complex typeclass situation in the following format:

```<code>sealed trait TypeClass[S <: MyType] {
  type Out <: MyType
}

sealed trait LowPriorityTypeClass {
  // Case: OtherTypeClass is NOT defined for the input type S.
  // The output type is the same as the input type.
  implicit def default[S <: MyType]: TypeClass.Aux[S, S] = ???
}

object TypeClass extends LowPriorityTypeClass {
  type Aux[S <: MyType, O <: MyType] = TypeClass[S] { type Out = O }

  // Case: OtherTypeClass is defined for the input type S.
  // The output type is the same as in the OtherTypeClass definition.
  implicit def hasOtherTC[S <: MyType, O <: MyType](
    implicit otherTC: OtherTypeClass.Aux[S, O],
  ): TypeClass.Aux[S, O] = ???
}
</code>```

The default definition was put in the LowPriorityTypeClass trait with the intention of having a lower priority. However, an ambiguity with hasOtherTC still happens for some type S, apparently because the declaration of default is more specific than the declaration of hasOtherTC for that type S.

Is there a general way to ensure that an implicit definition will always have a higher/lower priority than other definition? (My question is not for the specific code above.)

Let me know if posting a more complete sample code would help.

答:
Please see Why is this implicit ambiguity behaviour happening? including comments.

There is no sense in introducing trait LowPriorityTypeClass in this case because anyway implicit default is more specific than hasOtherTC.

There is no general way. You can use type classes Not (shapeless.Refute, implicitbox.Not) or shapeless.LowPriority, implicitbox.Priority or library https://github.com/milessabin/export-hook.

```<code>object TypeClass {
  type Aux[S <: MyType, O <: MyType] = TypeClass[S] {type Out = O}

  implicit def hasOtherTC[S <: MyType, O <: MyType](implicit
                                                    otherTC: OtherTypeClass.Aux[S, O]
                                                   ): TypeClass.Aux[S, O] = ???

  implicit def default[S <: MyType](implicit
                                    noOtherTC: Refute[OtherTypeClass[S]]
                                   ): TypeClass.Aux[S, S] = ???
}
</code>```

Body:
I have a somewhat complex typeclass situation in the following format:

sealed trait TypeClass[S <: MyType] {
  type Out <: MyType
}

sealed trait LowPriorityTypeClass {
  // Case: OtherTypeClass is NOT defined for the input type S.
  // The output type is the same as the input type.
  implicit def default[S <: MyType]: TypeClass.Aux[S, S] = ???
}

object TypeClass extends LowPriorityTypeClass {
  type Aux[S <: MyType, O <: MyType] = TypeClass[S] { type Out = O }

  // Case: OtherTypeClass is defined for the input type S.
  // The output type is the same as in the OtherTypeClass definition.
  implicit def hasOtherTC[S <: MyType, O <: MyType](
    implicit otherTC: OtherTypeClass.Aux[S, O],
  ): TypeClass.Aux[S, O] = ???
}

The default definition was put in the LowPriorityTypeClass trait with the intention of having a lower priority. However, an ambiguity with hasOtherTC still happens for some type S, apparently because the declaration of default is more specific than the declaration of hasOtherTC for that type S.

Is there a general way to ensure that an implicit definition will always have a higher/lower priority than other definition? (My question is not for the specific code above.)

Let me know if posting a more complete sample code would help.

Body:
Please see Why is this implicit ambiguity behaviour happening? including comments.

There is no sense in introducing trait LowPriorityTypeClass in this case because anyway implicit default is more specific than hasOtherTC.

There is no general way. You can use type classes Not (shapeless.Refute, implicitbox.Not) or shapeless.LowPriority, implicitbox.Priority or library https://github.com/milessabin/export-hook.

object TypeClass {
  type Aux[S <: MyType, O <: MyType] = TypeClass[S] {type Out = O}

  implicit def hasOtherTC[S <: MyType, O <: MyType](implicit
                                                    otherTC: OtherTypeClass.Aux[S, O]
                                                   ): TypeClass.Aux[S, O] = ???

  implicit def default[S <: MyType](implicit
                                    noOtherTC: Refute[OtherTypeClass[S]]
                                   ): TypeClass.Aux[S, S] = ???
}