问:
Sort an Arraylist using Comparator
To print an output as {first max,first min,second max,second min,third max,third min and so on.....}

```<code>   import java.util.ArrayList;
   import java.util.Collection;
   import java.util.Collections;
   import java.util.Comparator;
   import java.util.Iterator;
   import java.util.List;

  import compl.compl;

  public class Arraylist1 {

public static void main(String args[]){

    List <Integer>list= new ArrayList <Integer> ( );

 list.add(20);
 list.add(30);
 list.add(70);
 list.add(50);
 list.add(60);
 list.add(40);

  Comparator<Integer> cmp=new Comparator<Integer>() {

    @Override
    public int compare(Integer o1, Integer o2) {
        // TODO Auto-generated method stub
        int pos=0;
        if(pos%2==0){
            if(o1<o2){
                return 1;
            }
            }
           if(pos%2!=0){
            if(o1>o2){
                return -1;
            }
            }
            pos++;
        }
    }
};

Collections.sort(list, cmp);
for(int i=0;i<list.size();i++){
    System.out.println(list);
}

 }
}
</code>```

Getting an error as:

```<code>Exception in thread "main" java.lang.Error: Unresolved compilation problem:
    This method must return a result of type int

    at Arraylist1$1.compare(Arraylist1.java:51)
    at Arraylist1$1.compare(Arraylist1.java:1)
    at java.util.TimSort.countRunAndMakeAscending(TimSort.java:324)
    at java.util.TimSort.sort(TimSort.java:189)
    at java.util.TimSort.sort(TimSort.java:173)
    at java.util.Arrays.sort(Arrays.java:659)
    at java.util.Collections.sort(Collections.java:217)
    at Arraylist1.main(Arraylist1.java:67)
</code>```

Not getting exactly why am i getting this error, i guess this cause compartor need return type,but in my case here return type cannot be specified.

答:
Your code cannot be complied. For that you have return value in all cases n comparator.

```<code> if (pos % 2 == 0) {
      if (o1 < o2) {
           return 1;
      } else if (o1 > o2) {
           return -1;
      }
      pos++;
      TODO: defie return value here
} else { TODO: define return value here }
</code>```

important note: your variable pos will be always 0. As it is method variable and it is created every time you invoke method. If you need just to order live, you can define comparator as (in descending order)

```<code>return o2.compareTo(o1);
</code>```

in asceding order

```<code>return o1.compareTo(o2);
</code>```

Title: Sort an Arraylist using Comparator

Body:
To print an output as {first max,first min,second max,second min,third max,third min and so on.....}

   import java.util.ArrayList;
   import java.util.Collection;
   import java.util.Collections;
   import java.util.Comparator;
   import java.util.Iterator;
   import java.util.List;

  import compl.compl;

  public class Arraylist1 {

public static void main(String args[]){

    List <Integer>list= new ArrayList <Integer> ( );

 list.add(20);
 list.add(30);
 list.add(70);
 list.add(50);
 list.add(60);
 list.add(40);

  Comparator<Integer> cmp=new Comparator<Integer>() {

    @Override
    public int compare(Integer o1, Integer o2) {
        // TODO Auto-generated method stub
        int pos=0;
        if(pos%2==0){
            if(o1<o2){
                return 1;
            }
            }
           if(pos%2!=0){
            if(o1>o2){
                return -1;
            }
            }
            pos++;
        }
    }
};

Collections.sort(list, cmp);
for(int i=0;i<list.size();i++){
    System.out.println(list);
}

 }
}

Getting an error as:

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
    This method must return a result of type int

    at Arraylist1$1.compare(Arraylist1.java:51)
    at Arraylist1$1.compare(Arraylist1.java:1)
    at java.util.TimSort.countRunAndMakeAscending(TimSort.java:324)
    at java.util.TimSort.sort(TimSort.java:189)
    at java.util.TimSort.sort(TimSort.java:173)
    at java.util.Arrays.sort(Arrays.java:659)
    at java.util.Collections.sort(Collections.java:217)
    at Arraylist1.main(Arraylist1.java:67)

Not getting exactly why am i getting this error, i guess this cause compartor need return type,but in my case here return type cannot be specified.

Body:
Your code cannot be complied. For that you have return value in all cases n comparator.

 if (pos % 2 == 0) {
      if (o1 < o2) {
           return 1;
      } else if (o1 > o2) {
           return -1;
      }
      pos++;
      TODO: defie return value here
} else { TODO: define return value here }

important note: your variable pos will be always 0. As it is method variable and it is created every time you invoke method. If you need just to order live, you can define comparator as (in descending order)

return o2.compareTo(o1);

in asceding order

return o1.compareTo(o2);


来源: stackexchange

问:
Regex, optionally capture 3 groups at the end of a string
I have a string which looks like the following:

```<code>VAL "foo"
VAL2 "bar"
VAL3 "barbar"
OPTIONALVAL "optionalvalue"
SPECIALVAL "optionalval"
</code>```

Where OPTIONALVAL is optional (may or may not appear) and if it appears then it has a value pair in the second column ("optionalvalue" in the example), and SPECIALVAL is also optional, but it has no paired value in the second column.

Here is my regex, but it doesn't match anything if OPTIONALVAL is missing (should match all the others which are not missing)!

```<code> "^[[:space:]]*"
 "(VAL)[[:space:]]*\"(.*)\"[[:space:]]*"
 "(VAL2)[[:space:]]*\"(.*)\"[[:space:]]*"
 "(VAL3)[[:space:]]*\"(.*)\"[[:space:]]*"
 "(OPTIONALVAL)?[[:space:]]*\"(?(7)(.*))\"[[:space:]]*"; // conditional capture
 "(SPECIALVAL)?[[:space:]]*";
</code>```

What am I doing wrong? (I am using Boost regex, :space: should be equivalent to the space character.

答:
For your conditional capture, you can do something like (?:xyz)? where xyz is the conditional pattern.

```<code>VAL\s*"(.*?)"\s*
VAL2\s*"(.*?)"\s*
VAL3\s*"(.*?)"\s*
(?:OPTIONALVAL\s*"(.*?)"\s*)?
SPECIALVAL
</code>```

Live preview

Note that the live preview has the extended flag enabled, to ignore those newlines.

As your question reflects that you want to capture VAL, etc. Then you of course need to surround them with parenthesis.

The thing to notice, is that whether conditional capture is present or not. All the capture groups will still remain the same index-wise.

ContentLicense: CC BY-SA 3.0

Body:
I have a string which looks like the following:

VAL "foo"
VAL2 "bar"
VAL3 "barbar"
OPTIONALVAL "optionalvalue"
SPECIALVAL "optionalval"

Where OPTIONALVAL is optional (may or may not appear) and if it appears then it has a value pair in the second column ("optionalvalue" in the example), and SPECIALVAL is also optional, but it has no paired value in the second column.

Here is my regex, but it doesn't match anything if OPTIONALVAL is missing (should match all the others which are not missing)!

 "^[[:space:]]*"
 "(VAL)[[:space:]]*\"(.*)\"[[:space:]]*"
 "(VAL2)[[:space:]]*\"(.*)\"[[:space:]]*"
 "(VAL3)[[:space:]]*\"(.*)\"[[:space:]]*"
 "(OPTIONALVAL)?[[:space:]]*\"(?(7)(.*))\"[[:space:]]*"; // conditional capture
 "(SPECIALVAL)?[[:space:]]*";

What am I doing wrong? (I am using Boost regex, :space: should be equivalent to the space character.

Body:
For your conditional capture, you can do something like (?:xyz)? where xyz is the conditional pattern.

VAL\s*"(.*?)"\s*
VAL2\s*"(.*?)"\s*
VAL3\s*"(.*?)"\s*
(?:OPTIONALVAL\s*"(.*?)"\s*)?
SPECIALVAL

Live preview

Note that the live preview has the extended flag enabled, to ignore those newlines.

As your question reflects that you want to capture VAL, etc. Then you of course need to surround them with parenthesis.

The thing to notice, is that whether conditional capture is present or not. All the capture groups will still remain the same index-wise.


问:
Angular2 App: Fetch as Google doesn't load page content
I am working on Angular2 based web app. I used Angular CLI to generate app and then to build it for prod. I have hosted website on AWS S3 & Cloudfront. When I use 'Fetch as Google' tool from the webmaster, it shows only Loading....

Isn't Googlebot able to crawl my website?

答:
Since your frontend isn't being served by any server side language, I'd recommend using Angular2-Universal to serve a static HTML site on initial load.

You can checkout their quickstart guide and get it working pretty fast.


问:
Why isnt my css transition working?
I've looked over this simple code about hundred times, the transform property is working just fine, but its just snapping in place as if the transition property isnt working, what minor detail do I keep glossing over?
Here a jsfiddle with the transform property commented out.
https://jsfiddle.net/t8kbtjdy/30/</p>

```<code>#testItem{
  width: 100px;
  height: 100px;
  background-color: red;
  transform: rotate(45deg);
  transition: transform 1000ms ease-in-out 0ms;
}
</code>```

答:
I think you should go with s instead of  ms.

```<code>Transition: all 1s ;
</code>```

You can trim it to your need of course.

Title: Why isnt my css transition working?

Body:
I've looked over this simple code about hundred times, the transform property is working just fine, but its just snapping in place as if the transition property isnt working, what minor detail do I keep glossing over?
Here a jsfiddle with the transform property commented out.
https://jsfiddle.net/t8kbtjdy/30/

#testItem{
  width: 100px;
  height: 100px;
  background-color: red;
  transform: rotate(45deg);
  transition: transform 1000ms ease-in-out 0ms;
}

Body:
I think you should go with s instead of  ms.

Transition: all 1s ;

You can trim it to your need of course.


问:
Ruby on Rails: getting Prometheus metrics with Telegraf
I have a RoR application with installed Prometheus-client and Telegraf daemon with Prometheus input plugin working on the instance I want to monitor.

As far as I understand I need some kind of exporter middleware to collect metrics from Prometheus::Client.registry and expose them with /metrics HTTP endpoint.

What I don't really understand is how to pass all metrics from different envs (e.g from rake task and app's runtime code) into the same registry (it's an instance variable of Prometheus::Middleware::Exporter.new(registry))  of the same instance of Prometheus::Middleware::Exporter middleware?

Also, will urls = ["http://localhost:3000/metrics"] config of Prometheus input plugin for Telegraf work on EC2 instance for example?

Thank you for advices.

答:
Perhaps an easier way to go would be to setup a Telegraf client on the same host (with Prometheus output and statsd input) and then fire events from your application into Telegraf's input, in statsd format. Telegraf would then turn around and emit these metrics in Prometheus's format. </p>

<p>in this way you'll get both Telegraf's host-level metrics (free memory, disc usage, etc) AND your application's metrics, all exported in the same port. It doesn't require any Ruby-specific code, just the ability to fire UDP messages from your app into a local port. </p>

Body:
Perhaps an easier way to go would be to setup a Telegraf client on the same host (with Prometheus output and statsd input) and then fire events from your application into Telegraf's input, in statsd format. Telegraf would then turn around and emit these metrics in Prometheus's format.

in this way you'll get both Telegraf's host-level metrics (free memory, disc usage, etc) AND your application's metrics, all exported in the same port. It doesn't require any Ruby-specific code, just the ability to fire UDP messages from your app into a local port.


问:
Python store action/method in block/array
I am beginner in python and I am trying to write something like this in objective-c. In Objective-C, each method can be stored in block and those can be called again later. I have tried to find online but I don't know keyword in python. Can I write like that in python or is there any similar flow ? How shall I do? </p>

```<code>void (^successBlock)() = ^{
    NSLog(@"Test");
};

NSMutableArray *muArr = [NSMutableArray array];
[muArr addObject:successBlock];

for (void (^successBlock)() in muArr) {
    successBlock();
}
</code>```

答:
Try this code and it should work</p>

```<code>void (^successblock)() = ^^{
    NSLog(@"Test");
};

NSMutableArray *mUArr = [NsMutableArray array];
[muArr addObject:successBlock];

for (void (^successBlock)() in muArr) {
    successBlock()
}
</code>```

Body:
I am beginner in python and I am trying to write something like this in objective-c. In Objective-C, each method can be stored in block and those can be called again later. I have tried to find online but I don't know keyword in python. Can I write like that in python or is there any similar flow ? How shall I do?

void (^successBlock)() = ^{
    NSLog(@"Test");
};

NSMutableArray *muArr = [NSMutableArray array];
[muArr addObject:successBlock];

for (void (^successBlock)() in muArr) {
    successBlock();
}

Body:
Try this code and it should work

void (^successblock)() = ^^{
    NSLog(@"Test");
};

NSMutableArray *mUArr = [NsMutableArray array];
[muArr addObject:successBlock];

for (void (^successBlock)() in muArr) {
    successBlock()
}


问:
Call to undefined method stdClass::checkSubcategory()
I was trying to make a dynamic Menu where in menu section i want to show a category and if the category has any subcategory I wanted to show it under it..

I have read the following method on my category model

```<code>public static function checkSubcategory($id){
        $category = Category::find($id);
        $id = $category->id;
        $subcategories = \DB::table ('subcategories')
                    ->join('categories_subcategories','subcategories.id','=','categories_subcategories.subcategory_id')
                    ->join('categories','categories_subcategories.category_id','=','categories.id')
                    ->where('categories.id','=',$id)
                    ->select('subcategories.name')
                    ->get();
         return $subcategories;
    }
</code>```

And here is the View

```<code>@foreach($categories as $row)
                @if($row->checkSubcategory($row->id))
                <li class="dropdown">
                    <a href="#" class="dropdown-toggle">
                        {{$row->name}}
                    </a>
                <ul class="dropdown-menu">
                    <li>
                    @foreach($row->checkSubcategory($row->id) as $sub)
                    <a href="{{asset('subcategories/product/'.$sub->name)}}">{{$sub->name}}</a>
                    @endforeach
                    </li>
                </ul>
                </li>
                    @else
                <li class="pull-right"><a href="#">{{$row->name}}</a></li>
                    @endif
                @endforeach
</code>```

But the problem is when ever i tried to load the view i see the following Error

```<code>ErrorException in efd7d9fe55aa0c18c60d0a857a8a44ed1725a390.php line 213:
Call to undefined method stdClass::checkSubcategory()
</code>```

What could be reason for the error..any suggestion please.

答:
The object you are using of type stdClass and therefore cannot get access to the function you define in your controller model. A likely cause is that you are getting your categories using DB. It gives you an array with objects of type stdClass. What you need is objects of type Category. Therefore you should get your categories using the Category model

```<code>//change
$categories = DB::table('categories')->get();
//to
$categories = Category::get();
</code>```

Also, you defined it as a static function

```<code>public static function checkSubcategory($id)
</code>```

Means you cannot call it with an object

```<code>$row->checkSubcategory($row->id)
</code>```

Remove static keyword from the function definition.

Furthermore, you could refactor your function. Instead of passing it the id, just get the id with $this->id.

```<code>public function checkSubcategory(){
    return \DB::table ('subcategories')
                ->join('categories_subcategories','subcategories.id','=','categories_subcategories.subcategory_id')
                ->join('categories','categories_subcategories.category_id','=','categories.id')
                ->where('categories.id','=', $this->id)
                ->select('subcategories.name')
                ->get();
}
</code>```

You could even dive deeper and make your code nicer with relationships.

```<code>public function subcategories() {
    return $this->belongsToMany(SubCategory::class, 'categories_subcategories', 'category_id', 'subcategory_id');
    //Why do you have a many to many relationships between categories and subcategories ?
}
</code>```

Your checkSubcategory would then becomes

```<code>public function checkSucategory() {
    return $this->subcategories()->count();
}
</code>```

Body:
I was trying to make a dynamic Menu where in menu section i want to show a category and if the category has any subcategory I wanted to show it under it..

I have read the following method on my category model

public static function checkSubcategory($id){
        $category = Category::find($id);
        $id = $category->id;
        $subcategories = \DB::table ('subcategories')
                    ->join('categories_subcategories','subcategories.id','=','categories_subcategories.subcategory_id')
                    ->join('categories','categories_subcategories.category_id','=','categories.id')
                    ->where('categories.id','=',$id)
                    ->select('subcategories.name')
                    ->get();
         return $subcategories;
    }

And here is the View

@foreach($categories as $row)
                @if($row->checkSubcategory($row->id))

                        {{$row->name}}

                    @foreach($row->checkSubcategory($row->id) as $sub)
                    name)}}">{{$sub->name}}
                    @endforeach

                    @else

{{$row->name}}

                    @endif
                @endforeach

But the problem is when ever i tried to load the view i see the following Error

ErrorException in efd7d9fe55aa0c18c60d0a857a8a44ed1725a390.php line 213:
Call to undefined method stdClass::checkSubcategory()

What could be reason for the error..any suggestion please.

Body:
The object you are using of type stdClass and therefore cannot get access to the function you define in your controller model. A likely cause is that you are getting your categories using DB. It gives you an array with objects of type stdClass. What you need is objects of type Category. Therefore you should get your categories using the Category model

//change
$categories = DB::table('categories')->get();
//to
$categories = Category::get();

Also, you defined it as a static function

public static function checkSubcategory($id)

Means you cannot call it with an object

$row->checkSubcategory($row->id)

Remove static keyword from the function definition.

Furthermore, you could refactor your function. Instead of passing it the id, just get the id with $this->id.

public function checkSubcategory(){
    return \DB::table ('subcategories')
                ->join('categories_subcategories','subcategories.id','=','categories_subcategories.subcategory_id')
                ->join('categories','categories_subcategories.category_id','=','categories.id')
                ->where('categories.id','=', $this->id)
                ->select('subcategories.name')
                ->get();
}

You could even dive deeper and make your code nicer with relationships.

public function subcategories() {
    return $this->belongsToMany(SubCategory::class, 'categories_subcategories', 'category_id', 'subcategory_id');
    //Why do you have a many to many relationships between categories and subcategories ?
}

Your checkSubcategory would then becomes

public function checkSucategory() {
    return $this->subcategories()->count();
}


问:
Taking on value of a tuple in an array?
so I am creating a non-visible grid for a text based game. I have created an array of coordinates in a 10 by 10 grid. How do I access a single x and y value in the array?

----------Swift 3 Code!!

```<code>var gameArea: [(Int, Int)] = []

for x in 1...10 {
    for y in 1...10 {
        gameArea.append(x, y)
    }
}

var position = gameArea[5]

position.y
</code>```

答:
Your append call needs to a single arguement which is a tuple, not two arguments which are elements of the tuple, like so:

```<code>gameArea.append((x, y))
</code>```

The generation of your gameArea can be done in a single line of code:

```<code>let gameArea = (1...10).map{ x in (1...10).map{ y in (x: x, y: y) }}
</code>```

The tuple members can be accessed by index .0, .1, ..., or by name (if they have names:

```<code>gameArea[0].x //equivalent to gameArea[0].0
</code>```

Title: Taking on value of a tuple in an array?

Body:
so I am creating a non-visible grid for a text based game. I have created an array of coordinates in a 10 by 10 grid. How do I access a single x and y value in the array?

----------Swift 3 Code!!

var gameArea: [(Int, Int)] = []

for x in 1...10 {
    for y in 1...10 {
        gameArea.append(x, y)
    }
}

var position = gameArea[5]

position.y

Body:
Your append call needs to a single arguement which is a tuple, not two arguments which are elements of the tuple, like so:

gameArea.append((x, y))

The generation of your gameArea can be done in a single line of code:

let gameArea = (1...10).map{ x in (1...10).map{ y in (x: x, y: y) }}

The tuple members can be accessed by index .0, .1, ..., or by name (if they have names:

gameArea[0].x //equivalent to gameArea[0].0


问:
Scaling around center without viewBox?
I know much has been debated about this but i would like to know if there is a way to scale an element around its center without using viewBox (which, as far as i have learnt, must be applied to the svg, and not to a single object). In this exercise i am working on to understand the logic of svg scaling i would like the (invisible) red circle to appear and then to scale (as if it popped up) when you click on the yellow rect. Can anybody help me? Thanks in advance

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
   xmlns:dc="http://purl.org/dc/elements/1.1/"
   xmlns:cc="http://creativecommons.org/ns#"
   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
   xmlns:svg="http://www.w3.org/2000/svg"
   xmlns="http://www.w3.org/2000/svg"
   xmlns:xlink="http://www.w3.org/1999/xlink"
   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
   version="1.1"
   id="star"
   x="170px"
   y="385px"
   width="100px"
   height="100px"
   xml:space="preserve"
   inkscape:version="0.48.5 r10040"
   sodipodi:docname="Exercise n.1.svg"><metadata
   id="metadata17"><rdf:RDF><cc:Work
       rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
         rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title /></cc:Work></rdf:RDF></metadata><defs
   id="defs15" /><sodipodi:namedview
   pagecolor="#ffffff"
   bordercolor="#666666"
   borderopacity="1"
   objecttolerance="10"
   gridtolerance="10"
   guidetolerance="10"
   inkscape:pageopacity="0"
   inkscape:pageshadow="2"
   inkscape:window-width="1366"
   inkscape:window-height="705"
   id="namedview13"
   showgrid="false"
   inkscape:zoom="2.36"
   inkscape:cx="-22.881356"
   inkscape:cy="50"
   inkscape:window-x="-8"
   inkscape:window-y="-8"
   inkscape:window-maximized="1"
   inkscape:current-layer="star" />

<rect
   style="fill:#ffcc00;fill-opacity:1;stroke:none"
   id="yelrect"
   width="33.050846"
   height="30.084745"
   x="14.457626"
   y="25.847458"
   ry="1.6126924" />
<path
   sodipodi:type="arc"
   style="fill:#ff0000;fill-opacity:1;stroke:none;opacity:0"
   id="redcircle"
   sodipodi:cx="70.338982"
   sodipodi:cy="15.466102"
   sodipodi:rx="9.3220339"
   sodipodi:ry="8.2627115"
   d="m 79.661016,15.466102 a 9.3220339,8.2627115 0 1 1 -18.644068,0 9.3220339,8.2627115 0 1 1 18.644068,0 z"
   transform="matrix(0.96545455,0,0,1.0892308,1.1926041,24.577574)" />
 <animateTransform
     id="redcircle_anim1"
     xlink:href="#redcircle"
     attributeName="transform"
    type="scale"
     begin="yelrect.click"
     by="1"
     dur="1s"
     fill="freeze" />
 <animate
     id="redcircle_anim2"
     xlink:href="#redcircle"
     attributeName="opacity"
     begin="redcircle_anim1.begin"
     from="0"
    to="1"
     dur="1s"
     fill="freeze" />
</svg>```

答:
When you scale an element, you scale not only its size, but also its position. As you have seen.

There are various ways to implement the solution, but the general principle behind them all is that the circle has to be scaled around it's own origin, and not that of the SVG (which is the top-left).

One way, is to effectively put the circle in it's own coordinate space, by shifting the responsibility of positioning of it to a parent group.

```<code><g transform="translate(31,20)">
  <circle cx="0" cy="0" ... />
</g>
</code>```

So now, as far as the circle is concerned, it is at the origin (0,0).  When you scale it with the animation, it scales around the origin - and thus doesn't move.  However its final position is still determined by the translation transform of its parent group.

<svg id="star" width="100px" height="100px">

<rect
   style="fill:#ffcc00;fill-opacity:1;stroke:none"
   id="yelrect"
   width="33.050846"
   height="30.084745"
   x="14.457626"
   y="25.847458"
   ry="1.6126924" />
<g transform="translate(31,20)">
  <ellipse cx="0" cy="0" rx="9.3220339" ry="8.2627115"
           style="fill:#ff0000;fill-opacity:1;stroke:none;opacity:0"
           id="redcircle" />
</g>

<animateTransform
     id="redcircle_anim1"
     xlink:href="#redcircle"
     attributeName="transform"
    type="scale"
     begin="yelrect.click"
     by="1"
     dur="1s"
     fill="freeze" />
<animate
     id="redcircle_anim2"
     xlink:href="#redcircle"
     attributeName="opacity"
     begin="redcircle_anim1.begin"
     from="0"
    to="1"
     dur="1s"
     fill="freeze" />
</svg>```

Title: Scaling around center without viewBox?

Body:
When you scale an element, you scale not only its size, but also its position. As you have seen.

There are various ways to implement the solution, but the general principle behind them all is that the circle has to be scaled around it's own origin, and not that of the SVG (which is the top-left).

One way, is to effectively put the circle in it's own coordinate space, by shifting the responsibility of positioning of it to a parent group.

<g transform="translate(31,20)">
  <circle cx="0" cy="0" ... />
</g>

So now, as far as the circle is concerned, it is at the origin (0,0).  When you scale it with the animation, it scales around the origin - and thus doesn't move.  However its final position is still determined by the translation transform of its parent group.

<svg id="star" width="100px" height="100px">

<rect
   style="fill:#ffcc00;fill-opacity:1;stroke:none"
   id="yelrect"
   width="33.050846"
   height="30.084745"
   x="14.457626"
   y="25.847458"
   ry="1.6126924" />
<g transform="translate(31,20)">
  <ellipse cx="0" cy="0" rx="9.3220339" ry="8.2627115"
           style="fill:#ff0000;fill-opacity:1;stroke:none;opacity:0"
           id="redcircle" />
</g>

<animateTransform
     id="redcircle_anim1"
     xlink:href="#redcircle"
     attributeName="transform"
    type="scale"
     begin="yelrect.click"
     by="1"
     dur="1s"
     fill="freeze" />
<animate
     id="redcircle_anim2"
     xlink:href="#redcircle"
     attributeName="opacity"
     begin="redcircle_anim1.begin"
     from="0"
    to="1"
     dur="1s"
     fill="freeze" />
</svg>


问:
Preserving login session across multiple Android apps
I have two apps that both log in to the same system but they have separate functions and may not both be installed at the same time. I can sign the two apps with the same signature no problem, even make them run in the same process.

How can I store the login cookie (among other things) in such a way that it is shared by both apps and still be secured from unknown apps?

答:
Here's a good solution:

What's the best way to do "application settings" in Android?

Since you want to share this between two applications, regardless of the way you want to implement it, don't forget that this will be visible to all applications. You may want to encrypt your password or session ID. Here's an example:

http://android.voxisland.com/code_examples/How_to_encrypt_and_decrypt_strings.rhtml

Good luck!

ContentLicense: CC BY-SA 2.5


问:
Can you explain the thread profile graph?
I'm new to the java profiling

I have a thread which reads from a file are do some regex operation on each line. The above picture is the graph that I got from the JVisualVM profiler for my thread.

Green is running.

Purple is sleeping.

Orange is parked

It seems the thread sleep more than running. I know due to File read this is somewhat acceptable. But this seems way more than that.

Can you please explain, does it have anything to do which regex operation or do I need to look for more optimization?

答: The profiling result is not unexpected for this kind of work.  The thread is sleeping most of the time because of the file access.  To get substantial speed improvements, you will probably have to address file access in some way.</p>


问:
Entity Framework 6 exception: "The context cannot be used while the model is being created"
I'm a bit new when it is coming to Entity Framework 6 from the old style of ADO.NET, so bear with me here.

I'm trying to create a new WPF MVVM project and also a few WinForms that will use just straight out DBContext without data-binding with the EF 6.

Using Visual Studio 2013 Entity framework wizard, I created a code-first by reverse engineer a current database on our business server. I then separated the data model classes from the context

This is the DbContext code:

```<code>namespace EFModels
{
    public partial class MyDataContext : DbContext
    {
        public MyDataContext () : base("name=MyDataContext")
        {
        }

        public virtual DbSet<Calibration> Calibrations { get; set; }
        public virtual DbSet<OrderDetail> OrderDetails { get; set; }
        public virtual DbSet<OrderHistory> OrderHistories { get; set; }
        public virtual DbSet<WorkDetail> WorkDetails { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<WorkDetail>()
                    .HasMany(e => e.Calibrations)
                    .WithOptional(e => e.WorkDetail)
                    .HasForeignKey(e => e.WorkID);
        }
    }
}
</code>```

I've separated the data classes in a separate namespace, for example:

```<code>namespace MyDataDomain
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;

    public partial class OrderDetail
    {
        public OrderDetail()
        {
            Calibrations = new HashSet<Calibration>();
            JournalEntryDatas = new HashSet<JournalEntryData>();
            OrderHistories = new HashSet<OrderHistory>();
            WorkDetails = new HashSet<WorkDetail>();
        }

        [Key]
        public long OrderID { get; set; }

        [StringLength(50)]
        public string PONumber { get; set; }

        [Column(TypeName = "date")]
        public DateTime? Due { get; set; }

        [Column(TypeName = "date")]
        public DateTime? OrderDate { get; set; }

        [Column(TypeName = "date")]
        public DateTime? ShipDate { get; set; }

        [Column(TypeName = "text")]
        public string Comment { get; set; }

        public int? EnterByID { get; set; }

        public virtual ICollection<Calibration> Calibrations { get; set; }

        public virtual ICollection<JournalEntryData> JournalEntryDatas { get; set; }
        public virtual ICollection<OrderHistory> OrderHistories { get; set; }
        public virtual ICollection<WorkDetail> WorkDetails { get; set;      }
    }
}
</code>```

The rest of the classes are in similiar style, but when using the foreign key constraint it has something like this:

```<code>public virtual OrderDetail OrderDetail { get; set; }
</code>```

since in our little world, it will revolve around the Orders.

And the app.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>

  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
  </startup>
  <connectionStrings>
    <add name="MyDataContext" connectionString="data source=BIZSERVER\SQL2008R2DB;initial catalog=Company;persist security info=True;user id=DaBossMan;password=none_of_your_damn_business;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>
```

<p>So when I do this:</p>

```var context = New MyDataContext();
var list1 = context.JournalEntryDatas.ToList();
var list2 = context.OrderHistories.ToList();
```

<p>An exception is thrown:</p>

<blockquote>
  <p>The context cannot be used while the model is being created. This
  exception may be thrown if the context is used inside the
  <code>OnModelCreating</code> method or if the same context instance is accessed by
  multiple threads concurrently. Note that instance members of <code>DbContext</code>
  and related classes are not guaranteed to be thread safe.</p>
</blockquote>

<p>I'm going nuts here trying to figure out what I can do, and I've been reading that maybe doing a task factory could help, so then how can I use it to get the data from each table so I can populate the lists?</p>

<p>OR is there another alternative or a workaround that I can use?</p>

<p>EDIT: Here is the FULL stacktrace as requested (by Andez):</p>

```System.InvalidOperationException was caught
HResult=-2146233079
Message=The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe.
Source=EntityFramework
StackTrace:
   at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
   at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
   at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
   at System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator()
   at System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at MichellControls.JournalDataListView.JournalDataListView_Load(Object sender, EventArgs e) in c:\Users\Steve\Projects\Visual Studio 2013\Projects\MyControls\WinFormControls\JournalDataListView.cs:line 35
InnerException:
    // (there wasn't any InnerException)
```

答:
It might be the connection string or some other connection-related issue, the database not existing or authentication for example.

You might need to update the database as well.

From the nuget package manager console:

```<code>Update-Database
</code>```

"Context cannot be used while the model is being created" exception with ASP.NET Identity

Entity Framework - The context cannot be used while the model is being created

The context cannot be used while the model is being created

Body:
I'm a bit new when it is coming to Entity Framework 6 from the old style of ADO.NET, so bear with me here.

I'm trying to create a new WPF MVVM project and also a few WinForms that will use just straight out DBContext without data-binding with the EF 6.

Using Visual Studio 2013 Entity framework wizard, I created a code-first by reverse engineer a current database on our business server. I then separated the data model classes from the context

This is the DbContext code:

namespace EFModels
{
    public partial class MyDataContext : DbContext
    {
        public MyDataContext () : base("name=MyDataContext")
        {
        }

        public virtual DbSet<Calibration> Calibrations { get; set; }
        public virtual DbSet<OrderDetail> OrderDetails { get; set; }
        public virtual DbSet<OrderHistory> OrderHistories { get; set; }
        public virtual DbSet<WorkDetail> WorkDetails { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<WorkDetail>()
                    .HasMany(e => e.Calibrations)
                    .WithOptional(e => e.WorkDetail)
                    .HasForeignKey(e => e.WorkID);
        }
    }
}

I've separated the data classes in a separate namespace, for example:

namespace MyDataDomain
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;

    public partial class OrderDetail
    {
        public OrderDetail()
        {
            Calibrations = new HashSet<Calibration>();
            JournalEntryDatas = new HashSet<JournalEntryData>();
            OrderHistories = new HashSet<OrderHistory>();
            WorkDetails = new HashSet<WorkDetail>();
        }

        [Key]
        public long OrderID { get; set; }

        [StringLength(50)]
        public string PONumber { get; set; }

        [Column(TypeName = "date")]
        public DateTime? Due { get; set; }

        [Column(TypeName = "date")]
        public DateTime? OrderDate { get; set; }

        [Column(TypeName = "date")]
        public DateTime? ShipDate { get; set; }

        [Column(TypeName = "text")]
        public string Comment { get; set; }

        public int? EnterByID { get; set; }

        public virtual ICollection<Calibration> Calibrations { get; set; }

        public virtual ICollection<JournalEntryData> JournalEntryDatas { get; set; }
        public virtual ICollection<OrderHistory> OrderHistories { get; set; }
        public virtual ICollection<WorkDetail> WorkDetails { get; set;      }
    }
}

The rest of the classes are in similiar style, but when using the foreign key constraint it has something like this:

public virtual OrderDetail OrderDetail { get; set; }

since in our little world, it will revolve around the Orders.

And the app.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>

  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
  </startup>
  <connectionStrings>
    <add name="MyDataContext" connectionString="data source=BIZSERVER\SQL2008R2DB;initial catalog=Company;persist security info=True;user id=DaBossMan;password=none_of_your_damn_business;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

So when I do this:

var context = New MyDataContext();
var list1 = context.JournalEntryDatas.ToList();
var list2 = context.OrderHistories.ToList();

An exception is thrown:

The context cannot be used while the model is being created. This
  exception may be thrown if the context is used inside the
  OnModelCreating method or if the same context instance is accessed by
  multiple threads concurrently. Note that instance members of DbContext
  and related classes are not guaranteed to be thread safe.

I'm going nuts here trying to figure out what I can do, and I've been reading that maybe doing a task factory could help, so then how can I use it to get the data from each table so I can populate the lists?

OR is there another alternative or a workaround that I can use?

EDIT: Here is the FULL stacktrace as requested (by Andez):

System.InvalidOperationException was caught
HResult=-2146233079
Message=The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe.
Source=EntityFramework
StackTrace:
   at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
   at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
   at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
   at System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator()
   at System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at MichellControls.JournalDataListView.JournalDataListView_Load(Object sender, EventArgs e) in c:\Users\Steve\Projects\Visual Studio 2013\Projects\MyControls\WinFormControls\JournalDataListView.cs:line 35
InnerException:
    // (there wasn't any InnerException)

Body:
It might be the connection string or some other connection-related issue, the database not existing or authentication for example.

You might need to update the database as well.

From the nuget package manager console:

Update-Database

"Context cannot be used while the model is being created" exception with ASP.NET Identity

Entity Framework - The context cannot be used while the model is being created

The context cannot be used while the model is being created


答:
Your bug is not related to comparator/collections or not even to Java.
In programming a function must return its return value for any input.

Your compare function doen't return anything for the case where pos%2 != 0.

Title: Sort an Arraylist using Comparator


问:
Formating numbers with leading zeros in Blade view
I have the following code in a Blade view:

```<code>@for ($i = 1; $i <= 99; $i++)
    <div id="player-{{ $i }}">{{ $i }}</div>
@endfor
</code>```

Which generates divs with ids player-1, player-2, player-3, etc. But what I really need is to have the ids player-01, player-02, player-03, etc. Is there a function in blade to do that like printf in PHP? or using a ternary operator is the best way around?

(The ternary operator works fine when only one zero needs to be added, but doesn't work that fine when more zeros are needed)

答:
You can use str_pad($yourNumebr,$lengthOfYourNumber,$padString,$padType) to do this.

For more details  click here

```<code>@for ($i = 1; $i <= 99; $i++)
    <div id="player-{{ str_pad($i,2,'0',STR_PAD_LEFT) }}">{{ $i }}</div>
@endfor
</code>```

Or

```<code>sprintf('%02d', $i);
</code>```

Body:
I have the following code in a Blade view:

@for ($i = 1; $i <= 99; $i++)

{{ $i }}

@endfor

Which generates divs with ids player-1, player-2, player-3, etc. But what I really need is to have the ids player-01, player-02, player-03, etc. Is there a function in blade to do that like printf in PHP? or using a ternary operator is the best way around?

(The ternary operator works fine when only one zero needs to be added, but doesn't work that fine when more zeros are needed)

Body:
You can use str_pad($yourNumebr,$lengthOfYourNumber,$padString,$padType) to do this.

For more details  click here

@for ($i = 1; $i <= 99; $i++)
    <div id="player-{{ str_pad($i,2,'0',STR_PAD_LEFT) }}">{{ $i }}</div>
@endfor

Or

sprintf('%02d', $i);


问:
Informatica Mapping to create Target File of Mainframe File Layout
I am looking for suggestions, on how this requirement be approached.
I have to come-up with Informatica mapping to construct below Target File.

Source File

```
Key-1 Key-2 ACCOUNT-1
Key-1 Key-2 ACCOUNT-2
Key-1 Key-2 CC-ACC-1
Key-1 Key-2 CC-ACC-2
Key-1 Key-2 CC-ACC-3

```

For the above input source layout, I need to have one output record based on below Target File.

Basically, I need to group the data based on Key-1 & Key-2 Field & create a record that can have more than one accounts & more than one credit card account details for a customer.

TARGET FILE << MAINFRAME FILE LAYOUT >>

```

Key-1   String 10
Key-2   String 10
BANK-CUSTOMER-INFO
    MGR-NAME    STRING 50   — data to be extracted from MGR Table
    MGR-EMAIL   STRING 100  — data to be extracted from MGR-ADDTNL-INFO Table
    MGR-PHNE    STRING 10   — data to be extracted from MGR-ADDTNL-INFO Table
    CUST-NAME   STRING 100  — data to be extracted from Person Table
    CUST-EMAIL  STRING 100  — data to be extracted from Person-Addtnl_info Table
CUST-ACCOUNT-INFO
    BANK-ACCOUNT OCCURS 5 TIMES
        ACC-NO      STRING 10           ( Key Field )
        ACC-TYPE    STRING 10       — data to be extracted from  A Table
        ACC-TRXN-DTLS   OCCURS 10 TIMES
            ACC-TRXN-DATE   DATE 10     — data to be extracted from  X Table
            ACC-TRXN-MODE   STRING 10   — data to be extracted from Y Table
            ACC-TRXN-AMT    STRING 10   — data to be extracted from Z Table
    CREDIT-CARD-ACC OCCURS 5 TIMES
        CC-ACC-NO       STRING 10       ( Key Field )
        CC-ACC-TYPE     STRING 10   — data to be extracted from  B Table
        CC-TRXN-DTLS    OCCURS 10 TIMES
            CC-TRXN-DATE    DATE 10     — data o be extracted from  X1 Table
            CC-TRXN-MODE    STRING 10   — data o be extracted from  Y2 Table
            CC-TRXN-AMT STRING 10   — data o be extracted from  Z2 Table

```

Questions :-

```
How mapping can be accomplished.
Does Informatica supports to have Target Structure as defined above.
Most of my Target Attributes are to be fetched from multiple tables to construct one record, what should be most efficient way to come with Mapping.
Also, I need to denormalise the data as well to get above structure.
```

答:
The structure you've shown can easily be achieved with an xml target (so long as you're happy to have the target in xml).

One way to do it is to have a source qualifier for each field you want in the target and then to use joiner transformations to denormalise the details across records. The only drawback will be if you only want to extract a few records as this method will pick up all the records in the source tables each time the mapping runs.

Otherwise you'l need a source qualifier override query that denormalizes the incoming records right at the start (could also do this with inline lookups from powercenter 9.1 on which can be configured to return multiple matches but would be fiddly)

Body:
I am looking for suggestions, on how this requirement be approached.
I have to come-up with Informatica mapping to construct below Target File.

Source File

Key-1 Key-2 ACCOUNT-1
Key-1 Key-2 ACCOUNT-2
Key-1 Key-2 CC-ACC-1
Key-1 Key-2 CC-ACC-2
Key-1 Key-2 CC-ACC-3

For the above input source layout, I need to have one output record based on below Target File.

Basically, I need to group the data based on Key-1 & Key-2 Field & create a record that can have more than one accounts & more than one credit card account details for a customer.

TARGET FILE << MAINFRAME FILE LAYOUT >>

Key-1   String 10
Key-2   String 10
BANK-CUSTOMER-INFO
    MGR-NAME    STRING 50   — data to be extracted from MGR Table
    MGR-EMAIL   STRING 100  — data to be extracted from MGR-ADDTNL-INFO Table
    MGR-PHNE    STRING 10   — data to be extracted from MGR-ADDTNL-INFO Table
    CUST-NAME   STRING 100  — data to be extracted from Person Table
    CUST-EMAIL  STRING 100  — data to be extracted from Person-Addtnl_info Table
CUST-ACCOUNT-INFO
    BANK-ACCOUNT OCCURS 5 TIMES
        ACC-NO      STRING 10           ( Key Field )
        ACC-TYPE    STRING 10       — data to be extracted from  A Table
        ACC-TRXN-DTLS   OCCURS 10 TIMES
            ACC-TRXN-DATE   DATE 10     — data to be extracted from  X Table
            ACC-TRXN-MODE   STRING 10   — data to be extracted from Y Table
            ACC-TRXN-AMT    STRING 10   — data to be extracted from Z Table
    CREDIT-CARD-ACC OCCURS 5 TIMES
        CC-ACC-NO       STRING 10       ( Key Field )
        CC-ACC-TYPE     STRING 10   — data to be extracted from  B Table
        CC-TRXN-DTLS    OCCURS 10 TIMES
            CC-TRXN-DATE    DATE 10     — data o be extracted from  X1 Table
            CC-TRXN-MODE    STRING 10   — data o be extracted from  Y2 Table
            CC-TRXN-AMT STRING 10   — data o be extracted from  Z2 Table

Questions :-

How mapping can be accomplished.
Does Informatica supports to have Target Structure as defined above.
Most of my Target Attributes are to be fetched from multiple tables to construct one record, what should be most efficient way to come with Mapping.
Also, I need to denormalise the data as well to get above structure.


问:
Deducting numbers based on value in a different column
I have a C column with several rows containing numbers. I have another E Column with rankings.

I would like a formula that will automatically change the number in a 3rd column G based on the ranking in E column

So,

If the ranking is 2 in E the number in G is number in column C
minus 1

If the ranking is 1 the number in E the number in G is
number in column C minus 2

Any other ranking the number remains the
same.

Example -

C       E       G

19      2      18

12      1      10

15      3      15

答:
Put below formula in G column -

```<code>=IF(E1=1,C1-2,IF(E1=2,C1-1,C1))
</code>```

Above formula is for row 1. Adjust row value according to your need.

Explanation -

Check if E column contains 1, then subtract 2 from C column

Else, check if E column contains 2, then subtract 1 from C
column

Else, G column is same as C column

Body:
Put below formula in G column -

=IF(E1=1,C1-2,IF(E1=2,C1-1,C1))

Above formula is for row 1. Adjust row value according to your need.

Explanation -

Check if E column contains 1, then subtract 2 from C column

Else, check if E column contains 2, then subtract 1 from C
column

Else, G column is same as C column


问:
Cassandra: Who creates/distributes virtual Nodes among nodes - Leader?
In Cassandra, virtual nodes are created and distributed among nodes as given in http://www.datastax.com/dev/blog/virtual-nodes-in-cassandra-1-2. But who does that process ? Creating the virtual nodes, distributing among peers. Is it some sort of leader ? How does it work ?

Also in case a node joins, virtual nodes are re-distributed. Lot more similar actions are present. Who does all those ?

Edit: Is it like when a node joins, it takes up some part of virtual nodes from existing cluster thus eliminating the need of leader ?

答:
New node retrieves data about the cluster using seed nodes.

The new node will take his part of the cluster, based of num_tokens parameter (by default it will be distributed evenly between all nodes existing nodes), and will bootstrap it's part of data.
The rest of the cluster will be aware about the changes by "gossiping" - using gossip protocol.

Except the seed nodes part, there's no need for any "master" in the process.

Old nodes will not delete partitions automatically, you need to run nodetool cleanup on the old nodes after adding a new node.

Here's good article about it:

http://cassandra.apache.org/doc/latest/operating/topo_changes.html


问:
Generate Dagger components using Annotation Processor
I'm working on an Android App which follows the MVP architecture pattern. In all my fragments I'm injecting a Presenter. Therefore my Fragments (Views) need to have a Component in which I declare the injects. For example:

```<code>@ActivityScope
@Component(
        dependencies = AppComponent.class,
        modules = {
                PresenterModule.class,
                InteractorModule.class
        }
)
public interface ViewInjectorComponent {
    void inject(SelectEventOccurrenceFragment fragment);
    void inject(CreateOpponentFragment fragment);
    void inject(SelectOpponentFragment fragment);
    void inject(TeammatesInvitedFragment fragment);
    ...
}
</code>```

Every new View that I add into my App (Fragment) needs to have its entry declared here. I was wondering if It's possible to generate this code automatically with some kind of annotation processor. The App has already several fragments, this component file has easily more than 300 entries. It'd be awesome if I could do something like:

```<code>@Injectable
public class MyNewFragment implements MyNewView {
...
}
</code>```

And then automatically generate the entry in the ViewInjectorComponent file. It's possible? Where should I look at?

答:
The situation you are experiencing may be a consequence of organising your Modules and Components in an unusual way. In particular, grouping laterally (one Component injects all the Presenters) rather than vertically (one component injects the functionality related to SelectOpponentActivity) is problematic.

A good example to follow is in the Google Android Architecture Blueprints GitHub repo. If you peruse the code there, you will see that they have organised functionality related to Tasks inside one Java package together with a separate Component, Module, Presenter etc. This has the nice advantage of being able to restrict accessibility of the constructors of the classes contained therein and fulfilling Effective Java Item 13: Minimize the accesibility of classes and members.

Likewise, you've grouped all your modules together into a Presenter Module and an Interactor Module. The advice from the Dagger 2 official documentation is to organise Modules first for testability and then along functional lines. Again, you can refer to the Blueprint example for how to do this.

Finally, note that there is unavoidably some boilerplate involved in using most DI frameworks like Dagger 2. In a sense, you are exchanging a bigger problem ("how do I deal with all of these constructors?") with much smaller and more manageable problems ("how do I group my Components" etc.).

Update
There is a library called Auto Dagger2 that can generate components for you. See this Github repo. Here is an example of an annotation:

```<code>@AutoComponent
@Singleton
public class ExampleApplication extends Application {
}
</code>```

Which generates the following code:

```<code>@Component
@Singleton
public interface ExampleApplicationComponent {
}
</code>```

Also check out Google Auto if you are interested in code generation tools.

Body:
I'm working on an Android App which follows the MVP architecture pattern. In all my fragments I'm injecting a Presenter. Therefore my Fragments (Views) need to have a Component in which I declare the injects. For example:

@ActivityScope
@Component(
        dependencies = AppComponent.class,
        modules = {
                PresenterModule.class,
                InteractorModule.class
        }
)
public interface ViewInjectorComponent {
    void inject(SelectEventOccurrenceFragment fragment);
    void inject(CreateOpponentFragment fragment);
    void inject(SelectOpponentFragment fragment);
    void inject(TeammatesInvitedFragment fragment);
    ...
}

Every new View that I add into my App (Fragment) needs to have its entry declared here. I was wondering if It's possible to generate this code automatically with some kind of annotation processor. The App has already several fragments, this component file has easily more than 300 entries. It'd be awesome if I could do something like:

@Injectable
public class MyNewFragment implements MyNewView {
...
}

And then automatically generate the entry in the ViewInjectorComponent file. It's possible? Where should I look at?

Body:
The situation you are experiencing may be a consequence of organising your Modules and Components in an unusual way. In particular, grouping laterally (one Component injects all the Presenters) rather than vertically (one component injects the functionality related to SelectOpponentActivity) is problematic.

A good example to follow is in the Google Android Architecture Blueprints GitHub repo. If you peruse the code there, you will see that they have organised functionality related to Tasks inside one Java package together with a separate Component, Module, Presenter etc. This has the nice advantage of being able to restrict accessibility of the constructors of the classes contained therein and fulfilling Effective Java Item 13: Minimize the accesibility of classes and members.

Likewise, you've grouped all your modules together into a Presenter Module and an Interactor Module. The advice from the Dagger 2 official documentation is to organise Modules first for testability and then along functional lines. Again, you can refer to the Blueprint example for how to do this.

Finally, note that there is unavoidably some boilerplate involved in using most DI frameworks like Dagger 2. In a sense, you are exchanging a bigger problem ("how do I deal with all of these constructors?") with much smaller and more manageable problems ("how do I group my Components" etc.).

Update
There is a library called Auto Dagger2 that can generate components for you. See this Github repo. Here is an example of an annotation:

@AutoComponent
@Singleton
public class ExampleApplication extends Application {
}

Which generates the following code:

@Component
@Singleton
public interface ExampleApplicationComponent {
}

Also check out Google Auto if you are interested in code generation tools.


问:
ValueError: array is too big when loading GoogleNews-vectors-negative
I am trying to load the pretrained word vectors from Google using the following code:

```<code>from gensim import models
w = models.KeyedVectors.load_word2vec_format('GoogleNews-vectors-negative300.bin.gz', binary=True)
</code>```

But I am getting an error that tells me

File "C:\ProgramData\Anaconda3\lib\site-packages\gensim\models\keyedvectors.py", line 197, in load_word2vec_format
      result.syn0 = zeros((vocab_size, vector_size), dtype=datatype)

ValueError: array is too big; arr.size * arr.dtype.itemsize is larger than the maximum possible size.

Could anyone suggest a possible solution. Thanks in advance.

答:
This is likely triggered because the Python you have installed uses 32-bit-addressing, and thus can't allocate arrays of the size required to load the GoogleNews vectors. Some options:

Switch to a 64-bit Python. Note that that full vector set takes 3GB+ to load, so unless you have more RAM than 4GB, it will be hard to work with the full set no matter what.

Use the optional limit parameter of gensim's load_word2vec_format() method to read only some of the early entries in the file. The file seems to be in most-frequent to least-frequent token order, so often the early entries are all you'll need. For example, you could try limit=500000 to read just the 1st 500,000 entries (instead of all 3 million)

Body:
I am trying to load the pretrained word vectors from Google using the following code:

from gensim import models
w = models.KeyedVectors.load_word2vec_format('GoogleNews-vectors-negative300.bin.gz', binary=True)

But I am getting an error that tells me

File "C:\ProgramData\Anaconda3\lib\site-packages\gensim\models\keyedvectors.py", line 197, in load_word2vec_format
      result.syn0 = zeros((vocab_size, vector_size), dtype=datatype)

ValueError: array is too big; arr.size * arr.dtype.itemsize is larger than the maximum possible size.

Could anyone suggest a possible solution. Thanks in advance.


问:
Font-face web fonts looks bolder
I'm stuck with a problem. I'm trying to embed fonts with @font-face but they always looks bolder. I have tried everything: other fonts, change font-weight to "ligher" or "100" etc...
The font looks always as it is bolded. I'm pretty sure it could look good because I've seen it used in many other websites with @font-face and it looks thin and fine.

See the attached image link text (I know it would never look as in PS, but so different?)

thanks

答:
Fonts vary according to OS (Linux, Mac,PC) and even by browser, never mind the Photoshop blurring variants that Billeeb mentioned. For example Safari on windows applies some heavy anti-aliasing to make text smooth, which makes it look blaringly different on Firefox, even on the same machine.

In my opinion, the best way to have a consistent font experience is to use some sort of font replacement technology like Cufon.  But this only works for not standard fonts with simple effects, you wouldn't want to use this if you need crazy amounts of drop shadow or blurring.  For that its best to stick with images

Title: Font-face web fonts looks bolder


问:
angular 4 compile failed for awesome-typescript-loader
I updated my current angular 2 project to angular 4, and now, got these errors:

```<code>Module build failed: TypeError: Cannot read property 'exclude' of undefined
at applyDefaults (/Users/frankhe/jnpr_csc/node_modules/awesome-typescript-loader/src/instance.ts:266:72)
</code>```

package json is:

```<code> "@angular/animations": "^4.0.1",
        "@angular/common": "^4.0.1",
        "@angular/compiler": "^4.0.1",
        "@angular/compiler-cli": "^4.0.1
    "angular2-load-children-loader": "^0.1.3",
        "angular2-template-loader": "^0.4.0",
"typescript": "^2.0.3",
        "awesome-typescript-loader": "^2.2.4",
        "css-loader": "^0.23.1",
        "es6-promise-loader": "^1.0.1",
</code>```

and my tsconfig is

```<code>{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false,
    "suppressImplicitAnyIndexErrors": true
  }
}
</code>```

Any idea why compile failed?

Thanks

答:
This is a dependency issue with certain versions of Typescript and Awesome-Typescript-Loader. It should be working with

```<code>"typescript": "^2.1.4"
"awesome-typescript-loader": "^3.0.0-beta.9"
</code>```

try updating your dependencies for typescript / ATL

more info: https://github.com/s-panferov/awesome-typescript-loader/issues/190

Body:
I updated my current angular 2 project to angular 4, and now, got these errors:

Module build failed: TypeError: Cannot read property 'exclude' of undefined
at applyDefaults (/Users/frankhe/jnpr_csc/node_modules/awesome-typescript-loader/src/instance.ts:266:72)

package json is:

 "@angular/animations": "^4.0.1",
        "@angular/common": "^4.0.1",
        "@angular/compiler": "^4.0.1",
        "@angular/compiler-cli": "^4.0.1
    "angular2-load-children-loader": "^0.1.3",
        "angular2-template-loader": "^0.4.0",
"typescript": "^2.0.3",
        "awesome-typescript-loader": "^2.2.4",
        "css-loader": "^0.23.1",
        "es6-promise-loader": "^1.0.1",

and my tsconfig is

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false,
    "suppressImplicitAnyIndexErrors": true
  }
}

Any idea why compile failed?

Thanks

Body:
This is a dependency issue with certain versions of Typescript and Awesome-Typescript-Loader. It should be working with

"typescript": "^2.1.4"
"awesome-typescript-loader": "^3.0.0-beta.9"

try updating your dependencies for typescript / ATL

more info: https://github.com/s-panferov/awesome-typescript-loader/issues/190


答:
Functions are first-class members of Python. There's no extra syntax required beyond function definition. Check out this example using just standard library functions and a lambda function (which is roughly analogous to a block).

```<code>functions = [round, int, str, lambda x: x + 2]

for fn in functions:
    print(fn(3.1415))
# 3
# 3
# 3.1415
# 5.141500000000001
</code>```

Title: Python store action/method in block/array

Body:
I am beginner in python and I am trying to write something like this in objective-c. In Objective-C, each method can be stored in block and those can be called again later. I have tried to find online but I don't know keyword in python. Can I write like that in python or is there any similar flow ? How shall I do?

void (^successBlock)() = ^{
    NSLog(@"Test");
};

NSMutableArray *muArr = [NSMutableArray array];
[muArr addObject:successBlock];

for (void (^successBlock)() in muArr) {
    successBlock();
}

Body:
Functions are first-class members of Python. There's no extra syntax required beyond function definition. Check out this example using just standard library functions and a lambda function (which is roughly analogous to a block).

functions = [round, int, str, lambda x: x + 2]

for fn in functions:
    print(fn(3.1415))
# 3
# 3
# 3.1415
# 5.141500000000001


问:
Add toolbar in certain fragment
I have a main activity:

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</code>```

This activity just has a framelayout and uses this layout to add, replace, and delete fragments.

I have 2 fragments:

LoginFragment  (constraintLayout)

```<code><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#4CF">

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Go to Register"
    android:layout_marginLeft="8dp"
    app:layout_constraintLeft_toLeftOf="parent"
    android:layout_marginRight="8dp"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    android:layout_marginBottom="8dp"
    app:layout_constraintVertical_bias="0.500" />
</code>```

RegisterFragment  (constraintLayout)

```<code><android.support.v7.widget.Toolbar
    android:id="@+id/my_toolbar"
    android:layout_width="0dp"
    android:layout_height="56dp"
    android:background="?attr/colorPrimary"
    android:elevation="4dp"
    android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    tools:layout_editor_absoluteY="1dp"
    android:layout_marginLeft="8dp"
    app:layout_constraintLeft_toLeftOf="parent"
    android:layout_marginRight="8dp"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp" />

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Welcome to the Register fragment"
    tools:layout_editor_absoluteY="205dp"
    tools:layout_editor_absoluteX="62dp" />
</code>```

The login fragment shows up first. This should have no actionbar. There is a button in this fragment which will replace this login fragment with the register fragment. In this fragment I want the actionbar to show up so that it can have the back arrow in the actionbar to go back to the login view. I have no idea though where to place the toolbar widget in the code? I have tried to set it in the register fragment, but it kept displaying oddly.

答:
I have figured it out. In the activity I just wrap everything in a linear layout:

```<code><?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    xmlns:tools="http://schemas.android.com/tools">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:minHeight="?attr/actionBarSize"
        android:background="?attr/colorPrimary" />

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />
</LinearLayout>
</code>```

Then in the fragments themselves I have a method to hide/show the toolbar.

Title: Add toolbar in certain fragment

Body:
I have a main activity:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

This activity just has a framelayout and uses this layout to add, replace, and delete fragments.

I have 2 fragments:

LoginFragment  (constraintLayout)

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#4CF">

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Go to Register"
    android:layout_marginLeft="8dp"
    app:layout_constraintLeft_toLeftOf="parent"
    android:layout_marginRight="8dp"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    android:layout_marginBottom="8dp"
    app:layout_constraintVertical_bias="0.500" />

RegisterFragment  (constraintLayout)

<android.support.v7.widget.Toolbar
    android:id="@+id/my_toolbar"
    android:layout_width="0dp"
    android:layout_height="56dp"
    android:background="?attr/colorPrimary"
    android:elevation="4dp"
    android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    tools:layout_editor_absoluteY="1dp"
    android:layout_marginLeft="8dp"
    app:layout_constraintLeft_toLeftOf="parent"
    android:layout_marginRight="8dp"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp" />

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Welcome to the Register fragment"
    tools:layout_editor_absoluteY="205dp"
    tools:layout_editor_absoluteX="62dp" />

The login fragment shows up first. This should have no actionbar. There is a button in this fragment which will replace this login fragment with the register fragment. In this fragment I want the actionbar to show up so that it can have the back arrow in the actionbar to go back to the login view. I have no idea though where to place the toolbar widget in the code? I have tried to set it in the register fragment, but it kept displaying oddly.

Body:
I have figured it out. In the activity I just wrap everything in a linear layout:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    xmlns:tools="http://schemas.android.com/tools">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:minHeight="?attr/actionBarSize"
        android:background="?attr/colorPrimary" />

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />
</LinearLayout>

Then in the fragments themselves I have a method to hide/show the toolbar.


问:
Rancher deleting the ipsec service
It's been causing me only issues so far and all the containers I run are started with --net=host anyway. I was wondering if I could delete this service without any issue. Rancher forums are not responding.

答: Please file an issue on https://github.com/rancher/rancher with logs from the following containers: network-manager, rancher-metadata, ipsec-router, ipsec-cni*.</p>

Title: Rancher deleting the ipsec service


问:
How to update UILabel text in custom class after initialization (Swift 3)
I have custom UIStackView class but after initialization I cannot change labels in it, because its referring to different label objects.

```<code>//  ViewBlocksController.swift
//  player

import UIKit

let nowPlayingControl = NowPlayingController()

@IBDesignable class TitlesFrame: UIStackView {
    //Labels variables
    let songTitle = UILabel()
    let artistAlbumTitle = UILabel()

    //Initialization
    override init(frame: CGRect) {
        super.init(frame: frame)
        arrangeView()
    }

    required init(coder: NSCoder) {
        super.init(coder: coder)
        arrangeView()
    }

    func arrangeView(){
        //Get initial text
        (songTitle.text, artistAlbumTitle.text) = nowPlayingControl.getTitles()

        //Add labels to the stack
        addArrangedSubview(artistAlbumTitle)
        addArrangedSubview(songTitle)

        //Test what label is used
        print(songTitle)
    }

    func updateTitles(){
        (songTitle.text, artistAlbumTitle.text) = nowPlayingControl.getTitles()
    }
}
</code>```

I call updateTitles() from my MainViewController class:

```<code>//  MainViewController.swift
//  player

import UIKit

class MainViewController: UIViewController {

    let titlesFrame = TitlesFrame()

    //Will call this on custom notification
    func callUpdate(){
        titlesFrame.updateTitles()
    }
}
</code>```

Print gives me following objects:

```<code><**UILabel: 0x100c15b90**; frame = (0 0; 0 0); text = 'Unknown Artist
\342\200— Unknown ...'; userInteractionEnabled = NO; layer =
<_UILabelLayer: 0x1700956d0>>

<**UILabel: 0x100d19d90**; frame = (0 0; 0 0); text = 'Unknown Artist —
Unknown ...'; userInteractionEnabled = NO; layer = <_UILabelLayer:
0x174097f70>>
</code>```

When I try to update labels with updateTitles() method, it always update 1st object (UILabel: 0x100c15b90). But Storyboard instead displays 2nd object (UILabel: 0x100d19d90) and it is never updated.

How can I update labels on Storyboard?

答:
Thanks to @OOPer I figured out that my problem was not in the initializers, but in how I refer to my custom class.

To update labels on Storyboard I replaced let titlesFrame = TitlesFrame() with @IBOutlet var titlesFrame: TitlesFrame! in my MainViewController class. IBOutlet is connected to the inherited UIStackView object on the Storyboard:

```<code>//  MainViewController.swift
//  player

import UIKit

class MainViewController: UIViewController {

    //IBOutlet is connected to the UIStackView object on the Storyboard
    @IBOutlet weak var titlesFrame: TitlesFrame!

    //Will call this on custom notification
    func callUpdate(){
        titlesFrame.updateTitles()
    }
}
</code>```

Body:
I have custom UIStackView class but after initialization I cannot change labels in it, because its referring to different label objects.

//  ViewBlocksController.swift
//  player

import UIKit

let nowPlayingControl = NowPlayingController()

@IBDesignable class TitlesFrame: UIStackView {
    //Labels variables
    let songTitle = UILabel()
    let artistAlbumTitle = UILabel()

    //Initialization
    override init(frame: CGRect) {
        super.init(frame: frame)
        arrangeView()
    }

    required init(coder: NSCoder) {
        super.init(coder: coder)
        arrangeView()
    }

    func arrangeView(){
        //Get initial text
        (songTitle.text, artistAlbumTitle.text) = nowPlayingControl.getTitles()

        //Add labels to the stack
        addArrangedSubview(artistAlbumTitle)
        addArrangedSubview(songTitle)

        //Test what label is used
        print(songTitle)
    }

    func updateTitles(){
        (songTitle.text, artistAlbumTitle.text) = nowPlayingControl.getTitles()
    }
}

I call updateTitles() from my MainViewController class:

//  MainViewController.swift
//  player

import UIKit

class MainViewController: UIViewController {

    let titlesFrame = TitlesFrame()

    //Will call this on custom notification
    func callUpdate(){
        titlesFrame.updateTitles()
    }
}

Print gives me following objects:

<**UILabel: 0x100c15b90**; frame = (0 0; 0 0); text = 'Unknown Artist
\342\200— Unknown ...'; userInteractionEnabled = NO; layer =
<_UILabelLayer: 0x1700956d0>>

<**UILabel: 0x100d19d90**; frame = (0 0; 0 0); text = 'Unknown Artist —
Unknown ...'; userInteractionEnabled = NO; layer = <_UILabelLayer:
0x174097f70>>

When I try to update labels with updateTitles() method, it always update 1st object (UILabel: 0x100c15b90). But Storyboard instead displays 2nd object (UILabel: 0x100d19d90) and it is never updated.

How can I update labels on Storyboard?

Body:
Thanks to @OOPer I figured out that my problem was not in the initializers, but in how I refer to my custom class.

To update labels on Storyboard I replaced let titlesFrame = TitlesFrame() with @IBOutlet var titlesFrame: TitlesFrame! in my MainViewController class. IBOutlet is connected to the inherited UIStackView object on the Storyboard:

//  MainViewController.swift
//  player

import UIKit

class MainViewController: UIViewController {

    //IBOutlet is connected to the UIStackView object on the Storyboard
    @IBOutlet weak var titlesFrame: TitlesFrame!

    //Will call this on custom notification
    func callUpdate(){
        titlesFrame.updateTitles()
    }
}


问:
Gensim - Memory error using GoogleNews-vector model
I  getting memory error, when I use GoogleNews-vectors-negative300.bin or try to train a model with Gensim with wikipedia dataset corpus.(1 GB). I have 4GB RAM in my system. Is there any way to bypass this.

Can we host it on cloud service like AWS to get better speed ?

答: 4GB is very tight for that vector set; you should have 8GB or more to load the full set. Alternatively you could use the optional limit argument to load_word2vec_format() to just load some of the vectors. For example, limit=500000 would load just the first 500,000 (instead of the full 3 million). As the file appears to put the more-frequently-appearing tokens first, that may be sufficient for many purposes.


问:
How do I aggregate with group by in mysql withou setting sql mode?
This query gets the output I want.  In order to run it I have to run

```<code>SET sql_mode = '';
</code>```

Because otherwise I get an error:

SELECT list is not in GROUP BY clause and contains nonaggregated column 'knownLoss.t1.loss' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

```<code>SELECT
  t1.klDate AS LDate
  , t1.Category
  , t1.reason AS Reason
  , sum(t1.loss) AS Loss
  , round(t1.loss / t2.loss,2) AS Percentage
FROM
  deptkl t1
JOIN (
  SELECT
      Store
    , sum(loss) AS loss
  FROM
    deptkl
  WHERE
    klDate >= date_sub(SUBDATE(curdate(), WEEKDAY(curdate())), interval 7 day)
AND
    klDate < SUBDATE(curdate(), WEEKDAY(curdate()))
AND
    Store = 19
AND
    Department = 80
) t2 ON t1.Store = t2.Store

WHERE
  klDate >= date_sub(SUBDATE(curdate(), WEEKDAY(curdate())), interval 7 day)
  AND
  klDate < SUBDATE(curdate(), WEEKDAY(curdate()))
  AND
  t1.Store = 19
AND
  Department = 80
GROUP BY
  klDate
, Category
, reason
</code>```

When I place this into the Dataset and Query Dialog of Jasper Studio, I get the same error and I am unable to use the SET sql_mode = ''; command. Any thoughts?  If there is a way to achieve this without using SET sql_mode = '';?

答:
I'm guessing the error is from this line in your select:

```<code>round(t1.loss / t2.loss,2) AS Percentage
</code>```

Since you GROUP BY clause does not include this column it's somewhat of a coin toss which t1.loss and t2.loss values will be used. In some cases those values happen to always be the same based on your criteria and so you get the correct results regardless, but the db will still complain since it's being asked to return somewhat arbitrary results for those columns.  One way to deal with this would be to simply apply an aggregate function to the columns in question like this:

```<code>round(min(t1.loss) / min(t2.loss),2) AS Percentage
</code>```

or...

```<code>round(avg(t1.loss) / avg(t2.loss),2) AS Percentage
</code>```

Body:
This query gets the output I want.  In order to run it I have to run

SET sql_mode = '';

Because otherwise I get an error:

SELECT list is not in GROUP BY clause and contains nonaggregated column 'knownLoss.t1.loss' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

SELECT
  t1.klDate AS LDate
  , t1.Category
  , t1.reason AS Reason
  , sum(t1.loss) AS Loss
  , round(t1.loss / t2.loss,2) AS Percentage
FROM
  deptkl t1
JOIN (
  SELECT
      Store
    , sum(loss) AS loss
  FROM
    deptkl
  WHERE
    klDate >= date_sub(SUBDATE(curdate(), WEEKDAY(curdate())), interval 7 day)
AND
    klDate < SUBDATE(curdate(), WEEKDAY(curdate()))
AND
    Store = 19
AND
    Department = 80
) t2 ON t1.Store = t2.Store

WHERE
  klDate >= date_sub(SUBDATE(curdate(), WEEKDAY(curdate())), interval 7 day)
  AND
  klDate < SUBDATE(curdate(), WEEKDAY(curdate()))
  AND
  t1.Store = 19
AND
  Department = 80
GROUP BY
  klDate
, Category
, reason

When I place this into the Dataset and Query Dialog of Jasper Studio, I get the same error and I am unable to use the SET sql_mode = ''; command. Any thoughts?  If there is a way to achieve this without using SET sql_mode = '';?

Body:
I'm guessing the error is from this line in your select:

round(t1.loss / t2.loss,2) AS Percentage

Since you GROUP BY clause does not include this column it's somewhat of a coin toss which t1.loss and t2.loss values will be used. In some cases those values happen to always be the same based on your criteria and so you get the correct results regardless, but the db will still complain since it's being asked to return somewhat arbitrary results for those columns.  One way to deal with this would be to simply apply an aggregate function to the columns in question like this:

round(min(t1.loss) / min(t2.loss),2) AS Percentage

or...

round(avg(t1.loss) / avg(t2.loss),2) AS Percentage


问:
search file and print to the same directory
I want to search a file by name and run a python script on it and finally print the output to the directory that contains the file. The structure looks like

dir_a/common.txt

  dir_b/common.txt

  dir_c/common.txt

And so far I have came up with

```<code>find . -maxdepth 2 -name "common.txt" -exec cat "{}" \; | ~/myscript.py
</code>```

myscript.py prints to the stdout. But how can I redirect the output to

dir_a/out.txt

  dir_b/out.txt

  dir_c/out.txt

答:
Maybe small script runmypy.sh:

```<code>#!/bin/bash
topdir="${1:-.}"
while IFS= read -r -d '' file; do
    dir=$(dirname "$file")
    /path/to/myscript.py < "$file" >"$dir/out.txt"
done < <(find "$topdir" -maxdepth 2 -type f -name "common.txt" -print0)
</code>```

Body:
I want to search a file by name and run a python script on it and finally print the output to the directory that contains the file. The structure looks like

dir_a/common.txt

  dir_b/common.txt

  dir_c/common.txt

And so far I have came up with

find . -maxdepth 2 -name "common.txt" -exec cat "{}" \; | ~/myscript.py

myscript.py prints to the stdout. But how can I redirect the output to

dir_a/out.txt

  dir_b/out.txt

  dir_c/out.txt

Body:
Maybe small script runmypy.sh:

#!/bin/bash
topdir="${1:-.}"
while IFS= read -r -d '' file; do
    dir=$(dirname "$file")
    /path/to/myscript.py < "$file" >"$dir/out.txt"
done < <(find "$topdir" -maxdepth 2 -type f -name "common.txt" -print0)


问:
Use Container Metrics from Prometheus
I deployed Prometheus on my cluster as well as cAdvisor and Grafana. It works tremendously well. I get all the data I need on Grafana's UI.
I started using Prometheus Java API in order to use this data. For example get the CPU usage and if it has a certain value something will be done.

What I display on Grafana is the Container CPU usage for each container. Now I would like to get that information with the Java API if possible (or something if not). But of course the PromQL queries aren't usable from a Java program (from what I tried but I may be wrong).

I thought of several ways:

Clone the cAdvisor project and directly implement what I want to do in Go

Create a bash script with the docker stat command that would get me the container and CPU usage associated

Or maybe there is actually a way to send PromQL queries.
For instance we get the metric by its name via Java or the Prometheus interface:

ex: node_cpu would get me some data.
But if I want something more precise, I need to send a request, for example irate(node_cpu{job="prometheus"}[5m]) which is not possible via Java.

Is there a way for me to get more precise metrics ?

答:
Prometheus supports REST API requests, which are language-agnostic. You just need to send an HTTP request with your query and process the response.

see an example below, copied from their site.

the following HTTP GET request:

```<code>http://localhost:9090/api/v1/query?query=up&time=2015-07-01T20:10:51.781Z
</code>```

returns something like this:

```<code>{
   "status" : "success",
   "data" : {
      "resultType" : "vector",
      "result" : [
         {
            "metric" : {
               "__name__" : "up",
               "job" : "prometheus",
               "instance" : "localhost:9090"
            },
            "value": [ 1435781451.781, "1" ]
         },
         {
            "metric" : {
               "__name__" : "up",
               "job" : "node",
               "instance" : "localhost:9100"
            },
            "value" : [ 1435781451.781, "0" ]
         }
      ]
   }
}
</code>```

lots more details, here

Title: Use Container Metrics from Prometheus

Body:
Prometheus supports REST API requests, which are language-agnostic. You just need to send an HTTP request with your query and process the response.

see an example below, copied from their site.

the following HTTP GET request:

http://localhost:9090/api/v1/query?query=up&time=2015-07-01T20:10:51.781Z

returns something like this:

{
   "status" : "success",
   "data" : {
      "resultType" : "vector",
      "result" : [
         {
            "metric" : {
               "__name__" : "up",
               "job" : "prometheus",
               "instance" : "localhost:9090"
            },
            "value": [ 1435781451.781, "1" ]
         },
         {
            "metric" : {
               "__name__" : "up",
               "job" : "node",
               "instance" : "localhost:9100"
            },
            "value" : [ 1435781451.781, "0" ]
         }
      ]
   }
}

lots more details, here


问:
Tomcat share lib folder
I have a war file which not include the lib jars. I create share folder under the lib folder, put all jar files in it, and update the catalina.properties file. It's working on my Mac, but not the centos7 server. I check the centos7 tomcat log, it shows the log4j cannot be found, but the jar is in the share folder. What's other possible place to check?

thanks

catalina.properties

```<code>   shared.loader="${catalina.base}/lib/share","${catalina.base}/lib/share/*.jar","${catalina.home}/lib/share","${catalina.home}/lib/share/*.jar"
</code>```

tomcat 8.5.8

答:
This my own mistake, add  to the ../conf/context.xml file, the antiResourceLocking="false" privileged="true" should be remove!

correct sample:

```<code> <Context>

<!-- Default set of monitored resources. If one of these changes, the    -->
<!-- web application will be reloaded.                                   -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>

<!-- Uncomment this to disable session persistence across Tomcat restarts -->
<!--
<Manager pathname="" />
-->
</Context>
</code>```

Title: Tomcat share lib folder

Body:
I have a war file which not include the lib jars. I create share folder under the lib folder, put all jar files in it, and update the catalina.properties file. It's working on my Mac, but not the centos7 server. I check the centos7 tomcat log, it shows the log4j cannot be found, but the jar is in the share folder. What's other possible place to check?

thanks

catalina.properties

   shared.loader="${catalina.base}/lib/share","${catalina.base}/lib/share/*.jar","${catalina.home}/lib/share","${catalina.home}/lib/share/*.jar"

tomcat 8.5.8

Body:
This my own mistake, add  to the ../conf/context.xml file, the antiResourceLocking="false" privileged="true" should be remove!

correct sample:

 <Context>

<!-- Default set of monitored resources. If one of these changes, the    -->
<!-- web application will be reloaded.                                   -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>

<!-- Uncomment this to disable session persistence across Tomcat restarts -->
<!--
<Manager pathname="" />
-->
</Context>


问:
Price calculator for woocommerce
can someone tell me is there a plugin for this cost calculator for woocommerce. And if there isn't how to connect whit the woocommerce plug in. This is the example that I'm looking for https://z3ddota.com/dota2-mmr-boosting/.</p>

答: Same functionality is not available in WooCommerce any plugin.We can implement same functionality with custom plugin.So please share your requirement. </p>

Title: Price calculator for woocommerce


问: Are

答:
A script in the body of your document will be executed when it is encountered. If it's a function, then "executing it" simply means defining the function, i.e. adding it to the list of known functions. But if it's not a function, if it's a block of stand-alone statements, they will be executed where encountered.

For example, if you wrote:

```<code><html><head>... whatever ...</head>
<p>Foo
<script>
document.write("bar")
</script>
<p>Plugh
</html>
</code>```

The browser will display:

```<code>Foobar
Plugh
</code>```

This may or may not be what you want.

Title: Are <script>'s not in <head> ok?

Body:
I have had this question niggling at the curious bit of my mind for a while now and I thought I'd ask your collective expertise for an answer to this question.

To elaborate on the title, say I have this:

alert("Some JS outside ");

Outside the  tags of my HTML file. My question is whether it's ok to do this or not, and how much it is used like this.

My instincts tell me it's ok - I reckon browsers look through all HTML for

Body:
A script in the body of your document will be executed when it is encountered. If it's a function, then "executing it" simply means defining the function, i.e. adding it to the list of known functions. But if it's not a function, if it's a block of stand-alone statements, they will be executed where encountered.

For example, if you wrote:

<html><head>... whatever ...</head>
<p>Foo
<script>
document.write("bar")
</script>
<p>Plugh
</html>

The browser will display:

Foobar
Plugh

This may or may not be what you want.


问:
Hyphens between buttons when commenting out white space
When I try to remove gaps between my buttons by commenting out the white space between them, these little black dashes appear instead, which are selectable using the tab button. I can make them non visable with text-decoration: false and I can remove the gap with margin-left: -4px but whatever it is is still there and is selected when using the tab button.

Why are these dashes there and how do I get rid of them?

HTML:

```<code><a target="_blank" a href= "https://Google.com">
<button class="button">
<strong>LinkedIn</strong><br>
</button></a><!--
--><a target="_blank" a href= "https://www.Google.com">
<button class="button">
<strong>GitHub</strong><br>
</button></a>
<br><!--
--><a target="_blank" a href= "https://www.Google.com">
<button class="button">
<strong>Stack Overflow</strong><br>
</button></a><!--
--><a target="_blank" a href= "https://www.Google.com">
<button class="button">
<strong>HackerRank</strong><br>
</button></a>
</code>```

CSS:

```<code>div{
    display: inline-block;
    white-space: normal;
    height: 623px;
    padding: 10px;
    padding-top: 0;
    padding-left: 0;
    vertical-align: top;
    border-bottom: 3px solid black;
    border: 1px solid black;
  width: 500px;
}

.button{
    background-color: rgb(224,184,219);
    border: 2px solid white;
    border-radius: 10px;
    color: white;
    display: inline-block;
    font-size: 16px;
    text-decoration: none;
    text-align: center;
    padding: 10px;
    width: 160px;
    height: 100px;
    transition-duration: 0.2s;
    -webkit-transition-duration:0.2s;
    cursor: pointer;
    outline: none;
}
.button:hover{
    background-color: white;
    color: rgb(224,184,219);
    outline: none;
}
:focus, :visited{
    border: 2px solid rgb(153,217,234);
    outline: none;
    outline: 0;
}
</code>```

JSFiddle: https://jsfiddle.net/mpbev9ay/1/

答:
You shouldn't put <button> elements in  elements. They're both interactive controls and as such it's forbidden to nest them inside one another.

The W3C defines 's content model (i.e. what it can have inside) as

Transparent, but there must be no interactive content descendant.

where

Interactive content is content that is specifically intended for user interaction.

a, audio (if the controls attribute is present), button, details, embed, iframe, img (if the usemap attribute is present), input (if the type attribute is not in the Hidden state), keygen, label, menu (if the type attribute is in the toolbar state), object (if the usemap attribute is present), select, textarea, video (if the controls attribute is present)

(emphasis mine)

So the solution is to rearrange your HTML so that that no longer happens.

Body:
When I try to remove gaps between my buttons by commenting out the white space between them, these little black dashes appear instead, which are selectable using the tab button. I can make them non visable with text-decoration: false and I can remove the gap with margin-left: -4px but whatever it is is still there and is selected when using the tab button.

Why are these dashes there and how do I get rid of them?

HTML:

<button class="button">
LinkedIn

</button>
<button class="button">
GitHub

</button>

<button class="button">
Stack Overflow

</button>
<button class="button">
HackerRank

</button>

CSS:

div{
    display: inline-block;
    white-space: normal;
    height: 623px;
    padding: 10px;
    padding-top: 0;
    padding-left: 0;
    vertical-align: top;
    border-bottom: 3px solid black;
    border: 1px solid black;
  width: 500px;
}

.button{
    background-color: rgb(224,184,219);
    border: 2px solid white;
    border-radius: 10px;
    color: white;
    display: inline-block;
    font-size: 16px;
    text-decoration: none;
    text-align: center;
    padding: 10px;
    width: 160px;
    height: 100px;
    transition-duration: 0.2s;
    -webkit-transition-duration:0.2s;
    cursor: pointer;
    outline: none;
}
.button:hover{
    background-color: white;
    color: rgb(224,184,219);
    outline: none;
}
:focus, :visited{
    border: 2px solid rgb(153,217,234);
    outline: none;
    outline: 0;
}

JSFiddle: https://jsfiddle.net/mpbev9ay/1/

Body:
You shouldn't put <button> elements in <a> elements. They're both interactive controls and as such it's forbidden to nest them inside one another.

The W3C defines <a>'s content model (i.e. what it can have inside) as

Transparent, but there must be no interactive content descendant.

where

Interactive content is content that is specifically intended for user interaction.

a, audio (if the controls attribute is present), button, details, embed, iframe, img (if the usemap attribute is present), input (if the type attribute is not in the Hidden state), keygen, label, menu (if the type attribute is in the toolbar state), object (if the usemap attribute is present), select, textarea, video (if the controls attribute is present)

(emphasis mine)

So the solution is to rearrange your HTML so that that no longer happens.