问:
React-Bootstrap <FieldGroup> Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function
I'm trying to use a FieldGroup inside a Form and I came across this error:

"Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in. Check the render method of CreateUser.
    at invariant (invariant.js:44)

```<code>   import React, {Component} from 'react'
   import {Form, FormGroup , FormControl,AlertDismissable,Glyphicon} from 'react-bootstrap'
   import {FieldGroup} from 'react-bootstrap'
   class CreateUser extends Component {
   constructor(props){
    super(props);
}

displayName: 'Create User'
render() {
    return (
            <Form horizontal className="loginForm">
                <FormGroup controlId="formHorizontalUsername">
                    <FieldGroup>

                    </FieldGroup>
                </FormGroup>
            </Form>

    );
}
}  export default CreateUser;
</code>```

Please let me know what I am doing wrong.

答:
You can do add FieldGroup as function

```<code>import React, {Component} from 'react'
import {Form, FormGroup , FormControl, AlertDismissable, Glyphicon} from 'react-bootstrap'
import {FieldGroup} from 'react-bootstrap'
class CreateUser extends Component {
  constructor(props){
    super(props);
  }

  displayName: 'Create User'
  render() {
    function FieldGroup({ id, label, help, ...props }) {
      return (
        <FormGroup controlId={id}>
          <ControlLabel>{label}</ControlLabel>
          <FormControl {...props} />
          {help && <HelpBlock>{help}</HelpBlock>}
        </FormGroup>
      );
    }
    return (
      <Form horizontal className="loginForm">
          <FormGroup controlId="formHorizontalUsername">
              <FieldGroup>
                id="formControlsText"
                type="text"
                label="Text"
                placeholder="Enter text"
          </FormGroup>
      </Form>
    );
  }
}  export default CreateUser;
</code>```

For getting more detail you can go to this link FieldGroup.

Body:
I'm trying to use a FieldGroup inside a Form and I came across this error:

"Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in. Check the render method of CreateUser.
    at invariant (invariant.js:44)

   import React, {Component} from 'react'
   import {Form, FormGroup , FormControl,AlertDismissable,Glyphicon} from 'react-bootstrap'
   import {FieldGroup} from 'react-bootstrap'
   class CreateUser extends Component {
   constructor(props){
    super(props);
}

displayName: 'Create User'
render() {
    return (
            <Form horizontal className="loginForm">
                <FormGroup controlId="formHorizontalUsername">
                    <FieldGroup>

                    </FieldGroup>
                </FormGroup>
            </Form>

    );
}
}  export default CreateUser;

Please let me know what I am doing wrong.

Body:
You can do add FieldGroup as function

import React, {Component} from 'react'
import {Form, FormGroup , FormControl, AlertDismissable, Glyphicon} from 'react-bootstrap'
import {FieldGroup} from 'react-bootstrap'
class CreateUser extends Component {
  constructor(props){
    super(props);
  }

  displayName: 'Create User'
  render() {
    function FieldGroup({ id, label, help, ...props }) {
      return (
        <FormGroup controlId={id}>
          <ControlLabel>{label}</ControlLabel>
          <FormControl {...props} />
          {help && <HelpBlock>{help}</HelpBlock>}
        </FormGroup>
      );
    }
    return (
      <Form horizontal className="loginForm">
          <FormGroup controlId="formHorizontalUsername">
              <FieldGroup>
                id="formControlsText"
                type="text"
                label="Text"
                placeholder="Enter text"
          </FormGroup>
      </Form>
    );
  }
}  export default CreateUser;

For getting more detail you can go to this link FieldGroup.


来源: stackexchange

问:
Rails 3: how to reverse ERB "<%=" default behaviour so I can inject HTML?
My question relates to this one, but I am trying to reverse the default Rails 3 behavior of "<%=" so that I can inject HTML.

In my scenario, I have an old Rails 2 plug that generates HTML. My view will then need to inject this HTML in the page.

When this plugin creates HTML like this stored in a variable html_to_show:

```<code><p class="notice"><span></span>Sorry about this, but we have a problem...</p><p class="error"><span></span>Cannot go to next step</p>
</code>```

and in the view I try to show the contents of html_to_show like this:

```<code><%= html_to_show %>
</code>```

... what I get in my browser is this:

```<code><p class="notice"><span></span>Sorry about this, but we have a problem...</p><p class="error"><span></span>Cannot go to next step</p>
</code>```

How can I get Rails 3 to inject the contents of html_to_show exactly as it is, without any sanitization?

答:
Short answer:

```<code><%= html_to_show.html_safe %>
</code>```

Long answer:

Rails escapes all html to protect from XSS attacks. Adding .html_safe prevents the escaping.

ContentLicense: CC BY-SA 2.5

Body:
My question relates to this one, but I am trying to reverse the default Rails 3 behavior of "<%=" so that I can inject HTML.

In my scenario, I have an old Rails 2 plug that generates HTML. My view will then need to inject this HTML in the page.

When this plugin creates HTML like this stored in a variable html_to_show:

Sorry about this, but we have a problem...

Cannot go to next step

and in the view I try to show the contents of html_to_show like this:

<%= html_to_show %>

... what I get in my browser is this:

Sorry about this, but we have a problem...

Cannot go to next step

How can I get Rails 3 to inject the contents of html_to_show exactly as it is, without any sanitization?

Body:
Short answer:

<%= html_to_show.html_safe %>

Long answer:

Rails escapes all html to protect from XSS attacks. Adding .html_safe prevents the escaping.


问:
Is it possible to generate a box-shadow that follows the shape of a clip-path polygon?
Let's say I have this clip path (a triangle generated here)

```<code>-webkit-clip-path: polygon(50% 0%, 0% 100%, 100% 100%);
clip-path: polygon(50% 0%, 0% 100%, 100% 100%);
</code>```

Is it possible to create a box-shadow from this clip path?
Something like this:

```<code>box-shadow: 20px 25px 50px -25px #000;
</code>```

答:
You can use a filter on the containing div, try:

.container {
   filter: drop-shadow(0px 10px 5px rgba(0,0,0,0.1))
}
```

eg: https://plnkr.co/edit/kePuv7OLQwawPjiBLg3J?p=preview

ContentLicense: CC BY-SA 3.0

Body:
Let's say I have this clip path (a triangle generated here)

-webkit-clip-path: polygon(50% 0%, 0% 100%, 100% 100%);
clip-path: polygon(50% 0%, 0% 100%, 100% 100%);

Is it possible to create a box-shadow from this clip path?
Something like this:

box-shadow: 20px 25px 50px -25px #000;

Body:
You can use a filter on the containing div, try:

.container {
   filter: drop-shadow(0px 10px 5px rgba(0,0,0,0.1))
}

eg: https://plnkr.co/edit/kePuv7OLQwawPjiBLg3J?p=preview


问:
Round float in Python
I have a problem with float in Python...

I have this in a variable:

```<code>i = 9.600000000000001
</code>```

And I would transform in this:

```<code>i = 9.60000
</code>```

with five numbers after the decimal point and rounded.

答:
```<code>from decimal import *
getcontext().prec = 6
i = 9.600000000000001
newI = Decimal(i)/1

print(newI)
</code>```

returns 9.60000.  However, float(newI) return 9.6, which is correct.  The real question is do you want the actual value, in which case 9.60000 = 9.6, or just display 9.6 as 9.60000?  In that case, the print solutions above will get you there.

ContentLicense: CC BY-SA 4.0

Title: Round float in Python

Body:
I have a problem with float in Python...

I have this in a variable:

i = 9.600000000000001

And I would transform in this:

i = 9.60000

with five numbers after the decimal point and rounded.

Body:
from decimal import *
getcontext().prec = 6
i = 9.600000000000001
newI = Decimal(i)/1

print(newI)

returns 9.60000.  However, float(newI) return 9.6, which is correct.  The real question is do you want the actual value, in which case 9.60000 = 9.6, or just display 9.6 as 9.60000?  In that case, the print solutions above will get you there.


问:
Buildtime Canvas Pod xCode issue | missing a [super awakeFromNib] call || from CSAnimationView.m file
I just added the canvas pod (through cocoapods) and I can see the files in my workspace just fine, and I was able to "import Canvas" into my ViewController.swift. But I am getting a semantic build time error that the file CSAnimationView.m is possibly missing a method [super awakeFromNib][errorscreenshot]1</p>

```<code>/*
* This file is part of the Canvas package.
* (c) Canvas <usecanvas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

#import "CSAnimationView.h" @implementation CSAnimationView

- (void)awakeFromNib {
if (self.type && self.duration && ! self.pauseAnimationOnAwake) {[self startCanvasAnimation];
}
}

- (void)startCanvasAnimation {

    Class <CSAnimation> class = [CSAnimationclassForAnimationType:self.type];

    [class performAnimationOnView:self duration:self.durationdelay:self.delay];

    [super startCanvasAnimation];
}

@end
</code>```

答:
Since:

1) the library you are trying to add, "Canvas", is 3 and more years is not being updated, latest version is 0.1.2, see here: https://github.com/CanvasPod/Canvas/releases

2) Xcode >= 8 requires [super awakeFromNib], please read here:
Calling awakeFromNib of superclass and here:

You must call the super implementation of awakeFromNib to give parent
  classes the opportunity to perform any additional initialization they
  require. Although the default implementation of this method does
  nothing, many UIKit classes provide non-empty implementations. You may
  call the super implementation at any point during your own
  awakeFromNib method.

The only way to build it, is adding manually the branch master and fix by yourself the issue(s)

Body:
I just added the canvas pod (through cocoapods) and I can see the files in my workspace just fine, and I was able to "import Canvas" into my ViewController.swift. But I am getting a semantic build time error that the file CSAnimationView.m is possibly missing a method [super awakeFromNib][errorscreenshot]1

/*
* This file is part of the Canvas package.
* (c) Canvas <usecanvas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

#import "CSAnimationView.h" @implementation CSAnimationView

- (void)awakeFromNib {
if (self.type && self.duration && ! self.pauseAnimationOnAwake) {[self startCanvasAnimation];
}
}

- (void)startCanvasAnimation {

    Class <CSAnimation> class = [CSAnimationclassForAnimationType:self.type];

    [class performAnimationOnView:self duration:self.durationdelay:self.delay];

    [super startCanvasAnimation];
}

@end


问:
How do I output a result of an each statement to a variable?
I have this code that prints each character of a string twice:

```<code>r = "12345"
r.split("").each do |ch|
  puts "#{ch}#{ch}"
end
</code>```

I get this output:

```<code>11
22
33
44
55
</code>```

I want to store the output "1122334455" in a variable. How do I rewrite the code to do this?

答:
You could use chars to get each character in the string as a value in a "main" array, then using map format the elements inside, and then join all of them to make a final string, like:</p>

```<code>r = '12345'
capture = r.chars.map { |ch| ch * 2 }.join
p capture
# "1122334455"
</code>```

Body:
I have this code that prints each character of a string twice:

r = "12345"
r.split("").each do |ch|
  puts "#{ch}#{ch}"
end

I get this output:

11
22
33
44
55

I want to store the output "1122334455" in a variable. How do I rewrite the code to do this?

Body:
You could use chars to get each character in the string as a value in a "main" array, then using map format the elements inside, and then join all of them to make a final string, like:

r = '12345'
capture = r.chars.map { |ch| ch * 2 }.join
p capture
# "1122334455"


问:
Parsing google map matrix data
I have been trying to parse this data with the help of simple-Json within Java, I need a specific data set->"duration"-"text" and the corresponding value.

I have tried using https://www.journaldev.com/12668/json-simple-example and many other examples on Stack Overflow but still havent managed to complete the problem.

Does anyone have a solution?

```<code>   "destination_addresses" : [ "Wareham, UK" ],
   "origin_addresses" : [ "Longtown, Carlisle CA6, UK" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "378 mi",
                  "value" : 607958
               },
               "duration" : {
                  "text" : "6 hours 19 mins",
                  "value" : 22730
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
</code>```

答:
You can use GSON to JSON serialization/deserialization. Your solution could be something like this:

Java 7+:

```<code>public List<String> parse(final Gson gson, final String jsonText) {
    final JsonObject json = gson.fromJson(jsonText, JsonObject.class);
    final JsonArray rowsJson = json.getAsJsonArray("rows");

    final List<String> durations = new ArrayList<>(rowsJson.size());

    for (JsonElement row : rowsJson) {
        final JsonArray elements = row
                .getAsJsonObject()
                .getAsJsonArray("elements");

        for (JsonElement element : elements) {
            final JsonObject duration = element
                    .getAsJsonObject()
                    .getAsJsonObject("duration");

            durations.add(duration.getAsJsonPrimitive("text").getAsString());
        }
    }

    return durations;
}
</code>```

Java 8+:

```<code>public List<String> parse(final Gson gson, final String jsonText) {
    final JsonObject json = gson.fromJson(jsonText, JsonObject.class);

    return StreamSupport
            .stream(json.getAsJsonArray("rows").spliterator(), false)
            .map(row -> row.getAsJsonObject().getAsJsonArray("elements"))
            .flatMap(elements -> StreamSupport.stream(elements.spliterator(), false))
            .map(element -> element.getAsJsonObject().getAsJsonObject("duration"))
            .map(duration -> duration.getAsJsonPrimitive("text").getAsString())
            .collect(Collectors.toList());
}
</code>```

Example:

```<code>public static void main(final String... args) {
    final Gson gson = new Gson();
    System.out.println(parse(gson, yourJSON)); // Output -> [6 hours 19 mins]
}
</code>```

Or you can use json-simple, like this:

Java 7+:

```<code>public List<String> parse(final JSONParser parser, final String jsonText)
        throws ParseException {
    final JSONObject json = (JSONObject) parser.parse(jsonText);
    final JSONArray rows = (JSONArray) json.get("rows");

    final List<String> durations = new ArrayList<>();

    for (final Object row : rows) {
        final JSONArray elements = ((JSONArray) ((JSONObject) row).get("elements"));
        for (Object element : elements) {
            final JSONObject duration = (JSONObject) ((JSONObject) element).get("duration");
            durations.add((String) duration.get("text"));
        }
    }

    return durations;
}
</code>```

Example:

```<code>public static void main(final String... args) throws ParseException {
    System.out.println(parse(new JSONParser(), yourJson)); // Output -> [6 hours 19 mins]
}
</code>```

Title: Parsing google map matrix data

Body:
I have been trying to parse this data with the help of simple-Json within Java, I need a specific data set->"duration"-"text" and the corresponding value.

I have tried using https://www.journaldev.com/12668/json-simple-example and many other examples on Stack Overflow but still havent managed to complete the problem.

Does anyone have a solution?

   "destination_addresses" : [ "Wareham, UK" ],
   "origin_addresses" : [ "Longtown, Carlisle CA6, UK" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "378 mi",
                  "value" : 607958
               },
               "duration" : {
                  "text" : "6 hours 19 mins",
                  "value" : 22730
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"

Body:
You can use GSON to JSON serialization/deserialization. Your solution could be something like this:

Java 7+:

public List<String> parse(final Gson gson, final String jsonText) {
    final JsonObject json = gson.fromJson(jsonText, JsonObject.class);
    final JsonArray rowsJson = json.getAsJsonArray("rows");

    final List<String> durations = new ArrayList<>(rowsJson.size());

    for (JsonElement row : rowsJson) {
        final JsonArray elements = row
                .getAsJsonObject()
                .getAsJsonArray("elements");

        for (JsonElement element : elements) {
            final JsonObject duration = element
                    .getAsJsonObject()
                    .getAsJsonObject("duration");

            durations.add(duration.getAsJsonPrimitive("text").getAsString());
        }
    }

    return durations;
}

Java 8+:

public List<String> parse(final Gson gson, final String jsonText) {
    final JsonObject json = gson.fromJson(jsonText, JsonObject.class);

    return StreamSupport
            .stream(json.getAsJsonArray("rows").spliterator(), false)
            .map(row -> row.getAsJsonObject().getAsJsonArray("elements"))
            .flatMap(elements -> StreamSupport.stream(elements.spliterator(), false))
            .map(element -> element.getAsJsonObject().getAsJsonObject("duration"))
            .map(duration -> duration.getAsJsonPrimitive("text").getAsString())
            .collect(Collectors.toList());
}

Example:

public static void main(final String... args) {
    final Gson gson = new Gson();
    System.out.println(parse(gson, yourJSON)); // Output -> [6 hours 19 mins]
}

Or you can use json-simple, like this:

Java 7+:

public List<String> parse(final JSONParser parser, final String jsonText)
        throws ParseException {
    final JSONObject json = (JSONObject) parser.parse(jsonText);
    final JSONArray rows = (JSONArray) json.get("rows");

    final List<String> durations = new ArrayList<>();

    for (final Object row : rows) {
        final JSONArray elements = ((JSONArray) ((JSONObject) row).get("elements"));
        for (Object element : elements) {
            final JSONObject duration = (JSONObject) ((JSONObject) element).get("duration");
            durations.add((String) duration.get("text"));
        }
    }

    return durations;
}

Example:

public static void main(final String... args) throws ParseException {
    System.out.println(parse(new JSONParser(), yourJson)); // Output -> [6 hours 19 mins]
}


问:
iOS Text View Not Updating
I've got a UITextView defined by

```<code>@property (nonatomic, retain) IBOutlet UITextView *quote;
</code>```

in my view controller header, and I can set the value by using

```<code>quote.text = @"some text";
</code>```

but the view doens't want to update the value, what can I do

答:
Setting the text should immediately cause the UITextView to render your text under normal conditions.

Are you sure your that:

The UITextView is placed appropriately in your Nib and is visible?

The UITextView is appropriately linked with your outlet in your file owner (aka view controller)?

A quick test to verify the visibility of your UITextView - just place some sample text in it in the nib and verify that it appears on launch.  If so, then you know that at least your view is displaying appropriately.  At that point, it would have to be related to #2.

Title: iOS Text View Not Updating

Body:
I've got a UITextView defined by

@property (nonatomic, retain) IBOutlet UITextView *quote;

in my view controller header, and I can set the value by using

quote.text = @"some text";

but the view doens't want to update the value, what can I do


问:
Why symbol-type key in Object have a bracket around them
I just started JS, wondering why there are [] around Symbol. For example: in an object.

```<code>var bow = {
    [Symbol('apple')] : something,
    [Symbol('banana')] : something,
    ....
}
</code>```

Also, when it comes to iterator:

```<code>var iterableObject = {
    [Symbol.iterator] : function() {.....}
}
</code>```

Can anyone explain what is the use of these [] around them? I googled a while but didn't find satisfied answer, thank you in advance.

答:
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors

The bracket notation is just another way of accessing a property on an object. In particular, it's used when the property name is not valid for use with the dot notation, such as Symbol.iterator.

You may also want to look at computed property names: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names

These are similar but are instead used to set properties when an object is defined rather than get properties from an already defined object.

Body:
I just started JS, wondering why there are [] around Symbol. For example: in an object.

var bow = {
    [Symbol('apple')] : something,
    [Symbol('banana')] : something,
    ....
}

Also, when it comes to iterator:

var iterableObject = {
    [Symbol.iterator] : function() {.....}
}

Can anyone explain what is the use of these [] around them? I googled a while but didn't find satisfied answer, thank you in advance.


问:
Kivy Carousel and Button Widgets
Thanks to some friends on my last post I have a successfully working Kivy Carousel, now I am trying to add a "get started" type of button on the final page of the carousel that will take the user to the main app view when clicked.

I have a feeling that I need to implement logic such as "if the current picture is 'n' " to apply the button to the last screen only, but I am not sure how to make it work. I've looked all around for solutions but haven't found anything that relates to this particular concept..

This is my code for the carousel, thank you!!:

```<code>from kivy.app import App
from kivy.uix.carousel import Carousel
from kivy.uix.image import AsyncImage

class CarouselApp(App):

    def build(self):

        carousel = Carousel(direction='right')

        #For each loop to take each image from directory and place in carousel
        for i in range(0, 3):
            src = "carousel/%s.png" % str(i)
            image = AsyncImage(source=src, allow_stretch=True)
            carousel.add_widget(image)

        return carousel

CarouselApp().run()
</code>```

答:
On the last item of your carousel, instead of adding just an image, you must add a layout which will contain the image and the button:

with a boxlayout

```<code>from kivy.app import App
from kivy.uix.carousel import Carousel
from kivy.uix.image import AsyncImage
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button

class CarouselApp(App):

    def build(self):

        carousel = Carousel(direction='right')

        #For each loop to take each image from directory and place in carousel
        for i in range(0, 3):
            if i == 2:
                src = "carousel/%s.png" % str(i)
                button = Button(text='Get Started', on_press=self.get_started, size_hint_y=.1)
                image = AsyncImage(source=src, allow_stretch=True, size_hint_y=.9)
                layout = BoxLayout(orientation='vertical')
                layout.add_widget(image)
                layout.add_widget(button)
                carousel.add_widget(layout)
            else:
                src = "carousel/%s.png" % str(i)
                image = AsyncImage(source=src, allow_stretch=True)
                carousel.add_widget(image)
        return carousel

    def get_started(self, *args):
        print "let's start"

CarouselApp().run()
</code>```

with a floatlayout

```<code>...
from kivy.uix.floatlayout import FloatLayout

...

class CarouselApp(App):
    def build(self):
        carousel = Carousel(direction='right')
        #For each loop to take each image from directory and place in carousel
        for i in range(0, 3):
            if i == 2:
                src = "carousel/%s.png" % str(i)
                button = Button(text='Get Started', on_press=self.get_started, size_hint=(.5,.1), pos_hint={'center_x': .5, 'y': .1})
                image = AsyncImage(source=src, allow_stretch=True, size_hint=(1, 1), pos_hint={'center_x': .5, 'y': 0})
                layout = FloatLayout()
                layout.add_widget(image)
                layout.add_widget(button)
                carousel.add_widget(layout)

...
</code>```

Title: Kivy Carousel and Button Widgets

Body:
Thanks to some friends on my last post I have a successfully working Kivy Carousel, now I am trying to add a "get started" type of button on the final page of the carousel that will take the user to the main app view when clicked.

I have a feeling that I need to implement logic such as "if the current picture is 'n' " to apply the button to the last screen only, but I am not sure how to make it work. I've looked all around for solutions but haven't found anything that relates to this particular concept..

This is my code for the carousel, thank you!!:

from kivy.app import App
from kivy.uix.carousel import Carousel
from kivy.uix.image import AsyncImage

class CarouselApp(App):

    def build(self):

        carousel = Carousel(direction='right')

        #For each loop to take each image from directory and place in carousel
        for i in range(0, 3):
            src = "carousel/%s.png" % str(i)
            image = AsyncImage(source=src, allow_stretch=True)
            carousel.add_widget(image)

        return carousel

CarouselApp().run()

Body:
On the last item of your carousel, instead of adding just an image, you must add a layout which will contain the image and the button:

with a boxlayout

from kivy.app import App
from kivy.uix.carousel import Carousel
from kivy.uix.image import AsyncImage
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button

class CarouselApp(App):

    def build(self):

        carousel = Carousel(direction='right')

        #For each loop to take each image from directory and place in carousel
        for i in range(0, 3):
            if i == 2:
                src = "carousel/%s.png" % str(i)
                button = Button(text='Get Started', on_press=self.get_started, size_hint_y=.1)
                image = AsyncImage(source=src, allow_stretch=True, size_hint_y=.9)
                layout = BoxLayout(orientation='vertical')
                layout.add_widget(image)
                layout.add_widget(button)
                carousel.add_widget(layout)
            else:
                src = "carousel/%s.png" % str(i)
                image = AsyncImage(source=src, allow_stretch=True)
                carousel.add_widget(image)
        return carousel

    def get_started(self, *args):
        print "let's start"

CarouselApp().run()

with a floatlayout

...
from kivy.uix.floatlayout import FloatLayout

...

class CarouselApp(App):
    def build(self):
        carousel = Carousel(direction='right')
        #For each loop to take each image from directory and place in carousel
        for i in range(0, 3):
            if i == 2:
                src = "carousel/%s.png" % str(i)
                button = Button(text='Get Started', on_press=self.get_started, size_hint=(.5,.1), pos_hint={'center_x': .5, 'y': .1})
                image = AsyncImage(source=src, allow_stretch=True, size_hint=(1, 1), pos_hint={'center_x': .5, 'y': 0})
                layout = FloatLayout()
                layout.add_widget(image)
                layout.add_widget(button)
                carousel.add_widget(layout)

...


问:
boost MPL - doing transform on joint_view
Consider:

```<code>template<typename T>
struct MakeVectorOfType
{
    typedef std::vector<T> type;
};

typedef boost::mpl::vector<int, double> TScalarTypes;
typedef boost::mpl::transform<TScalarTypes, MakeVectorOfType<boost::mpl::placeholders::_1>>::type TVectorTypes;
typedef boost::mpl::joint_view<TScalarTypes, TVectorTypes>::type TTypes;

template<typename T>
struct Wrapper
{
    T value;
};

template<typename T>
struct MakeWrapper
{
    typedef Wrapper<T> type;
};

typedef boost::mpl::transform<
    TScalarTypes::type,
    MakeWrapper<boost::mpl::placeholders::_1>
>::type TScalarWrapperTypes; // <-- Works

typedef boost::mpl::transform<
    TTypes::type,
    MakeWrapper<boost::mpl::placeholders::_1>
>::type TAllWrapperTypes; // <-- Compiler error
</code>```

So essentially I have some types in an MPL sequence, I make another sequence with std::vectors of those types, then I want to do something with the union of the two. If I want to do another transform on that union (using joint_view), I get the following compiler error (using MSVC2017):

```<code>1>e:\source\trunk\thirdparty\boost\mpl\clear.hpp(31): error C2504: 'boost::mpl::clear_impl<boost::mpl::aux::joint_view_tag>::apply<Sequence>': base class undefined
1>        with
1>        [
1>            Sequence=boost::mpl::joint_view<TScalarTypes,TVectorTypes>
1>        ]
</code>```

(... plus a lot more tracing back to the code above, obviously)

The other one (where I do the transform directly on the sequence) works fine, so AFAICT it's the combination of applying a transform on a joint_view that is the problem here. So is it because the joint_view isn't a 'real' sequence but merely a 'view'? I can make a copy of the joint_view first and then apply the transform on that copy, but it just bugs me that I can't get this to work in one go.

答:
It seems mtl::transform is unable to handle the sequence generated by joint_view. joint_view generates a 'A lazy Forward Sequence' which mtl::transform may not support.

You can use boost::mpl::copy as below to solve the problem,

```<code>typedef typename boost::mpl::copy<TVectorTypes, boost::mpl::back_inserter<TScalarTypes> >::type TTypes;
</code>```

Body:
Consider:

template<typename T>
struct MakeVectorOfType
{
    typedef std::vector<T> type;
};

typedef boost::mpl::vector<int, double> TScalarTypes;
typedef boost::mpl::transform<TScalarTypes, MakeVectorOfType<boost::mpl::placeholders::_1>>::type TVectorTypes;
typedef boost::mpl::joint_view<TScalarTypes, TVectorTypes>::type TTypes;

template<typename T>
struct Wrapper
{
    T value;
};

template<typename T>
struct MakeWrapper
{
    typedef Wrapper<T> type;
};

typedef boost::mpl::transform<
    TScalarTypes::type,
    MakeWrapper<boost::mpl::placeholders::_1>
>::type TScalarWrapperTypes; // <-- Works

typedef boost::mpl::transform<
    TTypes::type,
    MakeWrapper<boost::mpl::placeholders::_1>
>::type TAllWrapperTypes; // <-- Compiler error

So essentially I have some types in an MPL sequence, I make another sequence with std::vectors of those types, then I want to do something with the union of the two. If I want to do another transform on that union (using joint_view), I get the following compiler error (using MSVC2017):

1>e:\source\trunk\thirdparty\boost\mpl\clear.hpp(31): error C2504: 'boost::mpl::clear_impl<boost::mpl::aux::joint_view_tag>::apply<Sequence>': base class undefined
1>        with
1>        [
1>            Sequence=boost::mpl::joint_view<TScalarTypes,TVectorTypes>
1>        ]

(... plus a lot more tracing back to the code above, obviously)

The other one (where I do the transform directly on the sequence) works fine, so AFAICT it's the combination of applying a transform on a joint_view that is the problem here. So is it because the joint_view isn't a 'real' sequence but merely a 'view'? I can make a copy of the joint_view first and then apply the transform on that copy, but it just bugs me that I can't get this to work in one go.

Body:
It seems mtl::transform is unable to handle the sequence generated by joint_view. joint_view generates a 'A lazy Forward Sequence' which mtl::transform may not support.

You can use boost::mpl::copy as below to solve the problem,

typedef typename boost::mpl::copy<TVectorTypes, boost::mpl::back_inserter<TScalarTypes> >::type TTypes;


问:
Uploading documents to a server using XQL/exist-db
APP Structure

```<code>NiC
| upload.xq
| upload.html
| controller.xql
| assignments.html (a lot of files are in the main dir, which is probably not good)
| templates/page.html
| inReview/
| data/all the xml files currently in the database
| images/all the images currently in the db
| modules/app.xql
| modules/view.xql
</code>```

Not all the files are here, but just some that are relevant and to give a flavor.

New discovery and problem as it now stands

I have been trying to get this uploader to work, and I've been stymied at every turn--BUT, I think it is finally working. However, it works in a very weird way, and I don't know why. Not knowing why it works this way and not another way is driving me crazy, and it will cause other problems down the line. So, I'm hoping someone can shed some light!

I'm basically hacking together something new from pieces of the sample Shakespeare archive in eXist-db. So, the structure of my whole app is virtually the same as the ship-with demo. That having been said:

in page.html, which templates the whole look of the page and provides the header/navigation information:

I have added a link to the navigation that goes to an upload page:

```<code><li><a href="../upload.html">Contribute</a></li>
</code>```

upload.html:

```<code><div xmlns="http://www.w3.org/1999/xhtml" class="templates:surround?with=templates/page.html&at=main">
        <form enctype="multipart/form-data" method="post" action="upload.xql">
            <fieldset>
            <legend>Upload an XML File for Review:</legend>
            <input type="file" name="file"/>
            <button id="f-btn-upload" name="f-btn-upload" value="true" type="submit" class="btn btn-danger">Upload</button>
        </fieldset>
    </form>
</div>
</code>```

upload.xql:

```<code>xquery version "3.0";

let $collection := '/db/apps/NiC/inReview/'
let $filename := request:get-uploaded-file-name('file')

(: make sure you use the right user permissions that has write access to this collection :)
let $login := xmldb:login($collection, 'username', 'superstrongpassword')
let $store := xmldb:store($collection, $filename, request:get-uploaded-file-data('file'))

return
<results>
   <message>File {$filename} has been stored at collection={$collection}.</message>
</results>
</code>```

All of this works, somehow. But the weird thing is in the controller.xql:

Here's the relevant bit:

```<code>else if ($exist:resource = ("search.html", "form1.html", "demo-queries.html", "search-help.html", "about-NiC.html", "assignments.html", "success.html", "upload.html")) then
    (: the html page is run through view.xql to expand templates :)
    (: question: 11/2017 why if upload.html is noted here does the URL need to be relative to ../upload.html from page.html, though others don't? :)
    <dispatch xmlns="http://exist.sourceforge.net/NS/exist">
        <forward url="{$exist:controller}/{$exist:resource}">
            <set-header name="Cache-Control" value="no-cache"/>
        </forward>
        <view>
            <forward url="{$exist:controller}/modules/view.xql"/>
        </view>
        <error-handler>
            <forward url="{$exist:controller}/error-page.html" method="get"/>
            <forward url="{$exist:controller}/modules/view.xql"/>
        </error-handler>
    </dispatch>
</code>```

If in page.html I use just the link "upload.html" as the controller would seem to require (upload.html is in the same place and doing the same kind of thing in general that the other pages are, like assignments.html and so on) it doesn't work. I get the SAX exception error/content not allowed in prolog. The other pages are accessible, and the URL resolution is working as expected. But if the link is "../upload.html," the page is accessible and the upload works as I want it to.

So my question is this: why? Why can't I just use upload.html as the path, trusting the controller to do what it does? Why do I have to gerrymander a solution with the relative path?

Argh!

答:
The return type of request:get-uploaded-file-data() is xs:base64Binary* while xmldb:store() expects "either a node, an xs:string, a Java file object or an xs:anyURI" (from the function documentation).
So you have to pipe the result through util:binary-to-string() first like

```<code>xmldb:store($collection, $filename, util:binary-to-string(request:get-uploaded-file-data('file')))
</code>```

The error you see is because xmldb:store() throws an XPathException if unsuccessful.

Body:
APP Structure

NiC
| upload.xq
| upload.html
| controller.xql
| assignments.html (a lot of files are in the main dir, which is probably not good)
| templates/page.html
| inReview/
| data/all the xml files currently in the database
| images/all the images currently in the db
| modules/app.xql
| modules/view.xql

Not all the files are here, but just some that are relevant and to give a flavor.

New discovery and problem as it now stands

I have been trying to get this uploader to work, and I've been stymied at every turn--BUT, I think it is finally working. However, it works in a very weird way, and I don't know why. Not knowing why it works this way and not another way is driving me crazy, and it will cause other problems down the line. So, I'm hoping someone can shed some light!

I'm basically hacking together something new from pieces of the sample Shakespeare archive in eXist-db. So, the structure of my whole app is virtually the same as the ship-with demo. That having been said:

in page.html, which templates the whole look of the page and provides the header/navigation information:

I have added a link to the navigation that goes to an upload page:

Contribute

upload.html:

        <form enctype="multipart/form-data" method="post" action="upload.xql">
            <fieldset>
            <legend>Upload an XML File for Review:</legend>
            <input type="file" name="file"/>
            <button id="f-btn-upload" name="f-btn-upload" value="true" type="submit" class="btn btn-danger">Upload</button>
        </fieldset>
    </form>

upload.xql:

xquery version "3.0";

let $collection := '/db/apps/NiC/inReview/'
let $filename := request:get-uploaded-file-name('file')

(: make sure you use the right user permissions that has write access to this collection :)
let $login := xmldb:login($collection, 'username', 'superstrongpassword')
let $store := xmldb:store($collection, $filename, request:get-uploaded-file-data('file'))

return
<results>
   <message>File {$filename} has been stored at collection={$collection}.</message>
</results>

All of this works, somehow. But the weird thing is in the controller.xql:

Here's the relevant bit:

else if ($exist:resource = ("search.html", "form1.html", "demo-queries.html", "search-help.html", "about-NiC.html", "assignments.html", "success.html", "upload.html")) then
    (: the html page is run through view.xql to expand templates :)
    (: question: 11/2017 why if upload.html is noted here does the URL need to be relative to ../upload.html from page.html, though others don't? :)
    <dispatch xmlns="http://exist.sourceforge.net/NS/exist">
        <forward url="{$exist:controller}/{$exist:resource}">
            <set-header name="Cache-Control" value="no-cache"/>
        </forward>
        <view>
            <forward url="{$exist:controller}/modules/view.xql"/>
        </view>
        <error-handler>
            <forward url="{$exist:controller}/error-page.html" method="get"/>
            <forward url="{$exist:controller}/modules/view.xql"/>
        </error-handler>
    </dispatch>

If in page.html I use just the link "upload.html" as the controller would seem to require (upload.html is in the same place and doing the same kind of thing in general that the other pages are, like assignments.html and so on) it doesn't work. I get the SAX exception error/content not allowed in prolog. The other pages are accessible, and the URL resolution is working as expected. But if the link is "../upload.html," the page is accessible and the upload works as I want it to.

So my question is this: why? Why can't I just use upload.html as the path, trusting the controller to do what it does? Why do I have to gerrymander a solution with the relative path?

Argh!

Body:
The return type of request:get-uploaded-file-data() is xs:base64Binary* while xmldb:store() expects "either a node, an xs:string, a Java file object or an xs:anyURI" (from the function documentation).
So you have to pipe the result through util:binary-to-string() first like

xmldb:store($collection, $filename, util:binary-to-string(request:get-uploaded-file-data('file')))

The error you see is because xmldb:store() throws an XPathException if unsuccessful.


问:
Unable to use Apache Commons CLI Option.builder() in Scala
In a spark shell or application (written in Scala/maven build), I am unable to use the static builder method from the Apache Commons CLI package.  I have confirmed that I am including the jar in the class path and have access to the Option class along with other classes in the package like Options, DefaultParser, etc.  Why can I not use this public static method in Scala?

```<code>import org.apache.commons.cli.Option

val opt = Option.builder("foo").build()
</code>```

error: value builder is not a member of object org.apache.commons.cli.Option

I can however see the static fields Option.UNINITIALIZED and Option.UNLIMITED_VALUES

using commons-cli 1.3.1

Scala version: 2.11.8

Spark version: 2.2.0

command to start the shell: spark-shell --jars .m2/repository/commons-cli/commons-cli/1.3.1/commons-cli-1.3.1.jar

答:
Let me help you clarify your problem scenario.

You can open your .idea folder, find that it have some internal jar dependencies already, and of the list commons_cli exists, but 1.2 version.

This would lead to class collision.

The solution is straightforward, refer the doc, use the compatible constructor method.

Body:
In a spark shell or application (written in Scala/maven build), I am unable to use the static builder method from the Apache Commons CLI package.  I have confirmed that I am including the jar in the class path and have access to the Option class along with other classes in the package like Options, DefaultParser, etc.  Why can I not use this public static method in Scala?

import org.apache.commons.cli.Option

val opt = Option.builder("foo").build()

error: value builder is not a member of object org.apache.commons.cli.Option

I can however see the static fields Option.UNINITIALIZED and Option.UNLIMITED_VALUES

using commons-cli 1.3.1

Scala version: 2.11.8

Spark version: 2.2.0

command to start the shell: spark-shell --jars .m2/repository/commons-cli/commons-cli/1.3.1/commons-cli-1.3.1.jar


问:
Optimizing react webpack config to production
My web production webpack config looks like:

```<code>const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
var webpack = require('webpack');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
const WebpackStrip = require('strip-loader');

module.exports = [
{
    devtool: 'cheap-module-source-map',
    entry: './ui/moduleTest/entry.js',
    output: { path: __dirname + '/public/compiled', filename: 'mod1bundle.js' },
    module: {
    loaders: [
         { test: /\.jsx?$/, loader: 'babel-loader', include: /ui/, query: { presets: ['es2015', 'stage-0', 'react'] } },
         { test: /\.scss$/, loader: ExtractTextPlugin.extract( "style", "css!sass") }
     ]
         },
    plugins: [
       new ExtractTextPlugin("styles.css"),
       new webpack.optimize.UglifyJsPlugin()
    ]
   },
 { devtool: 'cheap-module-source-map',
   entry: './ui/moduleTest2/entry.js',
   output: { path: __dirname + '/public/compiled', filename: 'mod2bundle.js' },
   module: {
        loaders: [
             { test: /\.jsx?$/, loader: 'babel-loader', include: /ui/, query: { presets: ['es2015', 'stage-0', 'react'] } },
           ]
   },
   plugins: [
         new ExtractTextPlugin("styles.css"),
         new ExtractTextPlugin("console.log"),
         new webpack.optimize.UglifyJsPlugin()
        ]
    },
   ....
  ];
</code>```

I tried to so many things and I can not make it production ready. The react dev tool tells me that I am using the dev version of react. I am kind of new to webpack. I also need to turn off the console.log messages. Any ideas on how to convert this config into a production ready? I've been reading a lot of things but I have problems to understand. I am using a command like:

```<code>  webpack --config=webpack.prod.config.js --watch --progress --watch-poll -p
</code>```

to compile my code

答:
You'll need to take a look at DefinePlugin.

Its job is to find instances of a given string, then replace them with some other string. Add this code to your plugins array to configure it to build the production version of React.

```<code>new webpack.DefinePlugin({
  'process.env.NODE_ENV': JSON.stringify('production')
})
</code>```

Then make sure you are using the UglifyJS plugin too and that it comes after the DefinePlugin in your config.

This will replace all of the following expressions:

```<code>if (process.env.NODE_ENV === "development") {
  // do slow development code
}
</code>```

With code that looks like:

```<code>if ("production" === "development") {
  // do slow development code
}
</code>```

Uglify can recognise this at compile time as an if expression that will never be true, and remove the entire statement.

If you want to remove all console.log statements, the easiest way is to make it a no op in an initialization file.

```<code>if (process.env.NODE_ENV === "production") {
  console.log = () => {};
  console.info = () => {};
  // ...
}
</code>```

Make sure this code runs before before any of the files that might have logging statements in.

Body:
My web production webpack config looks like:

const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
var webpack = require('webpack');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
const WebpackStrip = require('strip-loader');

module.exports = [
{
    devtool: 'cheap-module-source-map',
    entry: './ui/moduleTest/entry.js',
    output: { path: __dirname + '/public/compiled', filename: 'mod1bundle.js' },
    module: {
    loaders: [
         { test: /\.jsx?$/, loader: 'babel-loader', include: /ui/, query: { presets: ['es2015', 'stage-0', 'react'] } },
         { test: /\.scss$/, loader: ExtractTextPlugin.extract( "style", "css!sass") }
     ]
         },
    plugins: [
       new ExtractTextPlugin("styles.css"),
       new webpack.optimize.UglifyJsPlugin()
    ]
   },
 { devtool: 'cheap-module-source-map',
   entry: './ui/moduleTest2/entry.js',
   output: { path: __dirname + '/public/compiled', filename: 'mod2bundle.js' },
   module: {
        loaders: [
             { test: /\.jsx?$/, loader: 'babel-loader', include: /ui/, query: { presets: ['es2015', 'stage-0', 'react'] } },
           ]
   },
   plugins: [
         new ExtractTextPlugin("styles.css"),
         new ExtractTextPlugin("console.log"),
         new webpack.optimize.UglifyJsPlugin()
        ]
    },
   ....
  ];

I tried to so many things and I can not make it production ready. The react dev tool tells me that I am using the dev version of react. I am kind of new to webpack. I also need to turn off the console.log messages. Any ideas on how to convert this config into a production ready? I've been reading a lot of things but I have problems to understand. I am using a command like:

  webpack --config=webpack.prod.config.js --watch --progress --watch-poll -p

to compile my code

Body:
You'll need to take a look at DefinePlugin.

Its job is to find instances of a given string, then replace them with some other string. Add this code to your plugins array to configure it to build the production version of React.

new webpack.DefinePlugin({
  'process.env.NODE_ENV': JSON.stringify('production')
})

Then make sure you are using the UglifyJS plugin too and that it comes after the DefinePlugin in your config.

This will replace all of the following expressions:

if (process.env.NODE_ENV === "development") {
  // do slow development code
}

With code that looks like:

if ("production" === "development") {
  // do slow development code
}

Uglify can recognise this at compile time as an if expression that will never be true, and remove the entire statement.

If you want to remove all console.log statements, the easiest way is to make it a no op in an initialization file.

if (process.env.NODE_ENV === "production") {
  console.log = () => {};
  console.info = () => {};
  // ...
}

Make sure this code runs before before any of the files that might have logging statements in.


问:
How to open a shell command prompt inside Visual Studio Code?
When using Visual Studio Code, how do I run command-line programs, such as a choco (Chocolatey) command? Do I need to have a separate Command Line (CMD.exe) running outside VS Code, or is there a hotkey/window within Code where I can run those commands?

I see the "Command Palette", but it is not entirely clear what command engines run in that palette.

答: test with the Ctrl + J keys in ubuntu</p>

Body: test with the Ctrl + J keys in ubuntu


问:
How to generate indexes for related fields on Django models?
Say we're building a Django-based site that clones Medium.com's URL structure, where you have users and articles. We'd probably have this model:

```<code>class Article(models.Model):
    user = models.ForeignKey(User)
    slug = models.CharField()
</code>```

We want to be able to build URLs that look like /<username>/<slug>/. Since we're going to have billions of articles and zillions of pageviews, we want to put an index on that model:

```<code>class Meta:
    indexes = [
        models.Index(fields=['user__username', 'slug'])
    ]
</code>```

But this causes the makemigrations command to fail with the following error:

```<code>django.core.exceptions.FieldDoesNotExist: Article has no field named 'user__username'. The app cache isn't ready yet, so if this is an auto-created related field, it won't be available yet.
</code>```

So, plain vanilla models.Index doesn't support relational lookups like a QuerySet does. How would I add an index like this? Let's assume PostgreSQL, if that's helpful.

答:
It seems that you can't make multi-table index according to this answer.

So if it's not possible in the database, I don't see how can Django offer this feature...

What you can do to make your queries more efficients is an index using user_id and slug.

Body:
Say we're building a Django-based site that clones Medium.com's URL structure, where you have users and articles. We'd probably have this model:

class Article(models.Model):
    user = models.ForeignKey(User)
    slug = models.CharField()

We want to be able to build URLs that look like /<username>/<slug>/. Since we're going to have billions of articles and zillions of pageviews, we want to put an index on that model:

class Meta:
    indexes = [
        models.Index(fields=['user__username', 'slug'])
    ]

But this causes the makemigrations command to fail with the following error:

django.core.exceptions.FieldDoesNotExist: Article has no field named 'user__username'. The app cache isn't ready yet, so if this is an auto-created related field, it won't be available yet.

So, plain vanilla models.Index doesn't support relational lookups like a QuerySet does. How would I add an index like this? Let's assume PostgreSQL, if that's helpful.


问:
Change tabsetpanel with tag$button
I need to use custom buttons to pass from one tab to another. To do this, I've done a custom button tag$button in the ui.R file and a updateTabsetPanel in the server.R

The button is the following:

```<code>tags$button(
    id = "webleft",
    class = "btn action_button",
    tags$img(src='img/arrow-left.png',
    height = "50px")
),
</code>```

To change the tab I have the following function:

```<code>observeEvent(input$webleft,{
  updateTabsetPanel(session,"inTabset", selected = "Filtres")
})
</code>```

The problem is that with this button, the updateTabsetPanel does not work. Something that with an actionbutton such as actionButton("webleft", "Button") does. Any idea in how to solve the problem or any approach?

Thanks

答: The class name should be action-button with a hyphen

Title: Change tabsetpanel with tag$button

Body:
I need to use custom buttons to pass from one tab to another. To do this, I've done a custom button tag$button in the ui.R file and a updateTabsetPanel in the server.R

The button is the following:

tags$button(
    id = "webleft",
    class = "btn action_button",
    tags$img(src='img/arrow-left.png',
    height = "50px")
),

To change the tab I have the following function:

observeEvent(input$webleft,{
  updateTabsetPanel(session,"inTabset", selected = "Filtres")
})

The problem is that with this button, the updateTabsetPanel does not work. Something that with an actionbutton such as actionButton("webleft", "Button") does. Any idea in how to solve the problem or any approach?

Thanks


问:
Library for displaying image sets on an iPad
I'm looking for some cool libraries out there to display a bunch of images in my iPad application.

I think they are already out there, and I don't have to start from scratch, but I can't find some good ones.

答: Check out AQGridView as well. </p>

Body: Check out AQGridView as well.


问:
Java - What is the purpose of a "create" method that instantiates a new object?
Most of my experience with Java has been in the classroom setting, editing my own code. I'm finally venturing into the exciting world of deciphering other people's code, and I'm wondering about this:

```<code>public class MyClass {

    // Some fields here
    // A constructor there
    // Setters and getters abound

    public static MyClass create() {
        return new MyClass();
    }
}
</code>```

I'm wondering what the purpose of this method is. It doesn't seem like more trouble to write MyClass foo = new MyClass(); than to write MyClass foo = MyClass.create();. Is this some kind of Java idiom I'm unaware of? Is it completely unnecessary? Would it perhaps be somehow more useful in a class where the constructor took any parameters? What's the deal?

Thanks!

答:
Static factory method.

The constructor is normally private, that way the creation of new objects can be controlled by one method.

Further reading static builder class.

Body:
Most of my experience with Java has been in the classroom setting, editing my own code. I'm finally venturing into the exciting world of deciphering other people's code, and I'm wondering about this:

public class MyClass {

    // Some fields here
    // A constructor there
    // Setters and getters abound

    public static MyClass create() {
        return new MyClass();
    }
}

I'm wondering what the purpose of this method is. It doesn't seem like more trouble to write MyClass foo = new MyClass(); than to write MyClass foo = MyClass.create();. Is this some kind of Java idiom I'm unaware of? Is it completely unnecessary? Would it perhaps be somehow more useful in a class where the constructor took any parameters? What's the deal?

Thanks!


问:
Project Euler 1:Find the sum of all the multiples of 3 or 5 below 1000, works for 10 numbers but doesn't work for 1000

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.

So I decided to try and solve some problems on Euler site to improve with programming. While trying to solve the first problem I wrote a quick code to count the sum and it worked for 10 numbers, but for 1000 it shows me the answer: 166833 which is wrong and I can't really find an issue here. If someone could give me a hint to improve my algorythm so it would work.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Multiplies_of_3_and_5
{
  class Program
  {
    static void Main(string[] args)
    {
        int[] array = new int[7000];

        for (int j = 0; j<array.Length ;j++)
        {
            array[j] = j + 1;
        }

        int n = 1;
        int z = 1;
        int numbers = 0;

        for (int i = 0; i<999; i++)
        {
            if (array[i] == 3 * n )
            {
                n++;
                numbers += array[i];
            }

            else if (array[i] == 5 * z)
            {
                z++;
                numbers += array[i];
            }
        }
        Console.WriteLine(string.Join(" ", numbers));
        Console.ReadLine();
      }
   }
}
</code>```

答:
You should read up on the modulo operator (%).

```<code>  static void main(String[] args)
  {
    int sum = 0;
    for(int i=1; i< 1000; i++){
      if (i % 3 == 0 || i % 5 == 0){
        sum += i;
      }
    }
    Console.WriteLine(sum);
  }
</code>```

To give an explanation, the modulo operator gives the remainder when performing integer division on a value.

For example, 6 % 3 == 0 (3 evenly divides 6), 7 % 3 == 1 (7 divided by 3 leaves remainder 1).

So to sum all of the multiples of 3 and 5, just check if the value divides evenly by 3 or 5 (the if statement), and if so, add it to the running sum.

Note that your algorithm is going to screw up when you get to numbers that are multiple of 3 AND 5.  You never add to z in that case. You also need to change it to be <= 999, not <999 (you will never add 999 in your code, which divides by 3).

To sum things up:

Use your loop variable directly, no need to pre-populate another
array or have separate values keeping track of what multiple you're
at.

Modulo is super useful.

Body:
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.

So I decided to try and solve some problems on Euler site to improve with programming. While trying to solve the first problem I wrote a quick code to count the sum and it worked for 10 numbers, but for 1000 it shows me the answer: 166833 which is wrong and I can't really find an issue here. If someone could give me a hint to improve my algorythm so it would work.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Multiplies_of_3_and_5
{
  class Program
  {
    static void Main(string[] args)
    {
        int[] array = new int[7000];

        for (int j = 0; j<array.Length ;j++)
        {
            array[j] = j + 1;
        }

        int n = 1;
        int z = 1;
        int numbers = 0;

        for (int i = 0; i<999; i++)
        {
            if (array[i] == 3 * n )
            {
                n++;
                numbers += array[i];
            }

            else if (array[i] == 5 * z)
            {
                z++;
                numbers += array[i];
            }
        }
        Console.WriteLine(string.Join(" ", numbers));
        Console.ReadLine();
      }
   }
}

Body:
You should read up on the modulo operator (%).

  static void main(String[] args)
  {
    int sum = 0;
    for(int i=1; i< 1000; i++){
      if (i % 3 == 0 || i % 5 == 0){
        sum += i;
      }
    }
    Console.WriteLine(sum);
  }

To give an explanation, the modulo operator gives the remainder when performing integer division on a value.

For example, 6 % 3 == 0 (3 evenly divides 6), 7 % 3 == 1 (7 divided by 3 leaves remainder 1).

So to sum all of the multiples of 3 and 5, just check if the value divides evenly by 3 or 5 (the if statement), and if so, add it to the running sum.

Note that your algorithm is going to screw up when you get to numbers that are multiple of 3 AND 5.  You never add to z in that case. You also need to change it to be <= 999, not <999 (you will never add 999 in your code, which divides by 3).

To sum things up:

Use your loop variable directly, no need to pre-populate another
array or have separate values keeping track of what multiple you're
at.

Modulo is super useful.


问:
What does it mean for a function to return?
I was reading the Apple developer documentation's definition of escaping closures. It says "a closure is said to escape a function when the closure is passed as an argument to the function, but is called after the function returns".

I'm not sure what the last word "return" means in this context. I know a function can return values such as an Int value or a String value. But I'm not sure what it means by "after the function returns".

Please note that I'm not asking what escaping closures are. I just want to know what the word "return" means here. I asked the same question before but everyone was explaining what escaping closures are and none of them explained the word "return" so I just want to make my question clearer this time.

答: It's like saying "ends". Either the path of execution reaches the keyword return or it reaches the last line of the function body that it's ever going to reach. Either way, it "returns" at that moment. It is the moment when the path of execution resumes at the point where the function was called.


问:
Efficiently Iterating through image in Javascript
I am doing some image processing project in JavaScript where i need to iterate through each image pixels and do some other processing to achieve my target.

I am using canvas to get an image pixels data array.

For small images, like 500x300 px in dimensions, its working fine and taking acceptable time. But for large images, like 3000x3000 px in dimensions, the iteration process is becoming a bottleneck and taking a huge time, like 10-12 seconds.

So is there any method or trick which could be used to reduce the time used in the iteration steps?

Here is what I am thinking about: I am trying to use parallel web workers(let it be 4) to iterate through equal parts of the image data: (eg. 0-[len/4], [len/4]+1-[len/2], [len/2]+1 - [len*3/4], [len*3/4]+1 - len) where lenis the size of the image data array.

I doubt this approach will be more time efficient since Javascript is single threaded.

```<code> function rgb2grey(pix,offset){
        return (0.2989*pix[offset] + 0.5870*pix[offset+1] +
    0.1140*pix[offset+2]);

}

function imgcompare(fileData1,fileData2,targetpix){
        var len = pix.length;
        for (var j = 0; j <len; j+=4) {
                var grey1 = rgb2grey(fileData1,j);
            var grey2 = rgb2grey(fileData2,j);
            if(grey1!=grey2){
                targetpix[j] = 255;
                targetpix[j+1] = targetpix[j+2] = 0;
            }
            else{
                targetpix[j] = fileData1[j];
                targetpix[j+1] = fileData1[j+1];
                targetpix[j+2] = fileData1[j+2];
            }
            targetpix[j+3] = fileData1[j+3];
        }
}
</code>```

答:
You can use a Javascript Image Processing Framework like MarvinJ. The snippet below demonstrates how to iterate through pixels to implement a color threshold algorithm.

var canvas1 = document.getElementById("canvas1");
var canvas2 = document.getElementById("canvas2");

image = new MarvinImage();
image.load("https://i.imgur.com/gaW8OeL.jpg", imageLoaded);

function imageLoaded(){
  image.draw(canvas1);
  var threshold=200;
  for(var y=0; y<image.getHeight(); y++){
    for(var x=0; x<image.getWidth(); x++){
       var r = image.getIntComponent0(x,y);
       var g = image.getIntComponent1(x,y);
       var b = image.getIntComponent2(x,y);

       if(r <= threshold && g <= threshold && b <= threshold){
         image.setIntColor(x, y, 0xFF000000);
       } else{
         image.setIntColor(x, y, 0xFFFFFFFF);
       }
     }
   }

   image.draw(canvas2);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://www.marvinj.org/releases/marvinj-0.7.js"></script>
<canvas id="canvas1" width="200" height="200"></canvas>
<canvas id="canvas2" width="200" height="200"></canvas></code>```

Body:
I am doing some image processing project in JavaScript where i need to iterate through each image pixels and do some other processing to achieve my target.

I am using canvas to get an image pixels data array.

For small images, like 500x300 px in dimensions, its working fine and taking acceptable time. But for large images, like 3000x3000 px in dimensions, the iteration process is becoming a bottleneck and taking a huge time, like 10-12 seconds.

So is there any method or trick which could be used to reduce the time used in the iteration steps?

Here is what I am thinking about: I am trying to use parallel web workers(let it be 4) to iterate through equal parts of the image data: (eg. 0-[len/4], [len/4]+1-[len/2], [len/2]+1 - [len*3/4], [len*3/4]+1 - len) where lenis the size of the image data array.

I doubt this approach will be more time efficient since Javascript is single threaded.

 function rgb2grey(pix,offset){
        return (0.2989*pix[offset] + 0.5870*pix[offset+1] +
    0.1140*pix[offset+2]);

}

function imgcompare(fileData1,fileData2,targetpix){
        var len = pix.length;
        for (var j = 0; j <len; j+=4) {
                var grey1 = rgb2grey(fileData1,j);
            var grey2 = rgb2grey(fileData2,j);
            if(grey1!=grey2){
                targetpix[j] = 255;
                targetpix[j+1] = targetpix[j+2] = 0;
            }
            else{
                targetpix[j] = fileData1[j];
                targetpix[j+1] = fileData1[j+1];
                targetpix[j+2] = fileData1[j+2];
            }
            targetpix[j+3] = fileData1[j+3];
        }
}

Body:
You can use a Javascript Image Processing Framework like MarvinJ. The snippet below demonstrates how to iterate through pixels to implement a color threshold algorithm.

var canvas1 = document.getElementById("canvas1");
var canvas2 = document.getElementById("canvas2");

image = new MarvinImage();
image.load("https://i.imgur.com/gaW8OeL.jpg", imageLoaded);

function imageLoaded(){
  image.draw(canvas1);
  var threshold=200;
  for(var y=0; y<image.getHeight(); y++){
    for(var x=0; x<image.getWidth(); x++){
       var r = image.getIntComponent0(x,y);
       var g = image.getIntComponent1(x,y);
       var b = image.getIntComponent2(x,y);

       if(r <= threshold && g <= threshold && b <= threshold){
         image.setIntColor(x, y, 0xFF000000);
       } else{
         image.setIntColor(x, y, 0xFFFFFFFF);
       }
     }
   }

   image.draw(canvas2);
}

<script src="https://www.marvinj.org/releases/marvinj-0.7.js"></script>
<canvas id="canvas1" width="200" height="200"></canvas>
<canvas id="canvas2" width="200" height="200"></canvas>


问:
Load local data files to Colaboratory
I just wondering that is it possible to load local data files(like .xlsx or .csv files that on my google drive) into Colaboratory?</p>

答:
Yes, all of these scenarios are supported.

For recipes to access local and Drive files, check out the I/O example notebook.

For access to xls files, you'll want to upload the file to Google Sheets. Then, you can use the gspread recipes in the same I/O example notebook.

A recently added way to upload local files is to use the 'Files' tab in the right hand side drawer.

From there, you can upload a local file using the 'upload' button.

(You can also download files by right clicking on them in the file tree.)

Title: Load local data files to Colaboratory


问:
z-index not working on side nav
I am trying to have the hamburger menu "on top" of the side nav, to later toggle the sidenav with this hamburger (instead of having to close it with the x).

Problem is that the z-index seems to be ignored. Why is that and how can I resolve that to bring the hamburger to the front even when the sidenav comes in?

function openNav() {
    document.getElementById("myNav").style.width = "100%";
}

function closeNav() {
    document.getElementById("myNav").style.width = "0%";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.overlay {
    height: 100%;
    width: 0;
    position: fixed;
    z-index: 1;
    top: 0;
    left: 0;
    background-color: blue;
    overflow-x: hidden;
    transition: 0.5s;
}

.overlay-content {
    position: relative;
    top: 25%;
    width: 100%;
    text-align: center;
    margin-top: 30px;
}

.overlay a {
    padding: 8px;
    text-decoration: none;
    font-size: 36px;
    color: #818181;
    display: block;
    transition: 0.3s;
}

.overlay a:hover, .overlay a:focus {
    color: #f1f1f1;
}

.overlay .closebtn {
    position: absolute;
    top: 20px;
    right: 45px;
    font-size: 60px;
}

.front {
    z-index: 1050;
}</code>```

  ×

    About
    Services
    Clients
    Contact

Fullscreen Overlay Nav Example

☰ open```

答:
Please check the .front's position property.
position: static;, position: initial; ignore z-index.

If you want to give z-index without changing position, change to position: relative;

function openNav() {
    document.getElementById("myNav").style.width = "100%";
}

function closeNav() {
    document.getElementById("myNav").style.width = "0%";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.overlay {
    height: 100%;
    width: 0;
    position: fixed;
    z-index: 1;
    top: 0;
    left: 0;
    background-color: blue;
    overflow-x: hidden;
    transition: 0.5s;
}

.overlay-content {
    position: relative;
    top: 25%;
    width: 100%;
    text-align: center;
    margin-top: 30px;
}

.overlay a {
    padding: 8px;
    text-decoration: none;
    font-size: 36px;
    color: #818181;
    display: block;
    transition: 0.3s;
}

.overlay a:hover, .overlay a:focus {
    color: #f1f1f1;
}

.overlay .closebtn {
    position: absolute;
    top: 20px;
    right: 45px;
    font-size: 60px;
}

.front {
    position: absolute;
    z-index: 1050;
}</code>```

  ×

    About
    Services
    Clients
    Contact

Fullscreen Overlay Nav Example

☰ open```

Title: z-index not working on side nav

Body:
I am trying to have the hamburger menu "on top" of the side nav, to later toggle the sidenav with this hamburger (instead of having to close it with the x).

Problem is that the z-index seems to be ignored. Why is that and how can I resolve that to bring the hamburger to the front even when the sidenav comes in?

function openNav() {
    document.getElementById("myNav").style.width = "100%";
}

function closeNav() {
    document.getElementById("myNav").style.width = "0%";
}

.overlay {
    height: 100%;
    width: 0;
    position: fixed;
    z-index: 1;
    top: 0;
    left: 0;
    background-color: blue;
    overflow-x: hidden;
    transition: 0.5s;
}

.overlay-content {
    position: relative;
    top: 25%;
    width: 100%;
    text-align: center;
    margin-top: 30px;
}

.overlay a {
    padding: 8px;
    text-decoration: none;
    font-size: 36px;
    color: #818181;
    display: block;
    transition: 0.3s;
}

.overlay a:hover, .overlay a:focus {
    color: #f1f1f1;
}

.overlay .closebtn {
    position: absolute;
    top: 20px;
    right: 45px;
    font-size: 60px;
}

.front {
    z-index: 1050;
}

  ×

    About
    Services
    Clients
    Contact

Fullscreen Overlay Nav Example

☰ open

Body:
Please check the .front's position property.
position: static;, position: initial; ignore z-index.

If you want to give z-index without changing position, change to position: relative;

function openNav() {
    document.getElementById("myNav").style.width = "100%";
}

function closeNav() {
    document.getElementById("myNav").style.width = "0%";
}

.overlay {
    height: 100%;
    width: 0;
    position: fixed;
    z-index: 1;
    top: 0;
    left: 0;
    background-color: blue;
    overflow-x: hidden;
    transition: 0.5s;
}

.overlay-content {
    position: relative;
    top: 25%;
    width: 100%;
    text-align: center;
    margin-top: 30px;
}

.overlay a {
    padding: 8px;
    text-decoration: none;
    font-size: 36px;
    color: #818181;
    display: block;
    transition: 0.3s;
}

.overlay a:hover, .overlay a:focus {
    color: #f1f1f1;
}

.overlay .closebtn {
    position: absolute;
    top: 20px;
    right: 45px;
    font-size: 60px;
}

.front {
    position: absolute;
    z-index: 1050;
}

<div id="myNav" class="overlay">
  <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a>
  <div class="overlay-content">
    <a href="#">About</a>
    <a href="#">Services</a>
    <a href="#">Clients</a>
    <a href="#">Contact</a>
  </div>
</div>

<h2>Fullscreen Overlay Nav Example</h2>
<span class="front" style="font-size:30px;cursor:pointer" onclick="openNav()">&#9776; open</span>


问:
CQS with dispatcher casting issues
I am trying to build a microservice that pulls commands and queries off of a queue. My service watches a specific queue and pulls a message off that could be any type command for that domain. That message is pulled off and passed to the dispatcher. My problem is that in trying to make everything as generic as possible, my message is being passed into the dispatcher as an object, but the dispatcher needs a concrete IQuery class. I can cast it to IQuery because I know that it is that type, but when I try to resolve the dependencies in the dispatcher based on the type, it fails because the concrete type is not known. I will try to keep the code samples small and to the point:

Main Service

```<code>    private static async Task HandleMessageReceived(MessageReceivedEventArgs args) {
        await queryDispatcher.Dispatch((IQuery)args.Message.Payload);
    }
</code>```

Query Dispatcher

```<code>public class QueryDispatcher : IQueryDispatcher {
    #region attributes
    private readonly IComponentContext _context;
    #endregion

    #region ctor
    public QueryDispatcher(IComponentContext context) {
        _context = context;
    }
    #endregion

    #region methods
    public async Task<IEvent> Dispatch<T>(T query) where T : IQuery{
        if (query == null) {
            return new ArgumentNullEvent(nameof(query));
        }

        var validator = _context.Resolve<IValidator<T>>();
        var handler = _context.Resolve<IQueryHandler<T>>();

        List<ValidationResult> errors = await validator.Validate(query);

        if(errors.Count == 0) {
            return await handler.Handle(query);
        } else {
            return new ValidationFailedEvent(query.Id, errors);
        }
    }
    #endregion
}
</code>```

Queue Message

```<code>public class QueueMessage {
    public Guid OperationId { get; set; }
    public object Payload { get; set; }
}
</code>```

Concrete IQuery Impl

```<code>public class GetSite : BaseQuery, IQuery {
    public Guid SiteGuid { get; set; }
}
</code>```

答:
You could build the type using MakeGenericType:</p>

```<code>var validator = _context.Resolve(typeof(IValidator<>)
                        .MakeGenericType(new[] { query.GetType() }));
var handler = _context.Resolve(typeof(IQueryHandler<>)
                      .MakeGenericType(new[] { query.GetType() }));
</code>```

Title: CQS with dispatcher casting issues

Body:
I am trying to build a microservice that pulls commands and queries off of a queue. My service watches a specific queue and pulls a message off that could be any type command for that domain. That message is pulled off and passed to the dispatcher. My problem is that in trying to make everything as generic as possible, my message is being passed into the dispatcher as an object, but the dispatcher needs a concrete IQuery class. I can cast it to IQuery because I know that it is that type, but when I try to resolve the dependencies in the dispatcher based on the type, it fails because the concrete type is not known. I will try to keep the code samples small and to the point:

Main Service

    private static async Task HandleMessageReceived(MessageReceivedEventArgs args) {
        await queryDispatcher.Dispatch((IQuery)args.Message.Payload);
    }

Query Dispatcher

public class QueryDispatcher : IQueryDispatcher {
    #region attributes
    private readonly IComponentContext _context;
    #endregion

    #region ctor
    public QueryDispatcher(IComponentContext context) {
        _context = context;
    }
    #endregion

    #region methods
    public async Task<IEvent> Dispatch<T>(T query) where T : IQuery{
        if (query == null) {
            return new ArgumentNullEvent(nameof(query));
        }

        var validator = _context.Resolve<IValidator<T>>();
        var handler = _context.Resolve<IQueryHandler<T>>();

        List<ValidationResult> errors = await validator.Validate(query);

        if(errors.Count == 0) {
            return await handler.Handle(query);
        } else {
            return new ValidationFailedEvent(query.Id, errors);
        }
    }
    #endregion
}

Queue Message

public class QueueMessage {
    public Guid OperationId { get; set; }
    public object Payload { get; set; }
}

Concrete IQuery Impl

public class GetSite : BaseQuery, IQuery {
    public Guid SiteGuid { get; set; }
}

Body:
You could build the type using MakeGenericType:

var validator = _context.Resolve(typeof(IValidator<>)
                        .MakeGenericType(new[] { query.GetType() }));
var handler = _context.Resolve(typeof(IQueryHandler<>)
                      .MakeGenericType(new[] { query.GetType() }));


问:
Spring Test MVC : How to use object as Request Parameters
I am trying to write Spring MVC Tests to test Spring controllers.
Currently if I wanted to test a controller method with this signature:

```<code>@RequestMapping(value = "/new/save", method = RequestMethod.POST)
@Transactional
public String postGateway(@Valid GatewayForm gatewayForm, BindingResult bindingResult, RedirectAttributes flash, Model model)
</code>```

I would use MockMVC in this manner to populate the GatewayForm object parameter:

```<code>mvc.perform(
                post("/new/save")
                        .sessionAttr("account", account)
                        .param("serialNumber", "SN1QRTY334V")
                        .param("branchId", "1")
                        .param("model", "1")
                        .param("templateId", "1")
</code>```

The problem with this is that I can only set String/primitive values onto the GatewayForm object using the .param(String, String) method.

So there are object instance variables on the GatewayForm above that I cannot set. I have seen other people instead post a JSON string of the object, but this would require changing the implementation of the controller methods to consume "application/json" which I do not want to do.

Can anybody advise?

答:
As the comments to the question state that strings are essentially the input for HTTP requests parameters, the goal is to convert your form object into an accepted string.

Looking at the spring-mvc-test-utils library there are multiple strategies to converting an object into a String. However, the default strategy for converting an object into a String within the source code is to use:

```<code>String.valueOf(Object object)
</code>```

For example my use case was to pass a List as parameters into my integration test. My controller accepts an object with attributes:

```<code>public class MyObjectThatTheControllerExpects {
    List<SomeEnum> listOfEnums;
    Long id
    ...
</code>```

Therefore, my integration test posts the parameters like so:

```<code>mvc
    .perform(
        post("/some/endpoint")
            .param("listOfEnums", String.valueOf(SomeEnum.SOMEENUMCONSTANT), String.valueOf(SomeEnum.SOMEOTHERENUMCONSTANT))
            .param("id", "100")
</code>```

I am sure this may not be appropriate for more complex classes. However, for this trivial case it works.

Hope it helps!

Body:
I am trying to write Spring MVC Tests to test Spring controllers.
Currently if I wanted to test a controller method with this signature:

@RequestMapping(value = "/new/save", method = RequestMethod.POST)
@Transactional
public String postGateway(@Valid GatewayForm gatewayForm, BindingResult bindingResult, RedirectAttributes flash, Model model)

I would use MockMVC in this manner to populate the GatewayForm object parameter:

mvc.perform(
                post("/new/save")
                        .sessionAttr("account", account)
                        .param("serialNumber", "SN1QRTY334V")
                        .param("branchId", "1")
                        .param("model", "1")
                        .param("templateId", "1")

The problem with this is that I can only set String/primitive values onto the GatewayForm object using the .param(String, String) method.

So there are object instance variables on the GatewayForm above that I cannot set. I have seen other people instead post a JSON string of the object, but this would require changing the implementation of the controller methods to consume "application/json" which I do not want to do.

Can anybody advise?

Body:
As the comments to the question state that strings are essentially the input for HTTP requests parameters, the goal is to convert your form object into an accepted string.

Looking at the spring-mvc-test-utils library there are multiple strategies to converting an object into a String. However, the default strategy for converting an object into a String within the source code is to use:

String.valueOf(Object object)

For example my use case was to pass a List as parameters into my integration test. My controller accepts an object with attributes:

public class MyObjectThatTheControllerExpects {
    List<SomeEnum> listOfEnums;
    Long id
    ...

Therefore, my integration test posts the parameters like so:

mvc
    .perform(
        post("/some/endpoint")
            .param("listOfEnums", String.valueOf(SomeEnum.SOMEENUMCONSTANT), String.valueOf(SomeEnum.SOMEOTHERENUMCONSTANT))
            .param("id", "100")

I am sure this may not be appropriate for more complex classes. However, for this trivial case it works.

Hope it helps!


问:
What is an efficient SQL query to join to a double maximum in a sub query?
Sorry the title is crap - I could not think of a better way to phrase it. This is my data structure:

```<code>Widget   WidgetTransition
------   ----------------
Id,      WidgetId,
...      TransitionTypeId,
         Cost,
         ...
</code>```

I want a query that will give me a list of details for each widget along with the details of the most expensive (max WidgetTransition.Cost) transition. If a widget has two or more transitions that are 'tied' for the most expensive transition, the details of the most recent transition (max WidgetTransition.WidgetId) should be used. If the widget has no transitions, it should not appear in the results. This is the best that I could come up with:

```<code>SELECT *
FROM   Widget
JOIN   WidgetTransition
ON     WidgetTransition.WidgetId = Widget.Id
AND    WidgetTransition.Cost = (
       SELECT Max(MostExpensiveTransition.Cost)
       FROM   WidgetTransition MostExpensiveTransition
       WHERE  MostExpensiveTransition.WidgetId = Widget.Id
       )
</code>```

This almost works, but has two problems.

Doesn't deal with tied transitions properly. If a widget has two or more tied transitions, each transition will appear in the results, instead of the most recent.

With large data sets, the query is sloooow. The Sybase database that I am running it on will do two table scans (WidgetTransition.Cost is not in the index) on WidgetTransition for each widget. Presumably one is for the join and one to find the max cost.

Is there a better way to write this query that fixes the tied problem and/or runs more efficiently? I want to avoid using T-SQL or a stored procedure.

答:
If you are using a database product that supports ranking functions and common table expressions such as SQL Server 2005 and later (or recent versions of Sybase), you can do something like:</p>

```<code>With Data As
    (
    Select WidgetId, TransitionTypeId
        , Row_Number() Over ( Partition By WidgetId
                                Order By Cost Desc, WidgetId Desc ) As Rnk
    From WidgetTransition
    )
Select ...
From Widget As W
    Join Data As D
        On D.WidgetId = W.WidgetId
Where D.Rnk = 1
</code>```

Body:
Sorry the title is crap - I could not think of a better way to phrase it. This is my data structure:

Widget   WidgetTransition
------   ----------------
Id,      WidgetId,
...      TransitionTypeId,
         Cost,
         ...

I want a query that will give me a list of details for each widget along with the details of the most expensive (max WidgetTransition.Cost) transition. If a widget has two or more transitions that are 'tied' for the most expensive transition, the details of the most recent transition (max WidgetTransition.WidgetId) should be used. If the widget has no transitions, it should not appear in the results. This is the best that I could come up with:

SELECT *
FROM   Widget
JOIN   WidgetTransition
ON     WidgetTransition.WidgetId = Widget.Id
AND    WidgetTransition.Cost = (
       SELECT Max(MostExpensiveTransition.Cost)
       FROM   WidgetTransition MostExpensiveTransition
       WHERE  MostExpensiveTransition.WidgetId = Widget.Id
       )

This almost works, but has two problems.

Doesn't deal with tied transitions properly. If a widget has two or more tied transitions, each transition will appear in the results, instead of the most recent.

With large data sets, the query is sloooow. The Sybase database that I am running it on will do two table scans (WidgetTransition.Cost is not in the index) on WidgetTransition for each widget. Presumably one is for the join and one to find the max cost.

Is there a better way to write this query that fixes the tied problem and/or runs more efficiently? I want to avoid using T-SQL or a stored procedure.

Body:
If you are using a database product that supports ranking functions and common table expressions such as SQL Server 2005 and later (or recent versions of Sybase), you can do something like:

With Data As
    (
    Select WidgetId, TransitionTypeId
        , Row_Number() Over ( Partition By WidgetId
                                Order By Cost Desc, WidgetId Desc ) As Rnk
    From WidgetTransition
    )
Select ...
From Widget As W
    Join Data As D
        On D.WidgetId = W.WidgetId
Where D.Rnk = 1


答:
It's a very useful idiom, static factory method.  It gives full control on the new instance creation, whether it's a different instance, a cached instance etc.  It only makes sense if the constructor is set to private.</p>

```<code>public class MyClass {

  private MyClass() {}

  public static MyClass create() {
      return new MyOtherClass();
  }

  private static class MyOtherClass extends MyClass {
    ...
  }
}
</code>```

Title: Java - What is the purpose of a "create" method that instantiates a new object?

Body:
It's a very useful idiom, static factory method.  It gives full control on the new instance creation, whether it's a different instance, a cached instance etc.  It only makes sense if the constructor is set to private.

public class MyClass {

  private MyClass() {}

  public static MyClass create() {
      return new MyOtherClass();
  }

  private static class MyOtherClass extends MyClass {
    ...
  }
}


问:
Why are both `p()` and `(*p)()` valid?
Say for this simple code:

```<code>int foo(void);
int (*p)(void);
p = foo;
p = &foo;
int a = p();
int b = (*p)();
</code>```

In the above example, Line 3&4 are both valid, Line 5&6 are also both valid.

In fact if you try to play with variable pointers like that when you play with function pointers, your program will surely die. So why is it valid for function pointers?

答:
A function (more precisely, a function designator) is converted to a pointer to a function (except when it is the operand of sizeof, _Alignof, or the unary &). So foo and &foo are the same thing because foo is automatically converted to &foo.

Similarly, p is a pointer to a function, so *p is the function, so it is automatically converted to the address of the function.

In fact, because *p is converted back to a pointer right away, you can apply * to it again, as in int b = (**p)();. And you can do that again and again and again: int b = (************p)();.

From the 2011 C standard (committee draft N1570), 6.3.2.1 4:

A function designator is an expression that has function type. Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary & operator, a function designator with type “function returning type” is converted to an expression that has type “pointer to function returning type”.

This is just a consequence of the fact that C developers wanted to make it easy to use both functions like foo and pointers-to-functions like p. If you had to write foo() for one and (*p)() for the other, that would be a bit of a nuisance. Or at least more typing. Or, if you had to write (&foo)() for one and p() for the other, that is again more typing. So they just said whenever you write a function, we will automatically make it the pointer, and you can call it without typing any more.

I suppose they could have said the function call operator can accept either a function or a pointer to a function, but they chose the automatic conversion instead.

Corollary: If you do not know whether something is a function, or a pointer to a function, or a pointer to a pointer to a function, etc., just slap a hundred asterisks in front of it, and the compiler will stop when it gets to the function.

Title: Why are both `p()` and `(*p)()` valid?

Body:
Say for this simple code:

int foo(void);
int (*p)(void);
p = foo;
p = &foo;
int a = p();
int b = (*p)();

In the above example, Line 3&4 are both valid, Line 5&6 are also both valid.

In fact if you try to play with variable pointers like that when you play with function pointers, your program will surely die. So why is it valid for function pointers?


问:
Make table in R Markdown using tabular() and booktabs
I am using the tabular() function in the tables package to make tables in an R Markdown file.  I would like to use the booktabs() option to include a horizontal rule.  However, when I do so, the code from booktabs() appears in my LaTex document, even when I set the chuck option to echo=FALSE.

How can I use the booktabs() option with tabular?

Output:

And here is the code for the example:

```<code>---
title: "Making Tables"
output:
  pdf_document: default
header-includes: \usepackage{booktabs}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)

library(tables)
library(Hmisc)
```

```{r no line, results='asis'}
latex(tabular( (Species + 1) ~ (n=1) + Format(digits=2)*(Sepal.Length + Sepal.Width)*(mean + sd), data = iris))
```

```{r with line, results='asis', echo = FALSE}
booktabs()
latex(tabular( (Species + 1) ~ (n=1) + Format(digits=2)*(Sepal.Length + Sepal.Width)*(mean + sd), data = iris))
```
</code>```

答:
Just use the invisible function around booktabs like this:

```<code>```{r with line, echo = FALSE,results= "asis"}
invisible(booktabs())
latex(tabular( (Species + 1) ~ (n=1) + Format(digits=2)*(Sepal.Length + Sepal.Width)*(mean + sd), data = iris))
```
</code>```

Body:
I am using the tabular() function in the tables package to make tables in an R Markdown file.  I would like to use the booktabs() option to include a horizontal rule.  However, when I do so, the code from booktabs() appears in my LaTex document, even when I set the chuck option to echo=FALSE.

How can I use the booktabs() option with tabular?

Output:

And here is the code for the example:

---
title: "Making Tables"
output:
  pdf_document: default
header-includes: \usepackage{booktabs}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)

library(tables)
library(Hmisc)
```

```{r no line, results='asis'}
latex(tabular( (Species + 1) ~ (n=1) + Format(digits=2)*(Sepal.Length + Sepal.Width)*(mean + sd), data = iris))
```

```{r with line, results='asis', echo = FALSE}
booktabs()
latex(tabular( (Species + 1) ~ (n=1) + Format(digits=2)*(Sepal.Length + Sepal.Width)*(mean + sd), data = iris))
```

Body:
Just use the invisible function around booktabs like this:

```{r with line, echo = FALSE,results= "asis"}
invisible(booktabs())
latex(tabular( (Species + 1) ~ (n=1) + Format(digits=2)*(Sepal.Length + Sepal.Width)*(mean + sd), data = iris))
```


问:
Including carriage returns in PHP regex
How do I rewrite the following regex expression to include carriage returns and spaces?

```<code>mysql_query\("(.*)"\)
</code>```

It should match the following types of data.

String with carriage returns:

```<code>$result = my_mysql_query("
SELECT foo, bar
FROM mytable
ORDER BY name");
</code>```

String with some carriage returns:

```<code>$result = my_mysql_query("SELECT foo, bar
FROM mytable
ORDER BY name");
</code>```

String with no carriage returns:

```<code>$result = my_mysql_query("SELECT foo, bar FROM mytable ORDER BY name");
</code>```

答:
Answering my own question... The better regex is:</p>

```<code>/mysql_query\("(.?)"\)/s
</code>```

Title: Including carriage returns in PHP regex

Body:
How do I rewrite the following regex expression to include carriage returns and spaces?

mysql_query\("(.*)"\)

It should match the following types of data.

String with carriage returns:

$result = my_mysql_query("
SELECT foo, bar
FROM mytable
ORDER BY name");

String with some carriage returns:

$result = my_mysql_query("SELECT foo, bar
FROM mytable
ORDER BY name");

String with no carriage returns:

$result = my_mysql_query("SELECT foo, bar FROM mytable ORDER BY name");

Body:
Answering my own question... The better regex is:

/mysql_query\("(.?)"\)/s


问:
Multidex issue for androidTest with gradle plugin 3.0.0
Once I updated my app to gradle plugin 3.0.0 I started having issue with multidex, but only when I run androidTest.

My app was already multidex and with gradle plugin 2.3.3 both assembleDebug and assembleDebugAndroidTest were working fine. Then I just updated gradle plugin to 3.0.0 and I started receiving the following exception:

com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536

I tried different options like defining custom multidex runner for tests, adding androidTestCompile 'com.android.support:multidex-instrumentation:1.0.2' dependency, but nothing helped. I also didn't find in release notes of gradle plugin 3.0.0, if something changed there for android tests.

Does anybody have similar issue for androidTest?

答:
I believe it is a known issue: https://issuetracker.google.com/issues/37324038

The issue is that legacy multidex (min API < 21) is not supported in Android Gradle plugin 3.0.0 for androidTest APK's specifically.  I was able to get it working by making a product flavor with min API >= 21 like so:

```<code>productFlavors {
    local {
        minSdkVersion 21
    }
    ci {
        minSdkVersion 17
    }
}
</code>```

And then running androidTests using the connectedLocalDebugAndroidTest task

Body:
I believe it is a known issue: https://issuetracker.google.com/issues/37324038

The issue is that legacy multidex (min API < 21) is not supported in Android Gradle plugin 3.0.0 for androidTest APK's specifically.  I was able to get it working by making a product flavor with min API >= 21 like so:

productFlavors {
    local {
        minSdkVersion 21
    }
    ci {
        minSdkVersion 17
    }
}

And then running androidTests using the connectedLocalDebugAndroidTest task


问:
Need help on kivy mapview, works on windows, but just do not work on android, app just doesn't start
Below kivymapview works on windows, but doesnt work on Android. Please help </p>

```<code>import sys
from kivy.base import runTouchApp
from kivy.lang import Builder

if __name__ == '__main__' and __package__ is None:
    from os import sys, path
    sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))

import mapview

root = Builder.load_string("""
#:import sys sys
#:import MapSource mapview.MapSource
MapView:
    lat: 50.6394
    lon: 3.057
    zoom: 13
    map_source: MapSource(sys.argv[1], attribution="") if len(sys.argv) > 1 else "osm"
    MapMarkerPopup:
        lat: 50.6394
        lon: 3.057
        popup_size: dp(230), dp(130)
        Bubble:
            BoxLayout:
                orientation: "horizontal"
                padding: "5dp"
                AsyncImage:
                    source: "http://upload.wikimedia.org/wikipedia/commons/9/9d/France-Lille-VieilleBourse-FacadeGrandPlace.jpg"
                    mipmap: True
                Label:
                    text: "[b]Lille[/b]\\n1 154 861 hab\\n5 759 hab./km2"
                    markup: True
                    halign: "center"
""")

runTouchApp(root)
</code>```

答: Finally, i had this fixed, looks like i had to start fresh to build it and had to amend requirements..These examples at https://github.com/kivy-garden/garden.mapview/tree/master/examples are really good to have the mapview work on Android. Also follow this link carefully https://github.com/kivy-garden/garden.mapview for better ideas :)</p>

Body:
Below kivymapview works on windows, but doesnt work on Android. Please help

import sys
from kivy.base import runTouchApp
from kivy.lang import Builder

if __name__ == '__main__' and __package__ is None:
    from os import sys, path
    sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))

import mapview

root = Builder.load_string("""
#:import sys sys
#:import MapSource mapview.MapSource
MapView:
    lat: 50.6394
    lon: 3.057
    zoom: 13
    map_source: MapSource(sys.argv[1], attribution="") if len(sys.argv) > 1 else "osm"
    MapMarkerPopup:
        lat: 50.6394
        lon: 3.057
        popup_size: dp(230), dp(130)
        Bubble:
            BoxLayout:
                orientation: "horizontal"
                padding: "5dp"
                AsyncImage:
                    source: "http://upload.wikimedia.org/wikipedia/commons/9/9d/France-Lille-VieilleBourse-FacadeGrandPlace.jpg"
                    mipmap: True
                Label:
                    text: "[b]Lille[/b]\\n1 154 861 hab\\n5 759 hab./km2"
                    markup: True
                    halign: "center"
""")

runTouchApp(root)