问:
Sharepoint c# retrieve all site and subsite
I'am trying to retrieve all site and subsite in sharepoint but i get access denied.

I read about to use GetSubwebsForCurrentUser() property, but i get the same message.

My code is the next

```<code>            foreach (SPWebApplication webApp in SPWebService.ContentService.WebApplications)
            {
                foreach (SPSite siteCollection in webApp.Sites)
                {
                    foreach(SPWeb web in siteCollection.RootWeb.GetSubwebsForCurrentUser())
                    {
                       dropDownSite.Items.Add(web.Url);
                    }

                }
            }
</code>```

please i need help! Thanks!

答:
You will probably need to call SPSecurity.RunWithElevatedPrivileges(delegate())

You could do an inline delegate if you wish, something like:

```<code>SPSecurity.RunWithElevatedPrivileges(delegate()
{
    foreach (SPWebApplication webApp in SPWebService.ContentService.WebApplications)
    {
        foreach (SPSite siteCollection in webApp.Sites)
        {
            foreach(SPWeb web in siteCollection.RootWeb.GetSubwebsForCurrentUser())
            {
                 dropDownSite.Items.Add(web.Url);
            }
        }
    }
});
</code>```

Body:
I'am trying to retrieve all site and subsite in sharepoint but i get access denied.

I read about to use GetSubwebsForCurrentUser() property, but i get the same message.

My code is the next

            foreach (SPWebApplication webApp in SPWebService.ContentService.WebApplications)
            {
                foreach (SPSite siteCollection in webApp.Sites)
                {
                    foreach(SPWeb web in siteCollection.RootWeb.GetSubwebsForCurrentUser())
                    {
                       dropDownSite.Items.Add(web.Url);
                    }

                }
            }

please i need help! Thanks!

Body:
You will probably need to call SPSecurity.RunWithElevatedPrivileges(delegate())

You could do an inline delegate if you wish, something like:

SPSecurity.RunWithElevatedPrivileges(delegate()
{
    foreach (SPWebApplication webApp in SPWebService.ContentService.WebApplications)
    {
        foreach (SPSite siteCollection in webApp.Sites)
        {
            foreach(SPWeb web in siteCollection.RootWeb.GetSubwebsForCurrentUser())
            {
                 dropDownSite.Items.Add(web.Url);
            }
        }
    }
});


来源: stackexchange

问:
batch script move files with the same extension, not on parent-sub path to another directory
based on this question

I want to move ( not copy) files with a specific extension to another folder which is not a sub or the parent. The hierarchy is as follows

 I need the path to be relative, file names unknown,
The batch file will be in the same folder "source" , the files I want to move all are of a particular extension.

I have tried this in a .bat file:

```<code>move cd %~dp0\*.txt cd %~dpi\dest
</code>```

as well as this

```<code>move  %~dp0\*.txt %~dpi\dest
</code>```

and this

```<code>move  %~dp0\*.txt %~dp0\dest
</code>```

I have also tried running the .bat when it is in the parent folder with

```<code>move %~dp0\source\*.json %~dp0\dest
</code>```

none give any error, and the files are not moved from the source folder

答:
It should just be

```<code>move *.txt ..\dest
</code>```

if you're standing in source and want to move to dest.

ContentLicense: CC BY-SA 4.0

Body:
based on this question

I want to move ( not copy) files with a specific extension to another folder which is not a sub or the parent. The hierarchy is as follows

 I need the path to be relative, file names unknown,
The batch file will be in the same folder "source" , the files I want to move all are of a particular extension.

I have tried this in a .bat file:

move cd %~dp0\*.txt cd %~dpi\dest

as well as this

move  %~dp0\*.txt %~dpi\dest

and this

move  %~dp0\*.txt %~dp0\dest

I have also tried running the .bat when it is in the parent folder with

move %~dp0\source\*.json %~dp0\dest

none give any error, and the files are not moved from the source folder

Body:
It should just be

move *.txt ..\dest

if you're standing in source and want to move to dest.


问:
traefik - HTTP to HTTPS WWW Redirect
I could not find a question similar to this, there were others mentioning https redirects, but not about minimizing the redirects.

Been looking for a solution, and could not sort it out yet.

We use Docker > Traefik for WordPress and have www as the preferred version for WordPress. There are multiple WP instances. Domains are added dynamically.

However, with this config, I am receiving two redirects, from http to https to https www

```<code>http://example.com/
https://example.com/
https://www.example.com/
</code>```

Is there any way to minimize the redirect?

ideally a 301 redirect from

```<code>http://example.com directly to https://www.example.com
</code>```

Traefik config file as follows

defaultEntryPoints = ["http", "https"]

[web]
address = ":8080"

[entryPoints]

[entryPoints.http]
address = ":80"
[entryPoints.http.redirect]
entryPoint = "https"

[entryPoints.https]
address = ":443"
compress = true
[entryPoints.https.tls]

[acme]
email = "email@domain.com"
storage = "acme.json"
entryPoint = "https"
onDemand = false
OnHostRule = true

[docker]
endpoint = "unix:///var/run/docker.sock"
domain = "traefik.example.com"
watch = true
exposedbydefault = false```

答:
This is how I got it to work with docker provider behind AWS ELB.

traefik container

```<code>/usr/bin/docker run --rm \
  --name traefik \
  -p 5080:80 \
  -p 5443:443 \
  -v /etc/traefik/traefik.toml:/etc/traefik/traefik.toml \
  -v /var/run/docker.sock:/var/run/docker.sock \
  traefik
</code>```

traefik.toml

```<code>defaultEntryPoints = ["http", "https"]

[entryPoints]
  [entryPoints.http]
    address = ":80"

  [entryPoints.https]
    address = ":443"
</code>```

docker labels

```<code>  -l traefik.enable=true \
  -l traefik.http.middlewares.redirect.redirectregex.regex="^http://(.*)" \
  -l traefik.http.middlewares.redirect.redirectregex.replacement="https://\$1" \
  -l traefik.http.routers.web-redirect.rule="Host(\`domain.com\`)" \
  -l traefik.http.routers.web-redirect.entrypoints="http" \
  -l traefik.http.routers.web-redirect.middlewares="redirect" \
  -l traefik.http.routers.web-secure.rule="Host(\`domain.com\`)" \
  -l traefik.http.routers.web-secure.entrypoints="https" \
</code>```

ELB listeners

ContentLicense: CC BY-SA 3.0

Title: traefik - HTTP to HTTPS WWW Redirect

Body:
I could not find a question similar to this, there were others mentioning https redirects, but not about minimizing the redirects.

Been looking for a solution, and could not sort it out yet.

We use Docker > Traefik for WordPress and have www as the preferred version for WordPress. There are multiple WP instances. Domains are added dynamically.

However, with this config, I am receiving two redirects, from http to https to https www

http://example.com/
https://example.com/
https://www.example.com/

Is there any way to minimize the redirect?

ideally a 301 redirect from

http://example.com directly to https://www.example.com

Traefik config file as follows

defaultEntryPoints = ["http", "https"]

[web]
address = ":8080"

[entryPoints]

[entryPoints.http]
address = ":80"
[entryPoints.http.redirect]
entryPoint = "https"

[entryPoints.https]
address = ":443"
compress = true
[entryPoints.https.tls]

[acme]
email = "email@domain.com"
storage = "acme.json"
entryPoint = "https"
onDemand = false
OnHostRule = true

[docker]
endpoint = "unix:///var/run/docker.sock"
domain = "traefik.example.com"
watch = true
exposedbydefault = false

Body:
This is how I got it to work with docker provider behind AWS ELB.

traefik container

/usr/bin/docker run --rm \
  --name traefik \
  -p 5080:80 \
  -p 5443:443 \
  -v /etc/traefik/traefik.toml:/etc/traefik/traefik.toml \
  -v /var/run/docker.sock:/var/run/docker.sock \
  traefik

traefik.toml

defaultEntryPoints = ["http", "https"]

[entryPoints]
  [entryPoints.http]
    address = ":80"

  [entryPoints.https]
    address = ":443"

docker labels

  -l traefik.enable=true \
  -l traefik.http.middlewares.redirect.redirectregex.regex="^http://(.*)" \
  -l traefik.http.middlewares.redirect.redirectregex.replacement="https://\$1" \
  -l traefik.http.routers.web-redirect.rule="Host(\`domain.com\`)" \
  -l traefik.http.routers.web-redirect.entrypoints="http" \
  -l traefik.http.routers.web-redirect.middlewares="redirect" \
  -l traefik.http.routers.web-secure.rule="Host(\`domain.com\`)" \
  -l traefik.http.routers.web-secure.entrypoints="https" \

ELB listeners


问:
Embed message loop doesnt stop
If I type pingtest, my bot is sending the embed message over and over again (infinite loop)</p>

```<code>if (message.content='pingtest') {
    message.channel.send({embed: {

            color: 000000,
            author: {
              name: client.user.username,
              icon_url: client.user.avatarURL
            },
            title: "A RAID HAS BEGUN (for the Dark Side)",
            description: "",
            fields: [{
                name: "------------------------------",
                value:"Write !raid to enter."
              }

            ],
            footer: {
              icon_url: client.user.avatarURL,
            }
          }
        });
}
</code>```

答:
Problem: In your if statement, you're using the assignment operator, =.

Solution: Use an equality operator (i.e. ===) to compare message.content instead.

Explanation: Right now, your code is setting message.content instead of comparing it. This means that no matter what message.content is, you're receiving the intended result of "pingtest." As for the looping, I'm going to guess that you're allowing messages from other bots in your message event. Therefore, when the bot sees its own message, it triggers the same faulty code again, creating a chain reaction.

Revised Code:

if (message.author.bot) return; // bots will no longer trigger a command

if (message.content === 'pingtest') { // comparing message.content with ===
  // < your code for the 'pingtest' command >
}
```

Title: Embed message loop doesnt stop

Body:
If I type pingtest, my bot is sending the embed message over and over again (infinite loop)

if (message.content='pingtest') {
    message.channel.send({embed: {

            color: 000000,
            author: {
              name: client.user.username,
              icon_url: client.user.avatarURL
            },
            title: "A RAID HAS BEGUN (for the Dark Side)",
            description: "",
            fields: [{
                name: "------------------------------",
                value:"Write !raid to enter."
              }

            ],
            footer: {
              icon_url: client.user.avatarURL,
            }
          }
        });
}


问:
How to switch on CodeLens in Visual Studio 2017?
I have installed Microsoft Visual Studio Community 2017.
I cannot find any option to switch on CodeLens. Is this feature removed from this version?</p>

答:
CodeLens is now available since VS 2017 Community Update 8, but it only contains Requests and Exceptions of Application Insights, no References:

From Dante Gagne [MSFT] on Oct 31, 2018 at 05:38 PM:

The infrastructure for CodeLens has been released in the Visual Studio 2017 Update 8. Please install and let us know your feedback. Please continue to provide feedback and help us make Visual Studio even better.

Source

It can be enabled in the Text Editor Options under All Languages --> CodeLens --> Enable CodeLens


问:
Return instance of generic type
I wrote a generic class and want to crate its instance from a static method. The problem is that I can’t create generic instance of the object. I know that it sounds confusing and it is better to show the code.

```<code>public class Parameter<T> : IParameter<T>
{
    public string Name { get; set; }
    public T Value { get; set; }

    public bool IsValid()
    {
        if (String.IsNullOrEmpty(Name))
            return false;

        return (typeof(T) == typeof(String)) ||
               typeof(T) == typeof(bool) ||
               typeof(T) == typeof(int) ||
               typeof(T) == typeof(double);
    }

    public XElement ToXml()
    {
        if (!IsValid())
            throw new InvalidParameterException();

        var xElement = new XElement("Parameter", Value,
                                    new XAttribute("Type", typeof (T)),
                                    new XAttribute("Name", Name));
        return xElement;
    }

    public static Parameter<T> FromXml(XElement xElement)
    {
        var sType = xElement.Attributes()
                    .Where(attribute => attribute.Name == "Type")
                    .Single().Name.ToString();
        var name = xElement.Attributes()
                                .Where(attribute => attribute.Name == "Name")
                                .Single().Name.ToString();
        var sValue = xElement.Value;//need to use this
        var typeVar = Type.GetType(sType);// and this to create proper instance of Parameter<T>

        //I need somehow set T equal to typeVar here and Set
        return new Parameter<T>() {Name = name};//this is wrong.
        //I need return either Parameter<int> or Paramter<double> or Parameter<string> or Parameter<bool>
        //basing on typeVar
    }
}
</code>```

I'm not sure if this possible at all... but looks like it is trivial object design requirement. Any ideas?
Thanks!

UPD: I'm using .NET 4.0. Does it make any difference? :)

UPD2: Looking at the problem now I see that this is a silly question. And it is impossible to return such "generic" objects.

答:
As Indicated by SLaks, this is impossible. Think of it this way,

```<code>Parameter<???> value = Parameter<???>.FromXml(...);
</code>```

How will you ever resolve what the questionmarks should be when it depends on the content of the XmlElement?

You should use a common class which both captures Value as an object and exposes type information.

Title: Return instance of generic type

Body:
I wrote a generic class and want to crate its instance from a static method. The problem is that I can’t create generic instance of the object. I know that it sounds confusing and it is better to show the code.

public class Parameter<T> : IParameter<T>
{
    public string Name { get; set; }
    public T Value { get; set; }

    public bool IsValid()
    {
        if (String.IsNullOrEmpty(Name))
            return false;

        return (typeof(T) == typeof(String)) ||
               typeof(T) == typeof(bool) ||
               typeof(T) == typeof(int) ||
               typeof(T) == typeof(double);
    }

    public XElement ToXml()
    {
        if (!IsValid())
            throw new InvalidParameterException();

        var xElement = new XElement("Parameter", Value,
                                    new XAttribute("Type", typeof (T)),
                                    new XAttribute("Name", Name));
        return xElement;
    }

    public static Parameter<T> FromXml(XElement xElement)
    {
        var sType = xElement.Attributes()
                    .Where(attribute => attribute.Name == "Type")
                    .Single().Name.ToString();
        var name = xElement.Attributes()
                                .Where(attribute => attribute.Name == "Name")
                                .Single().Name.ToString();
        var sValue = xElement.Value;//need to use this
        var typeVar = Type.GetType(sType);// and this to create proper instance of Parameter<T>

        //I need somehow set T equal to typeVar here and Set
        return new Parameter<T>() {Name = name};//this is wrong.
        //I need return either Parameter<int> or Paramter<double> or Parameter<string> or Parameter<bool>
        //basing on typeVar
    }
}

I'm not sure if this possible at all... but looks like it is trivial object design requirement. Any ideas?
Thanks!

UPD: I'm using .NET 4.0. Does it make any difference? :)

UPD2: Looking at the problem now I see that this is a silly question. And it is impossible to return such "generic" objects.

Body:
As Indicated by SLaks, this is impossible. Think of it this way,

Parameter<???> value = Parameter<???>.FromXml(...);

How will you ever resolve what the questionmarks should be when it depends on the content of the XmlElement?

You should use a common class which both captures Value as an object and exposes type information.


问:
Laravel - Get value from an object
I have an PHP object coming back from an API. The following is dd($token):

```<code>OAuth2AccessToken {#559 ▼
  -accessTokenKey: "eyJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwiYWxn8F2X3MBCZYY1g7Do66LIK"
  -tokenType: "bearer"
  -refresh_token: "Q01156b975259zYyAN03aS8lf6YfRcYFK26w2xCvPu75zf0B9F"
  -accessTokenExpiresAt: 1559257067
  -refreshTokenExpiresAt: 1567975300
  -accessTokenValidationPeriod: 3600
  -refreshTokenValidationPeriod: 8751833
  -clientID: "Q06uUceuP2dpIJVmmqbWztlZ73dtb9Qd2shjbiKhkGt7lsimR"
  -clientSecret: "RD0fS7xiRNsmbwSBBXvgU3wsqtyNPy63DfoGq2"
  -realmID: "1385384240"
  -baseURL: "https://quickbooks.api.intuit.com/"
}
</code>```

How do I get the key "accessTokenKey" into a variable?

I have tried:

```<code>$token->accessTokenKey;
</code>```

or

```<code>$token['accessTokenKey'];
</code>```

I get error "Cannot access private property"

答:
You can use \ReflectionClass class

```<code>public function get_private_attribute_of($object, $property)
{
    $reflection = new \ReflectionClass($object);
    $property = $reflection->getProperty($property);
    $property->setAccessible(true);
    return $property->getValue($object);
}
</code>```

usage:

```<code>get_private_attribute_of($token, 'accessTokenKey');
</code>```

or can use dd(get_class_methods($object)) for now all available methods name and select needed method

Title: Laravel - Get value from an object

Body:
I have an PHP object coming back from an API. The following is dd($token):

OAuth2AccessToken {#559 ▼
  -accessTokenKey: "eyJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwiYWxn8F2X3MBCZYY1g7Do66LIK"
  -tokenType: "bearer"
  -refresh_token: "Q01156b975259zYyAN03aS8lf6YfRcYFK26w2xCvPu75zf0B9F"
  -accessTokenExpiresAt: 1559257067
  -refreshTokenExpiresAt: 1567975300
  -accessTokenValidationPeriod: 3600
  -refreshTokenValidationPeriod: 8751833
  -clientID: "Q06uUceuP2dpIJVmmqbWztlZ73dtb9Qd2shjbiKhkGt7lsimR"
  -clientSecret: "RD0fS7xiRNsmbwSBBXvgU3wsqtyNPy63DfoGq2"
  -realmID: "1385384240"
  -baseURL: "https://quickbooks.api.intuit.com/"
}

How do I get the key "accessTokenKey" into a variable?

I have tried:

$token->accessTokenKey;

or

$token['accessTokenKey'];

I get error "Cannot access private property"

Body:
You can use \ReflectionClass class

public function get_private_attribute_of($object, $property)
{
    $reflection = new \ReflectionClass($object);
    $property = $reflection->getProperty($property);
    $property->setAccessible(true);
    return $property->getValue($object);
}

usage:

get_private_attribute_of($token, 'accessTokenKey');

or can use dd(get_class_methods($object)) for now all available methods name and select needed method


问:
Facing Problem while returning object in response Example in Swashbuckle.Examples
I'm using Swashbuckle.Examples in Web API for better documentation. It is working fine for Swashbuckle Sample response but when I'm using Sample Example
When I run the project it is showing an Error.

My controller

```<code> [SwaggerResponse(HttpStatusCode.OK, Type = typeof(IEnumerable<ReasonReponsesuccessMessage_list>))]
 [SwaggerResponseExample(HttpStatusCode.OK, typeof(IEnumerable<ReasonReponseSuccessExample_list>))]
 [SwaggerResponse(HttpStatusCode.BadRequest, Type = typeof(IEnumerable<ReponseEmptyMessage>))]
 [SwaggerOperation("List reasons")]
 [ActionName("Reasons")]
 [Route("api/{Id}")]
 [HttpGet]
 public HttpResponseMessage GetReasons(string Id)
 {
 }
</code>```

Response Example Class

```<code>  public class ReasonReponseSuccessExample_list : IExamplesProvider
    {
        object IExamplesProvider.GetExamples()
        {
            ReasonReponsesuccessMessage_list ReasonReponsesuccessMessage_list = new ReasonReponsesuccessMessage_list();

            ReasonReponsesuccessMessage_list.Message = "Success";
            ReasonReponsesuccessMessage_list.Data = new List<tbl_reason>
            {
                new tbl_reason{ id="SAA133",primary_name="Wrong Invoice",alt_name="Wrong Invoice"},
                new tbl_reason{ id="B97123",primary_name="Payment Problem",alt_name=""}
            };
            ReasonReponsesuccessMessage_list.Extras = "";
            ReasonReponsesuccessMessage_list.Success = true;
            return ReasonReponsesuccessMessage_list;
        }
    }
</code>```

ERROR:

Expected examplesProviderType to implement
  Swashbuckle.Examples.IExamplesProvider.
  System.Collections.Generic.IEnumerable`1[IgniteAPI.Payload.ReasonReponseSuccessExample_list]
  does not.

I'm Getting this error in global.asmx

GlobalConfiguration.Configure(WebApiConfig.Register);

答:
As you can see in the error, you need to specify type that implements
 IExamplesProvider

Use

```<code>[SwaggerResponseExample(HttpStatusCode.OK, typeof(ReasonReponseSuccessExample_list))]
</code>```

instead of

```<code>[SwaggerResponseExample(HttpStatusCode.OK, typeof(IEnumerable<ReasonReponseSuccessExample_list>))]
</code>```

Body:
I'm using Swashbuckle.Examples in Web API for better documentation. It is working fine for Swashbuckle Sample response but when I'm using Sample Example
When I run the project it is showing an Error.

My controller

 [SwaggerResponse(HttpStatusCode.OK, Type = typeof(IEnumerable<ReasonReponsesuccessMessage_list>))]
 [SwaggerResponseExample(HttpStatusCode.OK, typeof(IEnumerable<ReasonReponseSuccessExample_list>))]
 [SwaggerResponse(HttpStatusCode.BadRequest, Type = typeof(IEnumerable<ReponseEmptyMessage>))]
 [SwaggerOperation("List reasons")]
 [ActionName("Reasons")]
 [Route("api/{Id}")]
 [HttpGet]
 public HttpResponseMessage GetReasons(string Id)
 {
 }

Response Example Class

  public class ReasonReponseSuccessExample_list : IExamplesProvider
    {
        object IExamplesProvider.GetExamples()
        {
            ReasonReponsesuccessMessage_list ReasonReponsesuccessMessage_list = new ReasonReponsesuccessMessage_list();

            ReasonReponsesuccessMessage_list.Message = "Success";
            ReasonReponsesuccessMessage_list.Data = new List<tbl_reason>
            {
                new tbl_reason{ id="SAA133",primary_name="Wrong Invoice",alt_name="Wrong Invoice"},
                new tbl_reason{ id="B97123",primary_name="Payment Problem",alt_name=""}
            };
            ReasonReponsesuccessMessage_list.Extras = "";
            ReasonReponsesuccessMessage_list.Success = true;
            return ReasonReponsesuccessMessage_list;
        }
    }

ERROR:

Expected examplesProviderType to implement
  Swashbuckle.Examples.IExamplesProvider.
  System.Collections.Generic.IEnumerable`1[IgniteAPI.Payload.ReasonReponseSuccessExample_list]
  does not.

I'm Getting this error in global.asmx

GlobalConfiguration.Configure(WebApiConfig.Register);

Body:
As you can see in the error, you need to specify type that implements
 IExamplesProvider

Use

[SwaggerResponseExample(HttpStatusCode.OK, typeof(ReasonReponseSuccessExample_list))]

instead of

[SwaggerResponseExample(HttpStatusCode.OK, typeof(IEnumerable<ReasonReponseSuccessExample_list>))]


问:
Tkinter GUI freezes while running looping
I'm new to python coding and I have been working on a project which could click on an image based on a chosen color. I have been using a program which loops the search 50 times when I click the start button. However, I have been trying to implement a stop button, but the problem is that my code freezes when the loop is running. Any ideas?

I have heard to try threading but it seems very complicated and I have been unable to follow any tutorials properly in relation to my code. By the way, the image searched has been testing images I've been using stored inside the program files.

```<code>from imagesearch import *
import pyautogui
import tkinter as tk
from tkinter import *
from tkinter.ttk import *
import time
import threading

# ---Defined Programs---
def run():
    global enterColor
    enterColor = str(enterColorField.get())
    program(enterColor)

def program(color):
    whitePos = imagesearch_numLoop(str(color) + ".PNG", 0, 50)
    pyautogui.moveTo(whitePos[0] + 20, whitePos[1] + 10)
    pyautogui.click()

def stop():
    print("Placeholder")

# ---Main Runner---
window = tk.Tk()
window.geometry("250x250")
window.configure(background="#181b54")

app = tk.Frame(window)
app.grid()

enterColorLabel = tk.Label(window, text="Enter Color:", bg="#181b54", fg="white")
enterColorLabel.place(x=10, y=50)

enterColorField = Combobox(window)
enterColorField['values'] = ("Black", "White")
enterColorField.current("0")  # set the selected item
enterColorField.place(x=10, y=70)

submitButton = tk.Button(window, text="Start", bg="#66ff00", command=run)
submitButton.place(x=10, y=130)

stopButton = tk.Button(window, text="Stop", bg="red", command=stop)
stopButton.place(x=50, y=130)

window.mainloop()

#---New Python Script---
import cv2
import numpy as np
import pyautogui
import random
import time

def imagesearch_numLoop(image, timesample, maxSamples, precision=0.8):
    pos = imagesearch(image, precision)
    count = 0
    while pos[0] == -1:
        print(image+" not found, waiting")
        count = count + 1
        if count>maxSamples:
            break
        pos = imagesearch(image, precision)
    return pos
</code>```

Whenever clicking start, the whole code freezes. I can't even (x) out.

答:
Here's a hopefully simple multiprocessing recipe that will work for you. We'll have three main functions. The first will be an example loop that you would put your processing inside. I included arguments in the function to show you that it's possible to pass args and kwargs while using multiprocessing.

def loop(a, b, c, d):
     # Will just sleep for 3 seconds.. simulates whatever processing you do.
    time.sleep(3)
    return
```

<p>Next is a function we will use to queue the multiprocessing process.</p>

<pre class="lang-py prettyprint-override"><code>def queue_loop():
    p = multiprocessing.Process(target = loop,
                                args = (1, 2),
                                kwargs = {"c": 3, "d": 4})
    # You can pass args and kwargs to the target function like that
    # Note that the process isn't started yet. You call p.start() to activate it.
    p.start()
    check_status(p) # This is the next function we'll define.
    return
</code>```

Then, you may be interested in knowing the status of your process throughout its execution. For example it is sometimes desirable to disable certain buttons while a command is being run.

def check_status(p):
    """ p is the multiprocessing.Process object """
    if p.is_alive(): # Then the process is still running
        label.config(text = "MP Running")
        mp_button.config(state = "disabled")
        not_mp_button.config(state = "disabled")
        root.after(200, lambda p=p: check_status(p)) # After 200 ms, it will check the status again.
    else:
        label.config(text = "MP Not Running")
        mp_button.config(state = "normal")
        not_mp_button.config(state = "normal")
    return
```

<p>Throwing this all together into one snippet:</p>

<pre class="lang-py prettyprint-override"><code>import tkinter as tk
import multiprocessing
import time

def loop(a, b, c, d):
     # Will just sleep for 3 seconds.. simulates whatever processing you do.
    time.sleep(3)
    return

def queue_loop():
    p = multiprocessing.Process(target = loop,
                                args = (1, 2),
                                kwargs = {"c": 3, "d": 4})
    # You can pass args and kwargs to the target function like that
    # Note that the process isn't started yet. You call p.start() to activate it.
    p.start()
    check_status(p) # This is the next function we'll define.
    return

def check_status(p):
    """ p is the multiprocessing.Process object """
    if p.is_alive(): # Then the process is still running
        label.config(text = "MP Running")
        mp_button.config(state = "disabled")
        not_mp_button.config(state = "disabled")
        root.after(200, lambda p=p: check_status(p)) # After 200 ms, it will check the status again.
    else:
        label.config(text = "MP Not Running")
        mp_button.config(state = "normal")
        not_mp_button.config(state = "normal")
    return

if __name__ == "__main__":
    root = tk.Tk()
    mp_button = tk.Button(master = root, text = "Using MP", command = queue_loop)
    mp_button.pack()
    label = tk.Label(master = root, text = "MP Not Running")
    label.pack()
    not_mp_button = tk.Button(master = root, text = "Not MP", command = lambda: loop(1,2,3,4))
    not_mp_button.pack()
    root.mainloop()
</code>```

The result is that when you click the "Using MP" button, the command buttons will be disabled and the process will be started without freezing your UI. Clicking the "Not MP" button will start the function like 'normal' and will freeze your UI as you noticed in your own code.

Body:
I'm new to python coding and I have been working on a project which could click on an image based on a chosen color. I have been using a program which loops the search 50 times when I click the start button. However, I have been trying to implement a stop button, but the problem is that my code freezes when the loop is running. Any ideas?

I have heard to try threading but it seems very complicated and I have been unable to follow any tutorials properly in relation to my code. By the way, the image searched has been testing images I've been using stored inside the program files.

from imagesearch import *
import pyautogui
import tkinter as tk
from tkinter import *
from tkinter.ttk import *
import time
import threading

# ---Defined Programs---
def run():
    global enterColor
    enterColor = str(enterColorField.get())
    program(enterColor)

def program(color):
    whitePos = imagesearch_numLoop(str(color) + ".PNG", 0, 50)
    pyautogui.moveTo(whitePos[0] + 20, whitePos[1] + 10)
    pyautogui.click()

def stop():
    print("Placeholder")

# ---Main Runner---
window = tk.Tk()
window.geometry("250x250")
window.configure(background="#181b54")

app = tk.Frame(window)
app.grid()

enterColorLabel = tk.Label(window, text="Enter Color:", bg="#181b54", fg="white")
enterColorLabel.place(x=10, y=50)

enterColorField = Combobox(window)
enterColorField['values'] = ("Black", "White")
enterColorField.current("0")  # set the selected item
enterColorField.place(x=10, y=70)

submitButton = tk.Button(window, text="Start", bg="#66ff00", command=run)
submitButton.place(x=10, y=130)

stopButton = tk.Button(window, text="Stop", bg="red", command=stop)
stopButton.place(x=50, y=130)

window.mainloop()

#---New Python Script---
import cv2
import numpy as np
import pyautogui
import random
import time

def imagesearch_numLoop(image, timesample, maxSamples, precision=0.8):
    pos = imagesearch(image, precision)
    count = 0
    while pos[0] == -1:
        print(image+" not found, waiting")
        count = count + 1
        if count>maxSamples:
            break
        pos = imagesearch(image, precision)
    return pos

Whenever clicking start, the whole code freezes. I can't even (x) out.

Body:
Here's a hopefully simple multiprocessing recipe that will work for you. We'll have three main functions. The first will be an example loop that you would put your processing inside. I included arguments in the function to show you that it's possible to pass args and kwargs while using multiprocessing.

def loop(a, b, c, d):
     # Will just sleep for 3 seconds.. simulates whatever processing you do.
    time.sleep(3)
    return

Next is a function we will use to queue the multiprocessing process.

def queue_loop():
    p = multiprocessing.Process(target = loop,
                                args = (1, 2),
                                kwargs = {"c": 3, "d": 4})
    # You can pass args and kwargs to the target function like that
    # Note that the process isn't started yet. You call p.start() to activate it.
    p.start()
    check_status(p) # This is the next function we'll define.
    return

Then, you may be interested in knowing the status of your process throughout its execution. For example it is sometimes desirable to disable certain buttons while a command is being run.

def check_status(p):
    """ p is the multiprocessing.Process object """
    if p.is_alive(): # Then the process is still running
        label.config(text = "MP Running")
        mp_button.config(state = "disabled")
        not_mp_button.config(state = "disabled")
        root.after(200, lambda p=p: check_status(p)) # After 200 ms, it will check the status again.
    else:
        label.config(text = "MP Not Running")
        mp_button.config(state = "normal")
        not_mp_button.config(state = "normal")
    return

Throwing this all together into one snippet:

import tkinter as tk
import multiprocessing
import time

def loop(a, b, c, d):
     # Will just sleep for 3 seconds.. simulates whatever processing you do.
    time.sleep(3)
    return

def queue_loop():
    p = multiprocessing.Process(target = loop,
                                args = (1, 2),
                                kwargs = {"c": 3, "d": 4})
    # You can pass args and kwargs to the target function like that
    # Note that the process isn't started yet. You call p.start() to activate it.
    p.start()
    check_status(p) # This is the next function we'll define.
    return

def check_status(p):
    """ p is the multiprocessing.Process object """
    if p.is_alive(): # Then the process is still running
        label.config(text = "MP Running")
        mp_button.config(state = "disabled")
        not_mp_button.config(state = "disabled")
        root.after(200, lambda p=p: check_status(p)) # After 200 ms, it will check the status again.
    else:
        label.config(text = "MP Not Running")
        mp_button.config(state = "normal")
        not_mp_button.config(state = "normal")
    return

if __name__ == "__main__":
    root = tk.Tk()
    mp_button = tk.Button(master = root, text = "Using MP", command = queue_loop)
    mp_button.pack()
    label = tk.Label(master = root, text = "MP Not Running")
    label.pack()
    not_mp_button = tk.Button(master = root, text = "Not MP", command = lambda: loop(1,2,3,4))
    not_mp_button.pack()
    root.mainloop()

The result is that when you click the "Using MP" button, the command buttons will be disabled and the process will be started without freezing your UI. Clicking the "Not MP" button will start the function like 'normal' and will freeze your UI as you noticed in your own code.


问:
Get the amount of days between two given days of the week
I want to find out how many days there are between two given days of the week.

This looks to be a case for a well executed slice method; but I just can't get my head around it.

```<code>const days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']

let today = 'Thursday'
let dispatch = 'Monday'
let remaining = '???'

console.log(`${remaining} Days until the next dispatch`)
</code>```

Monday to Thursday is easy enough :

```<code>let remaining = days.slice(days.indexOf('Monday'), days.indexOf('Thursday')).length + 1
</code>```

But Thursday to Monday (for example) needs some logic that I can't figure out.

答:
You can drop the slice and the if and make use of some modulo arithmetics.

const days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']

function getDays(start, end) {
    return (days.indexOf(end) + days.length - days.indexOf(start)) % days.length + 1;
}
console.log(getDays("Monday", "Thursday")); // 4
console.log(getDays("Thursday", "Monday")); // 5```

If you decide you want Monday to Thursday to just be 3 instead of 4 (which might be more natural depending on the context) just drop the +1 from the end.

Body:
I want to find out how many days there are between two given days of the week.

This looks to be a case for a well executed slice method; but I just can't get my head around it.

const days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']

let today = 'Thursday'
let dispatch = 'Monday'
let remaining = '???'

console.log(`${remaining} Days until the next dispatch`)

Monday to Thursday is easy enough :

let remaining = days.slice(days.indexOf('Monday'), days.indexOf('Thursday')).length + 1

But Thursday to Monday (for example) needs some logic that I can't figure out.

Body:
You can drop the slice and the if and make use of some modulo arithmetics.

const days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']

function getDays(start, end) {
    return (days.indexOf(end) + days.length - days.indexOf(start)) % days.length + 1;
}
console.log(getDays("Monday", "Thursday")); // 4
console.log(getDays("Thursday", "Monday")); // 5

If you decide you want Monday to Thursday to just be 3 instead of 4 (which might be more natural depending on the context) just drop the +1 from the end.


问:
PowerShell: group commands together, for redirect output
How to group commands together in PowerShell, for redirect output for e.g.?

Here is what I do in normal Unix shell:

```<code>{ echo a; echo b; echo c; } > testout

$ cat testout
a
b
c
</code>```

All three (different) commands' output are redirect to the same file.

Is that possible in PowerShell?

答:
Another use for $() besides inside strings...</p>

```<code>$(Echo a; Echo b; Echo c) > testout
</code>```

Body:
How to group commands together in PowerShell, for redirect output for e.g.?

Here is what I do in normal Unix shell:

{ echo a; echo b; echo c; } > testout

$ cat testout
a
b
c

All three (different) commands' output are redirect to the same file.

Is that possible in PowerShell?

Body:
Another use for $() besides inside strings...

$(Echo a; Echo b; Echo c) > testout


问:
ObjectMapper can generate a list of invalid types (java8)
This is not so much a question of what's wrong with the code as it is, why does java allow this code to work?

Using com.fasterxml.jackson.databind.ObjectMapper it's possible to create a List populated with data types that should be invalid for the declared list.

I'm telling it to convert a List<Potato> into a List<Potato> and storing the result in List<Tractor>

public class ObjectMapperExample {
    public static void main(String[] args){
        List<Potato> potatoList = new ArrayList<>();
        //add a potato to the potatoList

        List<Tractor> tractorList = new ObjectMapper()
                .convertValue(potatoList, new TypeReference<List<Potato>>() {});
        //add another tractor to the tractorList

        System.out.println(tractorList.getClass());
        System.out.println(tractorList.toString());
        System.out.println(tractorList.get(1).getClass());
        System.out.println(tractorList.get(0).getClass());
    }
}
```

<p>Potato.class</p>

<pre class="lang-java prettyprint-override"><code>public class Potato {
   // properties and getters/setters
}
</code>```

Tractor.class

public class Tractor {
   // properties and getters/setters
}
```

This code actually compiles and runs, up till you try to directly interact with the Potato object in the tractorList.  Resulting output...

class java.util.ArrayList

[Potato@20e2cbe0, Tractor@68be2bc2]

class Tractor

Exception in thread "main" java.lang.ClassCastException: Potato cannot be cast to Tractor     at ObjectMapperExample.main(ObjectMapperExample.java:27)

So the question is, why does java still run this?  Shouldn't a List<Tractor> that has a Potato object as it's first element have thrown an exception somewhere?  It's throwing an exception when accessing the element directly, which makes sense, but how did it manage to create a List with incompatible object types to begin with?

Here's a screenshot of the actual run I did...

答:
Because the ObjectMapper::convertValue is bogus in how the generics were declared:

```<code>public <T> T convertValue(Object fromValue, TypeReference<?> toValueTypeRef)
  throws IllegalArgumentException
public <T> T convertValue(Object fromValue, JavaType toValueType)
  throws IllegalArgumentException
</code>```

There is no relation between T and TypeReference<?>: the compiler infer the real type of T by using the context, and since the context is:

```<code>List<Tractor> tractorList = new ObjectMapper().convertValue(potatoList, new TypeReference<List<Potato>>() {});
</code>```

It tries to infer the type T: List<Tractor> matches and TypeReference<List<Potato>> matches TypeReference<?>: the TypeReference may be completely unrelated to the output type which is why it was able to create a list of Potato. And since the type erasure kicks in, this is possible in the virtual machine.

It seems the same apply for the method using JavaType.

The other using Class<T> would not apply in your case in your case because you can't do List<Tractor>.class.

[edit] if you wish to reproduce same kind of issues, then you can do that:

```<code>List<Potato> potatoes = asList(new Potato());
List<Tractor> tractors = badStuff(potatoes);

private static <T> T badStuff(Object value) {
  return (T) value; // should raise a warning due to the cast
}
</code>```

T is inferred from the context and in that context, this would be List<Tractor>. Some compiler might choke on this (Javac may accept this while Eclipse Compiler won't and vice versa) and require to precise the type:

```<code>List<Tractor> tractors = MyType.<List<Tractor>>badStuff(potatoes);
</code>```

If you wish to look more in depth, this would probably help: type inference.

Body:
This is not so much a question of what's wrong with the code as it is, why does java allow this code to work?

Using com.fasterxml.jackson.databind.ObjectMapper it's possible to create a List populated with data types that should be invalid for the declared list.

I'm telling it to convert a List<Potato> into a List<Potato> and storing the result in List<Tractor>

public class ObjectMapperExample {
    public static void main(String[] args){
        List<Potato> potatoList = new ArrayList<>();
        //add a potato to the potatoList

        List<Tractor> tractorList = new ObjectMapper()
                .convertValue(potatoList, new TypeReference<List<Potato>>() {});
        //add another tractor to the tractorList

        System.out.println(tractorList.getClass());
        System.out.println(tractorList.toString());
        System.out.println(tractorList.get(1).getClass());
        System.out.println(tractorList.get(0).getClass());
    }
}

Potato.class

public class Potato {
   // properties and getters/setters
}

Tractor.class

public class Tractor {
   // properties and getters/setters
}

This code actually compiles and runs, up till you try to directly interact with the Potato object in the tractorList.  Resulting output...

class java.util.ArrayList

[Potato@20e2cbe0, Tractor@68be2bc2]

class Tractor

Exception in thread "main" java.lang.ClassCastException: Potato cannot be cast to Tractor     at ObjectMapperExample.main(ObjectMapperExample.java:27)

So the question is, why does java still run this?  Shouldn't a List<Tractor> that has a Potato object as it's first element have thrown an exception somewhere?  It's throwing an exception when accessing the element directly, which makes sense, but how did it manage to create a List with incompatible object types to begin with?

Here's a screenshot of the actual run I did...

Body:
Because the ObjectMapper::convertValue is bogus in how the generics were declared:

public <T> T convertValue(Object fromValue, TypeReference<?> toValueTypeRef)
  throws IllegalArgumentException
public <T> T convertValue(Object fromValue, JavaType toValueType)
  throws IllegalArgumentException

There is no relation between T and TypeReference<?>: the compiler infer the real type of T by using the context, and since the context is:

List<Tractor> tractorList = new ObjectMapper().convertValue(potatoList, new TypeReference<List<Potato>>() {});

It tries to infer the type T: List<Tractor> matches and TypeReference<List<Potato>> matches TypeReference<?>: the TypeReference may be completely unrelated to the output type which is why it was able to create a list of Potato. And since the type erasure kicks in, this is possible in the virtual machine.

It seems the same apply for the method using JavaType.

The other using Class<T> would not apply in your case in your case because you can't do List<Tractor>.class.

[edit] if you wish to reproduce same kind of issues, then you can do that:

List<Potato> potatoes = asList(new Potato());
List<Tractor> tractors = badStuff(potatoes);

private static <T> T badStuff(Object value) {
  return (T) value; // should raise a warning due to the cast
}

T is inferred from the context and in that context, this would be List<Tractor>. Some compiler might choke on this (Javac may accept this while Eclipse Compiler won't and vice versa) and require to precise the type:

List<Tractor> tractors = MyType.<List<Tractor>>badStuff(potatoes);

If you wish to look more in depth, this would probably help: type inference.


答:
Yes, it is possible to do that in PowerShell too.
You can use the same syntax as you use in Unix in this example.

However, one thing you should add before this code block is call operator &, or otherwise what you wrote inside it will be printed literally.

So use this:

```<code>&{echo a; echo b; echo c;} > testout
cat testout
</code>```

Output is:

```<code>a
b
c
</code>```

Title: PowerShell: group commands together, for redirect output

Body:
Yes, it is possible to do that in PowerShell too.
You can use the same syntax as you use in Unix in this example.

However, one thing you should add before this code block is call operator &, or otherwise what you wrote inside it will be printed literally.

So use this:

&{echo a; echo b; echo c;} > testout
cat testout

Output is:

a
b
c


问:
Android App crashes on launch after downloading from Google Play
The app is made with React Native, and it's running fine in both simulators/emulators.

Also on iPhone (through usb... on debug mode).

I couldn't try it on Android (there was no "Build number" !?).

I haven't upload it yet to "App Store"...

But when I download it from "Google Play" the app crashes on launch.

Note: I "use the signing/keytool UI that's part of Android Studio" to generate the APK.

I've found this: Support third-party 64-bit libraries on Android.

And I tried this solution: Mixing 32- and 64-bit Dependencies in Android.

And some other similar to the above...

I tried deleting the ios and android files and then run ios and android again...

Also, tried to upload an "Android App Bundle" instead of APK (with this the app wouldn't even download... not just pending. There was only the spinner to see...

So, nothing worked!

Then I realised I get an error message on the Android device which was:

java.lang.RuntimeException: Unable to load script. Make sure you're either running a Metro server or that your bundle index.android.bundle is packaged correctly for release.

I've found this: Release APK fails immediately on launch.

I want to try the following comment, but I don't understand it.

@alexmbp

Well. It's working with

1 react-native run-android --variant=release

2 and with ./gradlew assembleRelease and configuring signing.

3 Also I've updated gradle and should set android.enableAapt2=false.

Probably issue connected with gradle update.

Could someone please explain...

I think 1 is just a command in terminal.

But what is 2 and 3?

Thanks :)

答:
Run the following command in the react native directory of your project and then build your app after that:

react-native bundle --platform android --dev false --entry-file index.js --bundle-output android\app\src\main\assets*index.android.bundle* --assets-dest android\app\src\main\res

Change the bold text to your app directory

Change the italic text to what you named the bundle file in your configurations

Hope this helps. Happy Coding!


问:
Regex for picking a Value After “=”
How i can select RQR-1BN6Q360090-0001 (without quotes) using Regex in below - </p>

```<code><html><head><title>Object moved</title></head><body>
<h2>Object moved to <a href="/gaits/CreateReport.aspx?RptNum=RQR-1BN6Q360090-0001">here</a>.</h2>
</body></html>

I tried this but it does  not work
RptNum=([A-Za-z]+)$
</code>```

答:
const text = 'RptNum=RQR-1BN6Q360090-0001';

console.log(text.match(/RptNum=.*/).map(m => m.match(/RptNum=.*/)[0])[0].split('RptNum=')[1]);```

I suppose that works

Title: Regex for picking a Value After “=”

Body:
How i can select RQR-1BN6Q360090-0001 (without quotes) using Regex in below -

<title>Object moved</title>

Object moved to here.

I tried this but it does  not work
RptNum=([A-Za-z]+)$

Body:
const text = 'RptNum=RQR-1BN6Q360090-0001';

console.log(text.match(/RptNum=.*/).map(m => m.match(/RptNum=.*/)[0])[0].split('RptNum=')[1]);

I suppose that works


问:
Chromium extension/userscript to shrink the Android Developer header
The Android developer documentation has a very large header -- one that becomes obnoxious when I increase the font size in Chromium (because the whole things scales).

I found a UserScript that reduces the size of the header. It works in Firefox, but I'm using Chromium (which has some support for UserScripts). In Chromium, the script successfully reduces the height of the header, but doesn't extend the body. (There's a big blank area at the bottom of the screen.)

To get the script partially working in Chromium and I made two changes: change @include to @match and insert the @required javascript into my script. In the Chromium debugger, the last if (that does the resizing) is skipped.

I tried setting the height of the content in the script (after the if):

```<code>$('#doc-content').height('auto');
</code>```

That looks right, but now there's no scrollbar. Adding overflow didn't help either:

```<code>$('#doc-content').overflow('scroll');
</code>```

I don't really know what I'm doing (I'm new to js and jquery), but I hope that someone else will see why the Android docs body doesn't fill the empty space when I shrink the header.

答:
The original script has been updated and now works for Chrome.

(Worked for me on Chromium 10.0.648.133 (77742) Ubuntu 10.10.)

ContentLicense: CC BY-SA 2.5

Body:
The Android developer documentation has a very large header -- one that becomes obnoxious when I increase the font size in Chromium (because the whole things scales).

I found a UserScript that reduces the size of the header. It works in Firefox, but I'm using Chromium (which has some support for UserScripts). In Chromium, the script successfully reduces the height of the header, but doesn't extend the body. (There's a big blank area at the bottom of the screen.)

To get the script partially working in Chromium and I made two changes: change @include to @match and insert the @required javascript into my script. In the Chromium debugger, the last if (that does the resizing) is skipped.

I tried setting the height of the content in the script (after the if):

$('#doc-content').height('auto');

That looks right, but now there's no scrollbar. Adding overflow didn't help either:

$('#doc-content').overflow('scroll');

I don't really know what I'm doing (I'm new to js and jquery), but I hope that someone else will see why the Android docs body doesn't fill the empty space when I shrink the header.


问:
Flutter - How to have A Dynamic Home Page by using Firebase?
I am new to Flutter and Firebase and am working on an authentication app.
How do I make the app go to the HomePage if a user is signed in already or go to the login page if no user is signed in?
Forgive my rusty code.</p>

```<code>FirebaseAuth auth = Firebase.instance;
void main() {

  Future<bool> home() async {
    if (await auth.currentUser() == null) {
      return false;
    }
    return true;
  }

  runApp(
    new MaterialApp(
      title: 'DASH',
      home: home() == null ? LoginScreen() : HomeScreen(),
      theme: DashTheme.theme,
      color: DashTheme.white,
      routes: <String, WidgetBuilder>{
      // Set routes for using the Navigator.
       '/home': (BuildContext context) => new HomeScreen(),
       '/login': (BuildContext context) => new LoginScreen(),
      },
    ),
  );
}
</code>```

答:
I'm using Future Builder</p>

```<code> Widget _getLandingPage() {
return FutureBuilder<FirebaseUser>(
  future: FirebaseAuth.instance.currentUser(),
  builder: (BuildContext context, AsyncSnapshot<FirebaseUser> snapshot){
    if (GlobalStore.state.userConfig != null && GlobalStore.state.userConfig.isDisplayIntroScreen == true) {
      return routes.buildPage('intro_screen', null);
    }

    if (snapshot.hasData) {
      return routes.buildPage('main', null);
    } else {
      return routes.buildPage('auth', null);
    }
  },);

home: _getLandingPage(),
</code>```

Body:
I am new to Flutter and Firebase and am working on an authentication app.
How do I make the app go to the HomePage if a user is signed in already or go to the login page if no user is signed in?
Forgive my rusty code.

FirebaseAuth auth = Firebase.instance;
void main() {

  Future<bool> home() async {
    if (await auth.currentUser() == null) {
      return false;
    }
    return true;
  }

  runApp(
    new MaterialApp(
      title: 'DASH',
      home: home() == null ? LoginScreen() : HomeScreen(),
      theme: DashTheme.theme,
      color: DashTheme.white,
      routes: <String, WidgetBuilder>{
      // Set routes for using the Navigator.
       '/home': (BuildContext context) => new HomeScreen(),
       '/login': (BuildContext context) => new LoginScreen(),
      },
    ),
  );
}

Body:
I'm using Future Builder

 Widget _getLandingPage() {
return FutureBuilder<FirebaseUser>(
  future: FirebaseAuth.instance.currentUser(),
  builder: (BuildContext context, AsyncSnapshot<FirebaseUser> snapshot){
    if (GlobalStore.state.userConfig != null && GlobalStore.state.userConfig.isDisplayIntroScreen == true) {
      return routes.buildPage('intro_screen', null);
    }

    if (snapshot.hasData) {
      return routes.buildPage('main', null);
    } else {
      return routes.buildPage('auth', null);
    }
  },);

home: _getLandingPage(),


问:
Gnu make on multiple host machine?
In clearmake there is an option to pass host names so that to run multiple jobs on these hosts but in gmake there is no option to pass multiple hosts although multiple jobs can be passed.
I want to know how i can mimic this clearmake functionality? </p>

答: Another alternative is [makeflow] (http://ccl.cse.nd.edu/software/makeflow/). It allows to run a make (simplified) file to many HPC infrastructures (e.g. SLURM, Torque)</p>

Title: Gnu make on multiple host machine?


问:
Can't understand why this simple recursion begins to work and then crashes
I was doing some trick questions about C++ and I run on similar code to this then I modified it to see what will happen.

I don't understand why at first place this recursion is working (it's printing values from 2 to 4764) and then suddenly it throws exception.

I don't understand also why I can say return in void function and actually return something other than "return;"

Can anyone explain this two problems?

```<code>#include<iostream>
using namespace std;

void function(int& a){
    a++;
    cout << a << endl;
    return function(a);
}

void main() {

    int b = 2;
    function(b);

    system("pause>0");
}
</code>```

答:
On x86-64 platforms, like your laptop or desktop, functions get called one of two ways:

with a call assembly instruction

with a jmp assembly instruction

What's the difference? A call assembly instruction has additional instructions after it: when the function is called, the code will return to the place it was called from. In order to keep track of where it is, the function uses memory on the stack. If a recursive function calls itself using call, then as it recurses it'll use up more and more of the stack, eventually resulting in a stack overflow.

On the other hand, a jmp instruction just tells the CPU to jump to the section of code where the other function is stored. If a function is calling itself, then the CPU will just jmp back up to the top of the function and start it over with the updated parameters. This is called a tail-call optimization, and it prevents stack overflow entirely in a lot of common cases because the stack doesn't grow.

If you compile your code at a higher optimization level (say, -O2 on GCC), then the compiler will use tail-call optimization and your code won't have a stack overflow.

Body:
I was doing some trick questions about C++ and I run on similar code to this then I modified it to see what will happen.

I don't understand why at first place this recursion is working (it's printing values from 2 to 4764) and then suddenly it throws exception.

I don't understand also why I can say return in void function and actually return something other than "return;"

Can anyone explain this two problems?

#include<iostream>
using namespace std;

void function(int& a){
    a++;
    cout << a << endl;
    return function(a);
}

void main() {

    int b = 2;
    function(b);

    system("pause>0");
}


问:
ContextVars across modules
I am completely newb on asyncio and ContextVars, I just read up what's new in 3.7 and discovered ContextVars, I struggle to understand it's usage, all I know it's helpful in coroutines, instead of using thread.local should use ContextVars. But none of the official doc and top google search result could help me truely understand its purpose.

So is convextvars shared across modules? I tried:

example.py

```<code>from contextvars import ContextVar

number = ContextVar('number', default=100)
number.set(1)
</code>```

then I try to import number.py

```<code>(playground) Jamess-MacBook-Pro-2:playground jlin$ python3.7
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 23:26:24)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import example
>>> from contextvars import ContextVar
>>> number = ContextVar('number', default=200)
>>> number.get()
200
</code>```

I was expecting number.get() would return 1, but obviously I have understood its purpose wrong.

Could someone please help me understand this?

答:
Not completely sure if my approach is correct but I will add my findings to answer, so I tried to use this in my django project to set the request var without using thread local.

```<code>from contextvars import ContextVar
request_var = ContextVar('request', default=None)

def request_middleware(get_response):
    """
    Sets the request into contextvar
    """
    def middleware(request):
        ctx = copy_context()
        return ctx.run(wrap_get_response, request)

    def wrap_get_response(request):
        request_var.set(request)
        return get_response(request)
    return middleware
</code>```

Then in somewhere else that need to use the request var:

```<code>from core.middlewares import request_var
request = request_var.get()
</code>```

Not sure if this is the correct usage, but it seems working fine for me.

I don't know how to get the request_var from context.get() eg.

```<code>from contextvars import copy_context
ctx = copy_context()
# the key here is `request_var` obj in middlewares.py,
# might as well just import `request_var` and use it directly?
request = ctx.get(...)
</code>```

Title: ContextVars across modules

Body:
I am completely newb on asyncio and ContextVars, I just read up what's new in 3.7 and discovered ContextVars, I struggle to understand it's usage, all I know it's helpful in coroutines, instead of using thread.local should use ContextVars. But none of the official doc and top google search result could help me truely understand its purpose.

So is convextvars shared across modules? I tried:

example.py

from contextvars import ContextVar

number = ContextVar('number', default=100)
number.set(1)

then I try to import number.py

(playground) Jamess-MacBook-Pro-2:playground jlin$ python3.7
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 23:26:24)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import example
>>> from contextvars import ContextVar
>>> number = ContextVar('number', default=200)
>>> number.get()
200

I was expecting number.get() would return 1, but obviously I have understood its purpose wrong.

Could someone please help me understand this?

Body:
Not completely sure if my approach is correct but I will add my findings to answer, so I tried to use this in my django project to set the request var without using thread local.

from contextvars import ContextVar
request_var = ContextVar('request', default=None)

def request_middleware(get_response):
    """
    Sets the request into contextvar
    """
    def middleware(request):
        ctx = copy_context()
        return ctx.run(wrap_get_response, request)

    def wrap_get_response(request):
        request_var.set(request)
        return get_response(request)
    return middleware

Then in somewhere else that need to use the request var:

from core.middlewares import request_var
request = request_var.get()

Not sure if this is the correct usage, but it seems working fine for me.

I don't know how to get the request_var from context.get() eg.

from contextvars import copy_context
ctx = copy_context()
# the key here is `request_var` obj in middlewares.py,
# might as well just import `request_var` and use it directly?
request = ctx.get(...)


问:
Casting and writing in pointer array reports misaligned address with clang sanitizer
I'm using a char* array to store different data types, like in the next example:

```<code>int main()
{
    char* arr = new char[8];
    *reinterpret_cast<uint32_t*>(&arr[1]) = 1u;
    return 0;
}
</code>```

Compiling and running with clang UndefinedBehaviorSanitizer will report the following error:

```<code>runtime error: store to misaligned address 0x602000000011 for type 'uint32_t' (aka 'unsigned int'), which requires 4 byte alignment
</code>```

I suppose I could do it another way, but why is this undefined behavior? What concepts are involved here?

答:
You cannot cast an arbitrary char* to uint32_t*, even if it points to an array large enough to hold a uint32_t

There are a couple reasons why.

The practical answer:

uint32_t generally likes 4-byte alignment: its address should be a multiple of 4.

char does not have such a restriction.  It can live at any address.

That means that an arbitrary char* is unlikely to be aligned properly for a uint32_t.

The Language Lawyer answer:

Aside from the alignment issue, your code exhibits undefined behavior because you're violating the strict aliasing rules.  No uint32_t object exists at the address you're writing to, but you're treating it as if there is one there.

In general, while char* may be used to point to any object and read its byte representation, a T* for any given type T, cannot be used to point at an array of bytes and write the byte-representation of the object into it.

No matter the reason for the error, the way to fix it is the same:

If you don't care about treating the bytes as a uint32_t and are just serializing them (to send over a network, or write to disk, for example), then you can std::copy the bytes into the buffer:

```<code>char buffer[BUFFER_SIZE] = {};
char* buffer_pointer = buffer;
uint32_t foo = 123;
char* pfoo = reinterpret_cast<char*>(&foo);
std::copy(pfoo, pfoo + sizeof(foo), buffer_pointer);
buffer_pointer += sizeof(foo);
uint32_t bar = 234;
char* pbar = reinterpret_cast<char*>(&bar);
std::copy(pbar, pbar + sizeof(bar), buffer_pointer);
buffer_pointer += sizeof(bar);
// repeat as needed
</code>```

If you do want to treat those bytes as a uint32_t (if you're implementing a std::vector-like data structure, for example) then you will need to ensure the buffer is properly-aligned, and use placement-new:

```<code>std::aligned_storage_t<sizeof(uint32_t), alignof(uint32_t)> buffer[BUFFER_SIZE];
uint32_t foo = 123;
uint32_t* new_uint = new (&buffer[0]) uint32_t(foo);
uint32_t bar = 234;
uint32_t* another_new_uint = new (&buffer[1]) uint32_t(foo);
// repeat as needed
</code>```

Body:
I'm using a char* array to store different data types, like in the next example:

int main()
{
    char* arr = new char[8];
    *reinterpret_cast<uint32_t*>(&arr[1]) = 1u;
    return 0;
}

Compiling and running with clang UndefinedBehaviorSanitizer will report the following error:

runtime error: store to misaligned address 0x602000000011 for type 'uint32_t' (aka 'unsigned int'), which requires 4 byte alignment

I suppose I could do it another way, but why is this undefined behavior? What concepts are involved here?

Body:
You cannot cast an arbitrary char* to uint32_t*, even if it points to an array large enough to hold a uint32_t

There are a couple reasons why.

The practical answer:

uint32_t generally likes 4-byte alignment: its address should be a multiple of 4.

char does not have such a restriction.  It can live at any address.

That means that an arbitrary char* is unlikely to be aligned properly for a uint32_t.

The Language Lawyer answer:

Aside from the alignment issue, your code exhibits undefined behavior because you're violating the strict aliasing rules.  No uint32_t object exists at the address you're writing to, but you're treating it as if there is one there.

In general, while char* may be used to point to any object and read its byte representation, a T* for any given type T, cannot be used to point at an array of bytes and write the byte-representation of the object into it.

No matter the reason for the error, the way to fix it is the same:

If you don't care about treating the bytes as a uint32_t and are just serializing them (to send over a network, or write to disk, for example), then you can std::copy the bytes into the buffer:

char buffer[BUFFER_SIZE] = {};
char* buffer_pointer = buffer;
uint32_t foo = 123;
char* pfoo = reinterpret_cast<char*>(&foo);
std::copy(pfoo, pfoo + sizeof(foo), buffer_pointer);
buffer_pointer += sizeof(foo);
uint32_t bar = 234;
char* pbar = reinterpret_cast<char*>(&bar);
std::copy(pbar, pbar + sizeof(bar), buffer_pointer);
buffer_pointer += sizeof(bar);
// repeat as needed

If you do want to treat those bytes as a uint32_t (if you're implementing a std::vector-like data structure, for example) then you will need to ensure the buffer is properly-aligned, and use placement-new:

std::aligned_storage_t<sizeof(uint32_t), alignof(uint32_t)> buffer[BUFFER_SIZE];
uint32_t foo = 123;
uint32_t* new_uint = new (&buffer[0]) uint32_t(foo);
uint32_t bar = 234;
uint32_t* another_new_uint = new (&buffer[1]) uint32_t(foo);
// repeat as needed


问:
Boolean Enum throws Action can't be blank for false value in Rails-Admin
I have a rails_admin form (using with rails4 ruby 2.0) with a boolean field : action which symbolises Credit or a Debit action.

I have used enums for the field which works upon selecting the Credit(true) option.
But throws a validation error upon saving 'Action can't be blank'.

I have the following code in place.

```<code>field :action, :enum do
  enum do
    [['Credit', true], ['Debit', false]]
  end
end
</code>```

I also tried interchanging the usage of enum by using it as a method.

```<code>def action_enum
  [['Credit', true], ['Debit', false]]
end
</code>```

but nothing has worked so far.
I tried going though the documentation of rails_admin wiki : https://github.com/sferik/rails_admin/wiki but could not work things out.

Can anyone please suggest any solution or point out what it is that i am missing??

答:
For those trying to validate the presence of a Boolean, you cannot use presence: true.

You need to use:

inclusion: { in: [ true, false ] }
```
<p>For some crazy reason, this is a thing:</p>
<pre class="lang-rb prettyprint-override"><code>false.present? #=> true
</code>```

As per https://github.com/rails/rails/issues/22962

Body:
I have a rails_admin form (using with rails4 ruby 2.0) with a boolean field : action which symbolises Credit or a Debit action.

I have used enums for the field which works upon selecting the Credit(true) option.
But throws a validation error upon saving 'Action can't be blank'.

I have the following code in place.

field :action, :enum do
  enum do
    [['Credit', true], ['Debit', false]]
  end
end

I also tried interchanging the usage of enum by using it as a method.

def action_enum
  [['Credit', true], ['Debit', false]]
end

but nothing has worked so far.
I tried going though the documentation of rails_admin wiki : https://github.com/sferik/rails_admin/wiki but could not work things out.

Can anyone please suggest any solution or point out what it is that i am missing??

Body:
For those trying to validate the presence of a Boolean, you cannot use presence: true.

You need to use:

inclusion: { in: [ true, false ] }

For some crazy reason, this is a thing:

false.present? #=> true

As per https://github.com/rails/rails/issues/22962


问:
Python to delete a row in excel spreadsheet
I have a really large excel file and i need to delete about 20,000 rows, contingent on meeting a simple condition and excel won't let me delete such a complex range when using a filter. The condition is:

If the first column contains the value, X, then I need to be able to delete the entire row.

I'm trying to automate this using python and xlwt, but am not quite sure where to start. Seeking some code snippits to get me started...
Grateful for any help that's out there!

答:
If you just need to delete the data (rather than 'getting rid of' the row, i.e. it shifts rows) you can try using my module, PyWorkbooks.  You can get the most recent version here:

https://sourceforge.net/projects/pyworkbooks/

There is a pdf tutorial to guide you through how to use it.  Happy coding!


问:
Saving an Image drawn on a Canvas
I have a simple HTML app where I can draw on a HTML5 canvas. I have a save button where I capture the image using canvas.todataURL. When I open this link in a web browser, the full drawing isn't shown -- only a subsection of the drawing. Below is my code. Try it out, it doesn't make sense.

JSFIDDLE: https://jsfiddle.net/v0a2Lfsk/1/

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js"></script>

<script>
var mousePressed = false;
var lastX, lastY;
var ctx;

$(window).on('load', function() {
  canv = document.getElementById('myCanvas');
  ctx = canv.getContext("2d");
  canv.width  = $(window).width();
  canv.height = 1000;

  $('#myCanvas').mousedown(function (e) {
    mousePressed = true;
    //Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, false);
    Draw(e.pageX, e.pageY, false);
  });

  $('#myCanvas').mousemove(function (e) {
    if (mousePressed) {
      //Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, true);
      Draw(e.pageX , e.pageY , true);
    }
  });

  $('#myCanvas').mouseup(function (e) {
    mousePressed = false;
  });
  $('#myCanvas').mouseleave(function (e) {
    mousePressed = false;
  });

});

function Draw(x, y, isDown) {
  if (isDown) {
    ctx.beginPath();
    ctx.strokeStyle = "blue";
    ctx.lineWidth = $('#selWidth').val();
    ctx.lineJoin = "round";
    ctx.moveTo(lastX, lastY);
    ctx.lineTo(x, y);
    ctx.closePath();
    ctx.stroke();
  }
  lastX = x; lastY = y;
}

function next(){

    var canvas = document.getElementById('myCanvas');

    var image = canvas.toDataURL("image/png");  // here is the most important part because if you dont replace you will get a DOM 18 exception.
    console.log(image);

    // html2canvas(document.querySelector("#myCanvas")).then(canvas => {
    //     document.body.appendChild(canvas);
    //     alert("dasds");
    // });

}

function clearArea() {
  // Use the identity matrix while clearing the canvas
  ctx.setTransform(1, 0, 0, 1, 0, 0);
  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}
</script>
<body>
 <canvas id="myCanvas"></canvas>
  <div class="controls">
    <button onclick="javascript:clearArea();return false;">Clear Area</button>
    <button onclick="javascript:next();return false;">Save (Print to Console Log)</button>
    <!-- Line width : <select id="selWidth">
    <option value="1">1</option>
    <option value="3">3</option>
    <option value="5" selected="selected">5</option>
    <option value="7">7</option>
    <option value="9">9</option>
    <option value="11">11</option>
    </select>
    Color : <select id="selColor">
    <option value="black">black</option>
    <option value="blue" selected="selected">blue</option>
    <option value="red">red</option>
    <option value="green">green</option>
    <option value="yellow">yellow</option>
    <option value="gray">gray</option>
    </select> -->
  </div>

</body>
  <style>
body{
  overflow:hidden;
}
#mycanvas
{
  background-color:#fff;
  position:absolute;
*/  background-repeat:   no-repeat;
}
.controls
{
  position:absolute;
  top:0px;
  right:0px;
  width: 600px;
  background-color:#2277dd;
  padding:5px;
  margin:2px;
  color:#fff;
  -webkit-border-radius: 3px;
  border-radius: 3px;
}
</style>
</code>```

答:
Make sure that you press the "Show More" button in the Console Tab of Developer Tools, otherwise you may copy only part of the output string (as per asdadsads's comment).

In some cases, showing a cut-off base64 string will lead to an error message, while in others (such as yours), a part of the image will be displayed.

Alternatively, just use the "Copy" button, which will copy the entire output.

Title: Saving an Image drawn on a Canvas

Body:
I have a simple HTML app where I can draw on a HTML5 canvas. I have a save button where I capture the image using canvas.todataURL. When I open this link in a web browser, the full drawing isn't shown -- only a subsection of the drawing. Below is my code. Try it out, it doesn't make sense.

JSFIDDLE: https://jsfiddle.net/v0a2Lfsk/1/

 <canvas id="myCanvas"></canvas>

    <button onclick="javascript:clearArea();return false;">Clear Area</button>
    <button onclick="javascript:next();return false;">Save (Print to Console Log)</button>


问:
Any idea why i dont have gutters between my articles ? Bootstrap 4
I'm Struggling adjusting my articles here  :

https://cryptoranger.net/news

I'm using bootstrap 4.3.0, here's the code of the rows :

```<code><div class="row bg-light">
    <?php
    foreach ($newsList as $news){?>
    <article class="col-md-4 blogpost border rounded p-0">
            <div class="imgBx">
                <img src="/images/<?=$news['image'] ?>" alt="" class="img-fluid">
            </div>
            <div class="content">
              <h2 class="itemrecent1"><?= $news['titre'] ?></h2>
              <p class="float-left m-0"><i class="fas fa-clock"></i>  <?= $news['dateAjout']->format('Y-m-d') ?></p><br>
              <p class="itemrecent1"><?= nl2br($news['contenu']) ?></p>
                <?php
                if ($category === 'news'){?>
              <div class="itemrecent1"><a href="/news/<?php echo $generator->generate($news['titre']); ?>_<?= $news['id'] ?>" class="btn btnD1">Read</a></div>
                <?php
                }else {?>
              <div class="itemrecent1 justify-self-end"><a href="/guide/<?= $category ?>/<?php echo $generator->generate($news['titre']); ?>_<?= $news['id'] ?>" class="btn btnD1">Read</a></div>
                <?php
                }?>
              <div class="clearfix"></div>
            </div>
    </article>
    <?php } ?>   <!-- End of news -->
</div>
</code>```

So i want gutters between my articles...

Besides, if you know how to adjust the content (text inside the box because i tried some flexbox css but nothing is changing (i want at least all Read link at the same level (bottom))...

==> It's working if i put some height in pixel but cant do that because i need responsive design..

Thanks... :D

答:
The gutters are there, they come from the padding on the col-* classes.  Because you added the border class to your articles the padding is, naturally, surrounded by a border.  Usually when using Bootstrap grid layouts, content is placed within a wrapper element that has the desired col-* class:

```<code><div class="row bg-light">
    <?php
    foreach ($newsList as $news){?>
  <div class="col-md-4">
    <article class="blogpost border rounded p-0">
            <div class="imgBx">
                <img src="/images/<?=$news['image'] ?>" alt="" class="img-fluid">
            </div>
            <div class="content">
              <h2 class="itemrecent1"><?= $news['titre'] ?></h2>
              <p class="float-left m-0"><i class="fas fa-clock"></i>  <?= $news['dateAjout']->format('Y-m-d') ?></p><br>
              <p class="itemrecent1"><?= nl2br($news['contenu']) ?></p>
                <?php
                if ($category === 'news'){?>
              <div class="itemrecent1"><a href="/news/<?php echo $generator->generate($news['titre']); ?>_<?= $news['id'] ?>" class="btn btnD1">Read</a></div>
                <?php
                }else {?>
              <div class="itemrecent1 justify-self-end"><a href="/guide/<?= $category ?>/<?php echo $generator->generate($news['titre']); ?>_<?= $news['id'] ?>" class="btn btnD1">Read</a></div>
                <?php
                }?>
              <div class="clearfix"></div>
            </div>
    </article>
  </div>
    <?php } ?>   <!-- End of news -->
</div>
</code>```

Looks like you actually have it correct on another page on your site

Body:
I'm Struggling adjusting my articles here  :

https://cryptoranger.net/news

I'm using bootstrap 4.3.0, here's the code of the rows :

    <?php
    foreach ($newsList as $news){?>

                <img src="/images/<?=$news['image'] ?>" alt="" class="img-fluid">

<?= $news['titre'] ?>

  <?= $news['dateAjout']->format('Y-m-d') ?>

<?= nl2br($news['contenu']) ?>

                <?php
                if ($category === 'news'){?>

<a href="/news/<?php echo $generator->generate($news['titre']); ?>_<?= $news['id'] ?>" class="btn btnD1">Read

                <?php
                }else {?>

<a href="/guide/<?= $category ?>/<?php echo $generator->generate($news['titre']); ?>_<?= $news['id'] ?>" class="btn btnD1">Read

                <?php
                }?>

    <?php } ?>

So i want gutters between my articles...

Besides, if you know how to adjust the content (text inside the box because i tried some flexbox css but nothing is changing (i want at least all Read link at the same level (bottom))...

==> It's working if i put some height in pixel but cant do that because i need responsive design..

Thanks... :D

Body:
The gutters are there, they come from the padding on the col-* classes.  Because you added the border class to your articles the padding is, naturally, surrounded by a border.  Usually when using Bootstrap grid layouts, content is placed within a wrapper element that has the desired col-* class:

<div class="row bg-light">
    <?php
    foreach ($newsList as $news){?>
  <div class="col-md-4">
    <article class="blogpost border rounded p-0">
            <div class="imgBx">
                <img src="/images/<?=$news['image'] ?>" alt="" class="img-fluid">
            </div>
            <div class="content">
              <h2 class="itemrecent1"><?= $news['titre'] ?></h2>
              <p class="float-left m-0"><i class="fas fa-clock"></i>  <?= $news['dateAjout']->format('Y-m-d') ?></p><br>
              <p class="itemrecent1"><?= nl2br($news['contenu']) ?></p>
                <?php
                if ($category === 'news'){?>
              <div class="itemrecent1"><a href="/news/<?php echo $generator->generate($news['titre']); ?>_<?= $news['id'] ?>" class="btn btnD1">Read</a></div>
                <?php
                }else {?>
              <div class="itemrecent1 justify-self-end"><a href="/guide/<?= $category ?>/<?php echo $generator->generate($news['titre']); ?>_<?= $news['id'] ?>" class="btn btnD1">Read</a></div>
                <?php
                }?>
              <div class="clearfix"></div>
            </div>
    </article>
  </div>
    <?php } ?>   <!-- End of news -->
</div>

Looks like you actually have it correct on another page on your site


问:
Laravel 5 Run queue:work on laravel schedule
I have a schedule like this:

```<code><?php

namespace App\Console;

use Illuminate\Support\Facades\Artisan;
use Illuminate\Console\Scheduling\Schedule;
protected function schedule(Schedule $schedule)
{
   Artisan::call('queue:work');
}
</code>```

I add this on my cronjob:

* * * * * cd /var/www/html/my_script_address && php  artisan schedule:run

Is it correct code? I am asking, because every minute run Artisan::call('queue:work').

Is it the best way?

答:
as per documentation https://laravel.com/docs/5.8/scheduling#scheduling-queued-jobs

you can simply queue a job via:

```<code>$schedule->job(new Heartbeat)->everyFiveMinutes();
</code>```

Body:
I have a schedule like this:

<?php

namespace App\Console;

use Illuminate\Support\Facades\Artisan;
use Illuminate\Console\Scheduling\Schedule;
protected function schedule(Schedule $schedule)
{
   Artisan::call('queue:work');
}

I add this on my cronjob:

* * * * * cd /var/www/html/my_script_address && php  artisan schedule:run

Is it correct code? I am asking, because every minute run Artisan::call('queue:work').

Is it the best way?

Body:
as per documentation https://laravel.com/docs/5.8/scheduling#scheduling-queued-jobs

you can simply queue a job via:

$schedule->job(new Heartbeat)->everyFiveMinutes();


问:
Can't extend generic struct for specific type
Wanted to toy with adding some sugar in Swift3. Basically, I wanted to be able to do something like:

```<code>let randomAdjust = (-10...10).random
</code>```

To do that, I decided I would need to extend ClosedRange. But then found it would probably be even better for my case, I really just plan on doing Int's for now, to use CountableClosedRange. My latest of multiple attempts looked like:

```<code>extension CountableClosedRange where Bound == Int {
    var random:Int {
        return Int(arc4random_uniform(UInt32(self.count) + 1)) + self.lowerBound
    }
}
</code>```

But the playground complains:

```<code>error: same-type requirement makes generic parameter 'Bound' non-generic
extension CountableClosedRange where Bound == Int {
</code>```

I don't even know what it's telling me there.

答:
In Swift 4, what you are attempting is now completely supported. Hooray!

extension Stack where Element: Equatable {
    func isTop(_ item: Element) -> Bool {
        guard let topItem = items.last else {
            return false
        }
        return topItem == item
    }
}
```

Example from Swift docs: https://docs.swift.org/swift-book/LanguageGuide/Generics.html#ID553

Body:
Wanted to toy with adding some sugar in Swift3. Basically, I wanted to be able to do something like:

let randomAdjust = (-10...10).random

To do that, I decided I would need to extend ClosedRange. But then found it would probably be even better for my case, I really just plan on doing Int's for now, to use CountableClosedRange. My latest of multiple attempts looked like:

extension CountableClosedRange where Bound == Int {
    var random:Int {
        return Int(arc4random_uniform(UInt32(self.count) + 1)) + self.lowerBound
    }
}

But the playground complains:

error: same-type requirement makes generic parameter 'Bound' non-generic
extension CountableClosedRange where Bound == Int {

I don't even know what it's telling me there.

Body:
In Swift 4, what you are attempting is now completely supported. Hooray!

extension Stack where Element: Equatable {
    func isTop(_ item: Element) -> Bool {
        guard let topItem = items.last else {
            return false
        }
        return topItem == item
    }
}

Example from Swift docs: https://docs.swift.org/swift-book/LanguageGuide/Generics.html#ID553


问:
How do change Heroku 500 error message?
How do I change heroku 500 error message and how to do a redirect to root_url ?</p>

答: There is an addon available, see http://devcenter.heroku.com/articles/custom-error-pages</p>

Title: How do change Heroku 500 error message?


问:
shred multiple xml elements into multiple columns
I am trying to shred this xml column into multiple xml columns but it seems to be in the wrong format.

Here is my data from using xml path()

```<code><claim id="1111111">
  <InsHistDB>2</InsHistDB>
  <ClaimHistID>111111</ClaimHistID>
  <PatID>00000001</PatID>
  <ProcedureData>
    <row proc_logid="0000009" proc_logdb="1000000" createdate="2000-09-21T00:00:00" pldate="2000-09-21T00:00:00" adacode="D0120" />
    <row proc_logid="1211557" proc_logdb="1000010" createdate="2015-09-21T00:00:00" pldate="2015-09-21T00:00:00" adacode="D0220" />
    <row proc_logid="1211558" proc_logdb="1000010" createdate="2015-09-21T00:00:00" pldate="2015-09-21T00:00:00" adacode="D0230" />
    <row proc_logid="1211556" proc_logdb="1000010" createdate="2015-09-21T00:00:00" pldate="2015-09-21T00:00:00" adacode="D0272" />
  </ProcedureData>
</claim>
</code>```

The select statement is currently this

```<code>SELECT TOP (1000)  [ClaimID] as '@id'
      ,[InsHistDB]
      ,[ClaimHistID]
      ,[PatID]
   -- ,[ProcedureData].value('declare namespace ns= "ProcedureData"; (/ns:ProcedureData/ns:row[1])','nvarchar(50)') as pp
     ,[ProcedureData]
     --,[ProcedureData].query('proc_logid').value('.','varchar(50)') as 'proc_1'
  FROM [Mine].[dbo].[claim]
  where claimid=1111111

 FOR XML PATH('claim')
</code>```

What I am wanting to do is divide out the {Proc_Log_id} into different columns so the row should read.

```<code>Claim ID         INSHISTDB       CLaimHistID       PATID      Proc_Id1      Proc_ID2      ProcID3   procID4
 11111              2               1111111      000000001     0000009    1211557        1211558      1211556
</code>```

Is this possible or am i just spinning my wheels? Also this will be for multiple patid's so the query without the where clause is expected. Also I believe there can be up to 10 proc_logids per xml data point. I am fine with null values, as i plan to pivot and normalize this data.

Thanks for reading.

答:
You can first graph the IDs from your XML content, and then you have to use PIVOT as you mentioned. Since you are not sure about number of columns, you can make use of dynamic pivot to make it more flexible.

First get the data using XML nodes and value and I stored the value in temp table as it would be convenient to do pivot.

```<code>Declare @xmlstring xml =
'<claim id="1111111">
  <InsHistDB>2</InsHistDB>
  <ClaimHistID>111111</ClaimHistID>
  <PatID>00000001</PatID>
  <ProcedureData>
    <row proc_logid="0000009" proc_logdb="1000000" createdate="2000-09-21T00:00:00" pldate="2000-09-21T00:00:00" adacode="D0120" />
    <row proc_logid="1211557" proc_logdb="1000010" createdate="2015-09-21T00:00:00" pldate="2015-09-21T00:00:00" adacode="D0220" />
    <row proc_logid="1211558" proc_logdb="1000010" createdate="2015-09-21T00:00:00" pldate="2015-09-21T00:00:00" adacode="D0230" />
    <row proc_logid="1211556" proc_logdb="1000010" createdate="2015-09-21T00:00:00" pldate="2015-09-21T00:00:00" adacode="D0272" />
  </ProcedureData>
</claim>'

if object_id('tempdb..#temp1') is not null
drop table #temp1

select m.Col.value('@id','varchar(150)') as ClaimID
,m.Col.value('(InsHistDB)[1]','varchar(150)') as InsHistDB
,m.Col.value('(ClaimHistID)[1]','varchar(150)') as ClaimHistID
,m.Col.value('(PatID)[1]','varchar(150)') as PatID
,t.new.value('(@proc_logid)[1]', 'Varchar(150)') IDcol,
concat('Proc_ID', cast(ROW_NUMBER() over (Partition by m.Col.value('@id','varchar(150)') order by t.new.value('(@proc_logid)[1]', 'Varchar(150)')) as varchar(10))) AS ProcID
into #temp1
from @xmlstring.nodes('/claim') as m(col)
CROSS APPLY @xmlstring.nodes('claim/ProcedureData/row') as t(new);
</code>```

You will have data in temp table like this. I have concatenated rownumber for a given claimID with proc ID to create column in the way you have mentioned.

```<code>ClaimID    InsHistDB    ClaimHistID PatID   IDcol   ProcID
1111111       2          111111    00000001 0000009 Proc_ID1
1111111       2          111111    00000001 1211557 Proc_ID2
1111111       2          111111    00000001 1211558 Proc_ID3
1111111       2          111111    00000001 1211556 Proc_ID4
</code>```

Then you can make use of dynamic pivot to get your expected output.

```<code>DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.procID)
        FROM #temp1 c
        FOR XML PATH(''))
    ,1,1,'')

    set @query = 'SELECT ClaimID, InsHistDB,ClaimHistID, PatID,  '+@cols+'  from
        (
            select ClaimID, InsHistDB,ClaimHistID, PatID, procID, IDcol

                from #temp1
       ) x
        pivot
        (
             max(IDcol)
            for procID in (' + @cols + ')
        ) p '

Exec sp_executesql @query
</code>```

Final output from the query:

```<code>ClaimID InsHistDB   ClaimHistID PatID   Proc_ID1    Proc_ID2    Proc_ID3    Proc_ID4
1111111     2        111111    00000001 0000009     1211557     1211558     1211556
</code>```

Body:
I am trying to shred this xml column into multiple xml columns but it seems to be in the wrong format.

Here is my data from using xml path()

<claim id="1111111">
  <InsHistDB>2</InsHistDB>
  <ClaimHistID>111111</ClaimHistID>
  <PatID>00000001</PatID>
  <ProcedureData>
    <row proc_logid="0000009" proc_logdb="1000000" createdate="2000-09-21T00:00:00" pldate="2000-09-21T00:00:00" adacode="D0120" />
    <row proc_logid="1211557" proc_logdb="1000010" createdate="2015-09-21T00:00:00" pldate="2015-09-21T00:00:00" adacode="D0220" />
    <row proc_logid="1211558" proc_logdb="1000010" createdate="2015-09-21T00:00:00" pldate="2015-09-21T00:00:00" adacode="D0230" />
    <row proc_logid="1211556" proc_logdb="1000010" createdate="2015-09-21T00:00:00" pldate="2015-09-21T00:00:00" adacode="D0272" />
  </ProcedureData>
</claim>

The select statement is currently this

SELECT TOP (1000)  [ClaimID] as '@id'
      ,[InsHistDB]
      ,[ClaimHistID]
      ,[PatID]
   -- ,[ProcedureData].value('declare namespace ns= "ProcedureData"; (/ns:ProcedureData/ns:row[1])','nvarchar(50)') as pp
     ,[ProcedureData]
     --,[ProcedureData].query('proc_logid').value('.','varchar(50)') as 'proc_1'
  FROM [Mine].[dbo].[claim]
  where claimid=1111111

 FOR XML PATH('claim')

What I am wanting to do is divide out the {Proc_Log_id} into different columns so the row should read.

Claim ID         INSHISTDB       CLaimHistID       PATID      Proc_Id1      Proc_ID2      ProcID3   procID4
 11111              2               1111111      000000001     0000009    1211557        1211558      1211556

Is this possible or am i just spinning my wheels? Also this will be for multiple patid's so the query without the where clause is expected. Also I believe there can be up to 10 proc_logids per xml data point. I am fine with null values, as i plan to pivot and normalize this data.

Thanks for reading.

Body:
You can first graph the IDs from your XML content, and then you have to use PIVOT as you mentioned. Since you are not sure about number of columns, you can make use of dynamic pivot to make it more flexible.

First get the data using XML nodes and value and I stored the value in temp table as it would be convenient to do pivot.

Declare @xmlstring xml =
'<claim id="1111111">
  <InsHistDB>2</InsHistDB>
  <ClaimHistID>111111</ClaimHistID>
  <PatID>00000001</PatID>
  <ProcedureData>
    <row proc_logid="0000009" proc_logdb="1000000" createdate="2000-09-21T00:00:00" pldate="2000-09-21T00:00:00" adacode="D0120" />
    <row proc_logid="1211557" proc_logdb="1000010" createdate="2015-09-21T00:00:00" pldate="2015-09-21T00:00:00" adacode="D0220" />
    <row proc_logid="1211558" proc_logdb="1000010" createdate="2015-09-21T00:00:00" pldate="2015-09-21T00:00:00" adacode="D0230" />
    <row proc_logid="1211556" proc_logdb="1000010" createdate="2015-09-21T00:00:00" pldate="2015-09-21T00:00:00" adacode="D0272" />
  </ProcedureData>
</claim>'

if object_id('tempdb..#temp1') is not null
drop table #temp1

select m.Col.value('@id','varchar(150)') as ClaimID
,m.Col.value('(InsHistDB)[1]','varchar(150)') as InsHistDB
,m.Col.value('(ClaimHistID)[1]','varchar(150)') as ClaimHistID
,m.Col.value('(PatID)[1]','varchar(150)') as PatID
,t.new.value('(@proc_logid)[1]', 'Varchar(150)') IDcol,
concat('Proc_ID', cast(ROW_NUMBER() over (Partition by m.Col.value('@id','varchar(150)') order by t.new.value('(@proc_logid)[1]', 'Varchar(150)')) as varchar(10))) AS ProcID
into #temp1
from @xmlstring.nodes('/claim') as m(col)
CROSS APPLY @xmlstring.nodes('claim/ProcedureData/row') as t(new);

You will have data in temp table like this. I have concatenated rownumber for a given claimID with proc ID to create column in the way you have mentioned.

ClaimID    InsHistDB    ClaimHistID PatID   IDcol   ProcID
1111111       2          111111    00000001 0000009 Proc_ID1
1111111       2          111111    00000001 1211557 Proc_ID2
1111111       2          111111    00000001 1211558 Proc_ID3
1111111       2          111111    00000001 1211556 Proc_ID4

Then you can make use of dynamic pivot to get your expected output.

DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.procID)
        FROM #temp1 c
        FOR XML PATH(''))
    ,1,1,'')

    set @query = 'SELECT ClaimID, InsHistDB,ClaimHistID, PatID,  '+@cols+'  from
        (
            select ClaimID, InsHistDB,ClaimHistID, PatID, procID, IDcol

                from #temp1
       ) x
        pivot
        (
             max(IDcol)
            for procID in (' + @cols + ')
        ) p '

Exec sp_executesql @query

Final output from the query:

ClaimID InsHistDB   ClaimHistID PatID   Proc_ID1    Proc_ID2    Proc_ID3    Proc_ID4
1111111     2        111111    00000001 0000009     1211557     1211558     1211556