问:
How to make an Extended Entry Decision Table for Testing
So I need to make a Decision Table to test a bit of code. The code is simple and straight forward but requires two user inputs to determine two proceeding variables. This is why I need to make this more than a binary (true/false) table.

The user is prompted to input total income, this will, in turn, determine which bracket the user falls into. Then the user is prompted to input the amount of dependents, which will determine the final tax. Depending on the income bracket, a switch statement will then set
tax = income * [certain percentage]. After this the amount of dependents will determine what percentage of the tax will be removed.

Essentially what I need to know is how to set up my Conditions, Actions, and Rules.

Here is an example of decision table but this one is binary (true/false)

I am using Java for the code but that isn't entirely relevant. What I need specifically is deciding what my Conditions should be, whether it's solely income or the combinations of income and dependents, etc. I do not need to write the code, just need to write the test table for it.

If anyone can help inform me as to what I should do or where I should look, that would be appreciated. I am willing to provide anymore information if need be!

Thanks!

答:
If you understand, what the regular (binary) decision table is, then it'll be easy for you to get the extended table as well - the difference is in conditions only.

Conditions in the extended decision table can have more than two values. For example, in your case you have two conditions:

Tax Bracket with values (for example): [0, 9275], [9276, 37650], [37651, 91150] etc.

Number of Dependents with values: 0, 1, 2, 3 etc. (what's the max?)

For Actions I'd choose the tax rate and the deduction amount - they depend on the bracket and on the number of dependents correspondingly.

Rules (=columns in the table) connect conditions and actions - for all the possible combinations of condition values you have a list of actions to perform. In your case these actions will be simply two numbers, which you will use in a tax formula.

(Frankly I don't see why you need a decision table in this case at all... I think, the tax formula with parameters, depending on income, will be enough)


来源: stackexchange

问:
Elasticsearch querying doesn't bring any hit
i'm trying to search elasticsearch with python the last events from the last 5 minutes. But I'm getting this answer with no hits. This is ES answer:

```<code>{"hits": {"hits": [], "total": 0, "max_score": null}, "_shards": {"successful": 45, "failed": 0, "total": 45}, "took": 13, "timed_out": false}
</code>```

And I know there are hits because I see them in Kibana.

This is my code:

```<code>from datetime import datetime
from elasticsearch import Elasticsearch, RequestsHttpConnection
import certifi
import datetime

def get_events():
    es = Elasticsearch([ELASTIC_SEARCH_ENDPOINT],use_ssl=True)
    from_date = datetime.datetime.now() - datetime.timedelta(minutes=15)
    to_date = datetime.datetime.now()
    query = {"query":
                {
                    "range":
                    {
                        "timestamp":
                        {
                            "gte": from_date,
                            "lte": to_date
                        }
                    }
                }
            }
    res = es.search(index="logstash-*", body=query)
    print '########### recent events ############'
    print res
    return res
</code>```

How can I fix this?

答:
Timestamp which is being stored in Elasticsearch is in the same timezone(UTC or your machine time) as from_date and to_date (which is being used in query).
This can be the reason why you are not seeing any result.</p>

ContentLicense: CC BY-SA 3.0

Body:
i'm trying to search elasticsearch with python the last events from the last 5 minutes. But I'm getting this answer with no hits. This is ES answer:

{"hits": {"hits": [], "total": 0, "max_score": null}, "_shards": {"successful": 45, "failed": 0, "total": 45}, "took": 13, "timed_out": false}

And I know there are hits because I see them in Kibana.

This is my code:

from datetime import datetime
from elasticsearch import Elasticsearch, RequestsHttpConnection
import certifi
import datetime

def get_events():
    es = Elasticsearch([ELASTIC_SEARCH_ENDPOINT],use_ssl=True)
    from_date = datetime.datetime.now() - datetime.timedelta(minutes=15)
    to_date = datetime.datetime.now()
    query = {"query":
                {
                    "range":
                    {
                        "timestamp":
                        {
                            "gte": from_date,
                            "lte": to_date
                        }
                    }
                }
            }
    res = es.search(index="logstash-*", body=query)
    print '########### recent events ############'
    print res
    return res

How can I fix this?


问:
axis.break does not move with axis R
I want to plot the vector 4:10 but from 0 to 10. I don't like the large gap in produces, and I want to create my own style of plot, so I write the code:

```<code>plot(4:10,axes=FALSE,ylim=c(2,10),xlim=c(0,8))
axis(1,pos=2)
axis(2,pos=0,at=seq(2,10,2),labels=c('0','4','6','8','10'))
</code>```

In order to not mislead the audience, I want to put in an axis break using axis.break() from plotrix. Unfortunately, when I add

```<code>axis.break(2,2.5)
</code>```

on my plot, I don't get the break where my axis is but where it would be if I used the default axis. How do I get axisbreak() to move with my axis? Or else, how do I put an axis break where I want it?

Title: axis.break does not move with axis R

Body:
I want to plot the vector 4:10 but from 0 to 10. I don't like the large gap in produces, and I want to create my own style of plot, so I write the code:

plot(4:10,axes=FALSE,ylim=c(2,10),xlim=c(0,8))
axis(1,pos=2)
axis(2,pos=0,at=seq(2,10,2),labels=c('0','4','6','8','10'))

In order to not mislead the audience, I want to put in an axis break using axis.break() from plotrix. Unfortunately, when I add

axis.break(2,2.5)

on my plot, I don't get the break where my axis is but where it would be if I used the default axis. How do I get axisbreak() to move with my axis? Or else, how do I put an axis break where I want it?

Body:
Add pos=0 to your axis.break:

plot(4:10,axes=FALSE,ylim=c(2,10),xlim=c(0,8))
axis(1,pos=2)
axis(2,pos=0,at=seq(2,10,2),labels=c('0','4','6','8','10'))
axis.break(2,2.5,pos=0)


问:
How to delete iOS runtime?
I've downloaded and installed iOS 8.4 Simulator from here Xcode > Preferences > Components. And now i don't need it anymore. How can i delete this runtime?

答:
You can find them in:

/Library/Developer/CoreSimulator/Profiles/Runtimes

Also restart Xcode when removing.

Title: How to delete iOS runtime?


问:
How to detect an "on scroll" event using angularJs & Ionic Framework
I come from a JQuery background and don't know if this is possible or not in AngularJS.

I am working on a project using Ionic framework & AngularJS

I am trying to capture the "on scrolling" event using angular.

Currently I use the following HTML to create a list of 20 items and the following code outputs the "test" string on the console log on page load. But when I scroll up or down the list the event doesn't seem to fire again.

I've been researching but I can't seem to come across a way to get the "on scroll event" after the page has been loaded.  At least directive doesn't get call when the user is interacting with the list, so I think this is the wrong approach.

How can I capture that event in angular? Is it possible?

HTML

```<code><ion-content>
      <div class="list" >
        <div class="item" ng-repeat="item in data.items" when-scrolled="loadMore()" >Item {{item}}</div>
      </div>
      </ion-content>
</code>```

JS

```<code>angular.module('starter.controllers', ["ionic"])
.controller('AppCtrl', function($scope,$ionicScrollDelegate) {

  $scope.myTitle = 'Template';

  $scope.data = {
    items : [],
    title : ''
  };

  for(var i = 0; i < 20; i++) {
    $scope.data.items.push(i);
  }
})
.directive('whenScrolled', function () {
    return function(scope, element, attrs) {
        console.log("test");
    };
});
</code>```

答:
we can use on-scroll or on-scroll-complete events on content then we need to call a function in the controller like below

```<code><ion-view view-title="Wall">
    <ion-content **on-scroll-complete="checkScroll()"**>
        <div class="list" ng-repeat="w in data.wallList">
        </div>
    </ion-content>
</ion-view>
</code>```

Complete tutorial is given here http://freakyjolly.com/detect-ionic-view-page-bottom-load-infinite-data/

Body:
I come from a JQuery background and don't know if this is possible or not in AngularJS.

I am working on a project using Ionic framework & AngularJS

I am trying to capture the "on scrolling" event using angular.

Currently I use the following HTML to create a list of 20 items and the following code outputs the "test" string on the console log on page load. But when I scroll up or down the list the event doesn't seem to fire again.

I've been researching but I can't seem to come across a way to get the "on scroll event" after the page has been loaded.  At least directive doesn't get call when the user is interacting with the list, so I think this is the wrong approach.

How can I capture that event in angular? Is it possible?

HTML

<ion-content>

Item {{item}}

      </ion-content>

JS

angular.module('starter.controllers', ["ionic"])
.controller('AppCtrl', function($scope,$ionicScrollDelegate) {

  $scope.myTitle = 'Template';

  $scope.data = {
    items : [],
    title : ''
  };

  for(var i = 0; i < 20; i++) {
    $scope.data.items.push(i);
  }
})
.directive('whenScrolled', function () {
    return function(scope, element, attrs) {
        console.log("test");
    };
});

Body:
we can use on-scroll or on-scroll-complete events on content then we need to call a function in the controller like below

<ion-view view-title="Wall">
    <ion-content **on-scroll-complete="checkScroll()"**>
        <div class="list" ng-repeat="w in data.wallList">
        </div>
    </ion-content>
</ion-view>

Complete tutorial is given here http://freakyjolly.com/detect-ionic-view-page-bottom-load-infinite-data/


问:
Angular 2 *ngFor causing bootstrap 4 column content to be too skinny
I have a results div that displays search results. The results are in bootstrap columns. However, the columns appear to have a heap of padding or margin, causing my results to be super skinny. If I take out the *ngFor and instead hardcode each result, it displays correctly.

Here is the div that iterates over a list of results, creating a result to display for each result:

```<code><div id="results" class="text-uppercase">
    <div id="up-button-row" class="row">
        <div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-xl-4
            offset-xl-4">
            <button id="up-button" class="m-x-auto" md-fab [disableRipple]="true" (click)="scrollUp()"></button>
        </div>
    </div>
    <div class="row" *ngIf="noResults">
        <div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-xl-4
            offset-xl-4">
            <h2 class="m-x-auto">No vegan stuff found :-(</h2>
        </div>
    </div>
    <div class="row" *ngIf="!noResults">
        <div *ngFor="let result of results">
            <result [result]="result"></result>
        </div>
    </div>
</div>
</code>```

this is the bit that holds the search results:

```<code><div class="row" *ngIf="!noResults">
    <div *ngFor="let result of results">
        <result [result]="result"></result>
    </div>
</div>
</code>```

Each search result is a component called result.component. Here is the template for that:

```<code><div class="col-sm-6 col-md-4 col-xl-3">
   <div class="product-item scale-on-hover">
      <div [ngStyle]="{background: result.image}" id="image"></div>
      <div id="info">
         <h6 id="brand" class="medium-text">{{result.brand}}</h6>
         <h6 id="name" class="medium-text">{{result.name}}</h6>
      </div>
   </div>
</div>
</code>```

For some reason, the results are super skinny, cutting out most of the content in the result.

Here is an image of what I mean:

So that is hovering over the actual result (which I am calling a product item).

Here is hovering over the bootstrap column:

So the column seems to have a heap of padding or margin.

Here is the output styling of the column copy and pasted from the styles tab of the console in Google Chrome:

```<code>element.style {
}
@media (min-width: 1200px)
.col-xl-3 {
    -webkit-box-flex: 0;
    -webkit-flex: 0 0 25%;
    -ms-flex: 0 0 25%;
    flex: 0 0 25%;
    max-width: 25%;
}
@media (min-width: 768px)
.col-md-4 {
    -webkit-box-flex: 0;
    -webkit-flex: 0 0 33.333333%;
    -ms-flex: 0 0 33.333333%;
    flex: 0 0 33.333333%;
    max-width: 33.333333%;
}

@media (min-width: 544px)
.col-sm-6 {
    -webkit-box-flex: 0;
    -webkit-flex: 0 0 50%;
    -ms-flex: 0 0 50%;
    flex: 0 0 50%;
    max-width: 50%;
}
.col-xs-1, .col-xs-2, .col-xs-3, .col-xs-4, .col-xs-5, .col-xs-6, .col-xs-7, .col-xs-8, .col-xs-9, .col-xs-10, .col-xs-11, .col-xs-12, .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12, .col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12, .col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12, .col-xl-1, .col-xl-2, .col-xl-3, .col-xl-4, .col-xl-5, .col-xl-6, .col-xl-7, .col-xl-8, .col-xl-9, .col-xl-10, .col-xl-11, .col-xl-12 {
    position: relative;
    min-height: 1px;
    padding-right: 15px;
    padding-left: 15px;
    width: 100%;
}
*, *::before, *::after {
    -webkit-box-sizing: inherit;
    box-sizing: inherit;
}
user agent stylesheet
div {
    display: block;
}
Inherited from div#results.text-uppercase
.text-uppercase {
    text-transform: uppercase !important;
}
Inherited from body
body {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
    font-size: 1rem;
    line-height: 1.5;
    color: #373a3c;
    background-color: #fff;
}
Inherited from html
html {
    font-size: 16px;
    -ms-overflow-style: scrollbar;
    -webkit-tap-highlight-color: transparent;
}
html {
    font-family: sans-serif;
    -ms-text-size-adjust: 100%;
    -webkit-text-size-adjust: 100%;
}
Pseudo ::before element
*, *::before, *::after {
    -webkit-box-sizing: inherit;
    box-sizing: inherit;
}
Pseudo ::after element
*, *::before, *::after {
    -webkit-box-sizing: inherit;
    box-sizing: inherit;
}
</code>```

Why are the results so skinny? What is causing the margin or padding in the bootstrap columns? The default width is 100%. I want the width of each result to be 100% of the column width. I cannot set a static width. I need them to scale with the bootstrap columns.

Here is my css for results:

```<code>#results {
  overflow-y: auto;
  overflow-x: hidden;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding-bottom: 50px;
  padding-top: 10px; }

h1 {
  margin-left: 25px;
  color: #ff8282; }

h2 {
  color: #ff8282;
  text-align: center; }

button {
  display: inherit;
  background: #00BFA5 url("../images/up-arrow.png") center no-repeat;
  background-size: 40%;
  position: fixed;
  top: 60px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 9999; }

#up-button-row {
  padding-bottom: 40px; }
</code>```

Here is my css for result:

```<code>#image {
  height: 160px;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  color: white;
  background: center no-repeat;
  background-size: cover;
  vertical-align: bottom; }

#info {
  height: 110px;
  padding: 10px;
  background: #fc4747; }

#brand {
  text-transform: uppercase;
  color: white;
  margin-top: 0;
  margin-bottom: 5px; }

#name {
  text-transform: uppercase;
  color: white;
  margin-bottom: 5px;
  display: inline; }

div.product-item.scale-on-hover:hover {
  transform: scale(1.15); }

div.product-item {
  border: 5px solid brand-red;
  border-radius: 15px;
  height: 240px;
  overflow: hidden;
  cursor: pointer; }
</code>```

edit: when I change the bootstrap column to col-xl-12 it looks like this:

So weird. col-xl-12 should make the column take up the whole width of the screen as I'm on an xl size screen.

It is something to do with the bootstrap row. Because I have 10 results, they do not all fit on one row. However I thought bootstrap simply pushes content down to a new row if content goes over the allotted columns.

If I take out class="row" I get this:

If I hardcode the results into the results template like this instead of using *ngfor, it works!! But i need to iterate over the list rather than hardcode :(

```<code><div id="results" class="text-uppercase">
    <div id="up-button-row" class="row">
        <div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-xl-4
            offset-xl-4">
            <button id="up-button" class="m-x-auto" md-fab [disableRipple]="true" (click)="scrollUp()"></button>
        </div>
    </div>
    <div class="row" *ngIf="noResults">
        <div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-xl-4
            offset-xl-4">
            <h2 class="m-x-auto">No vegan stuff found :-(</h2>
        </div>
    </div>
    <div class="row" *ngIf="!noResults">
        <!--<div *ngFor="let result of results">
            <result [result]="result"></result>
        </div>-->
        <div class="col-sm-6 col-md-4 col-xl-3">
   <div class="product-item scale-on-hover">
      <div  id="image"></div>
      <div id="info">
         <h6 id="brand" class="medium-text">result.brand</h6>
         <h6 id="name" class="medium-text">result.name</h6>
      </div>
   </div>
</div>
<div class="col-sm-6 col-md-4 col-xl-3">
   <div class="product-item scale-on-hover">
      <div  id="image"></div>
      <div id="info">
         <h6 id="brand" class="medium-text">result.brand</h6>
         <h6 id="name" class="medium-text">result.name</h6>
      </div>
   </div>
</div>
<div class="col-sm-6 col-md-4 col-xl-3">
   <div class="product-item scale-on-hover">
      <div  id="image"></div>
      <div id="info">
         <h6 id="brand" class="medium-text">result.brand</h6>
         <h6 id="name" class="medium-text">result.name</h6>
      </div>
   </div>
</div>
<div class="col-sm-6 col-md-4 col-xl-3">
   <div class="product-item scale-on-hover">
      <div  id="image"></div>
      <div id="info">
         <h6 id="brand" class="medium-text">result.brand</h6>
         <h6 id="name" class="medium-text">result.name</h6>
      </div>
   </div>
</div>
<div class="col-sm-6 col-md-4 col-xl-3">
   <div class="product-item scale-on-hover">
      <div  id="image"></div>
      <div id="info">
         <h6 id="brand" class="medium-text">result.brand</h6>
         <h6 id="name" class="medium-text">result.name</h6>
      </div>
   </div>
</div>
<div class="col-sm-6 col-md-4 col-xl-3">
   <div class="product-item scale-on-hover">
      <div  id="image"></div>
      <div id="info">
         <h6 id="brand" class="medium-text">result.brand</h6>
         <h6 id="name" class="medium-text">result.name</h6>
      </div>
   </div>
</div>
<div class="col-sm-6 col-md-4 col-xl-3">
   <div class="product-item scale-on-hover">
      <div  id="image"></div>
      <div id="info">
         <h6 id="brand" class="medium-text">result.brand</h6>
         <h6 id="name" class="medium-text">result.name</h6>
      </div>
   </div>
</div>
<div class="col-sm-6 col-md-4 col-xl-3">
   <div class="product-item scale-on-hover">
      <div  id="image"></div>
      <div id="info">
         <h6 id="brand" class="medium-text">result.brand</h6>
         <h6 id="name" class="medium-text">result.name</h6>
      </div>
   </div>
</div>
<div class="col-sm-6 col-md-4 col-xl-3">
   <div class="product-item scale-on-hover">
      <div  id="image"></div>
      <div id="info">
         <h6 id="brand" class="medium-text">result.brand</h6>
         <h6 id="name" class="medium-text">result.name</h6>
      </div>
   </div>
</div>
<div class="col-sm-6 col-md-4 col-xl-3">
   <div class="product-item scale-on-hover">
      <div  id="image"></div>
      <div id="info">
         <h6 id="brand" class="medium-text">result.brand</h6>
         <h6 id="name" class="medium-text">result.name</h6>
      </div>
   </div>
</div>
    </div>
</div>
</code>```

result (never mind the image not being there - I just didnt add it):

I am open to workarounds such as not having a seperate component for the result, or trying to use something other than *ngFor to iterate the results collection. However the result will get more complex so ideally it should be a seperate component.

Here is a jsfiddle. It has console errors, however, it is only one component so if you can make an angular 2 jsfiddle with that exact component that doesn't have any console errors then we are in business: https://jsfiddle.net/n5pjgev6/89/ I started it from this one:  https://jsfiddle.net/langdonx/u7c89uuz/ Now I am not sure which version of angular 2 he used so that may be the issue. I cannot find the angular 2 cdn. He bootstraps the app with different syntax than rc5. However, my component doesnt really look like it has anything that is rc5 specific so I wouldn't have thought it would matter.

答:
the below code worked for me. One more thing to note here - I forgot to include the bootstrap.css in the index.html file. Please check that as well</p>

```<code><div class="container">
<div *ngIf='projects && projects.length'>
    <div class="row">
    <div *ngFor='let project of projects'>
        <div class="col-md-3 col-sm-4 col-xs-6">
        <h4>{{project.by}}</h4>
        </div>
    </div>
    </div>
</div>
</div>
</code>```

Body:
I have a results div that displays search results. The results are in bootstrap columns. However, the columns appear to have a heap of padding or margin, causing my results to be super skinny. If I take out the *ngFor and instead hardcode each result, it displays correctly.

Here is the div that iterates over a list of results, creating a result to display for each result:

            <button id="up-button" class="m-x-auto" md-fab [disableRipple]="true" (click)="scrollUp()"></button>

No vegan stuff found :-(

            <result [result]="result"></result>

this is the bit that holds the search results:

        <result [result]="result"></result>

Each search result is a component called result.component. Here is the template for that:

{{result.brand}}

{{result.name}}

For some reason, the results are super skinny, cutting out most of the content in the result.

Here is an image of what I mean:

So that is hovering over the actual result (which I am calling a product item).

Here is hovering over the bootstrap column:

So the column seems to have a heap of padding or margin.

Here is the output styling of the column copy and pasted from the styles tab of the console in Google Chrome:

element.style {
}
@media (min-width: 1200px)
.col-xl-3 {
    -webkit-box-flex: 0;
    -webkit-flex: 0 0 25%;
    -ms-flex: 0 0 25%;
    flex: 0 0 25%;
    max-width: 25%;
}
@media (min-width: 768px)
.col-md-4 {
    -webkit-box-flex: 0;
    -webkit-flex: 0 0 33.333333%;
    -ms-flex: 0 0 33.333333%;
    flex: 0 0 33.333333%;
    max-width: 33.333333%;
}

@media (min-width: 544px)
.col-sm-6 {
    -webkit-box-flex: 0;
    -webkit-flex: 0 0 50%;
    -ms-flex: 0 0 50%;
    flex: 0 0 50%;
    max-width: 50%;
}
.col-xs-1, .col-xs-2, .col-xs-3, .col-xs-4, .col-xs-5, .col-xs-6, .col-xs-7, .col-xs-8, .col-xs-9, .col-xs-10, .col-xs-11, .col-xs-12, .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12, .col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12, .col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12, .col-xl-1, .col-xl-2, .col-xl-3, .col-xl-4, .col-xl-5, .col-xl-6, .col-xl-7, .col-xl-8, .col-xl-9, .col-xl-10, .col-xl-11, .col-xl-12 {
    position: relative;
    min-height: 1px;
    padding-right: 15px;
    padding-left: 15px;
    width: 100%;
}
*, *::before, *::after {
    -webkit-box-sizing: inherit;
    box-sizing: inherit;
}
user agent stylesheet
div {
    display: block;
}
Inherited from div#results.text-uppercase
.text-uppercase {
    text-transform: uppercase !important;
}
Inherited from body
body {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
    font-size: 1rem;
    line-height: 1.5;
    color: #373a3c;
    background-color: #fff;
}
Inherited from html
html {
    font-size: 16px;
    -ms-overflow-style: scrollbar;
    -webkit-tap-highlight-color: transparent;
}
html {
    font-family: sans-serif;
    -ms-text-size-adjust: 100%;
    -webkit-text-size-adjust: 100%;
}
Pseudo ::before element
*, *::before, *::after {
    -webkit-box-sizing: inherit;
    box-sizing: inherit;
}
Pseudo ::after element
*, *::before, *::after {
    -webkit-box-sizing: inherit;
    box-sizing: inherit;
}

Why are the results so skinny? What is causing the margin or padding in the bootstrap columns? The default width is 100%. I want the width of each result to be 100% of the column width. I cannot set a static width. I need them to scale with the bootstrap columns.

Here is my css for results:

#results {
  overflow-y: auto;
  overflow-x: hidden;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding-bottom: 50px;
  padding-top: 10px; }

h1 {
  margin-left: 25px;
  color: #ff8282; }

h2 {
  color: #ff8282;
  text-align: center; }

button {
  display: inherit;
  background: #00BFA5 url("../images/up-arrow.png") center no-repeat;
  background-size: 40%;
  position: fixed;
  top: 60px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 9999; }

#up-button-row {
  padding-bottom: 40px; }

Here is my css for result:

#image {
  height: 160px;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  color: white;
  background: center no-repeat;
  background-size: cover;
  vertical-align: bottom; }

#info {
  height: 110px;
  padding: 10px;
  background: #fc4747; }

#brand {
  text-transform: uppercase;
  color: white;
  margin-top: 0;
  margin-bottom: 5px; }

#name {
  text-transform: uppercase;
  color: white;
  margin-bottom: 5px;
  display: inline; }

div.product-item.scale-on-hover:hover {
  transform: scale(1.15); }

div.product-item {
  border: 5px solid brand-red;
  border-radius: 15px;
  height: 240px;
  overflow: hidden;
  cursor: pointer; }

edit: when I change the bootstrap column to col-xl-12 it looks like this:

So weird. col-xl-12 should make the column take up the whole width of the screen as I'm on an xl size screen.

It is something to do with the bootstrap row. Because I have 10 results, they do not all fit on one row. However I thought bootstrap simply pushes content down to a new row if content goes over the allotted columns.

If I take out class="row" I get this:

If I hardcode the results into the results template like this instead of using *ngfor, it works!! But i need to iterate over the list rather than hardcode :(

            <button id="up-button" class="m-x-auto" md-fab [disableRipple]="true" (click)="scrollUp()"></button>

No vegan stuff found :-(

result.brand

result.name

result.brand

result.name

result.brand

result.name

result.brand

result.name

result.brand

result.name

result.brand

result.name

result.brand

result.name

result.brand

result.name

result.brand

result.name

result.brand

result.name

result (never mind the image not being there - I just didnt add it):

I am open to workarounds such as not having a seperate component for the result, or trying to use something other than *ngFor to iterate the results collection. However the result will get more complex so ideally it should be a seperate component.

Here is a jsfiddle. It has console errors, however, it is only one component so if you can make an angular 2 jsfiddle with that exact component that doesn't have any console errors then we are in business: https://jsfiddle.net/n5pjgev6/89/ I started it from this one:  https://jsfiddle.net/langdonx/u7c89uuz/ Now I am not sure which version of angular 2 he used so that may be the issue. I cannot find the angular 2 cdn. He bootstraps the app with different syntax than rc5. However, my component doesnt really look like it has anything that is rc5 specific so I wouldn't have thought it would matter.

Body:
the below code worked for me. One more thing to note here - I forgot to include the bootstrap.css in the index.html file. Please check that as well

<div class="container">
<div *ngIf='projects && projects.length'>
    <div class="row">
    <div *ngFor='let project of projects'>
        <div class="col-md-3 col-sm-4 col-xs-6">
        <h4>{{project.by}}</h4>
        </div>
    </div>
    </div>
</div>
</div>


问:
Metro UI controls not showing on form
I have installed metro ui from nuGet package installer. Tools added in toolbox and also added reference. But when I drag a control and drop on form it does not show on form instead form components. someone please help</p>

答:
In the Manage Nuget Packages dialog, there are few versions of the Metroframework. download the one by Dennis Magno only. it will have a updated version 1.4.0.0 19/07/16.it works best.

Or else

you can install MetroModernUI by ,open Package Manager Console
Tools > NuGet Package Manager > Package Manager Console then type Install-Package MetroModernUI in there. now open your project folder and check this path \packages\MetroModernUI.1.4.0.0\lib\net\ .In there have 3 .dll files

MetroFramework.Design.dll

MetroFramework.dll

MetroFramework.Fonts.dll

add these 3 files to your project reference,hope this will be helped to you :)

Title: Metro UI controls not showing on form


问:
Ruby on rails - Change date format when importing csv to rails
I have a csv file to import to sqlite3 in ruby on rails. The csv file has a date column which is formatted as MM/DD/YYYY. The date in sqlite3 is formatted as DD/MM/YYYY. How can I convert to the same format without changing the csv file?</p>

答:
First of all, you're storing your dates in SQLite in the wrong format. From the fine SQLite manual:

2.2. Date and Time Datatype

SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values:

TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").

[...]

The recommended way of storing a date in SQLite would be in a text column using the ISO-8601 format (YYYY-MM-DD) so that you can use SQLite's functions for working with them and they'll compare/sort correctly.

The sensible thing to do is to parse the incoming dates use Date.strptime from the Ruby standard library:

```<code>date = Date.strptime(date_string_from_csv, '%m/%d/%Y')
</code>```

and then convert that to an ISO-8601 date string using the Date#iso8601 method:

```<code>date_for_sqlite = date.iso8601
</code>```

and then send date_for_sqlite into the database. As a bonus, any sane database will understand ISO-8601 formatted dates unambiguously so you shouldn't have to worry about this issue if you switch databases.

If you must use your non-standard DD/MM/YYYY format then use strftime:

```<code>date_for_sqlite = date.strftime('%d/%m/%Y')
</code>```

Body:
First of all, you're storing your dates in SQLite in the wrong format. From the fine SQLite manual:

2.2. Date and Time Datatype

SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values:

TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").

[...]

The recommended way of storing a date in SQLite would be in a text column using the ISO-8601 format (YYYY-MM-DD) so that you can use SQLite's functions for working with them and they'll compare/sort correctly.

The sensible thing to do is to parse the incoming dates use Date.strptime from the Ruby standard library:

date = Date.strptime(date_string_from_csv, '%m/%d/%Y')

and then convert that to an ISO-8601 date string using the Date#iso8601 method:

date_for_sqlite = date.iso8601

and then send date_for_sqlite into the database. As a bonus, any sane database will understand ISO-8601 formatted dates unambiguously so you shouldn't have to worry about this issue if you switch databases.

If you must use your non-standard DD/MM/YYYY format then use strftime:

date_for_sqlite = date.strftime('%d/%m/%Y')


问:
Dagger 2 modules depending on each other
I have a couple of classes that depend on each other, GamePresenter and GameManager.
I'm trying to inject them using constructor injection, but I still can't figure out how to make it work, since I got a dependency cycle error found.

GameFragment should inject the GamePresenter into the fragment, so the first would talk to the second, while GameManager would be injected into the GamePresenter.

GamePresenter is:

```<code>@Inject
GamePresenter(GameRepository gameRepository, GameManager gameManager, GameContract.View view) {
    DaggerGameManagerComponent.builder()
            .gameManagerModule(new GameManagerModule(this))
            .build()
            .inject(this);

    this.view = view;
    this.gameRepository = gameRepository;
    this.gameManager = gameManager;
}
</code>```

GamePresenterModule is:

```<code>@Module
public class GamePresenterModule {
    private final GameContract.View view;

    public GamePresenterModule(GameContract.View view) {
        this.view = view;
    }

    @Provides
    GameContract.View provideGameContractView() {
        return view;
    }
}
</code>```

GamePresenterComponent is:

```<code>@FragmentScoped
@Component(dependencies = RepositoryComponent.class, modules = GamePresenterModule.class)
public interface GamePresenterComponent {
    void inject(GameFragment gameFragment);
}
</code>```

GameManager is:

```<code>@Inject
public GameManager(GamePresenter gamePresenter, Game game) {
    this.gamePresenter = gamePresenter;
    this.game = game;
}
</code>```

GameManagerModule is:

```<code>@Module
public class GameManagerModule {
    private GamePresenter presenter;

    public GameManagerModule(GamePresenter presenter) {
        this.presenter = presenter;
    }

    @Provides
    GameManager provideGameManager(Game game) {
        return new GameManager(this.presenter, game);
    }

    @Provides
    Game provideGame() {
        return new Game();
    }
}
</code>```

GameManagerComponent is:

```<code>@FragmentScoped
@Component(dependencies = GamePresenterComponent.class, modules = GameManagerModule.class)
public interface GameManagerComponent {
    void inject(GamePresenter gamePresenter);
}
</code>```

and finally, GameFragment is:

```<code>@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);

    DaggerGamePresenterComponent.builder()
            .repositoryComponent(((GameApplication) getActivity().getApplication()).getRepositoryComponent())
            .gamePresenterModule(new GamePresenterModule(this))
            .build()
            .inject(this);
}
</code>```

Thanks a lot in advance!

答:
You should overthink your architecture when you have this kind of issues.

In this case I'd suggest to not inject the GameManager into the GamePresenter. Instead define an interface with whatever methods you need from GameManager, let the GameManager be implemented it and register it inside the constructor or provider.

Body:
I have a couple of classes that depend on each other, GamePresenter and GameManager.
I'm trying to inject them using constructor injection, but I still can't figure out how to make it work, since I got a dependency cycle error found.

GameFragment should inject the GamePresenter into the fragment, so the first would talk to the second, while GameManager would be injected into the GamePresenter.

GamePresenter is:

@Inject
GamePresenter(GameRepository gameRepository, GameManager gameManager, GameContract.View view) {
    DaggerGameManagerComponent.builder()
            .gameManagerModule(new GameManagerModule(this))
            .build()
            .inject(this);

    this.view = view;
    this.gameRepository = gameRepository;
    this.gameManager = gameManager;
}

GamePresenterModule is:

@Module
public class GamePresenterModule {
    private final GameContract.View view;

    public GamePresenterModule(GameContract.View view) {
        this.view = view;
    }

    @Provides
    GameContract.View provideGameContractView() {
        return view;
    }
}

GamePresenterComponent is:

@FragmentScoped
@Component(dependencies = RepositoryComponent.class, modules = GamePresenterModule.class)
public interface GamePresenterComponent {
    void inject(GameFragment gameFragment);
}

GameManager is:

@Inject
public GameManager(GamePresenter gamePresenter, Game game) {
    this.gamePresenter = gamePresenter;
    this.game = game;
}

GameManagerModule is:

@Module
public class GameManagerModule {
    private GamePresenter presenter;

    public GameManagerModule(GamePresenter presenter) {
        this.presenter = presenter;
    }

    @Provides
    GameManager provideGameManager(Game game) {
        return new GameManager(this.presenter, game);
    }

    @Provides
    Game provideGame() {
        return new Game();
    }
}

GameManagerComponent is:

@FragmentScoped
@Component(dependencies = GamePresenterComponent.class, modules = GameManagerModule.class)
public interface GameManagerComponent {
    void inject(GamePresenter gamePresenter);
}

and finally, GameFragment is:

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);

    DaggerGamePresenterComponent.builder()
            .repositoryComponent(((GameApplication) getActivity().getApplication()).getRepositoryComponent())
            .gamePresenterModule(new GamePresenterModule(this))
            .build()
            .inject(this);
}

Thanks a lot in advance!


问:
HTML upload directly image
I have a page that will allow users to upload their picture that will act as their profile picture. I have this code:

```<code><form method = "post" action = "" enctype="multipart/form-data">
    <input type = "hidden" name = "size" value = "1000000">
    <input type = "file" name = "image">
    <input type = "submit" name = "upload" value = "Upload Image">
</form>
</code>```

My php:

```<code>if(isset($_POST['upload'])) {
    $target = "profileimgs/".$key.basename($_FILES['image']['name']);

    $image = $key.basename($_FILES['image']['name']);

    $sql = "UPDATE users SET img = '$image' WHERE idnumber = $idnumber";
    mysqli_query($con,$sql);

    if(move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
        header("Location:home.php");
    } else {
        header("Location:error_uploading.php");
    }
}
</code>```

By choosing the picture, the only preview that will be shown is the picture's filename. I want to add a "preview" of their chosen image right after they chose the image. Just like when you upload a profile picture on facebook - you choose a picture from your computer, then when you click select picture it automatically upload your picture to the page and gives you a preview to that picture wihout having to click so many buttons.

Is there something I can do to achieve something this?

答: You can use the Image upload widgets of jasny plugin, there is a beautiful uploader

Title: HTML upload directly image

Body:
I have a page that will allow users to upload their picture that will act as their profile picture. I have this code:

<form method = "post" action = "" enctype="multipart/form-data">
    <input type = "hidden" name = "size" value = "1000000">
    <input type = "file" name = "image">
    <input type = "submit" name = "upload" value = "Upload Image">
</form>

My php:

if(isset($_POST['upload'])) {
    $target = "profileimgs/".$key.basename($_FILES['image']['name']);

    $image = $key.basename($_FILES['image']['name']);

    $sql = "UPDATE users SET img = '$image' WHERE idnumber = $idnumber";
    mysqli_query($con,$sql);

    if(move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
        header("Location:home.php");
    } else {
        header("Location:error_uploading.php");
    }
}

By choosing the picture, the only preview that will be shown is the picture's filename. I want to add a "preview" of their chosen image right after they chose the image. Just like when you upload a profile picture on facebook - you choose a picture from your computer, then when you click select picture it automatically upload your picture to the page and gives you a preview to that picture wihout having to click so many buttons.

Is there something I can do to achieve something this?


问:
Angularjs Mocha test $q promises without $rootScope.$apply
I have this service:

```<code>    angular.module('domeeApp')
        .factory('streamWidget', streamWidgetFactory);

    function streamWidgetFactory($q) {
        return {
            loadContent: function() {
                return $q(function(resolve, reject) {
                    resolve('test');
                })
            }
        }
    }
</code>```

I'm testing it with karma/mocha/chai:

```<code>describe('streamWidget', function() {
    beforeEach(module('domeeApp'));
    var streamWidget;
    var $timeout;

    beforeEach(inject(function(_$timeout_, _streamWidget_) {
        streamWidget = _streamWidget_;
        $timeout = _$timeout_;
    }));

    it('should load new content', function(done) {
        streamWidget.loadContent()
        .then(function(res) {
            expect(res).to.equal('test');
            done();
        })
        .catch(function(){})
        $timeout.flush();
    });
});
</code>```

Since $q promises doesn't work well with mocha i'm following this answer, which says to add $timeout.flush() to force the .then method of the promise to be executed.

The problem is, after calling .flush(), all my app wakes up and i start to get this errors from angular-mocks:

Error: Unexpected request: GET /partials/page/view/index.

I know about $httpBackend, but it would be insane to mock ALL the requests my app is making on startup.

Is there a way to make $q promises work with mocha without calling $timeout.flush() or $rootScope.$apply()?

答:
Here's an alternative strategy that we use because we never actually need $httpBackend, but it sometimes (randomly) fails making requests for templates used by directives (even though those templates are available in $templateCache):

```<code>beforeEach(function() {
  module('app', function($provide) {
    // This is using jasmine, but the idea is the same with mocha.
    // Basically just replace $httpBackend with a function that does nothing.
    $provide.constant('$httpBackend', jasmine.createSpy('$httpBackend'));
  });
});
</code>```

Of course, if you actually use $httpBackend in other cases, then this won't work, as you'll need it to mock response objects.

Body:
I have this service:

    angular.module('domeeApp')
        .factory('streamWidget', streamWidgetFactory);

    function streamWidgetFactory($q) {
        return {
            loadContent: function() {
                return $q(function(resolve, reject) {
                    resolve('test');
                })
            }
        }
    }

I'm testing it with karma/mocha/chai:

describe('streamWidget', function() {
    beforeEach(module('domeeApp'));
    var streamWidget;
    var $timeout;

    beforeEach(inject(function(_$timeout_, _streamWidget_) {
        streamWidget = _streamWidget_;
        $timeout = _$timeout_;
    }));

    it('should load new content', function(done) {
        streamWidget.loadContent()
        .then(function(res) {
            expect(res).to.equal('test');
            done();
        })
        .catch(function(){})
        $timeout.flush();
    });
});

Since $q promises doesn't work well with mocha i'm following this answer, which says to add $timeout.flush() to force the .then method of the promise to be executed.

The problem is, after calling .flush(), all my app wakes up and i start to get this errors from angular-mocks:

Error: Unexpected request: GET /partials/page/view/index.

I know about $httpBackend, but it would be insane to mock ALL the requests my app is making on startup.

Is there a way to make $q promises work with mocha without calling $timeout.flush() or $rootScope.$apply()?

Body:
Here's an alternative strategy that we use because we never actually need $httpBackend, but it sometimes (randomly) fails making requests for templates used by directives (even though those templates are available in $templateCache):

beforeEach(function() {
  module('app', function($provide) {
    // This is using jasmine, but the idea is the same with mocha.
    // Basically just replace $httpBackend with a function that does nothing.
    $provide.constant('$httpBackend', jasmine.createSpy('$httpBackend'));
  });
});

Of course, if you actually use $httpBackend in other cases, then this won't work, as you'll need it to mock response objects.


问:
How to write if and else statement more elegantly in Swift
I'm having a bit of a brain fart in Swift and I know this code could be written better. Basically what it is, I have two images and I check if a value is over 3 to show an image and hide the other.
currently I have it like this

```<code>let greaterThanThree = value > 3
image1.isHidden = greaterThanThree
image2.isHidden = !greaterThanThree
</code>```

But I feel like there is a more elegant way to write this.

答:
I'd write it like this:

```<code>image1.isHidden = value > 3
image2.isHidden = !image1.isHidden
</code>```

Anything shorter than that is just code golfing.

Body:
I'm having a bit of a brain fart in Swift and I know this code could be written better. Basically what it is, I have two images and I check if a value is over 3 to show an image and hide the other.
currently I have it like this

let greaterThanThree = value > 3
image1.isHidden = greaterThanThree
image2.isHidden = !greaterThanThree

But I feel like there is a more elegant way to write this.

Body:
I'd write it like this:

image1.isHidden = value > 3
image2.isHidden = !image1.isHidden

Anything shorter than that is just code golfing.


问:
Can memory from /dev/shm be cached in the CPU cache?
When memory is frequently accessed, it's put onto the CPU cache (L1, L2, L3). However, is the same true of memory that is mmap'd to a file living in /dev/shm? I ask because I wanted to know if having it backed to a file in /dev/shm would bypass any kind of caching by the CPU, and rather letting it fall through to a cache miss.</p>

答: Yes they'll be cached in the core's L1/L2/L3 caches unless for instance the pages are marked uncached (e.g., by configuring the PAT accordingly) or the data is accessed via streaming reads/writes.</p>


问:
How to get column name in tab separated dataframe?
I have a tab separated file which I extracted in pandas dataframe as below:

```<code>import pandas as pd
data1 = pd.DataFrame.from_csv(r"C:\Users\Ashish\Documents\indeed_ml_dataset\train.tsv", sep="\t")
</code>```

data1

Here is how the data1 looks like:

Now, I want to view the column name tags. I don't know whether I should call it a column or not, but I have tried accessing it using the norm:

```<code>data2=data1[['tags']]
</code>```

but it errors out. I have tried several other things as well using index and loc, but all of them fails. Any suggestions?

答:
To fix this you'll need to remove description from the index by resetting. Try the below:

```<code>data2 = data1.reset_index()
data2['tags']
</code>```

You'll then be able to select by "tags".

Body:
I have a tab separated file which I extracted in pandas dataframe as below:

import pandas as pd
data1 = pd.DataFrame.from_csv(r"C:\Users\Ashish\Documents\indeed_ml_dataset\train.tsv", sep="\t")

data1

Here is how the data1 looks like:

Now, I want to view the column name tags. I don't know whether I should call it a column or not, but I have tried accessing it using the norm:

data2=data1[['tags']]

but it errors out. I have tried several other things as well using index and loc, but all of them fails. Any suggestions?

Body:
To fix this you'll need to remove description from the index by resetting. Try the below:

data2 = data1.reset_index()
data2['tags']

You'll then be able to select by "tags".


问:
Objects as Map keys without Hashcode and equals
```<code>public class Contact
{
    int i;
    String name;
    public Contact(int iVal, String nameVal)
    {
        i = iVal;
        name = nameVal;
    }
}

public class MultiMap
{
    public static void main (String args[])
    {
        java.util.HashMap m = new java.util.HashMap();
                Contact m1 = new Contact(1, "name");
        Contact m2 = new Contact(1, "name");
        m.put(m1, "first");
        m.put(m2, "second");
        System.out.println(m.get(m1));
        System.out.println(m.get(m2));
    }
}
</code>```

Output is:

```<code>first
second
</code>```

How does this "get" method behave ? As both m1 and M2 have same values and I have not overridden hashcode(), will Object class's equals() method be called ?

Is this correct ?

There is no hashcode method so there is no way for the JVM to see if objects m1 and m2 contain different values

There is no equals method overridden so Object class's equals() is invoked and as both objects are different the code above works fine without m2 replacing m1's value.

答:
By default Object class override the hashCode and equals method. This is the reason you get the desired output.

If you do not override equals and hashcode method, JVM checks it behind the scene. As m1 and m2 both are different object instances, equals method always return false.
i.e :

1. For equals:

m1.equals(m2) //return false because both are different instances.

2. For hashCode: //See the source code inside HashMap.java

HashMap internally uses to rehash the key before putting in hashMap. See bellow.

```<code>[![Source code of put method][1]][1]
public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}
</code>```

for the rehash, hashMap has it's own static hash method:

```<code>[![Source code of hash method][1]][1]
static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
</code>```

Internally, both equals and hashCode method work in this way, that is why you get both the values stored in the HashMap.

Hope this helps :)

Body:
public class Contact
{
    int i;
    String name;
    public Contact(int iVal, String nameVal)
    {
        i = iVal;
        name = nameVal;
    }
}

public class MultiMap
{
    public static void main (String args[])
    {
        java.util.HashMap m = new java.util.HashMap();
                Contact m1 = new Contact(1, "name");
        Contact m2 = new Contact(1, "name");
        m.put(m1, "first");
        m.put(m2, "second");
        System.out.println(m.get(m1));
        System.out.println(m.get(m2));
    }
}

Output is:

first
second

How does this "get" method behave ? As both m1 and M2 have same values and I have not overridden hashcode(), will Object class's equals() method be called ?

Is this correct ?

There is no hashcode method so there is no way for the JVM to see if objects m1 and m2 contain different values

There is no equals method overridden so Object class's equals() is invoked and as both objects are different the code above works fine without m2 replacing m1's value.

Body:
By default Object class override the hashCode and equals method. This is the reason you get the desired output.

If you do not override equals and hashcode method, JVM checks it behind the scene. As m1 and m2 both are different object instances, equals method always return false.
i.e :

1. For equals:

m1.equals(m2) //return false because both are different instances.

2. For hashCode: //See the source code inside HashMap.java

HashMap internally uses to rehash the key before putting in hashMap. See bellow.

[![Source code of put method][1]][1]
public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}

for the rehash, hashMap has it's own static hash method:

[![Source code of hash method][1]][1]
static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

Internally, both equals and hashCode method work in this way, that is why you get both the values stored in the HashMap.

Hope this helps :)


问:
Export maven project from eclipse
Is there a way to export an entire Maven project from eclipse? I don't just want a jar file, I'm looking for a way that another person can download the entire project with the dependencies and all that already set up the same way that I have it. </p>

答: If you export it as war file then you will not get back maven file. So it is better to just copy the project send it to other person, he/she just need to import as an exist project from path.</p>

Title: Export maven project from eclipse


问:
Linking ViewController and Scene to Show Ads (SpriteKit)
So I was following this tutorial to show a banner ad http://insaneplatypusgames.com/2016/03/29/adding-admob-banners-to-spritekit-games/

And the code it provided was pretty straightforward. I am looking to add an ad at the beginning of my app, at the Main Menu.

I get to the last step,

```<code>// Linking view controller and scene to show ads
scene.ViewController = self
</code>```

and I get an error:

Value of type MainMenuScene has no member 'ViewController' - Did you
  mean inutViewController? And I didn't mean inputViewController.

You might need more information but I am not sure what so just as I can include it.

答:
scene.viewController = self not scene.ViewController = self

viewController is member variable having type GameViewController in your GameScene.(according to your tutorial)

Body:
So I was following this tutorial to show a banner ad http://insaneplatypusgames.com/2016/03/29/adding-admob-banners-to-spritekit-games/

And the code it provided was pretty straightforward. I am looking to add an ad at the beginning of my app, at the Main Menu.

I get to the last step,

// Linking view controller and scene to show ads
scene.ViewController = self

and I get an error:

Value of type MainMenuScene has no member 'ViewController' - Did you
  mean inutViewController? And I didn't mean inputViewController.

You might need more information but I am not sure what so just as I can include it.


问:
My photo application
I have a problem. I created a camera app. This app is working like this:
first you should take a picture and after you need to grant a permission and this picture will be set onto an ImageView. It's working, but if you click to close the camera, this app stops working. I don't know what should I do?

Code: https://gyazo.com/50453035c08f194fe9957971db142bef

Problem: https://gyazo.com/4df726655e52351f440445a701374b72

答:
you should check resultCode in your OnActivityResult().

The reason is simple when you click cancel button the data is null but since you don't check the resultCode your app will get null pointer

Title: My photo application


问:
SimpleCursorAdapter within a ScrollView
I'm having  abit of an issue and i'm not too sure how to go about solving it.

Essentially i have an activity which has a base xml layout of ScrollView and i want this activity to list some results from a Cursor. So i thought i'd use SimpleCursorAdapter... however when i got it all set up it appears that the ListView that the SimpleCursorAdapter goes into doesn't play nice being within another scrollable layout element.

I've sorta got it working programmically but i'd much rather use a ListAdapter as it will make each list entry look like a button and keep it inline with the design of the rest of the application and can handle the ids of each item and where to send the user upon clicking.

So my question is this: is there anyway to either make ListView show all the items such that it never needs to scroll, or can i change the ListView to something like a LinearLayout?

I hope that makes sense!
Any help / insight / ideas are welcome!
Cheers!

答:
It doesn't really make sense to have a ListView inside a ScrollView at all. The ListView implements it's own scroll function so it should not be used in conjunction with a ScrollView anyway.

You should rethink your UI design.

ContentLicense: CC BY-SA 2.5

Title: SimpleCursorAdapter within a ScrollView


问:
Multiple string append together with index
I have multiple string required original string to append different strings. Both of origin string and append string contains 1 int variable Based on my knowledge, both of following code are working but what is the best way to do it or if there is a better way to do it?
or is there any way I can write something like

```<code>newstrg = '{}{}'.format(org%OrgInt, appd%appdInt)
</code>```

first method

```<code>org = "org__%s"
appd = "appd__%s"
orgInt = 1
appdInt = 7
newstrg = org % orgInt + appd % appdInt
print(newstrg)
org__1appd__7
</code>```

Second method

```<code>org = "org__{}"
appd = "appd__{}"
orgInt = 1
appdInt = 7
newstrg = (org + appd).format(orgInt, appdInt)
org__1appd__7
</code>```

答:
What about "org__{org}appd{appd}".format (org =1, appd= 7) or similar?  Your format string can be arbitrary, and it's cleaner to use named placeholders.

edit

if the tokens and the numbers are variable, feed them in as a list of token-value pairs:

```<code>tokenpairs = [('org',1), ('appd', 7)] # etc
unit = lambda t,v : "{0}__{1}".format(t ,v)
renamed = "".join([unit (t, v) for t, v in tokenpairs])
</code>```

Body:
I have multiple string required original string to append different strings. Both of origin string and append string contains 1 int variable Based on my knowledge, both of following code are working but what is the best way to do it or if there is a better way to do it?
or is there any way I can write something like

newstrg = '{}{}'.format(org%OrgInt, appd%appdInt)

first method

org = "org__%s"
appd = "appd__%s"
orgInt = 1
appdInt = 7
newstrg = org % orgInt + appd % appdInt
print(newstrg)
org__1appd__7

Second method

org = "org__{}"
appd = "appd__{}"
orgInt = 1
appdInt = 7
newstrg = (org + appd).format(orgInt, appdInt)
org__1appd__7

Body:
What about "org__{org}appd{appd}".format (org =1, appd= 7) or similar?  Your format string can be arbitrary, and it's cleaner to use named placeholders.

edit

if the tokens and the numbers are variable, feed them in as a list of token-value pairs:

tokenpairs = [('org',1), ('appd', 7)] # etc
unit = lambda t,v : "{0}__{1}".format(t ,v)
renamed = "".join([unit (t, v) for t, v in tokenpairs])


问:
How to parse key:value pair on JSON-like string with RegEx on JavaScript?
I'm struggling to parse a key:value pair in a JSON-like string. I know people will automatically say "Use JSON.parse() for this!" and I absolutely agree. The problem is that I'm not dealing with JSON strings, but JSON-like strings.

At least my attempts of parsing these strings with JSON.parse have failed (I've tried to sanitize the string so that JSON.parse doesn't complain about malformed strings)

The problem I have is that the JSON-like string sometimes is truncated and some other times is not. What is guaranteed to happen is that the key publicProfileUrl will be in the text, all the time (or at least that's been consistent with observations) and I need to parse its value:

For example, this is an example of the string:

```<code>%%"fullName":"Eduardo Saverin",
"contactInfo":{
"publicProfileUrl":"https://sg.linkedin.com/in/saverin",
"twitterAccounts":["esaverin"],
"websites":[]},
"industry":"Internet",%%
</code>```

all I'm interested in is parsing the value of publicProfileUrl.

This is my latest attempt at doing it:

```<code>\"publicProfileUrl\":\"(.*)\",
</code>```

but it is matching all the way to the last comma (I added line breaks for formatting purposes only, but the original string doesn't have any line breaks).

Here's the original string:

```<code>%%"fullName":"Eduardo Saverin","contactInfo":{"publicProfileUrl":"https://sg.linkedin.com/in/saverin","twitterAccounts":["esaverin"],"websites":[]},"industry":"Internet",%%
</code>```

答:
For the group matching add ? which means as little as possible

```<code>\"publicProfileUrl\":\"(.*?)\",
</code>```

Body:
I'm struggling to parse a key:value pair in a JSON-like string. I know people will automatically say "Use JSON.parse() for this!" and I absolutely agree. The problem is that I'm not dealing with JSON strings, but JSON-like strings.

At least my attempts of parsing these strings with JSON.parse have failed (I've tried to sanitize the string so that JSON.parse doesn't complain about malformed strings)

The problem I have is that the JSON-like string sometimes is truncated and some other times is not. What is guaranteed to happen is that the key publicProfileUrl will be in the text, all the time (or at least that's been consistent with observations) and I need to parse its value:

For example, this is an example of the string:

%%"fullName":"Eduardo Saverin",
"contactInfo":{
"publicProfileUrl":"https://sg.linkedin.com/in/saverin",
"twitterAccounts":["esaverin"],
"websites":[]},
"industry":"Internet",%%

all I'm interested in is parsing the value of publicProfileUrl.

This is my latest attempt at doing it:

\"publicProfileUrl\":\"(.*)\",

but it is matching all the way to the last comma (I added line breaks for formatting purposes only, but the original string doesn't have any line breaks).

Here's the original string:

%%"fullName":"Eduardo Saverin","contactInfo":{"publicProfileUrl":"https://sg.linkedin.com/in/saverin","twitterAccounts":["esaverin"],"websites":[]},"industry":"Internet",%%

Body:
For the group matching add ? which means as little as possible

\"publicProfileUrl\":\"(.*?)\",


问:
multiple stopwatch not working correctly
I have made two stopwatch to track activity of a user, one gets paused when another starts/resumes. But its getting the time from other clock everytime. please help me with correction, or please suggest any better way of doing this, I want to use 10 stopwatch together to keep track on activity and want my all stopwatches in one side and buttons on another. Thanks in advance.

$(document).ready(function(){

    var clocDiv = '';

    $(".act-butn").button().click(function(){

            var act = $(this).attr('value');
             clocDiv = '#'+act+' span';
            prev_hours = parseInt($(clocDiv).eq(0).html());
            prev_minutes = parseInt($(clocDiv).eq(1).html());
            prev_seconds = parseInt($(clocDiv).eq(2).html());
            prev_milliseconds = parseInt($(clocDiv).eq(3).html());

            updateTime(prev_hours, prev_minutes, prev_seconds, prev_milliseconds);

    });

    // Update time in stopwatch periodically - every 25ms
    function updateTime(prev_hours, prev_minutes, prev_seconds, prev_milliseconds){
        var startTime = new Date();    // fetch current time

        timeUpdate = setInterval(function () {
            var timeElapsed = new Date().getTime() - startTime.getTime();    // calculate the time elapsed in milliseconds

            // calculate hours
            hours = parseInt(timeElapsed / 1000 / 60 / 60) + prev_hours;

            // calculate minutes
            minutes = parseInt(timeElapsed / 1000 / 60) + prev_minutes;
            if (minutes > 60) minutes %= 60;

            // calculate seconds
            seconds = parseInt(timeElapsed / 1000) + prev_seconds;
            if (seconds > 60) seconds %= 60;

            // calculate milliseconds
            milliseconds = timeElapsed + prev_milliseconds;
            if (milliseconds > 1000) milliseconds %= 1000;

            // set the stopwatch
            setStopwatch(hours, minutes, seconds, milliseconds);

        }, 25); // update time in stopwatch after every 25ms

    }

    // Set the time in stopwatch
    function setStopwatch(hours, minutes, seconds, milliseconds){
        $(clocDiv).eq(0).html(prependZero(hours, 2));
        $(clocDiv).eq(1).html(prependZero(minutes, 2));
        $(clocDiv).eq(2).html(prependZero(seconds, 2));
        $(clocDiv).eq(3).html(prependZero(milliseconds, 3));
    }

    // Prepend zeros to the digits in stopwatch
    function prependZero(time, length) {
        time = new String(time);    // stringify time
        return new Array(Math.max(length - time.length + 1, 0)).join("0") + time;
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>

<div id="break">
    <span id="hours">00</span> :
    <span id="minutes">00</span> :
    <span id="seconds">00</span> ::
    <span id="milliseconds">000</span>
</div><br>

<div id="production">
    <span id="hours">00</span> :
    <span id="minutes">00</span> :
    <span id="seconds">00</span> ::
    <span id="milliseconds">000</span>
</div><br>
<div id="controls">
    <button class="act-butn" value="break">Break</button>
    <button class="act-butn" value="production">Production</button>

</div></code>```

答:
for your code, 'id' are unique, you should not use same id more than once.

what I did here have two part,
1st part are stop watch, you can create as many stop watch you want. just copy more Watch x but make sure you have same number of btngroup and watchgroup

2nd part below will drive all clock dynamically, start one will pause all others:

```<code>//click one btn, stop all other watch
$('#btngroup button').live('click', function() {
  var btnClicked = $(this).index();
  $('.basic').each(function(index) {
    if(btnClicked == index){
      $(this).find('a:eq(0)')[0].click();
    } else {
      $(this).find('a:eq(1)')[0].click();
    }
  });
});
</code>```

lots of code, play around and should fit your need

// stopwatch functions...
var Stopwatch = function(elem, options) {
  var timer = createTimer(),
    startButton = createButton("start", start),
    stopButton = createButton("stop", stop),
    resetButton = createButton("reset", reset),
    offset,
    clock,
    interval;

  // default options
  options = options || {};
  options.delay = options.delay || 1;

  // append elements
  elem.appendChild(timer);
  elem.appendChild(startButton);
  elem.appendChild(stopButton);
  elem.appendChild(resetButton);

  // initialize
  reset();

  // private functions
  function createTimer() {
    return document.createElement("span");
  }

  function createButton(action, handler) {
    var a = document.createElement("a");
    a.href = "#" + action;
    a.style = "display: none;";
    a.innerHTML = action;
    a.addEventListener("click", function(event) {
      handler();
      event.preventDefault();
    });
    return a;
  }

  function start() {
    if (!interval) {
      offset = Date.now();
      interval = setInterval(update, options.delay);
    }
  }

  function stop() {
    if (interval) {
      clearInterval(interval);
      interval = null;
    }
  }

  function reset() {
    clock = 0;
    render(0);
  }

  function update() {
    clock += delta();
    render();
  }

  function render() {
    var h = Math.floor(clock / (1000 * 60 * 60)) % 24;
    var m = Math.floor(clock / (1000 * 60)) % 60;
    var s = Math.floor(clock / 1000) % 60;
    var ms = Math.floor(clock % 1000);

    if (h < 10) {
      h = "0" + h;
    }
    if (m < 10) {
      m = "0" + m;
    }
    if (s < 10) {
      s = "0" + s;
    }
    if (ms < 100) {
      ms = "0" + ms;
    }
    if (ms < 10) {
      ms = "0" + ms;
    }

    timer.innerHTML = h + ':' + m + ':' + s + '::' + ms;

  }

  function delta() {
    var now = Date.now(),
      d = now - offset;

    offset = now;
    return d;
  }

  this.start = start;
  this.stop = stop;
  this.reset = reset;
};

var elems = document.getElementsByClassName("basic");
for (var i = 0, len = elems.length; i < len; i++) {
  new Stopwatch(elems[i]);
}

//click one btn, stop all other watch
$('#btngroup button').live('click', function() {
  var btnClicked = $(this).index();
  $('.basic').each(function(index) {
    if(btnClicked == index){
      $(this).find('a:eq(0)')[0].click();
    } else {
      $(this).find('a:eq(1)')[0].click();
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.stopwatch {
  display: inline-block;
  background-color: white;
  border: 1px solid #eee;
  padding: 5px;
  margin: 5px;
}

.stopwatch span {
  font-weight: bold;
  display: block;
}

.stopwatch a {
  padding-right: 5px;
  text-decoration: none;
}</code>```

  <button>Btn 1</button>
  <button>Btn 2</button>
  <button>Btn 3</button>
  <button>Btn 4</button>
  <button>Btn 5</button>
  <button>Btn 6</button>
  <button>Btn 7</button>
  <button>Btn 8</button>
  <button>Btn 9</button>
  <button>Btn 10</button>

  Watch 1
  Watch 2
  Watch 3
  Watch 4
  Watch 5
  Watch 6
  Watch 7
  Watch 8
  Watch 9
  Watch 10

```

Body:
I have made two stopwatch to track activity of a user, one gets paused when another starts/resumes. But its getting the time from other clock everytime. please help me with correction, or please suggest any better way of doing this, I want to use 10 stopwatch together to keep track on activity and want my all stopwatches in one side and buttons on another. Thanks in advance.

$(document).ready(function(){

    var clocDiv = '';

    $(".act-butn").button().click(function(){

            var act = $(this).attr('value');
             clocDiv = '#'+act+' span';
            prev_hours = parseInt($(clocDiv).eq(0).html());
            prev_minutes = parseInt($(clocDiv).eq(1).html());
            prev_seconds = parseInt($(clocDiv).eq(2).html());
            prev_milliseconds = parseInt($(clocDiv).eq(3).html());

            updateTime(prev_hours, prev_minutes, prev_seconds, prev_milliseconds);

    });

    // Update time in stopwatch periodically - every 25ms
    function updateTime(prev_hours, prev_minutes, prev_seconds, prev_milliseconds){
        var startTime = new Date();    // fetch current time

        timeUpdate = setInterval(function () {
            var timeElapsed = new Date().getTime() - startTime.getTime();    // calculate the time elapsed in milliseconds

            // calculate hours
            hours = parseInt(timeElapsed / 1000 / 60 / 60) + prev_hours;

            // calculate minutes
            minutes = parseInt(timeElapsed / 1000 / 60) + prev_minutes;
            if (minutes > 60) minutes %= 60;

            // calculate seconds
            seconds = parseInt(timeElapsed / 1000) + prev_seconds;
            if (seconds > 60) seconds %= 60;

            // calculate milliseconds
            milliseconds = timeElapsed + prev_milliseconds;
            if (milliseconds > 1000) milliseconds %= 1000;

            // set the stopwatch
            setStopwatch(hours, minutes, seconds, milliseconds);

        }, 25); // update time in stopwatch after every 25ms

    }

    // Set the time in stopwatch
    function setStopwatch(hours, minutes, seconds, milliseconds){
        $(clocDiv).eq(0).html(prependZero(hours, 2));
        $(clocDiv).eq(1).html(prependZero(minutes, 2));
        $(clocDiv).eq(2).html(prependZero(seconds, 2));
        $(clocDiv).eq(3).html(prependZero(milliseconds, 3));
    }

    // Prepend zeros to the digits in stopwatch
    function prependZero(time, length) {
        time = new String(time);    // stringify time
        return new Array(Math.max(length - time.length + 1, 0)).join("0") + time;
    }
});

    00 :
    00 :
    00 ::
    000

    00 :
    00 :
    00 ::
    000

    <button class="act-butn" value="break">Break</button>
    <button class="act-butn" value="production">Production</button>

Body:
for your code, 'id' are unique, you should not use same id more than once.

what I did here have two part,
1st part are stop watch, you can create as many stop watch you want. just copy more <span class="basic stopwatch">Watch x</span> but make sure you have same number of btngroup and watchgroup

2nd part below will drive all clock dynamically, start one will pause all others:

//click one btn, stop all other watch
$('#btngroup button').live('click', function() {
  var btnClicked = $(this).index();
  $('.basic').each(function(index) {
    if(btnClicked == index){
      $(this).find('a:eq(0)')[0].click();
    } else {
      $(this).find('a:eq(1)')[0].click();
    }
  });
});

lots of code, play around and should fit your need

// stopwatch functions...
var Stopwatch = function(elem, options) {
  var timer = createTimer(),
    startButton = createButton("start", start),
    stopButton = createButton("stop", stop),
    resetButton = createButton("reset", reset),
    offset,
    clock,
    interval;

  // default options
  options = options || {};
  options.delay = options.delay || 1;

  // append elements
  elem.appendChild(timer);
  elem.appendChild(startButton);
  elem.appendChild(stopButton);
  elem.appendChild(resetButton);

  // initialize
  reset();

  // private functions
  function createTimer() {
    return document.createElement("span");
  }

  function createButton(action, handler) {
    var a = document.createElement("a");
    a.href = "#" + action;
    a.style = "display: none;";
    a.innerHTML = action;
    a.addEventListener("click", function(event) {
      handler();
      event.preventDefault();
    });
    return a;
  }

  function start() {
    if (!interval) {
      offset = Date.now();
      interval = setInterval(update, options.delay);
    }
  }

  function stop() {
    if (interval) {
      clearInterval(interval);
      interval = null;
    }
  }

  function reset() {
    clock = 0;
    render(0);
  }

  function update() {
    clock += delta();
    render();
  }

  function render() {
    var h = Math.floor(clock / (1000 * 60 * 60)) % 24;
    var m = Math.floor(clock / (1000 * 60)) % 60;
    var s = Math.floor(clock / 1000) % 60;
    var ms = Math.floor(clock % 1000);

    if (h < 10) {
      h = "0" + h;
    }
    if (m < 10) {
      m = "0" + m;
    }
    if (s < 10) {
      s = "0" + s;
    }
    if (ms < 100) {
      ms = "0" + ms;
    }
    if (ms < 10) {
      ms = "0" + ms;
    }

    timer.innerHTML = h + ':' + m + ':' + s + '::' + ms;

  }

  function delta() {
    var now = Date.now(),
      d = now - offset;

    offset = now;
    return d;
  }

  this.start = start;
  this.stop = stop;
  this.reset = reset;
};

var elems = document.getElementsByClassName("basic");
for (var i = 0, len = elems.length; i < len; i++) {
  new Stopwatch(elems[i]);
}

//click one btn, stop all other watch
$('#btngroup button').live('click', function() {
  var btnClicked = $(this).index();
  $('.basic').each(function(index) {
    if(btnClicked == index){
      $(this).find('a:eq(0)')[0].click();
    } else {
      $(this).find('a:eq(1)')[0].click();
    }
  });
});

.stopwatch {
  display: inline-block;
  background-color: white;
  border: 1px solid #eee;
  padding: 5px;
  margin: 5px;
}

.stopwatch span {
  font-weight: bold;
  display: block;
}

.stopwatch a {
  padding-right: 5px;
  text-decoration: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<div id="btngroup">
  <button>Btn 1</button>
  <button>Btn 2</button>
  <button>Btn 3</button>
  <button>Btn 4</button>
  <button>Btn 5</button>
  <button>Btn 6</button>
  <button>Btn 7</button>
  <button>Btn 8</button>
  <button>Btn 9</button>
  <button>Btn 10</button>
</div>
<br><br>
<div id="watchgroup">
  <span class="basic stopwatch">Watch 1</span>
  <span class="basic stopwatch">Watch 2</span>
  <span class="basic stopwatch">Watch 3</span>
  <span class="basic stopwatch">Watch 4</span>
  <span class="basic stopwatch">Watch 5</span>
  <span class="basic stopwatch">Watch 6</span>
  <span class="basic stopwatch">Watch 7</span>
  <span class="basic stopwatch">Watch 8</span>
  <span class="basic stopwatch">Watch 9</span>
  <span class="basic stopwatch">Watch 10</span>
</div>


答:
So, something like

```<code>\"publicProfileUrl\":\"(.*?)\",
</code>```

should work.

If you want to be absolutely safe:

As others have pointed out, this is not always "watertight". In your current application (url!) it is probably not an issue, but in a general case we might encounter an escaped " followed by a comma, like in "this is \"it\", no doubt!", which is supposed to be part of our target string. This pattern would so far cause a premature end of our target string. If we modify the regexp a little by adding a [^\\] into our search group then even this nasty little pattern can cause us no harm any more:

```<code>\"publicProfileUrl\":"(.*?[^\\])\",
</code>```

Title: How to parse key:value pair on JSON-like string with RegEx on JavaScript?

Body:
So, something like

\"publicProfileUrl\":\"(.*?)\",

should work.

If you want to be absolutely safe:

As others have pointed out, this is not always "watertight". In your current application (url!) it is probably not an issue, but in a general case we might encounter an escaped " followed by a comma, like in "this is \"it\", no doubt!", which is supposed to be part of our target string. This pattern would so far cause a premature end of our target string. If we modify the regexp a little by adding a [^\\] into our search group then even this nasty little pattern can cause us no harm any more:

\"publicProfileUrl\":"(.*?[^\\])\",


问:
Fabric beta testing: I can't install beta app
I'm using fabric for beta testing.

I got a notification about beta app from Crashlytics. The title is "XXX v1.0.0 (5) is ready to test".

I expected that I could see a download button on the install page, but I could not find it.

How should I do next? Any help will be appreciated.

I have attached the screen shot.

Thanks.

答:
I had the same problem and my solution was ensure that the development provisioning profile is used to build the app.

In my case, i had two different provisioning profiles, one for distribution and one for development. I used fastlane with gym to build the archive. My failure was to not specify what profile it should use.

The failure happened by invoking gym without explicitly saying to use the dev profile:

```<code>gym
</code>```

The solution was to add the export_method with development.

```<code>gym(export_method: 'development')
</code>```

In this case it will use the development provisioning profile.

If you don't use fastlane, please ensure that the used profile is matching the one you have specified in the crashlytics beta setup.

Good Luck Everyone!

Body:
I had the same problem and my solution was ensure that the development provisioning profile is used to build the app.

In my case, i had two different provisioning profiles, one for distribution and one for development. I used fastlane with gym to build the archive. My failure was to not specify what profile it should use.

The failure happened by invoking gym without explicitly saying to use the dev profile:

gym

The solution was to add the export_method with development.

gym(export_method: 'development')

In this case it will use the development provisioning profile.

If you don't use fastlane, please ensure that the used profile is matching the one you have specified in the crashlytics beta setup.

Good Luck Everyone!


问:
Object reference not set to an instance of an object. but the Properties are accessable
I am passing a IList into another class which looks as follows:

```<code>public class KundenViewModel
{
    public IList<Kunde> _kunden;

    /// <summary>
    /// Add a list of Kunde to the View
    /// </summary>
    /// <param name="kunden">A list of Kunde objects</param>
    public KundenViewModel(IList<Kunde> kunden)
    {
        foreach (var k in kunden)
        {
            var test = k._Name;
            _kunden.Add(k);
        }
        //_kunden.AddRange(kunden);
    }

    /// <summary>
    /// Add one Object of Kunde to the View
    /// </summary>
    /// <param name="kunde">A Kunde Object</param>
    public KundenViewModel(Kunde kunde)
    {
        _kunden.Add(kunde);
    }
}
</code>```

But at runtime I receive at the Line 14 (_kunden.Add(k);) the error "Object reference not set to an instance of an object." Well I would say the object has never been initialized, but It has been and I also can access the properties for example the line before, there is no error.

Thanks in Advance

答: Have you initialized _kunden list?</p>

Body:
I am passing a IList into another class which looks as follows:

public class KundenViewModel
{
    public IList<Kunde> _kunden;

    ///
    /// Add a list of Kunde to the View
    ///
    /// <param name="kunden">A list of Kunde objects</param>
    public KundenViewModel(IList<Kunde> kunden)
    {
        foreach (var k in kunden)
        {
            var test = k._Name;
            _kunden.Add(k);
        }
        //_kunden.AddRange(kunden);
    }

    ///
    /// Add one Object of Kunde to the View
    ///
    /// <param name="kunde">A Kunde Object</param>
    public KundenViewModel(Kunde kunde)
    {
        _kunden.Add(kunde);
    }
}

But at runtime I receive at the Line 14 (_kunden.Add(k);) the error "Object reference not set to an instance of an object." Well I would say the object has never been initialized, but It has been and I also can access the properties for example the line before, there is no error.

Thanks in Advance

Body: Have you initialized _kunden list?


答:
Try excluding the closing double quote in your capture:

```<code>\"publicProfileUrl\":\"([^"]*)\",
</code>```

Normally, line breaks would workaround the greedy matching

Body:
Try excluding the closing double quote in your capture:

\"publicProfileUrl\":\"([^"]*)\",

Normally, line breaks would workaround the greedy matching


问:
Angular2 - Pass parameters to a dynamically generated component?
I have a simple demo app which I'm simulating  manually insert / fetch data from DB and injecting new components - according to the num entered.

Plunker

So if I click the "manual " button twice :

And if I set "3" in the text and click "fetch from db" - I get the expected delay(simulate db) and then :

This all works as expected.

The "parent" component is :

```<code>//src/MainPage.ts
@Component({
  selector: 'my-app',
  template: `
    <button (click)="putInMyHtml()">Insert component manually</button>
    <p> # Items to fetch  : <input type="text" style='width:40px'  [(ngModel)]="dbNumItems" name="dbNumItems"/> <input type='button' value='fetch from db' (click)='fetchItems($event)'/></p>
    <div #myDiv>
       <template #target></template>
    </div>
  `
})
export class MainPage {
  @ViewChild('target', { read: ViewContainerRef }) target: ViewContainerRef;
  dbNumItems: string;
  constructor(private cfr: ComponentFactoryResolver) {}

  fetchItems(){
        var p= new Promise((resolve, reject) => { //simulate db
        setTimeout(()=>resolve(this.dbNumItems),2000)
    });

  p.then(v=>{

    for (let i =0;i<v;i++)
    {
         this.putInMyHtml() ;// inject "v" times
    }
  })

}

  putInMyHtml() {
   // this.target.clear();
   let compFactory = this.cfr.resolveComponentFactory(TestPage);
    this.target.createComponent(compFactory);
  }
}
</code>```

This is the Injected component :

```<code>//src/TestPage.ts
@Component({
  selector: 'test-component',
  template: '<b>Content  : Name={{user.Name}} Age={{user.Age}}</b><br/>',
})
export class TestPage {
    @Input
     User:Person;

}
</code>```

So where is the problem ?

As you can see , in the injected component I have :

```<code>@Input
User:Person;
</code>```

which means that I want the parent component to pass a Person object to each injection.

In other words :

Question

Looking at the "after db stage" , How can I pass a customized person to each injection ?

```<code>  p.then(v=>{

    for (let i =0;i<v;i++)
    {
         let p = new Person();
         p.Name = "name"+i;
         p.Age = i;

         this.putInMyHtml() ; //how to I pass `p` ???

    }
  })

}
</code>```

Expected output   :

NB
I don't want to use ngFor because I don't need to hold an Array at the back end. this is an app which injects new articles periodically.and I will be glad to know if there's a better way of doing it.

答:
use *ngFor and iterate through an array of Person, that way you can use the @Input.  You probably want something like

```<code><ul>
  <li *ngFor="let person of people">
    <test-component [User]=person></test-component>
  </li>
</ul>
</code>```

add people: Person[] to your main component and when you fetch items

```<code>p.then(v=>{

for (let i =0;i<v;i++)
{
   let p = new Person();
   p.Name = "name"+i;
   p.Age = i;
   people.push(p)
}
})
</code>```

Body:
I have a simple demo app which I'm simulating  manually insert / fetch data from DB and injecting new components - according to the num entered.

Plunker

So if I click the "manual " button twice :

And if I set "3" in the text and click "fetch from db" - I get the expected delay(simulate db) and then :

This all works as expected.

The "parent" component is :

//src/MainPage.ts
@Component({
  selector: 'my-app',
  template: `
    <button (click)="putInMyHtml()">Insert component manually</button>

 # Items to fetch  : <input type="text" style='width:40px'  [(ngModel)]="dbNumItems" name="dbNumItems"/> <input type='button' value='fetch from db' (click)='fetchItems($event)'/>

       <template #target></template>

  `
})
export class MainPage {
  @ViewChild('target', { read: ViewContainerRef }) target: ViewContainerRef;
  dbNumItems: string;
  constructor(private cfr: ComponentFactoryResolver) {}

  fetchItems(){
        var p= new Promise((resolve, reject) => { //simulate db
        setTimeout(()=>resolve(this.dbNumItems),2000)
    });

  p.then(v=>{

    for (let i =0;i<v;i++)
    {
         this.putInMyHtml() ;// inject "v" times
    }
  })

}

  putInMyHtml() {
   // this.target.clear();
   let compFactory = this.cfr.resolveComponentFactory(TestPage);
    this.target.createComponent(compFactory);
  }
}

This is the Injected component :

//src/TestPage.ts
@Component({
  selector: 'test-component',
  template: 'Content  : Name={{user.Name}} Age={{user.Age}}
',
})
export class TestPage {
    @Input
     User:Person;

}

So where is the problem ?

As you can see , in the injected component I have :

@Input
User:Person;

which means that I want the parent component to pass a Person object to each injection.

In other words :

Question

Looking at the "after db stage" , How can I pass a customized person to each injection ?

  p.then(v=>{

    for (let i =0;i<v;i++)
    {
         let p = new Person();
         p.Name = "name"+i;
         p.Age = i;

         this.putInMyHtml() ; //how to I pass `p` ???

    }
  })

}

Expected output   :

NB
I don't want to use ngFor because I don't need to hold an Array at the back end. this is an app which injects new articles periodically.and I will be glad to know if there's a better way of doing it.

Body:
use *ngFor and iterate through an array of Person, that way you can use the @Input.  You probably want something like

<ul>
  <li *ngFor="let person of people">
    <test-component [User]=person></test-component>
  </li>
</ul>

add people: Person[] to your main component and when you fetch items

p.then(v=>{

for (let i =0;i<v;i++)
{
   let p = new Person();
   p.Name = "name"+i;
   p.Age = i;
   people.push(p)
}
})


问:
What is a preferred way of closing a third-application thread without waiting for it to complete?
I am currently running the JAR that I cannot change, and sometimes it simply gets stuck for no good reason. I have tried finding the ways to interrupt the thread, stop the thread, etceteras, but no luck.

Each solution offered was about doing the complete exit or waiting for a thread to complete.

What I want to do is to simply close the thread, exactly when the timeout completes, and carry on with the program.

What I do not want to do is use the while loop with a timeout, java.util.concurrent.Future, System.exit, and make a Thread.interrupt call.

None of these will help!

答:
Actually, you can't really solve this!

What I mean is: even if you would manage to kill "your" thread that you used to trigger the 3rd party code - you have no way of killing threads or processes created by the code you are invoking.

If you want to be absolutely sure to kill all and anything, you might have to look into rather complex solutions like:

instead of just using a thread, you create a new process with a new JVM B

in that JVM B,  you can call that library

but of course, that requires that you put additional code around; so that "your" code in JVM A can talk to "your" code in JVM B

And now you might be able to tear down that process, and all artifacts belonging to it. Maybe.

And seriously: to be really really sure that the 3rd party library didn't kick of anything that you can't stop; you might even have to run that JVM inside some kind of container (for example a docker instance). That you could tear down and be sure that everything is gone.

Long story short: I think there is no way to absolutely control the threads created in a thread. If you need that level of control, you need to look into "outsourcing" those calls.


问:
SpringMVC won't map hierarchical urls
I have a problem with my rest endpoint mappings.  They involve a hierarchical natural key.  So I want paths where I shorten the path, and it will then get results from a larger item space.

The issue is, the most fully qualified path works and the leas qualified path works, but not the two paths in the middle; they return 404 without ever getting into the controller.  So I assume it is an mapping issue.  Any help would be appreciated.

```<code>@RestController
@RequestMapping("/bookmark/v1")
public class BookmarkRestController
{
  // this works
  @GetMapping("/member/{memberId}/content/{contentSource}/{contentType}/{contentId}")
  public ResponseEntity<Bookmark> read(
    @PathVariable final String memberId,
      @PathVariable final String contentSource,
      @PathVariable final String contentType,
      @PathVariable final String contentId)
  {
    ...
  }

  // this returns 404 without ever getting into the controller
  @GetMapping("/member/{memberId}content/{contentSource}/{contentType}")
  public ResponseEntity<Iterable<Bookmark>> read(
    @PathVariable final String memberId,
    @PathVariable final String contentSource,
    @PathVariable final String contentType)
  {
    ...
  }

  // this returns 404 without ever getting into the controller
  @GetMapping("/member/{memberId}content/{contentSource}")
  public ResponseEntity<Iterable<Bookmark>> read(
    @PathVariable final String memberId,
    @PathVariable final String contentSource)
  {
    ...
  }

  // this works
  @GetMapping("/member/{memberId}")
  public ResponseEntity<Iterable<Bookmark>> read(@PathVariable final String memberId)
  {
    ...
  }

}

@GetMapping("/member/{memberId}/content/{contentSource}/{contentType}/{contentId}")
public ResponseEntity<Bookmark> read(
  @PathVariable final String memberId,
    @PathVariable final String contentSource,
    @PathVariable final String contentType,
    @PathVariable final String contentId)

@GetMapping("/member/{memberId}content/{contentSource}/{contentType}")
public ResponseEntity<Iterable<Bookmark>> read(
    @PathVariable final String memberId,
    @PathVariable final String contentSource,
    @PathVariable final String contentType)

@GetMapping("/member/{memberId}content/{contentSource}")
public ResponseEntity<Iterable<Bookmark>> read(
    @PathVariable final String memberId,
    @PathVariable final String contentSource)

@GetMapping("/member/{memberId}")
public ResponseEntity<Iterable<Bookmark>> read(@PathVariable final String memberId)
</code>```

答:
Your url mapping is incorrect for those two methods, i.e., you are missing / in between, so you need to change this /member/{memberId}content to /member/{memberId}/content

/member/{memberId}content url (with out /) works only when the request is like /member/1content.
In other words, when the controller is mapped to /member/{memberId}content url & the request comes as /member/1/content 9with path separator) you will get 404 error.

Title: SpringMVC won't map hierarchical urls

Body:
I have a problem with my rest endpoint mappings.  They involve a hierarchical natural key.  So I want paths where I shorten the path, and it will then get results from a larger item space.

The issue is, the most fully qualified path works and the leas qualified path works, but not the two paths in the middle; they return 404 without ever getting into the controller.  So I assume it is an mapping issue.  Any help would be appreciated.

@RestController
@RequestMapping("/bookmark/v1")
public class BookmarkRestController
{
  // this works
  @GetMapping("/member/{memberId}/content/{contentSource}/{contentType}/{contentId}")
  public ResponseEntity<Bookmark> read(
    @PathVariable final String memberId,
      @PathVariable final String contentSource,
      @PathVariable final String contentType,
      @PathVariable final String contentId)
  {
    ...
  }

  // this returns 404 without ever getting into the controller
  @GetMapping("/member/{memberId}content/{contentSource}/{contentType}")
  public ResponseEntity<Iterable<Bookmark>> read(
    @PathVariable final String memberId,
    @PathVariable final String contentSource,
    @PathVariable final String contentType)
  {
    ...
  }

  // this returns 404 without ever getting into the controller
  @GetMapping("/member/{memberId}content/{contentSource}")
  public ResponseEntity<Iterable<Bookmark>> read(
    @PathVariable final String memberId,
    @PathVariable final String contentSource)
  {
    ...
  }

  // this works
  @GetMapping("/member/{memberId}")
  public ResponseEntity<Iterable<Bookmark>> read(@PathVariable final String memberId)
  {
    ...
  }

}

@GetMapping("/member/{memberId}/content/{contentSource}/{contentType}/{contentId}")
public ResponseEntity<Bookmark> read(
  @PathVariable final String memberId,
    @PathVariable final String contentSource,
    @PathVariable final String contentType,
    @PathVariable final String contentId)

@GetMapping("/member/{memberId}content/{contentSource}/{contentType}")
public ResponseEntity<Iterable<Bookmark>> read(
    @PathVariable final String memberId,
    @PathVariable final String contentSource,
    @PathVariable final String contentType)

@GetMapping("/member/{memberId}content/{contentSource}")
public ResponseEntity<Iterable<Bookmark>> read(
    @PathVariable final String memberId,
    @PathVariable final String contentSource)

@GetMapping("/member/{memberId}")
public ResponseEntity<Iterable<Bookmark>> read(@PathVariable final String memberId)


问:
How accurately does Google geocode UK postcodes using the maps api?
If I provide a full UK postcode how much of it is taken into account? I remember reading that not all of it was used?</p>

答: From my basic tests I think that it is only the first part, plus first number of the second part. e.g. SW1A 0 that are used for geocoding. Adding any more (SW1A 0AA) makes no difference to the returned lat lng values.</p>