问:
Laravel Ajax request, No 'Access-Control-Allow-Origin' header
Today i extended my workflow with Heroku and when i got everything up and running and started testing things like registration/login modal, then i got this error to my console.

Access to XMLHttpRequest at 'http://app-name.herokuapp.com/register' from origin 'https://app-name.herokuapp.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Tried adding Content-Security-Policy to my header in layout file, also adding X-CSRF-TOKEN to my ajax request header removed some part of the error, but then is just googled different solutions and tried them.

<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
```

``` $(document).on('submit', '#formRegister', function(e) {
            e.preventDefault();

            $('input+small').text('');
            $('#formRegister input').removeClass('is-invalid');

            $.ajax({
                method: $(this).attr('method'),
                url: $(this).attr('action'),
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                    'Access-Control-Allow-Methods' : 'POST',
                    'Access-Control-Allow-Headers' : 'X-Requested-With, Content-Type, X-Auth-Token, Origin, Authorization'
                },
                data: $(this).serialize(),
                dataType: "json",
                crossDomain: false
            })
                .done(function(data) {
                    $('.success-registered').removeClass('d-none');
                    $('#formRegister input').val('');
                    setTimeout(function() {
                        $('.success-registered').addClass('d-none');
                        location.reload();
                    }, 3000);
                    $('#login').modal('hide');
                })
                .fail(function(data) {
                    if (data.status === 422 && data.responseJSON) {
                        if (Object.keys(data.responseJSON.errors).length) {
                            for (field in data.responseJSON.errors) {
                                var error = data.responseJSON.errors[field];
                                var input = '#formRegister input[name=' + field + ']';
                                $(input).addClass('is-invalid');
                                $(input).next('span').find('strong').text(error[0]);
                            }
                        }
                    }
                });
        });
```

<pre class="lang-php prettyprint-override"><code>public function register(Request $request)
    {
        $this->validator($request->all())->validate();

        event(new Registered($user = $this->create($request->all())));

        $this->guard()->login($user);

        return $this->registered($request, $user)
            ?: response()->json();
    }
</code>```

 protected function sendLoginResponse(Request $request)
    {
        $request->session()->regenerate();

        $this->clearLoginAttempts($request);

        return $this->authenticated($request, $this->guard()->user())
            ?: response()->json();
    }
```

I except JSON output for my validation and page reload on successful request from the controller.

答:
Your sites have different protocols. One uses http and the other https. According to MDN:

A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, and port) than its own origin.

– Cross-Origin Resource Sharing

To fix this, use the same protocol for both sites.

Body:
Today i extended my workflow with Heroku and when i got everything up and running and started testing things like registration/login modal, then i got this error to my console.

Access to XMLHttpRequest at 'http://app-name.herokuapp.com/register' from origin 'https://app-name.herokuapp.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Tried adding Content-Security-Policy to my header in layout file, also adding X-CSRF-TOKEN to my ajax request header removed some part of the error, but then is just googled different solutions and tried them.

<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">

 $(document).on('submit', '#formRegister', function(e) {
            e.preventDefault();

            $('input+small').text('');
            $('#formRegister input').removeClass('is-invalid');

            $.ajax({
                method: $(this).attr('method'),
                url: $(this).attr('action'),
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                    'Access-Control-Allow-Methods' : 'POST',
                    'Access-Control-Allow-Headers' : 'X-Requested-With, Content-Type, X-Auth-Token, Origin, Authorization'
                },
                data: $(this).serialize(),
                dataType: "json",
                crossDomain: false
            })
                .done(function(data) {
                    $('.success-registered').removeClass('d-none');
                    $('#formRegister input').val('');
                    setTimeout(function() {
                        $('.success-registered').addClass('d-none');
                        location.reload();
                    }, 3000);
                    $('#login').modal('hide');
                })
                .fail(function(data) {
                    if (data.status === 422 && data.responseJSON) {
                        if (Object.keys(data.responseJSON.errors).length) {
                            for (field in data.responseJSON.errors) {
                                var error = data.responseJSON.errors[field];
                                var input = '#formRegister input[name=' + field + ']';
                                $(input).addClass('is-invalid');
                                $(input).next('span').find('strong').text(error[0]);
                            }
                        }
                    }
                });
        });

public function register(Request $request)
    {
        $this->validator($request->all())->validate();

        event(new Registered($user = $this->create($request->all())));

        $this->guard()->login($user);

        return $this->registered($request, $user)
            ?: response()->json();
    }

 protected function sendLoginResponse(Request $request)
    {
        $request->session()->regenerate();

        $this->clearLoginAttempts($request);

        return $this->authenticated($request, $this->guard()->user())
            ?: response()->json();
    }

I except JSON output for my validation and page reload on successful request from the controller.


来源: stackexchange

问:
Recusion - calculating sum of digits in a mixed string. (homework dead end)
I've got into a dead end while trying to fix some lines
in my code.

The task is writing a Recursion function which takes a string and calculating
the sum of the numbers in it.

For example -

```<code>input - "5a-f5-11"
output- The numbers are 5, 5 and 11, therefore the sum is 21.
</code>```

the Catch in this task is to sum numbers that are more than one digit.
(11 in our case)

I have not planned to use Char arrays or anything, but working with strings in some lines made it difficult.

My code doesn't compile so far but i'm sure the logic is in the right spot - (i made a helper function, which means its not the final function but its doing the main work).

```<code>public static int  sumNumbersInText(String str, int i, String subStr, int sum) {

    if(str.length() >= i) return sum;

    char[] array = new char[str.length()];
    str.getChars(0, str.length(), array, 0);

    char oneStr = array[i];
    String newSubStr = subStr;
    if(Character.isDigit(oneStr)); //if the new index is not a number and the index before IS a number>
    {

        if(Character.isDigit(subStr));// new index IS a number, therefore will sum up.
        {
            int num = 0;
            sum+=num;
            newSubStr = "";
        }
    }

    else
    {
        newSubStr += oneStr;
    }

    return sumNumbersInText(str, i+1, subStr, sum);
}
</code>```

答:
Somehow managed to figure it out, it actually works:</p>

```<code>public static int sum(String str, int i, String subStr, int sum) {
    if(str.length() <= i) return sum;
    String newSubStr = subStr;
    char oneStr = str.charAt(i);

    if(!Character.isDigit(oneStr)) //if the new index is not a number and the index before IS a number>
    {
        if(isNumeric(subStr))// new index IS a number, therefore will sum up.
        {
            int num = Integer.parseInt(subStr);
            sum+=num;
            newSubStr = "";
        }
    }
    else
    {
        String temp = oneStr+"";
        newSubStr += temp;
    }
    System.out.println(sum);
    return sum(str, i+1, newSubStr, sum);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've got into a dead end while trying to fix some lines
in my code.

The task is writing a Recursion function which takes a string and calculating
the sum of the numbers in it.

For example -

input - "5a-f5-11"
output- The numbers are 5, 5 and 11, therefore the sum is 21.

the Catch in this task is to sum numbers that are more than one digit.
(11 in our case)

I have not planned to use Char arrays or anything, but working with strings in some lines made it difficult.

My code doesn't compile so far but i'm sure the logic is in the right spot - (i made a helper function, which means its not the final function but its doing the main work).

public static int  sumNumbersInText(String str, int i, String subStr, int sum) {

    if(str.length() >= i) return sum;

    char[] array = new char[str.length()];
    str.getChars(0, str.length(), array, 0);

    char oneStr = array[i];
    String newSubStr = subStr;
    if(Character.isDigit(oneStr)); //if the new index is not a number and the index before IS a number>
    {

        if(Character.isDigit(subStr));// new index IS a number, therefore will sum up.
        {
            int num = 0;
            sum+=num;
            newSubStr = "";
        }
    }

    else
    {
        newSubStr += oneStr;
    }

    return sumNumbersInText(str, i+1, subStr, sum);
}

Body:
Somehow managed to figure it out, it actually works:

public static int sum(String str, int i, String subStr, int sum) {
    if(str.length() <= i) return sum;
    String newSubStr = subStr;
    char oneStr = str.charAt(i);

    if(!Character.isDigit(oneStr)) //if the new index is not a number and the index before IS a number>
    {
        if(isNumeric(subStr))// new index IS a number, therefore will sum up.
        {
            int num = Integer.parseInt(subStr);
            sum+=num;
            newSubStr = "";
        }
    }
    else
    {
        String temp = oneStr+"";
        newSubStr += temp;
    }
    System.out.println(sum);
    return sum(str, i+1, newSubStr, sum);
}


问:
Plot annotation in R-Markdown + tikzDevice
I'm preparing a presentation using R-Markdown + Beamer, and want every plot annotation to be typeset with a serif font.

Here's a minimal example (in order to run this, the code should be pasted in a .Rmd file and compiled with knitr):

```<code>---
title: An example
subtitle: which should work
output:
  beamer_presentation:
    theme: metropolis
header-includes:
  \usefonttheme[onlymath]{serif}
---

## A slide

```{r test, echo=FALSE, fig.height=3.2, fig.width=4, fig.align='center', dev='tikz', external=FALSE}
plot(2*pi*(0:19)/20, sin( 2*pi*(0:19)/20 ), xlab = '$x$', ylab='$\\sin(2\\pi x)$', pch=21, bg=rgb(0,.4,.7,.5), main='A plot using \\LaTeX', font.main=1)
```
</code>```

In the generated plot, I expect the font annotations in the axes' numbering, plot title, etc, to be typeset with a serif font (the same fonts that appear in math annotations), but the actual output is typesetting with a sans-serif font. It is important that the rest of the document still typesets with sans-serif fonts.

答:
That is because the plots are compiled in seperate tex files. To change anything about the plots you should change the tikzLatexPackages option. The default is

```<code>options(
tikzLatexPackages = c(
    "\\usepackage{tikz}",
    "\\usepackage[active,tightpage]{preview}",
    "\\PreviewEnvironment{pgfpicture}",
    "\\setlength\\PreviewBorder{0pt}")
),
tikzXelatexPackages = c(
    "\\usepackage{tikz}\n",
    "\\usepackage[active,tightpage,xetex]{preview}\n",
    "\\usepackage{fontspec,xunicode}\n",
    "\\PreviewEnvironment{pgfpicture}\n",
    "\\setlength\\PreviewBorder{0pt}\n"
),
tikzLualatexPackages = c(
    "\\usepackage{tikz}\n",
    "\\usepackage[active,tightpage,psfixbb]{preview}\n",
    "\\usepackage{fontspec,xunicode}\n",
    "\\PreviewEnvironment{pgfpicture}\n",
"\\setlength\\PreviewBorder{0pt}\n")
)
</code>```

So adding \usefonttheme[onlymath]{serif} to that first option should do it.

You can find more info on this on page 6 of the tikzDevice manual.

Note that it is also possible to include the tex code rather then the precompiled code. Though I had some issues with this approach in the past.

Body:
I'm preparing a presentation using R-Markdown + Beamer, and want every plot annotation to be typeset with a serif font.

Here's a minimal example (in order to run this, the code should be pasted in a .Rmd file and compiled with knitr):

---
title: An example
subtitle: which should work
output:
  beamer_presentation:
    theme: metropolis
header-includes:
  \usefonttheme[onlymath]{serif}
---

## A slide

```{r test, echo=FALSE, fig.height=3.2, fig.width=4, fig.align='center', dev='tikz', external=FALSE}
plot(2*pi*(0:19)/20, sin( 2*pi*(0:19)/20 ), xlab = '$x$', ylab='$\\sin(2\\pi x)$', pch=21, bg=rgb(0,.4,.7,.5), main='A plot using \\LaTeX', font.main=1)
```

In the generated plot, I expect the font annotations in the axes' numbering, plot title, etc, to be typeset with a serif font (the same fonts that appear in math annotations), but the actual output is typesetting with a sans-serif font. It is important that the rest of the document still typesets with sans-serif fonts.

Body:
That is because the plots are compiled in seperate tex files. To change anything about the plots you should change the tikzLatexPackages option. The default is

options(
tikzLatexPackages = c(
    "\\usepackage{tikz}",
    "\\usepackage[active,tightpage]{preview}",
    "\\PreviewEnvironment{pgfpicture}",
    "\\setlength\\PreviewBorder{0pt}")
),
tikzXelatexPackages = c(
    "\\usepackage{tikz}\n",
    "\\usepackage[active,tightpage,xetex]{preview}\n",
    "\\usepackage{fontspec,xunicode}\n",
    "\\PreviewEnvironment{pgfpicture}\n",
    "\\setlength\\PreviewBorder{0pt}\n"
),
tikzLualatexPackages = c(
    "\\usepackage{tikz}\n",
    "\\usepackage[active,tightpage,psfixbb]{preview}\n",
    "\\usepackage{fontspec,xunicode}\n",
    "\\PreviewEnvironment{pgfpicture}\n",
"\\setlength\\PreviewBorder{0pt}\n")
)

So adding \usefonttheme[onlymath]{serif} to that first option should do it.

You can find more info on this on page 6 of the tikzDevice manual.

Note that it is also possible to include the tex code rather then the precompiled code. Though I had some issues with this approach in the past.


问:
How does Xcode know which profile the application belongs to?
I have been wondering about how does xcode link the provisioning profile to a particular application.

For example, I install profile named 'myprofile' in the organizer and go to the project name 'newapp' and say build and go.

The application 'newapp' is installed fine on the iphone but how do i know if there is a link between 'newapp' and 'myprofile'.

What happens if i change my app name and again say build and go?

This is what i do:

 1. Login to my account.

 2. Create a new app id: 'first'

 3. Use existing device: 'myiphone'

 4. enter the profile name: 'myprofile', download it

 5. install it inside organizer. (Till this point no application is assigned to the profile)

 6. Now go to my project: 'newapp' just say build and go and app runs on the device.

I never selected a profile and said assign the app to this profile so...
How can i say that 'myprofile' is tied to 'newapp'?

Thanks

答: Its your app bundle identifier from the project-info.plist file that is mapped to a profile. You can ofcourse have wildcard characters and use a profile to build multiple apps.</p>

ContentLicense: CC BY-SA 3.0


问:
How can I type check a generic then cast to it in swift?
I like the ideas presented in this post, about making database-agnostic, protocol-oriented code.

So say I have a protocol such as:

```<code>protocol Database {
    func loadObjects<T>(matching query: Query) -> [T]
    func loadObject<T>(withID id: String) -> T?
    func save<T>(_ object: T)
}
</code>```

where Query is a struct that has filter and sort specifiers.

Then, given a persistence framework, such as Realm or CoreData, I can just support this protocol, as such:

```<code>extension NSManagedObjectContext: Database {
    ...
}

extension Realm: Database {
    ...
}

extension MockedDatabase: Database {
    ...
}

extension UITestingDatabase: Database {
    ...
}
</code>```

The issue arises when I would want to use CoreData.

If we look at the method:

func loadObjects<T>(matching query: Query) -> [T]

I have no way to 'cast' T to NSManagedObject.

For example, my desired implementation might be something like:

```<code>extension NSManagedObjectContext: Database {

    func loadObjects<T>(matching query: Query<T>) -> [T] {

        // you need a fetch request for these models.  This guard statement compiles.  How do we make it work with NSFetchRequestResult however?
        guard T.self is NSManagedObject.Type else {
            return []
        }

        // This line below Fails compiling.  Type 'T' does not conform to protocol 'NSFetchRequestResult'
        var request = NSFetchRequest<T>(entityName: String(describing: T))

        // then set sortDescriptors and predicate, etc.

        var objects: [T] = []
        self.performAndWait {
            do {
                if let results = try self.fetch(request!) as? [T] {
                    objects = results
                }

            } catch let error {
                print("Error fetching: \(error.localizedDescription)")
            }
        }
        return objects
    }
}
</code>```

So if I can determine if T's Type is a kind of NSManagedObject, then is it possible to instantiate a NSFetchRequest by 'casting' T to something that will work?  It would seem I can't cast or force T to be anything.

Database is a technology-agnostic protocol and therefore shouldn't know anything about Core Data.  I'd like to do this in the event I need to change my data persistence framework.

How might I accomplish this in Swift?  Would I have to add to the Model protocol to return optionals that would be used for the given frameworks I would support?  Or make them support NSFetchRequestResult?  I would rather that only the implementation of the protocol need to care about the details of the persistence framework.

答:
Rather than checking the type at runtime constrain the type at compile time, for example

```<code>extension NSManagedObjectContext: Database {

    func loadObjects<T: NSManagedObject>(matching query: Query<T>) -> [T] {

        let request = NSFetchRequest<T>(entityName: String(describing: T.self))

        var objects = [T]()
        self.performAndWait {
            do {
                objects = try self.fetch(request) // a generic fetch request returns an array of the generic type or throws an error
            } catch let error {
                print("Error fetching: \(error.localizedDescription)")
            }
        }
        return objects
    }
}
</code>```

Body:
I like the ideas presented in this post, about making database-agnostic, protocol-oriented code.

So say I have a protocol such as:

protocol Database {
    func loadObjects<T>(matching query: Query) -> [T]
    func loadObject<T>(withID id: String) -> T?
    func save<T>(_ object: T)
}

where Query is a struct that has filter and sort specifiers.

Then, given a persistence framework, such as Realm or CoreData, I can just support this protocol, as such:

extension NSManagedObjectContext: Database {
    ...
}

extension Realm: Database {
    ...
}

extension MockedDatabase: Database {
    ...
}

extension UITestingDatabase: Database {
    ...
}

The issue arises when I would want to use CoreData.

If we look at the method:

func loadObjects<T>(matching query: Query) -> [T]

I have no way to 'cast' T to NSManagedObject.

For example, my desired implementation might be something like:

extension NSManagedObjectContext: Database {

    func loadObjects<T>(matching query: Query<T>) -> [T] {

        // you need a fetch request for these models.  This guard statement compiles.  How do we make it work with NSFetchRequestResult however?
        guard T.self is NSManagedObject.Type else {
            return []
        }

        // This line below Fails compiling.  Type 'T' does not conform to protocol 'NSFetchRequestResult'
        var request = NSFetchRequest<T>(entityName: String(describing: T))

        // then set sortDescriptors and predicate, etc.

        var objects: [T] = []
        self.performAndWait {
            do {
                if let results = try self.fetch(request!) as? [T] {
                    objects = results
                }

            } catch let error {
                print("Error fetching: \(error.localizedDescription)")
            }
        }
        return objects
    }
}

So if I can determine if T's Type is a kind of NSManagedObject, then is it possible to instantiate a NSFetchRequest by 'casting' T to something that will work?  It would seem I can't cast or force T to be anything.

Database is a technology-agnostic protocol and therefore shouldn't know anything about Core Data.  I'd like to do this in the event I need to change my data persistence framework.

How might I accomplish this in Swift?  Would I have to add to the Model protocol to return optionals that would be used for the given frameworks I would support?  Or make them support NSFetchRequestResult?  I would rather that only the implementation of the protocol need to care about the details of the persistence framework.

Body:
Rather than checking the type at runtime constrain the type at compile time, for example

extension NSManagedObjectContext: Database {

    func loadObjects<T: NSManagedObject>(matching query: Query<T>) -> [T] {

        let request = NSFetchRequest<T>(entityName: String(describing: T.self))

        var objects = [T]()
        self.performAndWait {
            do {
                objects = try self.fetch(request) // a generic fetch request returns an array of the generic type or throws an error
            } catch let error {
                print("Error fetching: \(error.localizedDescription)")
            }
        }
        return objects
    }
}


问:
Default activity not found in my android studio
I have created a new project in android studio and when i am trying to run it ,it is saying default activity not found.i have checked my manifest file this does not contain any problem.
there is a Red X Mark android studio application while running</p>

答:
Check whether your Launcher activity intent filter has this

```<code>tools:node="remove"
</code>```

If yes, remove it and error will be resolved. This piece of code will be used when we are having flavors in our project structure, in-order to remove a Launcher activity.

Else, Two launcher icons will be installed.

Body:
Check whether your Launcher activity intent filter has this

tools:node="remove"

If yes, remove it and error will be resolved. This piece of code will be used when we are having flavors in our project structure, in-order to remove a Launcher activity.

Else, Two launcher icons will be installed.


问:
Wicket authentication error following example
I am learning wicket and trying to implement Authentication based on the flowing strategy

Example

I created MyAuthenticatedWebApplication class and also MyAuthenticatedWebSession with all other components, but as soon as I am trying to go to MySignInPage, I get this error.

Last cause: org.apache.wicket.protocol.http.WebSession cannot be cast to org.apache.wicket.authroles.authentication.AuthenticatedWebSession
WicketMessage: Error attaching this container for rendering: [Page class = com.myapp.wicket.SignInPage, id = 3, render count = 1]

Can someone please help?

答:
Instead of

```<code>@Override
protected Class<? extends AbstractAuthenticatedWebSession > getWebSessionClass() {
    return BasicAuthenticationSession.class;
}
</code>```

try to use

```<code>@Override
protected Class<? extends AuthenticatedWebSession> getWebSessionClass() {
    return BasicAuthenticationSession.class;
}
</code>```

Body:
Instead of

@Override
protected Class<? extends AbstractAuthenticatedWebSession > getWebSessionClass() {
    return BasicAuthenticationSession.class;
}

try to use

@Override
protected Class<? extends AuthenticatedWebSession> getWebSessionClass() {
    return BasicAuthenticationSession.class;
}


问:
Replace each occurrence ending with a specific letter from a string separated by blanks
I would like to remove all occurrences which end with a specific letter (lets say "a") from a string. I am not dealing with a vector composed of different elements but rather a string separated by spaces.

Here are the data:

```<code>have = "Da 4e 5c 6a 7a"
want = "4e 5c"
</code>```

Any idea?

Thank you in advance,

Anthony

答:
This is a way with ws trimming on both sides

Find

(?<!\S)(?:[^\S\r\n]*\S*a[^\S\r\n]*)+

Replace

nothing

Rationale

```<code> (?<! \S )              # Wsp boundary, this will leave 1 space behind for separation
 (?:                    # Group
      [^\S\r\n]*             # optional horizontal whitespaces
      \S*                    # optional non-whitespaces
      a                      # required, ends with an  'a'
      [^\S\r\n]*             # optional horizontal whitespaces
 )+                     # End group, do 1 to many sequences
</code>```

Body:
I would like to remove all occurrences which end with a specific letter (lets say "a") from a string. I am not dealing with a vector composed of different elements but rather a string separated by spaces.

Here are the data:

have = "Da 4e 5c 6a 7a"
want = "4e 5c"

Any idea?

Thank you in advance,

Anthony

Body:
This is a way with ws trimming on both sides

Find

(?<!\S)(?:[^\S\r\n]*\S*a[^\S\r\n]*)+

Replace

nothing

Rationale

 (?<! \S )              # Wsp boundary, this will leave 1 space behind for separation
 (?:                    # Group
      [^\S\r\n]*             # optional horizontal whitespaces
      \S*                    # optional non-whitespaces
      a                      # required, ends with an  'a'
      [^\S\r\n]*             # optional horizontal whitespaces
 )+                     # End group, do 1 to many sequences


问:
Failing consul health check on local machine
I have Consul running via docker using docker-compose

```<code>version: '3'

services:
  consul:
    image: unifio/consul:latest
    ports:
      - "8500:8500"
      - "8300:8300"
    volumes:
      - ./config:/config
      - ./.data/consul:/data
    command: agent -server -data-dir=/data -ui -bind 0.0.0.0 -client 0.0.0.0 -bootstrap-expect=1
  mongo:
    image: mongo
    ports:
      - "27017:27017"
      - "27018:27018"
    volumes:
      - ./.data/mongodb:/data/db
    command: mongod --bind_ip_all
</code>```

and have a nodejs service running on port 6001 which exposes a /health endpoint for health checks.
I am able to register the service via this consul package.
However, visiting the consul UI I can see that the service has a status of failing because the health check is not working.

The UI show this message:

```<code>Get http://127.0.0.1:6001/health: dial tcp 127.0.0.1:6001: getsockopt: connection refused
</code>```

Not sure why is not working exactly, but I kind of sense that i may have misconfigured consul.
Any help would be great.

答:
Consul is running in your docker container. When you use 127.0.0.1 in this container, it refers to itself, not to your host.

You need to use a host IP that is known to your container (and of course make sure your service is reachable and listening on this particular IP).

In most cases, you should be able to contact your host from a container through the default docker0 bridge ip that you can get with ip addr show dev docker0 from your host as outlined in this other answer.

The best solution IMO is to discover the gateway that your container is using which will point to the particular bridge IP on your host (i.e. the bridge created for your docker-compose project when starting it). There are several methods you can use to discover this ip from the container depending on the installed tooling and your linux flavor.

Body:
I have Consul running via docker using docker-compose

version: '3'

services:
  consul:
    image: unifio/consul:latest
    ports:
      - "8500:8500"
      - "8300:8300"
    volumes:
      - ./config:/config
      - ./.data/consul:/data
    command: agent -server -data-dir=/data -ui -bind 0.0.0.0 -client 0.0.0.0 -bootstrap-expect=1
  mongo:
    image: mongo
    ports:
      - "27017:27017"
      - "27018:27018"
    volumes:
      - ./.data/mongodb:/data/db
    command: mongod --bind_ip_all

and have a nodejs service running on port 6001 which exposes a /health endpoint for health checks.
I am able to register the service via this consul package.
However, visiting the consul UI I can see that the service has a status of failing because the health check is not working.

The UI show this message:

Get http://127.0.0.1:6001/health: dial tcp 127.0.0.1:6001: getsockopt: connection refused

Not sure why is not working exactly, but I kind of sense that i may have misconfigured consul.
Any help would be great.


问:
Java: what's the big-O time of declaring an array of size n?
What is the running time of declaring an array of size n in Java? I suppose this would depend on whether the memory is zero'ed out on garbage collection (in which case it could be O(1) ) or on initialization (in which case it'd have to be O(n) ).</p>

答:
I am pretty sure that it is O(n), as the memory is initialized when the array is allocated. It should not be higher than O(n), and I can see no way to make it less than O(n), so that seems the only option.

To elaborate further, Java initializes arrays on allocation. There is no way to zero a region of memory without walking across it, and the size of the region dictates the number of instructions. Therefore, the lower bound is O(n). Also, it would make no sense to use a zeroing algorithm slower than linear, since there is a linear solution, so the upper bound must be O(n). Therefore, O(n) is the only answer that makes sense.

Just for fun, though, imagine a weird piece of hardware where the OS has control over the power to individual regions of memory and may zero a region by flipping the power off and then on. This seems like it would be O(1). But a region can only be so large before the utility disappears (wouldn't want to lose everything), so asking to zero a region will still be O(n) with a large divisor.


问:
decimal formatting pattern in Java
I want format this number using java :  1546521.23 to 1 546 521.23
for exemple when i format this number 70000.0 it output 7 00 00

I tried this pattern but not work :

```<code>DecimalFormat decimalFormat = new DecimalFormat("### ###,##");
</code>```

答:
See the DecimalFormat documentation:

```<code>Symbol  Location    Localized?  Meaning
.       Number      Yes         Decimal separator or monetary decimal separator
,       Number      Yes         Grouping separator
</code>```

Change code to

```<code>DecimalFormat decimalFormat = new DecimalFormat("### ###.##");
</code>```

The comma needs to be replaced with a period.

Title: decimal formatting pattern in Java

Body:
I want format this number using java :  1546521.23 to 1 546 521.23
for exemple when i format this number 70000.0 it output 7 00 00

I tried this pattern but not work :

DecimalFormat decimalFormat = new DecimalFormat("### ###,##");

Body:
See the DecimalFormat documentation:

Symbol  Location    Localized?  Meaning
.       Number      Yes         Decimal separator or monetary decimal separator
,       Number      Yes         Grouping separator

Change code to

DecimalFormat decimalFormat = new DecimalFormat("### ###.##");

The comma needs to be replaced with a period.


问:
How to make std::istream_iterator read only until the end of line?
Having the following piece of code:

std::vector<int64> values;
std::copy(
  std::istream_iterator<int64>(std::cin),
  std::istream_iterator<int64>(),
  std::back_inserter(values)
);
```

I'd like to make it read the input stream only until the end of line. How can I do that with std::istream_iterator?

答:
It is impossible to change istream_iterator in this way, because it has no knowledge of newlines, or even of characters, for that matter. It only knows about int64(Or whatever type you instantiated it with) and if the stream ended or failed (When it then will return false on operator bool()).

This means that our point of customization must be the actual stream.

The stream object is actually just a wrapper around a std::basic_streambuf. The streambuf will spit out characters until it finds an EOF. You can simply adapt it to return an EOF once it finds a newline, then the stream will temporarily treat that as the end of stream.

Doing this is easy: The streambuf object is accessible through the member funtion rdbuf(). You can just replace the buffer with your custom one using this function. To have it continue reading after the newline when you're done, you can just return the original std::basic_streambuf back to the stream.

```<code>#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <streambuf>
#include <vector>

// This is our custom std::basic_streambuf object.
// We chose the underflow function as our point of customization, because
// it is there that the action is happening: it is this function that
// that is responsible for reading more data from the stream.
class newline_buf : public std::streambuf {
    std::streambuf* src;
    char ch; // single-byte buffer
protected:
    int underflow() {
        if( (ch= src->sbumpc()) == '\n') {
            return traits_type::eof(); // return EOF on new line.
        }
        setg(&ch, &ch, &ch+1); // make one read position available
        return ch; // may also return EOF by the regular means
    }
public:
    newline_buf(std::streambuf* buf) : src(buf) {
        setg(&ch, &ch+1, &ch+1); // buffer is initially full
    }
};

int main() {
    // testing with a stringstream to make things easier to reproduce.
    // Should work fine with any type of input stream.
    std::istringstream iss(R"(12345 12345 12345
    67890 67890 67890)");

    // We store the original rdbuf so we can recover it later.
    auto original_rdbuf = iss.rdbuf();
    newline_buf buf(original_rdbuf);
    iss.basic_ios::rdbuf(&buf);

    // Do the copy and then recover the original rdbuf
    std::copy(std::istream_iterator<int>(iss), std::istream_iterator<int>(), std::ostream_iterator<int>(std::cout, " "));
    iss.basic_ios::rdbuf(original_rdbuf);

    // You can try doing a new copy, just to convince yourself that the stream is still in a valid state.
    //std::copy(std::istream_iterator<int>(iss), std::istream_iterator<int>(), std::ostream_iterator<int>(std::cout, " "));
}
</code>```

See it live!

Body:
Having the following piece of code:

std::vector<int64> values;
std::copy(
  std::istream_iterator<int64>(std::cin),
  std::istream_iterator<int64>(),
  std::back_inserter(values)
);

I'd like to make it read the input stream only until the end of line. How can I do that with std::istream_iterator?

Body:
It is impossible to change istream_iterator in this way, because it has no knowledge of newlines, or even of characters, for that matter. It only knows about int64(Or whatever type you instantiated it with) and if the stream ended or failed (When it then will return false on operator bool()).

This means that our point of customization must be the actual stream.

The stream object is actually just a wrapper around a std::basic_streambuf. The streambuf will spit out characters until it finds an EOF. You can simply adapt it to return an EOF once it finds a newline, then the stream will temporarily treat that as the end of stream.

Doing this is easy: The streambuf object is accessible through the member funtion rdbuf(). You can just replace the buffer with your custom one using this function. To have it continue reading after the newline when you're done, you can just return the original std::basic_streambuf back to the stream.

#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <streambuf>
#include <vector>

// This is our custom std::basic_streambuf object.
// We chose the underflow function as our point of customization, because
// it is there that the action is happening: it is this function that
// that is responsible for reading more data from the stream.
class newline_buf : public std::streambuf {
    std::streambuf* src;
    char ch; // single-byte buffer
protected:
    int underflow() {
        if( (ch= src->sbumpc()) == '\n') {
            return traits_type::eof(); // return EOF on new line.
        }
        setg(&ch, &ch, &ch+1); // make one read position available
        return ch; // may also return EOF by the regular means
    }
public:
    newline_buf(std::streambuf* buf) : src(buf) {
        setg(&ch, &ch+1, &ch+1); // buffer is initially full
    }
};

int main() {
    // testing with a stringstream to make things easier to reproduce.
    // Should work fine with any type of input stream.
    std::istringstream iss(R"(12345 12345 12345
    67890 67890 67890)");

    // We store the original rdbuf so we can recover it later.
    auto original_rdbuf = iss.rdbuf();
    newline_buf buf(original_rdbuf);
    iss.basic_ios::rdbuf(&buf);

    // Do the copy and then recover the original rdbuf
    std::copy(std::istream_iterator<int>(iss), std::istream_iterator<int>(), std::ostream_iterator<int>(std::cout, " "));
    iss.basic_ios::rdbuf(original_rdbuf);

    // You can try doing a new copy, just to convince yourself that the stream is still in a valid state.
    //std::copy(std::istream_iterator<int>(iss), std::istream_iterator<int>(), std::ostream_iterator<int>(std::cout, " "));
}

See it live!


问:
Sending HTML in an e-mail message's body
I'm trying to send an e-mail containing HTML, but the HTML shows up literally. How can I send an HTML link? Here's my current code:</p>

```<code>Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("text/html");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]
{"[EMAIL PROTECTED]"});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
"Subject");
<b>emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,
"<html><body>Example</body></html>");</b>
context.startActivity(Intent.createChooser(emailIntent, "Send
mail..."));</code>```

答: There seems to be bugs in both gmail and email apps on Android. The email app cannot send links correctly if you put it into html, gmail sends the link okay. Gmail doesn't display the email with the links though, and the email app does display them correctly so they are clickable. At least it is the case if you are using custom uri's.</p>

Body:
I'm trying to send an e-mail containing HTML, but the HTML shows up literally. How can I send an HTML link? Here's my current code:

Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("text/html");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]
{"[EMAIL PROTECTED]"});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
"Subject");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,
"Example");
context.startActivity(Intent.createChooser(emailIntent, "Send
mail..."));


问:
How to select letters from a string until predefined point?
I would like to extract all consonants in a string before the first vowel, ideally without using regex. If I have the word truck for example I would like to extract the "tr", for "street" I would like to extract "str".

I tried the following but received the error wrong number of arguments (given 0, expected 1) for the execution of the block in vowels.

Can someone explain where the error is or suggest an easier way to do this?

```<code>vowels = ["a", "e", "i", "o", "u"]

def vowels(words)
  letters = words.split("")
  consonants = []
  letters.each do |letter|
    consonants << letter until vowels.include?(letter)
  end
  consonants
end
</code>```

答:
Consider using Enumerable#chunk:

```<code>VOWELS = ["a", "e", "i", "o", "u"]
word = "truck"
word.chars.chunk { |e| VOWELS.include? e }.first.last.join
#=> "tr"
</code>```

The first part returns

```<code>word.chars.chunk { |e| VOWELS.include? e }.to_a #=> [[false, ["t", "r"]], [true, ["u"]], [false, ["c", "k"]]]
</code>```

Body:
I would like to extract all consonants in a string before the first vowel, ideally without using regex. If I have the word truck for example I would like to extract the "tr", for "street" I would like to extract "str".

I tried the following but received the error wrong number of arguments (given 0, expected 1) for the execution of the block in vowels.

Can someone explain where the error is or suggest an easier way to do this?

vowels = ["a", "e", "i", "o", "u"]

def vowels(words)
  letters = words.split("")
  consonants = []
  letters.each do |letter|
    consonants << letter until vowels.include?(letter)
  end
  consonants
end

Body:
Consider using Enumerable#chunk:

VOWELS = ["a", "e", "i", "o", "u"]
word = "truck"
word.chars.chunk { |e| VOWELS.include? e }.first.last.join
#=> "tr"

The first part returns

word.chars.chunk { |e| VOWELS.include? e }.to_a #=> [[false, ["t", "r"]], [true, ["u"]], [false, ["c", "k"]]]


问:
Calculating time 90 minutes prior to due date/time in Objective C (iPhone app)
This is a completely noobish question, but I spent 2 hours yesterday trying to make it work, and I'm obviously missing something very basic.

What I need to do is take input from user of date/time and count back 90 minutes for an alert.

Could someone please post an example calculation, where you have a var that holds user input and a new var that receives the result of this computation? (all done in Objective C for use in an iPhone app) Thank you!

答:
I think this should work:

```<code>NSDate * alarmDate = [NSDate dateWithTimeInterval:5400 sinceDate:userDefinedDate];
NSDate * now = [NSDate date];
NSTimeInterval wait = [now timeIntervalSinceDate:alarmDate];

[self performSelector:@selector(callAlarm) withObject:nil afterDelay:fabs(wait)];
</code>```

Although I do agree with Nick too, adding your work its much more productive..

Body:
I think this should work:

NSDate * alarmDate = [NSDate dateWithTimeInterval:5400 sinceDate:userDefinedDate];
NSDate * now = [NSDate date];
NSTimeInterval wait = [now timeIntervalSinceDate:alarmDate];

[self performSelector:@selector(callAlarm) withObject:nil afterDelay:fabs(wait)];

Although I do agree with Nick too, adding your work its much more productive..


问:
How to draw a circle on a FigureCanvasQTAgg on mouse click
I am new to Qt and I am trying to do a program, that I've previously done in tkinter, to learn how to use it. I have embedded a FigureCanvasQtAgg in a Qt window. I have ploted thing on it. Now I want to plot on this canvas a circle on user's mouse click.

What I have done to do it on Tkinter is to use :

```<code>self.canvas.get_tk_widget().create_oval()
</code>```

Is there a simple way to have the same results in PySide2?

Here is a simpler code with what I've tried :

```<code>from PySide2.QtWidgets import *
from PySide2.QtCore import *
from PySide2.QtGui import *

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as plt

import numpy as np
import sys

class MyPaintWidget(QWidget):

    def __init__(self):
        super().__init__()
        layout_canvas = QVBoxLayout()
        self.fig = plt.gcf()
        plt.plot(np.cos([i for i in np.arange(0, 10, 0.1)]))
        self.canvas = FigureCanvas(self.fig)
        self.canvas.mpl_connect('button_press_event', self._on_left_click)
        layout_canvas.addWidget(self.canvas)
        self.setLayout(layout_canvas)

    def _on_left_click(self, event):
        print(event.xdata, event.ydata)
        qp = QPainter()
        qp.drawEllipse(QPointF(event.x, event.y), 10, 10)
        qp.end()
        self.canvas.draw()

if __name__=="__main__":
    app = QApplication(sys.argv)

    w = MyPaintWidget()
    w.show()

    app.exec_()
</code>```

What I have done in tkinter (when I click on the canvas a green point does appear) :

```<code>import tkinter as tk
import tkinter.ttk as ttk
import numpy as np
import sys

from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.backend_bases import key_press_handler
import matplotlib.pyplot as plt

class MainFrame(ttk.Frame):
    def __init__(self, master):
        ttk.Frame.__init__(self, master)
        self.master = master
        self.fig = plt.gcf()
        plt.plot(np.cos([i for i in np.arange(0, 10, 0.1)]))
        self.canvas = FigureCanvasTkAgg(self.fig, master=self.master)  # A tk.DrawingArea.
        self.canvas.get_tk_widget().grid(row=0, column=0)
        self.canvas.draw()
        self.canvas.mpl_connect('button_press_event', self._on_left_click)

    def _on_left_click(self, event):
        self._add_point(event.x, event.y)

    def _add_point(self, x, y):
        self.canvas.get_tk_widget().create_oval(x - 4, self.canvas.get_tk_widget().winfo_height() - (y - 4), x + 4,
                                                self.canvas.get_tk_widget().winfo_height() - (y + 4), fill='green')

if __name__=="__main__":
    window = tk.Tk()
    main_frame = MainFrame(window)
    window.mainloop()

</code>```

Any ideas to get this result in QT ? Thanks !

答:
Unlike tkinter Qt does not implement a function like create_oval() to make the circles so an alternative is to use the tools of matplotlib.

from PySide2 import QtCore, QtGui, QtWidgets

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as plt

import numpy as np

class MyPaintWidget(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()

        self.figure = plt.gcf()
        self.canvas = FigureCanvas(self.figure)
        self.canvas.mpl_connect("button_press_event", self._on_left_click)
        self.axes = self.figure.add_subplot(111)
        x = np.arange(0, 10, 0.1)
        y = np.cos(x)
        self.axes.plot(x, y)

        layout_canvas = QtWidgets.QVBoxLayout(self)
        layout_canvas.addWidget(self.canvas)

    def _on_left_click(self, event):
        self.axes.scatter(event.xdata, event.ydata)
        self.figure.canvas.draw()

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)

    w = MyPaintWidget()
    w.show()
    sys.exit(app.exec_())
```

<p><img src="https://i.stack.imgur.com/8Vzhz.png" alt="enter image description here"></p>

<p>Another possible solution is to implement the method create_oval() inheriting from the class FigureCanvas:</p>

<pre class="lang-py prettyprint-override"><code>from PySide2 import QtCore, QtGui, QtWidgets

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

import numpy as np

class PainterCanvas(FigureCanvas):
    def __init__(self, parent=None, width=5, height=4, dpi=100):
        fig = Figure(figsize=(width, height), dpi=dpi)
        FigureCanvas.__init__(self, fig)
        self.setParent(parent)
        self._instructions = []
        self.axes = self.figure.add_subplot(111)

    def paintEvent(self, event):
        super().paintEvent(event)
        painter = QtGui.QPainter(self)
        painter.setRenderHint(QtGui.QPainter.Antialiasing, True)
        width, height = self.get_width_height()
        for x, y, rx, ry, br_color in self._instructions:
            x_pixel, y_pixel_m = self.axes.transData.transform((x, y))
            # In matplotlib, 0,0 is the lower left corner,
            # whereas it's usually the upper right
            # for most image software, so we'll flip the y-coor
            y_pixel = height - y_pixel_m
            painter.setBrush(QtGui.QColor(br_color))
            painter.drawEllipse( QtCore.QPoint(x_pixel, y_pixel), rx, ry)

    def create_oval(self, x, y, radius_x=5, radius_y=5, brush_color="red"):
        self._instructions.append([x, y, radius_x, radius_y, brush_color])
        self.update()

class MyPaintWidget(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()

        self.canvas = PainterCanvas()
        self.canvas.mpl_connect("button_press_event", self._on_left_click)
        x = np.arange(0, 10, 0.1)
        y = np.cos(x)
        self.canvas.axes.plot(x, y)

        layout_canvas = QtWidgets.QVBoxLayout(self)
        layout_canvas.addWidget(self.canvas)

    def _on_left_click(self, event):
        self.canvas.create_oval(event.xdata, event.ydata, brush_color="green")

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)

    w = MyPaintWidget()
    w.show()
    sys.exit(app.exec_())
</code>```

Body:
I am new to Qt and I am trying to do a program, that I've previously done in tkinter, to learn how to use it. I have embedded a FigureCanvasQtAgg in a Qt window. I have ploted thing on it. Now I want to plot on this canvas a circle on user's mouse click.

What I have done to do it on Tkinter is to use :

self.canvas.get_tk_widget().create_oval()

Is there a simple way to have the same results in PySide2?

Here is a simpler code with what I've tried :

from PySide2.QtWidgets import *
from PySide2.QtCore import *
from PySide2.QtGui import *

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as plt

import numpy as np
import sys

class MyPaintWidget(QWidget):

    def __init__(self):
        super().__init__()
        layout_canvas = QVBoxLayout()
        self.fig = plt.gcf()
        plt.plot(np.cos([i for i in np.arange(0, 10, 0.1)]))
        self.canvas = FigureCanvas(self.fig)
        self.canvas.mpl_connect('button_press_event', self._on_left_click)
        layout_canvas.addWidget(self.canvas)
        self.setLayout(layout_canvas)

    def _on_left_click(self, event):
        print(event.xdata, event.ydata)
        qp = QPainter()
        qp.drawEllipse(QPointF(event.x, event.y), 10, 10)
        qp.end()
        self.canvas.draw()

if __name__=="__main__":
    app = QApplication(sys.argv)

    w = MyPaintWidget()
    w.show()

    app.exec_()

What I have done in tkinter (when I click on the canvas a green point does appear) :

import tkinter as tk
import tkinter.ttk as ttk
import numpy as np
import sys

from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.backend_bases import key_press_handler
import matplotlib.pyplot as plt

class MainFrame(ttk.Frame):
    def __init__(self, master):
        ttk.Frame.__init__(self, master)
        self.master = master
        self.fig = plt.gcf()
        plt.plot(np.cos([i for i in np.arange(0, 10, 0.1)]))
        self.canvas = FigureCanvasTkAgg(self.fig, master=self.master)  # A tk.DrawingArea.
        self.canvas.get_tk_widget().grid(row=0, column=0)
        self.canvas.draw()
        self.canvas.mpl_connect('button_press_event', self._on_left_click)

    def _on_left_click(self, event):
        self._add_point(event.x, event.y)

    def _add_point(self, x, y):
        self.canvas.get_tk_widget().create_oval(x - 4, self.canvas.get_tk_widget().winfo_height() - (y - 4), x + 4,
                                                self.canvas.get_tk_widget().winfo_height() - (y + 4), fill='green')

if __name__=="__main__":
    window = tk.Tk()
    main_frame = MainFrame(window)
    window.mainloop()

Any ideas to get this result in QT ? Thanks !

Body:
Unlike tkinter Qt does not implement a function like create_oval() to make the circles so an alternative is to use the tools of matplotlib.

from PySide2 import QtCore, QtGui, QtWidgets

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as plt

import numpy as np

class MyPaintWidget(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()

        self.figure = plt.gcf()
        self.canvas = FigureCanvas(self.figure)
        self.canvas.mpl_connect("button_press_event", self._on_left_click)
        self.axes = self.figure.add_subplot(111)
        x = np.arange(0, 10, 0.1)
        y = np.cos(x)
        self.axes.plot(x, y)

        layout_canvas = QtWidgets.QVBoxLayout(self)
        layout_canvas.addWidget(self.canvas)

    def _on_left_click(self, event):
        self.axes.scatter(event.xdata, event.ydata)
        self.figure.canvas.draw()

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)

    w = MyPaintWidget()
    w.show()
    sys.exit(app.exec_())

Another possible solution is to implement the method create_oval() inheriting from the class FigureCanvas:

from PySide2 import QtCore, QtGui, QtWidgets

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

import numpy as np

class PainterCanvas(FigureCanvas):
    def __init__(self, parent=None, width=5, height=4, dpi=100):
        fig = Figure(figsize=(width, height), dpi=dpi)
        FigureCanvas.__init__(self, fig)
        self.setParent(parent)
        self._instructions = []
        self.axes = self.figure.add_subplot(111)

    def paintEvent(self, event):
        super().paintEvent(event)
        painter = QtGui.QPainter(self)
        painter.setRenderHint(QtGui.QPainter.Antialiasing, True)
        width, height = self.get_width_height()
        for x, y, rx, ry, br_color in self._instructions:
            x_pixel, y_pixel_m = self.axes.transData.transform((x, y))
            # In matplotlib, 0,0 is the lower left corner,
            # whereas it's usually the upper right
            # for most image software, so we'll flip the y-coor
            y_pixel = height - y_pixel_m
            painter.setBrush(QtGui.QColor(br_color))
            painter.drawEllipse( QtCore.QPoint(x_pixel, y_pixel), rx, ry)

    def create_oval(self, x, y, radius_x=5, radius_y=5, brush_color="red"):
        self._instructions.append([x, y, radius_x, radius_y, brush_color])
        self.update()

class MyPaintWidget(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()

        self.canvas = PainterCanvas()
        self.canvas.mpl_connect("button_press_event", self._on_left_click)
        x = np.arange(0, 10, 0.1)
        y = np.cos(x)
        self.canvas.axes.plot(x, y)

        layout_canvas = QtWidgets.QVBoxLayout(self)
        layout_canvas.addWidget(self.canvas)

    def _on_left_click(self, event):
        self.canvas.create_oval(event.xdata, event.ydata, brush_color="green")

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)

    w = MyPaintWidget()
    w.show()
    sys.exit(app.exec_())


问:
How can I bind to a view model in C# Xamarin Forms?
My C# code is like this now:

```<code> stack.Children.Add(new FooterTemplate() { Text = Japanese.Helpers.Deck.SetIntro() });
</code>```

but I would like to get the value of Text from my viewModel:

```<code> vm.IntroFooter = Japanese.Helpers.Deck.SetIntro();
</code>```

How can I bind the Text to vm.IntroFooter in C#

答:
Here's how to bind a property in C#:

```<code>FooterTemplate ft = new FooterTemplate();
Binding binding = new Binding("IntroFooter");
ft.SetBinding(FooterTemplate.TextProperty, binding);
stack.Children.Add(ft);
</code>```

I am assuming that you are properly using INotifyPropertyChanged interface:

```<code>...
string _introFooter;
public string IntroFooter
{
    get
    {
        return this._introFooter;
    }
    set
    {
        if (value != this._introFooter)
        {
            this._introFooter = value;
            NotifyPropertyChanged();
        }
    }
}
</code>```

Body:
My C# code is like this now:

 stack.Children.Add(new FooterTemplate() { Text = Japanese.Helpers.Deck.SetIntro() });

but I would like to get the value of Text from my viewModel:

 vm.IntroFooter = Japanese.Helpers.Deck.SetIntro();

How can I bind the Text to vm.IntroFooter in C#

Body:
Here's how to bind a property in C#:

FooterTemplate ft = new FooterTemplate();
Binding binding = new Binding("IntroFooter");
ft.SetBinding(FooterTemplate.TextProperty, binding);
stack.Children.Add(ft);

I am assuming that you are properly using INotifyPropertyChanged interface:

...
string _introFooter;
public string IntroFooter
{
    get
    {
        return this._introFooter;
    }
    set
    {
        if (value != this._introFooter)
        {
            this._introFooter = value;
            NotifyPropertyChanged();
        }
    }
}


问:
How to have text closer to image?
I've been fiddling around with Css and got to have my text and image be responsive on mobile. When I shrink my browser the image the text shrinks to show the image, but now my lorem ipsum text is pushed down. I'm not using padding or margin for this to happen, I'm trying to keep all of my text in a div but there seems to be alot of margin on text.

I've looked over my code and couldn't find anything that would cause this, and delete each segment of code to try and see if it fixes the problem. Nothing seems to work.

html:

```<code><body>

    <table >
    <tr>
        <td >Home</td> <!--Made 8 boxes, 100%/8boxes is 12.5, so to make them even just assign 12.5%-->
        <td >About Us</td> <!--Can see how CSS comes in handy...could just call td{width:12.5%; align:center;-->
        <td`enter code here` >Contact Us</td>
        <td >Menus</td>
        <td >Varieties</td>
        <td >Feedback</td>
        <td >SignUp</td>
        <td >Login</td>
    </tr>
    </table>

    <p id="mainWall"></p>
    <h1 class="mImageText">Paratore's Pizza</h1>

    <p>
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
    </p>

</body>
</html>

table{
    width:100%;
}

td{
    height: 100px;
    color:white;
    background-color: #c40909;
    text-align: center;
    width: 12.5%;
    border-radius: 22px;
    font-size: 25px;
}

td:hover{
    background-color: #ff9a26;
    transform: scale(.9, .9);
}

#mainWall{

    margin-left: auto;
    margin-right: auto;
    text-align: center;
    height: 75vh;

    width: 100%;
    background: url(images/mainWall.jpg);
      background-repeat: no-repeat;
      background-position: bottom bottom;
      background-position: center center;

      background-attachment: scroll;
      background-size:cover;
      border-radius: 20px;
}

.mImageText {
    position: relative;
    top: 50%;
    transform: translateY(-175%);
    color: #ffffff;
    font-family: 'Russo One', sans-serif;
    font-size: 9vw;
    text-align: center;
    opacity: 1;
    letter-spacing: 2vw;
    text-shadow: 10px 15px #a80303;
    }
</code>```

I expect the text to come closer to the image instead of being all the way down requiring a scroll

答:
One way to keep your lorem ipsum text closer to the elements above it is to put a class or id on that paragraph. Then give it a negative top-margin:

CSS:

```<code>   #lorem {
    margin-top: -8em;
    }
</code>```

HTML:

```<code><p id = "lorem">
    Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
            Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos
    </p>
</code>```

Title: How to have text closer to image?

Body:
I've been fiddling around with Css and got to have my text and image be responsive on mobile. When I shrink my browser the image the text shrinks to show the image, but now my lorem ipsum text is pushed down. I'm not using padding or margin for this to happen, I'm trying to keep all of my text in a div but there seems to be alot of margin on text.

I've looked over my code and couldn't find anything that would cause this, and delete each segment of code to try and see if it fixes the problem. Nothing seems to work.

html:

        Home
        About Us
        <td`enter code here` >Contact Us
        Menus
        Varieties
        Feedback
        SignUp
        Login

Paratore's Pizza

        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.

table{
    width:100%;
}

td{
    height: 100px;
    color:white;
    background-color: #c40909;
    text-align: center;
    width: 12.5%;
    border-radius: 22px;
    font-size: 25px;
}

td:hover{
    background-color: #ff9a26;
    transform: scale(.9, .9);
}

#mainWall{

    margin-left: auto;
    margin-right: auto;
    text-align: center;
    height: 75vh;

    width: 100%;
    background: url(images/mainWall.jpg);
      background-repeat: no-repeat;
      background-position: bottom bottom;
      background-position: center center;

      background-attachment: scroll;
      background-size:cover;
      border-radius: 20px;
}

.mImageText {
    position: relative;
    top: 50%;
    transform: translateY(-175%);
    color: #ffffff;
    font-family: 'Russo One', sans-serif;
    font-size: 9vw;
    text-align: center;
    opacity: 1;
    letter-spacing: 2vw;
    text-shadow: 10px 15px #a80303;
    }

I expect the text to come closer to the image instead of being all the way down requiring a scroll

Body:
One way to keep your lorem ipsum text closer to the elements above it is to put a class or id on that paragraph. Then give it a negative top-margin:

CSS:

   #lorem {
    margin-top: -8em;
    }

HTML:

<p id = "lorem">
    Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos cumque necessitatibus distinctio iste aperiam.
            Lorem, ipsum dolor sit amet consectetur adipisicing elit. Rerum deleniti incidunt iusto architecto animi dolore cum quod modi earum, nisi est aspernatur quibusdam iure eos
    </p>


问:
Laravel union and join in the query
I have 3 tables

send_to_employees

onprocess

employees

I want to do union of the two table send_to_employees and onprocess. After that I want to join the result with the employees table.

I have done it in a raw SQL query like the following already:

```<code>SELECT *
FROM (
  SELECT
    send_to_employees.caseid,
    send_to_employees.docs,
    send_to_employees.helper,
    send_to_employees.employee_id
  FROM send_to_employees
  UNION
  SELECT
    onprocess.caseid,
    onprocess.docs,
    onprocess.helper,
    onprocess.employee_id
  FROM onprocess
) t1
INNER JOIN employees
  ON employees.employee_id = t1.employee_id
</code>```

But I can't figure out how to do it with Laravel. Please help me to write this query using the query builder of Laravel 5.8.

答:
What you are looking for is something like this:

```<code>DB::query()
    ->fromSub(
        DB::table('send_to_employees')
            ->select([
                'caseid',
                'docs',
                'helper',
                'employee_id'
            ])
            ->union(
                DB::table('onprocess')
                    ->select([
                        'caseid',
                        'docs',
                        'helper',
                        'employee_id'
                    ])
            ),
        'inner'
    )
    ->join('employees', 'employees.employee_id', '=', 'inner.employee_id')
    ->select(['inner.*', 'employees.*'])
    ->get();
</code>```

The key to success is using fromSub() which allows you to perform a subquery. Please make sure to not use ->get() in a sub query though as it would wrap a collection and therefore fail.

Title: Laravel union and join in the query

Body:
I have 3 tables

send_to_employees

onprocess

employees

I want to do union of the two table send_to_employees and onprocess. After that I want to join the result with the employees table.

I have done it in a raw SQL query like the following already:

SELECT *
FROM (
  SELECT
    send_to_employees.caseid,
    send_to_employees.docs,
    send_to_employees.helper,
    send_to_employees.employee_id
  FROM send_to_employees
  UNION
  SELECT
    onprocess.caseid,
    onprocess.docs,
    onprocess.helper,
    onprocess.employee_id
  FROM onprocess
) t1
INNER JOIN employees
  ON employees.employee_id = t1.employee_id

But I can't figure out how to do it with Laravel. Please help me to write this query using the query builder of Laravel 5.8.

Body:
What you are looking for is something like this:

DB::query()
    ->fromSub(
        DB::table('send_to_employees')
            ->select([
                'caseid',
                'docs',
                'helper',
                'employee_id'
            ])
            ->union(
                DB::table('onprocess')
                    ->select([
                        'caseid',
                        'docs',
                        'helper',
                        'employee_id'
                    ])
            ),
        'inner'
    )
    ->join('employees', 'employees.employee_id', '=', 'inner.employee_id')
    ->select(['inner.*', 'employees.*'])
    ->get();

The key to success is using fromSub() which allows you to perform a subquery. Please make sure to not use ->get() in a sub query though as it would wrap a collection and therefore fail.


问:
VUE add a component with JS
Can I create/mount a VUE component calling a JS function in a fullyloaded page?

As a async call? Something like:

```<code>function getComponent(obj){
    return <component parameters="obj"></component >;
}
</code>```

答:
Can I create/mount a VUE component calling a JS function in a fullyloaded page?

I think you want to load/mount the component in a certain condition and not on page initialization.

If that the case then you can take advantage of lazy-loading and dynamic components:

```<code><template>
  //...
    <button @click="activateComponent">Activate component</button>
    <component :is="dynamicComponent" />
  //...
</template>

<script>
  export default {
     components: {
        MyCmp: () => import('./MyCmp.vue') //lazy loading
     },

     data: () => ({
      dynamicComponent: null
     }),

     methods: {
       activateComponent () {
         this.dynamicComponent = 'MyCmp'
       }
     }
  }
</script>
</code>```

Title: VUE add a component with JS

Body:
Can I create/mount a VUE component calling a JS function in a fullyloaded page?

As a async call? Something like:

function getComponent(obj){
    return <component parameters="obj"></component >;
}

Body:
Can I create/mount a VUE component calling a JS function in a fullyloaded page?

I think you want to load/mount the component in a certain condition and not on page initialization.

If that the case then you can take advantage of lazy-loading and dynamic components:

<template>
  //...
    <button @click="activateComponent">Activate component</button>
    <component :is="dynamicComponent" />
  //...
</template>

<script>
  export default {
     components: {
        MyCmp: () => import('./MyCmp.vue') //lazy loading
     },

     data: () => ({
      dynamicComponent: null
     }),

     methods: {
       activateComponent () {
         this.dynamicComponent = 'MyCmp'
       }
     }
  }
</script>


问:
How to avoid query taking long time when adding new node to cluster
I found query (just a simple select query) takes long time when adding a new node to cluster.

My execution time log :

```<code>
17:49:40.008 [ThreadPoolTaskScheduler-14] INFO  task.DiskCounting - void task.DiskCounting.runJob()  executed in 8 ms
17:50:00.010 [ThreadPoolTaskScheduler-3] INFO  task.DiskCounting - void task.DiskCounting.runJob()  executed in 15010 ms
17:50:15.008 [ThreadPoolTaskScheduler-4] INFO  task.DiskCounting - void task.DiskCounting.runJob()  executed in 10008 ms
17:50:20.008 [ThreadPoolTaskScheduler-16] INFO  task.DiskCounting - void task.DiskCounting.runJob()  executed in 7 ms

</code>```

Normally it takes about 10ms, and suddently takes 15000ms when adding node.

And I found it stuck because waiting for new node init data

Cassandra log (the new node):

```<code>INFO  [HANDSHAKE-/194.187.1.52] 2019-05-31 17:49:36,056 OutboundTcpConnection.java:560 - Handshaking version with /194.187.1.52
INFO  [GossipStage:1] 2019-05-31 17:49:36,059 Gossiper.java:1055 - Node /194.187.1.52 is now part of the cluster
INFO  [RequestResponseStage-1] 2019-05-31 17:49:36,069 Gossiper.java:1019 - InetAddress /194.187.1.52 is now UP
INFO  [GossipStage:1] 2019-05-31 17:49:36,109 TokenMetadata.java:479 - Updating topology for /194.187.1.52
INFO  [GossipStage:1] 2019-05-31 17:49:36,109 TokenMetadata.java:479 - Updating topology for /194.187.1.52
INFO  [MigrationStage:1] 2019-05-31 17:49:39,347 ViewManager.java:137 - Not submitting build tasks for views in keyspace system_traces as storage service is not initialized
INFO  [MigrationStage:1] 2019-05-31 17:49:39,352 ColumnFamilyStore.java:411 - Initializing system_traces.events
INFO  [MigrationStage:1] 2019-05-31 17:49:39,382 ColumnFamilyStore.java:411 - Initializing system_traces.sessions

</code>```

Stuck when : Node /194.187.1.52 is now part of the cluster

And client will wait for new node init all data

What I have tried:

```<code>1. I try use consistency with ONE or QUORUM, and is no difference

2. I try turn replication factor to 1, 2 or 3, and still no difference
</code>```

Why new node become part of cluster when that node not init data completely.

Is there a way to solve this.

I expect when I query to old node, the performance is not influenced by just waiting for new node to init data.

.
.
.

I resolved this problem.

I write wrong config, I let all node become seeds even before they joining cluster, this cause read timed-out during adding new node to cluster.

After fix this. all read is normal, but somehow I found insert query timed-out during adding node.

Finally I tune this to avoid insert timed-out:

```<code>/sbin/sysctl -w net.ipv4.tcp_keepalive_time=60 net.ipv4.tcp_keepalive_intvl=60 net.ipv4.tcp_keepalive_probes=5
</code>```

and also change conf to limit throughput

```<code>stream_throughput_outbound_megabits_per_sec : 100
</code>```

Really thanks for help.

答:
This is just a theory, but one possible cause of this is that the new node is being chosen as a coordinator by your driver client, in this case, consistency level and replication aren't the main contributing factor to the delay in servicing your query.

If the new node is slowly performing initially for whatever reason and the driver is sending requests to it, the behavior of the coordinator can impact the servicing of your request.

What exactly is runJob doing?  You suggested it is making a single query, but is it possible that it's a range query?

If it's a single query and it's taking as long as 10 seconds, that seems odd as the default read_request_timeout is 5 seconds.  If it's a range query (a read involving multiple partitions), the default is 10 seconds.  Are you adjusting those timeouts?

When you see responses that long for a single query that could mean the coordinator is what is impeding responsiveness as otherwise if the coordinator was responsive and the replicas were slow, you'd see ReadTimeoutException message serviced to the client.

To better react to these cases, a number of client drivers implement a strategy called 'speculative execution'.  As described in the documentation for the DataStax Java Driver for Apache Cassandra:

Sometimes a Cassandra node might be experiencing difficulties (ex: long GC pause) and take longer than usual to reply. Queries sent to that node will experience bad latency.

One thing we can do to improve that is pre-emptively start a second execution of the query against another node, before the first node has replied or errored out. If that second node replies faster, we can send the response back to the client (we also cancel the first execution – note that “cancelling” in this context simply means discarding the response when it arrives later, Cassandra does not support cancellation of in flight requests at this stage)

You could configure your driver to speculatively execute with a constant threshold for idempotent requests (such as reads are).  In the 3.x java driver, its done this way:

Cluster cluster = Cluster.builder()
  .addContactPoint("127.0.0.1")
  .withSpeculativeExecutionPolicy(
    new ConstantSpeculativeExecutionPolicy(
      500, // delay before a new execution is launched
      2    // maximum number of executions
  ))
  .build();
```

In this case, if the coordinator was slow to respond, after 500ms the driver chooses another coordinator and submits a second quest, and the first coordinator to respond wins.

Note that this might cause an amplification of requests sent to your cluster overall, so you want to tune that delay in such a way that it only kicks in when response time is highly anomalous.  In your case, if requests normally take less than 10ms, 500ms is probably a reasonable number depending on what your higher percentile latencies look like.

All that being said, if you are able to identify that the problem is the new node behaving poorly as a coordinator.  It's worth understanding why.  Adding speculative execution could be a nice way of possibly working around the problem, but it's probably better to try to understand why the new node is so slowly performing.  Having monitoring in place to observe Cassandra's metrics would likely give great visibility into the problem.

Body:
I found query (just a simple select query) takes long time when adding a new node to cluster.

My execution time log :

17:49:40.008 [ThreadPoolTaskScheduler-14] INFO  task.DiskCounting - void task.DiskCounting.runJob()  executed in 8 ms
17:50:00.010 [ThreadPoolTaskScheduler-3] INFO  task.DiskCounting - void task.DiskCounting.runJob()  executed in 15010 ms
17:50:15.008 [ThreadPoolTaskScheduler-4] INFO  task.DiskCounting - void task.DiskCounting.runJob()  executed in 10008 ms
17:50:20.008 [ThreadPoolTaskScheduler-16] INFO  task.DiskCounting - void task.DiskCounting.runJob()  executed in 7 ms

Normally it takes about 10ms, and suddently takes 15000ms when adding node.

And I found it stuck because waiting for new node init data

Cassandra log (the new node):

INFO  [HANDSHAKE-/194.187.1.52] 2019-05-31 17:49:36,056 OutboundTcpConnection.java:560 - Handshaking version with /194.187.1.52
INFO  [GossipStage:1] 2019-05-31 17:49:36,059 Gossiper.java:1055 - Node /194.187.1.52 is now part of the cluster
INFO  [RequestResponseStage-1] 2019-05-31 17:49:36,069 Gossiper.java:1019 - InetAddress /194.187.1.52 is now UP
INFO  [GossipStage:1] 2019-05-31 17:49:36,109 TokenMetadata.java:479 - Updating topology for /194.187.1.52
INFO  [GossipStage:1] 2019-05-31 17:49:36,109 TokenMetadata.java:479 - Updating topology for /194.187.1.52
INFO  [MigrationStage:1] 2019-05-31 17:49:39,347 ViewManager.java:137 - Not submitting build tasks for views in keyspace system_traces as storage service is not initialized
INFO  [MigrationStage:1] 2019-05-31 17:49:39,352 ColumnFamilyStore.java:411 - Initializing system_traces.events
INFO  [MigrationStage:1] 2019-05-31 17:49:39,382 ColumnFamilyStore.java:411 - Initializing system_traces.sessions

Stuck when : Node /194.187.1.52 is now part of the cluster

And client will wait for new node init all data

What I have tried:

1. I try use consistency with ONE or QUORUM, and is no difference

2. I try turn replication factor to 1, 2 or 3, and still no difference

Why new node become part of cluster when that node not init data completely.

Is there a way to solve this.

I expect when I query to old node, the performance is not influenced by just waiting for new node to init data.

.
.
.

I resolved this problem.

I write wrong config, I let all node become seeds even before they joining cluster, this cause read timed-out during adding new node to cluster.

After fix this. all read is normal, but somehow I found insert query timed-out during adding node.

Finally I tune this to avoid insert timed-out:

/sbin/sysctl -w net.ipv4.tcp_keepalive_time=60 net.ipv4.tcp_keepalive_intvl=60 net.ipv4.tcp_keepalive_probes=5

and also change conf to limit throughput

stream_throughput_outbound_megabits_per_sec : 100

Really thanks for help.

Body:
This is just a theory, but one possible cause of this is that the new node is being chosen as a coordinator by your driver client, in this case, consistency level and replication aren't the main contributing factor to the delay in servicing your query.

If the new node is slowly performing initially for whatever reason and the driver is sending requests to it, the behavior of the coordinator can impact the servicing of your request.

What exactly is runJob doing?  You suggested it is making a single query, but is it possible that it's a range query?

If it's a single query and it's taking as long as 10 seconds, that seems odd as the default read_request_timeout is 5 seconds.  If it's a range query (a read involving multiple partitions), the default is 10 seconds.  Are you adjusting those timeouts?

When you see responses that long for a single query that could mean the coordinator is what is impeding responsiveness as otherwise if the coordinator was responsive and the replicas were slow, you'd see ReadTimeoutException message serviced to the client.

To better react to these cases, a number of client drivers implement a strategy called 'speculative execution'.  As described in the documentation for the DataStax Java Driver for Apache Cassandra:

Sometimes a Cassandra node might be experiencing difficulties (ex: long GC pause) and take longer than usual to reply. Queries sent to that node will experience bad latency.

One thing we can do to improve that is pre-emptively start a second execution of the query against another node, before the first node has replied or errored out. If that second node replies faster, we can send the response back to the client (we also cancel the first execution – note that “cancelling” in this context simply means discarding the response when it arrives later, Cassandra does not support cancellation of in flight requests at this stage)

You could configure your driver to speculatively execute with a constant threshold for idempotent requests (such as reads are).  In the 3.x java driver, its done this way:

Cluster cluster = Cluster.builder()
  .addContactPoint("127.0.0.1")
  .withSpeculativeExecutionPolicy(
    new ConstantSpeculativeExecutionPolicy(
      500, // delay before a new execution is launched
      2    // maximum number of executions
  ))
  .build();

In this case, if the coordinator was slow to respond, after 500ms the driver chooses another coordinator and submits a second quest, and the first coordinator to respond wins.

Note that this might cause an amplification of requests sent to your cluster overall, so you want to tune that delay in such a way that it only kicks in when response time is highly anomalous.  In your case, if requests normally take less than 10ms, 500ms is probably a reasonable number depending on what your higher percentile latencies look like.

All that being said, if you are able to identify that the problem is the new node behaving poorly as a coordinator.  It's worth understanding why.  Adding speculative execution could be a nice way of possibly working around the problem, but it's probably better to try to understand why the new node is so slowly performing.  Having monitoring in place to observe Cassandra's metrics would likely give great visibility into the problem.


问:
Custom Format for Current Date and Time in C++
I am trying to save a file into a directory of files based on the current date and time. I am trying to get the format of the following:

"FullMonth-FullYear" example:
"April-2011"

"FullMonth-littleDay-year" example:
"March-7-11"

hour-minutes-seconds. example: "18:05:09" in 24 hour format

答: It depends on the format you have the time in right now. I'm a big fan of sprintf(), and since I mostly deal with big piles of seconds, milliseconds, or nanoseconds, I do a lot of modulus arithmetic to get what I want.


问:
Initialize array in Kotlin based on list size
I need to add LineChart(using MpAndroidChart) dynamically in LinearLayout.

I have declared an arrayList,named list.

```<code> val list = arrayListOf<ABC>()
       ....

 for (i in list) {
   chart[] = LineChart(activity)
 }
</code>```

What is the value I should put inside [] ? Let say the list's saiz is 2, I need to have 2 chart in LinearLayout.

How should I initialize LineChart?

Example

chart[i] = LineChart(activity) ???

LineChart

```<code>public class LineChart extends BarLineChartBase<LineData> implements LineDataProvider {

    public LineChart(Context context) {
        super(context);
    }

    public LineChart(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public LineChart(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void init() {
        super.init();

        mRenderer = new LineChartRenderer(this, mAnimator, mViewPortHandler);
    }

    @Override
    public LineData getLineData() {
        return mData;
    }

    @Override
    protected void onDetachedFromWindow() {
        // releases the bitmap in the renderer to avoid oom error
        if (mRenderer != null && mRenderer instanceof LineChartRenderer) {
            ((LineChartRenderer) mRenderer).releaseBitmap();
        }
        super.onDetachedFromWindow();
    }
}
</code>```

答:
This is my answer</p>

```<code>for (i in 0 unti list.size) {
   chart[i] = LineChart(activity)
 }
</code>```

Body:
I need to add LineChart(using MpAndroidChart) dynamically in LinearLayout.

I have declared an arrayList,named list.

 val list = arrayListOf<ABC>()
       ....

 for (i in list) {
   chart[] = LineChart(activity)
 }

What is the value I should put inside [] ? Let say the list's saiz is 2, I need to have 2 chart in LinearLayout.

How should I initialize LineChart?

Example

chart[i] = LineChart(activity) ???

LineChart

public class LineChart extends BarLineChartBase<LineData> implements LineDataProvider {

    public LineChart(Context context) {
        super(context);
    }

    public LineChart(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public LineChart(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void init() {
        super.init();

        mRenderer = new LineChartRenderer(this, mAnimator, mViewPortHandler);
    }

    @Override
    public LineData getLineData() {
        return mData;
    }

    @Override
    protected void onDetachedFromWindow() {
        // releases the bitmap in the renderer to avoid oom error
        if (mRenderer != null && mRenderer instanceof LineChartRenderer) {
            ((LineChartRenderer) mRenderer).releaseBitmap();
        }
        super.onDetachedFromWindow();
    }
}

Body:
This is my answer

for (i in 0 unti list.size) {
   chart[i] = LineChart(activity)
 }


问:
why i can edit my first object with my handmade jquery plugin?
my jQuery plugin is simple but it only works in my first object

I tried to solve it with a for loop but i can't do that

```<code>
(function ($) {
    $.fn.omToolTip = function (userOptions) {
        var options = $.extend({
            width: 200,
        }, userOptions)

        this.each(function () {
            var elm = $(this);
            var ttBox = $("<div>").attr("class", "ttb");

            elm.hover(function () {
                alert("salam");
            }, function () {
                alert("khodafez");
            })

        })
    }
})(jQuery)

</code>```

答:
Let me guess .. you're using this plugin with id change it to class
  and try again .. id should be unique so don't use same id for more
  than one element

No you shouldn't duplicate id .. Take a look at the next example to know the difference between using same class and same id

$(document).ready(function(){
  // How to use?
  $('.anyDiv').omToolTip(); // elements with same class
  $('#anyDiv').omToolTip(); // elements with same id just the first one will work if you use id
});
(function ($) {
    $.fn.omToolTip = function (userOptions) {
        var options = $.extend({
            width: 200,
        }, userOptions)

        this.each(function () {
            var elm = $(this);
            var ttBox = $("
").addClass("ttb"); // use addClass instead of attr

            elm.hover(function () {
                console.log("salam");
            }, function () {
                console.log("khodafez");
            })

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

<!-- With same Class -->
<div class="anyDiv">Class Any Div</div>
<div class="anyDiv">Class Any Div</div>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>

<!-- With same Id (only the first one here will work with the plugin)-->
<div id="anyDiv">Id Any Div</div>
<div id="anyDiv">Id Any Div</div></code>```

Also to add class you can use .addClass() instead of attr('class'.....)

Body:
my jQuery plugin is simple but it only works in my first object

I tried to solve it with a for loop but i can't do that

(function ($) {
    $.fn.omToolTip = function (userOptions) {
        var options = $.extend({
            width: 200,
        }, userOptions)

        this.each(function () {
            var elm = $(this);
            var ttBox = $("
").attr("class", "ttb");

            elm.hover(function () {
                alert("salam");
            }, function () {
                alert("khodafez");
            })

        })
    }
})(jQuery)

Body:
Let me guess .. you're using this plugin with id change it to class
  and try again .. id should be unique so don't use same id for more
  than one element

No you shouldn't duplicate id .. Take a look at the next example to know the difference between using same class and same id

$(document).ready(function(){
  // How to use?
  $('.anyDiv').omToolTip(); // elements with same class
  $('#anyDiv').omToolTip(); // elements with same id just the first one will work if you use id
});
(function ($) {
    $.fn.omToolTip = function (userOptions) {
        var options = $.extend({
            width: 200,
        }, userOptions)

        this.each(function () {
            var elm = $(this);
            var ttBox = $("<div>").addClass("ttb"); // use addClass instead of attr

            elm.hover(function () {
                console.log("salam");
            }, function () {
                console.log("khodafez");
            })

        })
    }
})(jQuery)

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

<!-- With same Class -->
<div class="anyDiv">Class Any Div</div>
<div class="anyDiv">Class Any Div</div>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>

<!-- With same Id (only the first one here will work with the plugin)-->
<div id="anyDiv">Id Any Div</div>
<div id="anyDiv">Id Any Div</div>

Also to add class you can use .addClass() instead of attr('class'.....)


问:
How to divide an unknown integer into a given number of even parts using Python
I need help with the ability to divide an unknown integer into a given number of even parts — or at least as even as they can be. The sum of the parts should be the original value, but each part should be an integer, and they should be as close as possible.

```<code>Parameters
num: Integer - The number that should be split into equal parts

parts: Integer - The number of parts that the number should be split
into

Return Value
List (of Integers) - A list of parts, with each index representing the part and the number contained within it representing the size of the part. The parts will be ordered from smallest to largest.
</code>```

This is what I have

def split_integer(num,parts):
    if (num < parts):
      print(-1)

    elif (num % parts == 0):
      for i in range(parts):
        print(num // parts),
    else:
      parts_remaining = parts - (num % parts)
      quotient = num // parts

      for i in range(parts):
        if (i >= parts_remaining):
          print(quotient + 1),
        else:
          print(quotient),

split_integer(10, 1)
```

<p>This is the sample tests</p>

```import unittest

class Test(unittest.TestCase):
    def test_should_handle_evenly_distributed_cases(self):
        self.assertEqual(split_integer(10, 1), [10])
        self.assertEqual(split_integer(2, 2), [1,1])
        self.assertEqual(split_integer(20, 5), [4,4,4,4,4])
```

<p>Examples of the expected output</p>

```num parts   Return Value
Completely even parts example   10  5   [2,2,2,2,2]
Even as can be parts example    20  6   [3,3,3,3,4,4]
```

<p>I am getting the error </p>

```Failure
AssertionError: None != [10]
```

答:
This problem is very similar to the "giving change" problem.

Let us start by looking at the simplest scenario of split(10, 1) where you're dealing with a partition size of 1 i.e parts = 1, an intuitive solution would be: partition = [10]. Of course, this assumes that the remainder = 0 and parts = 1 or 0.

If that is a generic idea of a base case, then the total partitions can be calculated by way of recursion where both the num and parts are continuesly reduced as shown below:

```<code>def split_integer(num, parts):
    """
    split_integer(integer, parts) -> [ value[, values] ]
    divides an integer into an ""even as can be"" number of parts.
    >>> split_integer(10, 1)
    [10]
    >>> split_integer(2, 2)
    [1, 1]
    >>> split_integer(20, 5)
    [4, 4, 4, 4, 4]
    >>> split_integer(10, 5)
    [2, 2, 2, 2, 2]
    >>> split_integer(20, 6)
    [3, 3, 3, 3, 4, 4]
    >>> split_integer(5, 4)
    [1, 1, 1, 2]
    """
    lower_bound, remainder = divmod(num, parts)
    sub_partition = [lower_bound ] * (parts - remainder)
    num -= len(sub_partition) * lower_bound
    if remainder:
        sub_partition += split_integer(num, remainder)
    return sub_partition

if __name__ == "__main__":
    import doctest
    doctest.testmod()

</code>```

Body:
I need help with the ability to divide an unknown integer into a given number of even parts — or at least as even as they can be. The sum of the parts should be the original value, but each part should be an integer, and they should be as close as possible.

Parameters
num: Integer - The number that should be split into equal parts

parts: Integer - The number of parts that the number should be split
into

Return Value
List (of Integers) - A list of parts, with each index representing the part and the number contained within it representing the size of the part. The parts will be ordered from smallest to largest.

This is what I have

def split_integer(num,parts):
    if (num < parts):
      print(-1)

    elif (num % parts == 0):
      for i in range(parts):
        print(num // parts),
    else:
      parts_remaining = parts - (num % parts)
      quotient = num // parts

      for i in range(parts):
        if (i >= parts_remaining):
          print(quotient + 1),
        else:
          print(quotient),

split_integer(10, 1)

This is the sample tests

import unittest

class Test(unittest.TestCase):
    def test_should_handle_evenly_distributed_cases(self):
        self.assertEqual(split_integer(10, 1), [10])
        self.assertEqual(split_integer(2, 2), [1,1])
        self.assertEqual(split_integer(20, 5), [4,4,4,4,4])

Examples of the expected output

num parts   Return Value
Completely even parts example   10  5   [2,2,2,2,2]
Even as can be parts example    20  6   [3,3,3,3,4,4]

I am getting the error

Failure
AssertionError: None != [10]

Body:
This problem is very similar to the "giving change" problem.

Let us start by looking at the simplest scenario of split(10, 1) where you're dealing with a partition size of 1 i.e parts = 1, an intuitive solution would be: partition = [10]. Of course, this assumes that the remainder = 0 and parts = 1 or 0.

If that is a generic idea of a base case, then the total partitions can be calculated by way of recursion where both the num and parts are continuesly reduced as shown below:

def split_integer(num, parts):
    """
    split_integer(integer, parts) -> [ value[, values] ]
    divides an integer into an ""even as can be"" number of parts.
    >>> split_integer(10, 1)
    [10]
    >>> split_integer(2, 2)
    [1, 1]
    >>> split_integer(20, 5)
    [4, 4, 4, 4, 4]
    >>> split_integer(10, 5)
    [2, 2, 2, 2, 2]
    >>> split_integer(20, 6)
    [3, 3, 3, 3, 4, 4]
    >>> split_integer(5, 4)
    [1, 1, 1, 2]
    """
    lower_bound, remainder = divmod(num, parts)
    sub_partition = [lower_bound ] * (parts - remainder)
    num -= len(sub_partition) * lower_bound
    if remainder:
        sub_partition += split_integer(num, remainder)
    return sub_partition

if __name__ == "__main__":
    import doctest
    doctest.testmod()


问:
call a function from external class unto the codeigniter library
I have this external class that I'm trying to call inside the codeigniter library class

Loader.php

```<code><?php

namespace PDLoader;

class Loader{

    public function load($comp=false){

        if( $comp ){

            $comp = ucfirst($comp);

            if( !file_exists(__DIR__.'/modules/'.$comp.'/'.$comp.'.php') ){
                print_r('Component '.$comp.' not found.');
                return;
            }

            require_once(__DIR__.'/modules/'.$comp.'/'.$comp.'.php');

            $module = __NAMESPACE__ . '\\' .$comp;

            return new $module;

        }
    }
}
</code>```

and in my codeigniter library

```<code>defined('BASEPATH') OR exit('No direct script access allowed');

require_once(__DIR__.'/../../../Loader/Loader.php');

$loader = new Loader;

class Loader{

    public function loadModule(){

        global $loader;

        $loader->load('basicwebsite')->appheader([]);
    }
}
</code>```

yet it throws me this

An uncaught Exception was encountered Type: Error

Message: Call to a member function load() on null

How can I resolve this?

答:
You need to specify the namespace when you create your loader:</p>

```<code>$loader = new \PDLoader\Loader;
</code>```

Body:
I have this external class that I'm trying to call inside the codeigniter library class

Loader.php

<?php

namespace PDLoader;

class Loader{

    public function load($comp=false){

        if( $comp ){

            $comp = ucfirst($comp);

            if( !file_exists(__DIR__.'/modules/'.$comp.'/'.$comp.'.php') ){
                print_r('Component '.$comp.' not found.');
                return;
            }

            require_once(__DIR__.'/modules/'.$comp.'/'.$comp.'.php');

            $module = __NAMESPACE__ . '\\' .$comp;

            return new $module;

        }
    }
}

and in my codeigniter library

defined('BASEPATH') OR exit('No direct script access allowed');

require_once(__DIR__.'/../../../Loader/Loader.php');

$loader = new Loader;

class Loader{

    public function loadModule(){

        global $loader;

        $loader->load('basicwebsite')->appheader([]);
    }
}

yet it throws me this

An uncaught Exception was encountered Type: Error

Message: Call to a member function load() on null

How can I resolve this?

Body:
You need to specify the namespace when you create your loader:

$loader = new \PDLoader\Loader;