问:
LocationManager.requestLocationUpdates with firebase crashing the app
This activity has 2 button, Start and Stop. When button start clicked, its save
user location to firebase and button stop to stop it. So, I use LocationManager.requestLocationUpdates to make every 5 second user location inserted to firebase. But this makes my app crash, here is my code

```<code>package com.example.julio.firebasemaster;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    TextView condition;
    Button start;
    Button stop;

    DatabaseReference mDatabase;
    DatabaseReference mChild;

    LocationManager locationManager;
    LocationListener locationListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mDatabase = FirebaseDatabase.getInstance().getReference();
        mChild = mDatabase.child("user");

        start = (Button) findViewById(R.id.btnStart);
        stop = (Button) findViewById(R.id.btnStop);

        permission();

        start.setOnClickListener(new View.OnClickListener() {
            @SuppressWarnings("MissingPermission")
            @Override
            public void onClick(View view) {

                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, locationListener);
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 0, locationListener);
                permission();

                locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

                locationListener = (new LocationListener() {
                    @Override
                    public void onLocationChanged(Location location) {
                        String latitude = location.getLatitude() + " ";
                        String longitude = location.getLongitude() + " ";

                        HashMap<String, String> data = new HashMap<>();
                        data.put("latitude", latitude);
                        data.put("longitude", longitude);

                        mChild.setValue(data);
                    }

                    @Override
                    public void onStatusChanged(String s, int i, Bundle bundle) {

                    }

                    @Override
                    public void onProviderEnabled(String s) {

                    }

                    @Override
                    public void onProviderDisabled(String s) {

                    }
                });
            }
        });

        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                locationManager.removeUpdates(locationListener);
            }
        });

    }

    private void permission() {
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
    }
}
</code>```

The Crush occur when I click start button

I'm using firebase assistant, so there is no problem with the initialization

Help me please, my head want to explode thinking this bug :(

答:
Add null check inside onLocationChanged

```<code> public void onLocationChanged(Location location) {
                        if (location != null) {
                        String latitude = location.getLatitude() + " ";
                        String longitude = location.getLongitude() + " ";

                        HashMap<String, String> data = new HashMap<>();
                        data.put("latitude", latitude);
                        data.put("longitude", longitude);

                        mChild.setValue(data);
                        }
}
</code>```

I hope this will help you

Body:
This activity has 2 button, Start and Stop. When button start clicked, its save
user location to firebase and button stop to stop it. So, I use LocationManager.requestLocationUpdates to make every 5 second user location inserted to firebase. But this makes my app crash, here is my code

package com.example.julio.firebasemaster;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    TextView condition;
    Button start;
    Button stop;

    DatabaseReference mDatabase;
    DatabaseReference mChild;

    LocationManager locationManager;
    LocationListener locationListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mDatabase = FirebaseDatabase.getInstance().getReference();
        mChild = mDatabase.child("user");

        start = (Button) findViewById(R.id.btnStart);
        stop = (Button) findViewById(R.id.btnStop);

        permission();

        start.setOnClickListener(new View.OnClickListener() {
            @SuppressWarnings("MissingPermission")
            @Override
            public void onClick(View view) {

                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, locationListener);
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 0, locationListener);
                permission();

                locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

                locationListener = (new LocationListener() {
                    @Override
                    public void onLocationChanged(Location location) {
                        String latitude = location.getLatitude() + " ";
                        String longitude = location.getLongitude() + " ";

                        HashMap<String, String> data = new HashMap<>();
                        data.put("latitude", latitude);
                        data.put("longitude", longitude);

                        mChild.setValue(data);
                    }

                    @Override
                    public void onStatusChanged(String s, int i, Bundle bundle) {

                    }

                    @Override
                    public void onProviderEnabled(String s) {

                    }

                    @Override
                    public void onProviderDisabled(String s) {

                    }
                });
            }
        });

        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                locationManager.removeUpdates(locationListener);
            }
        });

    }

    private void permission() {
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
    }
}

The Crush occur when I click start button

I'm using firebase assistant, so there is no problem with the initialization

Help me please, my head want to explode thinking this bug :(

Body:
Add null check inside onLocationChanged

 public void onLocationChanged(Location location) {
                        if (location != null) {
                        String latitude = location.getLatitude() + " ";
                        String longitude = location.getLongitude() + " ";

                        HashMap<String, String> data = new HashMap<>();
                        data.put("latitude", latitude);
                        data.put("longitude", longitude);

                        mChild.setValue(data);
                        }
}

I hope this will help you


来源: stackexchange

问:
Button position in div
I have a inspiration post style:

So when I'm trying to make one I face some problem such as:

button not rounded when I change window size

social icons doesn't show

I can't click social icons

not responsive

code on codepen (https://codepen.io/youssefelmajbri/pen/eRjKoj):

.media {
  background-color: #fff;
  border: 1px solid rgba(0, 0, 0, 0.125);
  border-radius: 0.25rem;
  width: 550px;
  height: 151px;
}

.media-body {
  padding: 20px;
}

.thumb {
  height: 150px;
  width: 250px;
}

img {
  max-width: 100%;
  max-height: 100%;
}

#social-fb {
  color: white;
  padding-top: 50%;
  padding-left: 20%;
  font-size: 20px;
}

#social-tw {
  color: white;
  font-size: 20px;
  padding-left: 20px;
}

#social-yt {
  color: white;
  font-size: 20px;
  padding-left: 20px;
}

#social-rd {
  color: white;
  font-size: 20px;
  padding-left: 20px;
}

#btn {
  border-radius: 50%;
  width: 8%;
  height: 7%;
  margin-top: -30;
  margin-left: -10;
  background-color: #E91E63;
  color: white;
}

.img {
  width: 20%;
  height: 10%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />
<div class="jumbotron">
  <div class="container-fluid">
    <div class="row">
      <div class="col-lg-6">
        <div class="media">
          <div class="media-body">
            <h1 class="lead text-center">THis a text</h1>

            <hr>
            <p class="small"> that you'll remeber and don't forget if that you want to forget you'll not able to.</p>

          </div>

            <img src="http://img02.deviantart.net/712d/i/2015/231/3/e/flat_landscape_by_eocdesigns-d96dbbn.jpg">

            <i class="fa fa-facebook" id="social-fb"></i>
            <i class="fa fa-twitter" id="social-tw"></i>
            <i class="fa fa-youtube" id="social-yt"></i>
            <i class="fa fa-reddit" id="social-rd"></i>

        </div>
        <button class="btn" id="btn" ><i class="fa fa-arrow-left"></i></button>
      </div>

    </div>
  </div></code>```

答:
button not rounded when I change window size

This is because you are using percentages to set button width/height. These percentages will be fractions of the parent element, so 8% of width and 7% of height will not necessarily be equal, and if the parent width/height changes, these sizes will as well. Use static values instead (px/em/rem, etc).

social icons doesn't show

I would suggest placing these using absolute positioning. Surround the icons width a div, set this in div style:

```<code>position: absolute;
width: 100%;
left: 0;
bottom: 0;
text-align: center;
</code>```

And add position: relative to parent element.

I can't click social icons

Well there aren't any click events attached to them, you need to give them an onclick event or similar, or surround them with a styled, clickable component like a href="..." or button.

Additionally I would suggest using, width and height instead of max-width and max-height on the image, so as to remove that white space beneath it.

ContentLicense: CC BY-SA 3.0

Title: Button position in div

Body:
I have a inspiration post style:

So when I'm trying to make one I face some problem such as:

button not rounded when I change window size

social icons doesn't show

I can't click social icons

not responsive

code on codepen (https://codepen.io/youssefelmajbri/pen/eRjKoj):

.media {
  background-color: #fff;
  border: 1px solid rgba(0, 0, 0, 0.125);
  border-radius: 0.25rem;
  width: 550px;
  height: 151px;
}

.media-body {
  padding: 20px;
}

.thumb {
  height: 150px;
  width: 250px;
}

img {
  max-width: 100%;
  max-height: 100%;
}

#social-fb {
  color: white;
  padding-top: 50%;
  padding-left: 20%;
  font-size: 20px;
}

#social-tw {
  color: white;
  font-size: 20px;
  padding-left: 20px;
}

#social-yt {
  color: white;
  font-size: 20px;
  padding-left: 20px;
}

#social-rd {
  color: white;
  font-size: 20px;
  padding-left: 20px;
}

#btn {
  border-radius: 50%;
  width: 8%;
  height: 7%;
  margin-top: -30;
  margin-left: -10;
  background-color: #E91E63;
  color: white;
}

.img {
  width: 20%;
  height: 10%;
}

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />

THis a text

 that you'll remeber and don't forget if that you want to forget you'll not able to.

        <button class="btn" id="btn" ></button>

Body:
button not rounded when I change window size

This is because you are using percentages to set button width/height. These percentages will be fractions of the parent element, so 8% of width and 7% of height will not necessarily be equal, and if the parent width/height changes, these sizes will as well. Use static values instead (px/em/rem, etc).

social icons doesn't show

I would suggest placing these using absolute positioning. Surround the icons width a div, set this in div style:

position: absolute;
width: 100%;
left: 0;
bottom: 0;
text-align: center;

And add position: relative to parent element.

I can't click social icons

Well there aren't any click events attached to them, you need to give them an onclick event or similar, or surround them with a styled, clickable component like a href="..." or button.

Additionally I would suggest using, width and height instead of max-width and max-height on the image, so as to remove that white space beneath it.


问:
SVG to Ico using icomoon generates multiple path instead of single object glyph
I am using illustrator to create a SVG file that will be converted to a font icon using icomoon. But I am having problems with the end result. My icon is essentially set of concentric circles, which is saved as SVG in illustrator. The SVG is converted to icons using iconmoon, I see that the icon is converted to multiple paths instead of a single object.

```<code>    <span class="icon-4">
<span class="path1"></span>
<span class="path2"></span>
<span class="path3"></span>
<span class="path4"></span>
<span class="path5"></span>
<span class="path6"></span>
</span>
</code>```

Link to the image : http://imgur.com/FnWgQNF

答:
I had this exact same issue.  Tried view transparency grid in illustrator, removing all color in illustrator, subtracting the transparencies, all with no luck.

Then i discovered in IcoMoon, that if at the bottom instead of clicking "Generate Font" you choose "SVG and More" you can click on the problem icon and edit the SVG right in the app.  IcoMoon helpfully has a "Remove Colors" button (drop with x).  Once you've done that you can close that box and your svg is monochrome, no need to reimport it.  You can then download it, or just click to generate your font.  Tada! :-)

It took me a while to figure this out, but once i did i was sold on how awesome icomoon really is.

Body:
I am using illustrator to create a SVG file that will be converted to a font icon using icomoon. But I am having problems with the end result. My icon is essentially set of concentric circles, which is saved as SVG in illustrator. The SVG is converted to icons using iconmoon, I see that the icon is converted to multiple paths instead of a single object.

Link to the image : http://imgur.com/FnWgQNF


问:
Using a class as a part of another class in django models
Assume I am writing an app to change configurations in a machine. I have 3 created tables as below. Machine configuration shows the current state of configurations for our machine. Users can create their tickets and request for changes of the configurations. RequestDetails will be the table to keep the proposed cofigurations plus some extra info such as the name of the requestor, date etc.

These classes are just a simple examples, in the real model I would have nearly 600+ fields=configuration presented in class MachineConfiguration. I should have EXACTLY THE SAME fields in RequestDetails class too. I was wondering there is a way NOT TO REPEAT MYSELF when defining class RequestDetails when it comes to all the fields that exist in MachineConfiguration model?

I want to write it in a way that if I changed anything in MachineConfiguration table, the same change would apply to RequestDetails table too.

Thanks in advance for the help.

```<code>class RequestTicket(models.Model):
    subject=models.CharField(max_length=50, null=False, blank=False)
    description=models.TextField(null=False, blank=True)

class MachineConfiguration(models.Model):
    field_1 = models.CharField(null=False,blank=True)
    field_2 = models.CharField(null=False, blank=True)
    field_3 = models.CharField(null=False, blank=True)

class RequestDetails(models.Model):
    tracking_number=models.ForeignKey('RequestTicket')
    field_A=models.DateField(null=True, blank=False)
    field_B=models.TextField(null=True, blank=False)
    field_1 = models.CharField(null=False, blank=True)
    field_2 = models.CharField(null=False, blank=True)
    field_3 = models.CharField(null=False, blank=True)
</code>```

答:
Yes you can create the base class and inherit that class in another class like,

```<code>class BaseModel(models.Model):
    field1 = models.CharField()
    field2 = models.CharField()

    class Meta:
        abstract = True
</code>```

And inherit this class in another model to get those same field,

```<code># Now if you change any field in BaseModel, it will reflect in both the models
class MachineConfiguration(BaseModel):
    pass

class RequestDetails(BaseModel):
    field3 = models.CharField()
</code>```

Body:
Assume I am writing an app to change configurations in a machine. I have 3 created tables as below. Machine configuration shows the current state of configurations for our machine. Users can create their tickets and request for changes of the configurations. RequestDetails will be the table to keep the proposed cofigurations plus some extra info such as the name of the requestor, date etc.

These classes are just a simple examples, in the real model I would have nearly 600+ fields=configuration presented in class MachineConfiguration. I should have EXACTLY THE SAME fields in RequestDetails class too. I was wondering there is a way NOT TO REPEAT MYSELF when defining class RequestDetails when it comes to all the fields that exist in MachineConfiguration model?

I want to write it in a way that if I changed anything in MachineConfiguration table, the same change would apply to RequestDetails table too.

Thanks in advance for the help.

class RequestTicket(models.Model):
    subject=models.CharField(max_length=50, null=False, blank=False)
    description=models.TextField(null=False, blank=True)

class MachineConfiguration(models.Model):
    field_1 = models.CharField(null=False,blank=True)
    field_2 = models.CharField(null=False, blank=True)
    field_3 = models.CharField(null=False, blank=True)

class RequestDetails(models.Model):
    tracking_number=models.ForeignKey('RequestTicket')
    field_A=models.DateField(null=True, blank=False)
    field_B=models.TextField(null=True, blank=False)
    field_1 = models.CharField(null=False, blank=True)
    field_2 = models.CharField(null=False, blank=True)
    field_3 = models.CharField(null=False, blank=True)

Body:
Yes you can create the base class and inherit that class in another class like,

class BaseModel(models.Model):
    field1 = models.CharField()
    field2 = models.CharField()

    class Meta:
        abstract = True

And inherit this class in another model to get those same field,

# Now if you change any field in BaseModel, it will reflect in both the models
class MachineConfiguration(BaseModel):
    pass

class RequestDetails(BaseModel):
    field3 = models.CharField()


问:
Box with multiple borders
I am trying to code and style a box which will contain a post. My problem is with multiple borders (i guess), trying to find the best way to code this, i prefer semantic HTML5 and CSS3, but if there is no other way, i can do "old style" with 3 divs (top, center, bottom) with css background: url..., can anyone give me some lights please?

If you please check the following url, you can check what i need to accomplish.

http://dl.dropbox.com/u/3696224/postBox.jpg

If you notice it has:

one border around all the box with a dark gray (#cccccc); (border)

a small space between that border and other light gray (#f7f7f7), almost white;

and only then the content with a white background;

Any suggestions? Very sorry for English grammar, thanks in advance.

Regards

PS - I almost forgot, i don't know is if needed or not, but the all around the box i have a box-shadow (i know how to do this part)

答:
Here's a solution using no messy markup. See this in action at http://jsfiddle.net/7xGKk/.

This should work properly in Firefox 3.5+, Safari 4+, Chrome 4+, Opera 10+ and Internet Explorer 8+.  Others will get a 7px outside-colour border; if you wished to change the colour of the three selected you could remove the .fancyframe background-color and modify z-indicies, e.g. to make #f7f7f7 the border.

This plays nicely with box-shadow etc; the border is contained inside the div.

HTML:

```<code><div class="fancyframe">content</div>
</code>```

CSS:

```<code>.fancyframe {
    background-color: white;
    border: 7px solid #cccccc;
    position: relative;
    /* The rest of this block is purely stylistic to make it look precisely
       like the original image except for font. */
    padding: 50px;
    text-align: center;
    text-transform: uppercase;
    line-height: 4em;
    font-size: 50px;
    width: 492px;
    font-family: Impact, sans-serif;
    color: #595959;
}
.fancyframe:before {
    content: "";
    margin: -6px;
    position: absolute;
    border: 6px solid #ffffff;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}
.fancyframe:after {
    content: "";
    margin: -5px;
    position: absolute;
    border: 5px solid #f8f8f8;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Box with multiple borders

Body:
Here's a solution using no messy markup. See this in action at http://jsfiddle.net/7xGKk/.

This should work properly in Firefox 3.5+, Safari 4+, Chrome 4+, Opera 10+ and Internet Explorer 8+.  Others will get a 7px outside-colour border; if you wished to change the colour of the three selected you could remove the .fancyframe background-color and modify z-indicies, e.g. to make #f7f7f7 the border.

This plays nicely with box-shadow etc; the border is contained inside the div.

HTML:

<div class="fancyframe">content</div>

CSS:

.fancyframe {
    background-color: white;
    border: 7px solid #cccccc;
    position: relative;
    /* The rest of this block is purely stylistic to make it look precisely
       like the original image except for font. */
    padding: 50px;
    text-align: center;
    text-transform: uppercase;
    line-height: 4em;
    font-size: 50px;
    width: 492px;
    font-family: Impact, sans-serif;
    color: #595959;
}
.fancyframe:before {
    content: "";
    margin: -6px;
    position: absolute;
    border: 6px solid #ffffff;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}
.fancyframe:after {
    content: "";
    margin: -5px;
    position: absolute;
    border: 5px solid #f8f8f8;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}


问:
AngularJS 1.2 $injector:modulerr
When using angular 1.2 instead of 1.07 the following piece of code is not valid anymore, why?

```<code>'use strict';

var app = angular.module('myapp', []);

app.config(['$routeProvider', '$locationProvider',
    function($routeProvider, $locationProvider) {
        $locationProvider.html5Mode(true);
        $routeProvider.
        when('/', {
            templateUrl: 'part.html',
            controller: 'MyCtrl'
        }).
        otherwise({
            redirectTo: '/'
        });
    }
]);
</code>```

the issue is in the injector configuration part (app.config):

```<code>Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.0rc1/$injector/modulerr?p0=muninn&p1=Error%…eapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.0rc1%2Fangular.min.js%3A31%3A252)
</code>```

If I remember correctly this issue started with angular 1.1.6.

答:
Its an injector error. You may have use lots of JavaScript files so the injector may be missing.

Some are here:

```<code>var app = angular.module('app',
    ['ngSanitize', 'ui.router', 'pascalprecht.translate', 'ngResource',
     'ngMaterial', 'angularMoment','md.data.table', 'angularFileUpload',
     'ngMessages', 'ui.utils.masks', 'angular-sortable-view',
     'mdPickers','ngDraggable','as.sortable', 'ngAnimate', 'ngTouch']
);
</code>```

Please check the injector you need to insert in your app.js

Title: AngularJS 1.2 $injector:modulerr

Body:
When using angular 1.2 instead of 1.07 the following piece of code is not valid anymore, why?

'use strict';

var app = angular.module('myapp', []);

app.config(['$routeProvider', '$locationProvider',
    function($routeProvider, $locationProvider) {
        $locationProvider.html5Mode(true);
        $routeProvider.
        when('/', {
            templateUrl: 'part.html',
            controller: 'MyCtrl'
        }).
        otherwise({
            redirectTo: '/'
        });
    }
]);

the issue is in the injector configuration part (app.config):

Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.0rc1/$injector/modulerr?p0=muninn&p1=Error%…eapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.0rc1%2Fangular.min.js%3A31%3A252)

If I remember correctly this issue started with angular 1.1.6.

Body:
Its an injector error. You may have use lots of JavaScript files so the injector may be missing.

Some are here:

var app = angular.module('app',
    ['ngSanitize', 'ui.router', 'pascalprecht.translate', 'ngResource',
     'ngMaterial', 'angularMoment','md.data.table', 'angularFileUpload',
     'ngMessages', 'ui.utils.masks', 'angular-sortable-view',
     'mdPickers','ngDraggable','as.sortable', 'ngAnimate', 'ngTouch']
);

Please check the injector you need to insert in your app.js


问:
ASP.NET C# How to hide and display particular field inside Repeater? (if statement)
Needed some help here,
So I am using repeater and retrieve some data from DB then put into the repeater, the thing is that for certain data value I would like to display it differently in the HTML, basically do IF checking inside Repeater to determine which HTML code to use, can someone help me with that?

I have two different codes

```<code><div class="message-data">
  <span class="message-data-name"><i class="fa fa-circle you"></i> You</span>
</div>
<div class="message you-message">
A new client?!?! I would love to help them, but where are we going to find the time?
</code>```

and

```<code> <li class="clearfix">
    <div class="message-data align-right">
      <span class="message-data-name">Ada, your OperationsAlly</span> <i class="fa fa-circle me"></i>
    </div>
    <div class="message me-message float-right"> We should take a look at your onboarding and service delivery workflows, for most businesess there are many ways to save time and not compromise quality.  </div>
  </li>
</code>```

As you can see, how do I put IF statement, for the first one like if (username == "You") and second one if (Username != "You"). Assume that the DB I retrieve has attribute named "Username"

Thanks

答:
If you're using ASP.net MVC Identity you can simply use this below:</p>

```<code>@if(!Request.IsAuthenticated)
{
   <div class="message-data">
    <span class="message-data-name"><i class="fa fa-circle you"></i>You</span>
   </div>
    <div class="message you-message">A new client?!?! I would love to help them, but where are we going to find the time? </div>
}
else
{
      <div class="message-data align-right">
        <span class="message-data-name">@Html.Raw(User.Identity.GetUserName()), your OperationsAlly</span>      <i class="fa fa-circle me"></i>
       </div>
      <div class="message me-message float-right"> We should take a look at your onboarding and service delivery workflows, for most businesess there are many ways to save time and not compromise quality.  </div>
}
</code>```

Body:
Needed some help here,
So I am using repeater and retrieve some data from DB then put into the repeater, the thing is that for certain data value I would like to display it differently in the HTML, basically do IF checking inside Repeater to determine which HTML code to use, can someone help me with that?

I have two different codes

   You

A new client?!?! I would love to help them, but where are we going to find the time?

and

      Ada, your OperationsAlly

 We should take a look at your onboarding and service delivery workflows, for most businesess there are many ways to save time and not compromise quality.

As you can see, how do I put IF statement, for the first one like if (username == "You") and second one if (Username != "You"). Assume that the DB I retrieve has attribute named "Username"

Thanks

Body:
If you're using ASP.net MVC Identity you can simply use this below:

@if(!Request.IsAuthenticated)
{
   <div class="message-data">
    <span class="message-data-name"><i class="fa fa-circle you"></i>You</span>
   </div>
    <div class="message you-message">A new client?!?! I would love to help them, but where are we going to find the time? </div>
}
else
{
      <div class="message-data align-right">
        <span class="message-data-name">@Html.Raw(User.Identity.GetUserName()), your OperationsAlly</span>      <i class="fa fa-circle me"></i>
       </div>
      <div class="message me-message float-right"> We should take a look at your onboarding and service delivery workflows, for most businesess there are many ways to save time and not compromise quality.  </div>
}


问:
Is there a KairosDB component for Apache Camel?
I can't find a Camel component for KairosDB. Is there none?

Should I write a custom component or is there a smarter way?

Thanks

答:
There is no official component for that. You can find the list of components at: https://github.com/apache/camel/tree/master/components#components

Yes you would need to write your own component, or just use regular Java code in a Java bean to integrate with KairosDB and then Camel can integrate with your Java bean. Or use a Camel Processor instead of a Java bean.

But writing a component is not so hard, and if you use KairosDB in more projects with Camel then it starts to make sense to build a Camel component for it. The Apache Camel project loves contributions: http://camel.apache.org/contributing


问:
How do you deploy cron jobs to production?
How do people deploy/version control cronjobs to production?  I'm more curious about conventions/standards people use than any particular solution, but I happen to be using git for revision control, and the cronjob is running a python/django script.</p>

答:
Having your project under version control, including your crontab.txt, is what I prefer. Then, with Fabric, it is as simple as this:

```<code>@task
def crontab():
    run('crontab deployment/crontab.txt')
</code>```

This will install the contents of deployment/crontab.txt to the crontab of the user you connect to the server. If you dont have your complete project on the server, you'd want to put the crontab file first.

Body:
Having your project under version control, including your crontab.txt, is what I prefer. Then, with Fabric, it is as simple as this:

@task
def crontab():
    run('crontab deployment/crontab.txt')

This will install the contents of deployment/crontab.txt to the crontab of the user you connect to the server. If you dont have your complete project on the server, you'd want to put the crontab file first.


问:
"TypeError: User is not a constructor " while sending object to server in node.js
I am trying to save a user to mongodb database using post request as follow, but I got the error TypeError: User is not a constructor. It's a pretty simple set up of the code but i can't figure out anything wrong with it.

```<code>//models/users.js
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const confic = require('../models/users');

// User schema
const UserSchema = mongoose.Schema({
      name: {
          type: String,
         },
     email: {
          type: String,
          required: true
         },
    username:{
          type: String,
          required: true
         },
    password: {
        type: String,
        required: true
      }
   });

 const User = module.exports = mongoose.model('User', UserSchema);

   module.exports.getUserById = function(id,callback){
    User.findById(id,callback);
   }

  module.exports.getUserByUsername = function(username,callback){
    const query = {username:username}
    User.findOne(query,callback);
  }

 module.exports.addUser= function (newUser, callback) {
   bcrypt.gensalt(10,(err,salt) => {
    bcrypt.hash(newUser.password, salt , (err, hash) =>{
       if(err) throw err;
       newUser.password=hash;
       newUser.save(callback);
     });
   });
}
</code>```

routes/users.js

```<code> //routes/users.js

 const express = require('express');
 const router = express.Router();
 const passport = require('passport');
 const jwt = require('jsonwebtoken');
 User = require('../models/users');

  // // Register
  router.post('/register', (req, res, next) => {
    var newUser = new User({
    name: req.body.name,
    email: req.body.email,
    username: req.body.username,
    password: req.body.password
  });

  User.addUser(newUser, (err, User) => {
    if(err){
      res.json({success: false, msg:'Failed to register user'});
     } else {
      res.json({success: true, msg:'User registered'});
    }

 });

});

  // Authenticate
 router.post('/authenticate', (req, res, next) => {
 res.send('AUTHENTICATE');
 });

  // Profile
 router.get('/profile', (req, res, next) => {
 res.send('PROFILE');
 });

 module.exports = router;
</code>```

I am using Postman chrome to send data but it is not showing user registered according to program.

答:
You are exporting your user model from a different file and trying to import from a different file.

change this line:

```<code> const User = require('../config/database');
</code>```

to this:

```<code> const User = require('../models/users')  # import your user model
</code>```

Body:
I am trying to save a user to mongodb database using post request as follow, but I got the error TypeError: User is not a constructor. It's a pretty simple set up of the code but i can't figure out anything wrong with it.

//models/users.js
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const confic = require('../models/users');

// User schema
const UserSchema = mongoose.Schema({
      name: {
          type: String,
         },
     email: {
          type: String,
          required: true
         },
    username:{
          type: String,
          required: true
         },
    password: {
        type: String,
        required: true
      }
   });

 const User = module.exports = mongoose.model('User', UserSchema);

   module.exports.getUserById = function(id,callback){
    User.findById(id,callback);
   }

  module.exports.getUserByUsername = function(username,callback){
    const query = {username:username}
    User.findOne(query,callback);
  }

 module.exports.addUser= function (newUser, callback) {
   bcrypt.gensalt(10,(err,salt) => {
    bcrypt.hash(newUser.password, salt , (err, hash) =>{
       if(err) throw err;
       newUser.password=hash;
       newUser.save(callback);
     });
   });
}

routes/users.js

 //routes/users.js

 const express = require('express');
 const router = express.Router();
 const passport = require('passport');
 const jwt = require('jsonwebtoken');
 User = require('../models/users');

  // // Register
  router.post('/register', (req, res, next) => {
    var newUser = new User({
    name: req.body.name,
    email: req.body.email,
    username: req.body.username,
    password: req.body.password
  });

  User.addUser(newUser, (err, User) => {
    if(err){
      res.json({success: false, msg:'Failed to register user'});
     } else {
      res.json({success: true, msg:'User registered'});
    }

 });

});

  // Authenticate
 router.post('/authenticate', (req, res, next) => {
 res.send('AUTHENTICATE');
 });

  // Profile
 router.get('/profile', (req, res, next) => {
 res.send('PROFILE');
 });

 module.exports = router;

I am using Postman chrome to send data but it is not showing user registered according to program.

Body:
You are exporting your user model from a different file and trying to import from a different file.

change this line:

 const User = require('../config/database');

to this:

 const User = require('../models/users')  # import your user model


问:
Regular Expression match day
I'm learning about Regex in C#, I've written the codes to check a valid day but Regex.Match is always false.

```<code>var pat = @"(today|tomorrow|yesterday)((?:\s*[+-]?\s*\d+\s*[dwym])*)"; // Can not change

Match match = Regex.Match(value, pat);
</code>```

the match.Success is always false (value = 2017-07-07)

Which format can match with that pattern?

答:
What are you actually trying to achieve? From the looks of it you are trying to match either some text (today/tomorrow/yesterday), or a date in a specific format?

Try this:

```<code>(today|tomorrow|yesterday|\d{4}-\d{2}-\d{2})
</code>```

Try using a regular expression designer as well. I use Rad Software Regular Expression Designer 1.4.

Title: Regular Expression match day

Body:
I'm learning about Regex in C#, I've written the codes to check a valid day but Regex.Match is always false.

var pat = @"(today|tomorrow|yesterday)((?:\s*[+-]?\s*\d+\s*[dwym])*)"; // Can not change

Match match = Regex.Match(value, pat);

the match.Success is always false (value = 2017-07-07)

Which format can match with that pattern?

Body:
What are you actually trying to achieve? From the looks of it you are trying to match either some text (today/tomorrow/yesterday), or a date in a specific format?

Try this:

(today|tomorrow|yesterday|\d{4}-\d{2}-\d{2})

Try using a regular expression designer as well. I use Rad Software Regular Expression Designer 1.4.


问:
OpenLayers 4: WFS Layer not shown on the map when using ol.format.WFS
I am trying to show a WFS layer using Openlayers 4. If I query the server asking for the format as json and use ol.format.GeoJSON the layer shows up correctly in the map. But querying the server with request for gml3 (and using ol.format.WFS) does not show the layer. I checked the vectorSource and it indeed has features loaded, but they are not shown.

Anyone has any clue of what this might be? Bellow is my code and a snippet of the xml response.

```<code>loadLayer: function() {
      var wfsFormat = new ol.format.WFS();
      var self = this;
      this._vectorSource = new ol.source.Vector({
        format: wfsFormat,
        url: function(extent) {
          var url = self.serviceUrl +                  '&request=GetFeature&typeName=cite:dl_3&outputFormat=gml3&srsname=EPSG:3857' +
              '&bbox=' + extent.join(',') + ',EPSG:3857';
          return url;
      },
        strategy: ol.loadingstrategy.bbox,
        projection: 'EPSG:3857',
      });

      this.inherited(arguments);
    }
</code>```

This loader is in a class called WFSLayer. Bellow is the code in the main:

```<code>var wfsLayer = WFSLayer({
            serviceUrl: wfsServiceUrl,
        });
        wfsLayer.loadLayer();

        var wfsVector = new ol.layer.Vector({
            source: wfsLayer.getVectorSource(),
            style: new ol.style.Style({
                stroke: new ol.style.Stroke({
                    color: 'rgba(0, 0, 255, 1.0)',
                    width: 2,
                }),
            }),
        });

        var raster = new ol.layer.Tile({
            source: new ol.source.XYZ({
                attributions: 'Tiles © <a href="https://services.arcgisonline.com/ArcGIS/' +
                'rest/services/World_Topo_Map/MapServer">ArcGIS</a>',
                url: 'https://server.arcgisonline.com/ArcGIS/rest/services/' +
                'World_Topo_Map/MapServer/tile/{z}/{y}/{x}',
            }),
        });

        var map = new ol.Map({
            layers: [raster, wfsVector],
            target: document.getElementById('map'),
            view: new ol.View({
                center: [705208.0811999999, 6839435.416199997],
                zoom: 8,
                projection: 'EPSG:3857',
            }),
        });
</code>```

And here is a snippet of the xml response:

```<code><wfs:FeatureCollection xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:wfs="http://www.opengis.net/wfs" xmlns:gml="http://www.opengis.net/gml" xmlns:cite="http://www.opengeospatial.net/cite" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" numberOfFeatures="10070" timeStamp="2017-06-15T15:06:48Z" xsi:schemaLocation="http://www.opengeospatial.net/cite http://geoserver:8080/geoserver/wfs?service=WFS&version=1.1.0&request=DescribeFeatureType&typeName=cite%3Adl_3 http://www.opengis.net/wfs http://geoserver:8080/geoserver/schemas/wfs/1.1.0/wfs.xsd">
<gml:featureMembers>
<cite:dl_3 gml:id="dl_3.1">
<cite:the_geom>
<gml:MultiLineString srsName="http://www.opengis.net/gml/srs/epsg.xml#3857" srsDimension="3">
<gml:lineStringMember>
<gml:LineString>
<gml:posList>
498498.93497989 6786346.91870299 43.80370511 498497.04800763 6786352.73097019 43.68967084 498495.16103228 6786358.54324726 43.83243658 498498.89640871 6786359.76200893 43.70402609 498499.33127574 6786359.90391212 43.65502487 498501.21824812 6786354.09163816 43.72265914 498503.10521781 6786348.27936783 43.7882934 498502.63037784 6786348.12447027 43.82089473 498498.93497989 6786346.91870299 43.80370511
</gml:posList>
</gml:LineString>
</gml:lineStringMember>
</gml:MultiLineString>
</cite:the_geom>
</cite:dl_3>
<cite:dl_3 gml:id="dl_3.2">
<cite:the_geom>
<gml:MultiLineString srsName="http://www.opengis.net/gml/srs/epsg.xml#3857" srsDimension="3">
<gml:lineStringMember>
<gml:LineString>
<gml:posList>
498509.86707833 6786343.314062 43.70141855 498508.02631507 6786349.10070888 43.75378441 498506.18554938 6786354.88735662 43.69115027 498509.61544357 6786355.98400546 43.67794078 498510.10837676 6786356.14156283 43.62683941 498511.94913995 6786350.35491354 43.70037356 498513.78990048 6786344.56826831 43.7912077 498513.44929737 6786344.45934742 43.78340864 498509.86707833 6786343.314062 43.70141855
</gml:posList>
</gml:LineString>
</gml:lineStringMember>
</gml:MultiLineString>
</cite:the_geom>
</cite:dl_3>
<cite:dl_3 gml:id="dl_3.3">
<cite:the_geom>
<gml:MultiLineString srsName="http://www.opengis.net/gml/srs/epsg.xml#3857" srsDimension="3">
<gml:lineStringMember>
<gml:LineString>
<gml:posList>
498513.37376869 6786275.58223307 43.95293282 498510.96125125 6786281.14230307 43.92010051 498508.54873049 6786286.70237625 43.89516819 498511.70049349 6786288.07686893 43.8335572 498514.11293161 6786282.51679254 43.84838951 498516.5253664 6786276.95671993 43.89402182 498513.70936863 6786275.72873202 43.95213165 498513.37376869 6786275.58223307 43.95293282
</gml:posList>
</gml:LineString>
</gml:lineStringMember>
</gml:MultiLineString>
</cite:the_geom>
</cite:dl_3>
<cite:dl_3 gml:id="dl_3.4">
<cite:the_geom>
<gml:MultiLineString srsName="http://www.opengis.net/gml/srs/epsg.xml#3857" srsDimension="3">
<gml:lineStringMember>
<gml:LineString>
<gml:posList>
498547.56469744 6786240.41906434 43.91062195 498546.95224789 6786240.21669251 43.91602369 498547.4916903 6786238.48738942 43.91663392 498548.12052306 6786238.67374152 43.91073226 498547.56469744 6786240.41906434 43.91062195
</gml:posList>
</gml:LineString>
</gml:lineStringMember>
</gml:MultiLineString>
</cite:the_geom>
</cite:dl_3>
<cite:dl_3 gml:id="dl_3.20">
<cite:the_geom>
<gml:MultiLineString srsName="http://www.opengis.net/gml/srs/epsg.xml#3857" srsDimension="3">
<gml:lineStringMember>
<gml:LineString>
<gml:posList>
498835.21795003 6785163.91809574 46.00415766 498829.6138097 6785161.26036719 46.02577907
</gml:posList>
</gml:LineString>
</gml:lineStringMember>
</gml:MultiLineString>
</cite:the_geom>
</cite:dl_3>
</code>```

答: I figured it out. In case someone out there has the same problem. The problem is I was using GML3 with a 3D layer. Openlayers does not correctly take the srsDimension attribute from the XML so the coordinates will be incorrect. As of now you can use GML2 for this (or process the XML before). I have added it as an issue to git.</p>

Body:
I am trying to show a WFS layer using Openlayers 4. If I query the server asking for the format as json and use ol.format.GeoJSON the layer shows up correctly in the map. But querying the server with request for gml3 (and using ol.format.WFS) does not show the layer. I checked the vectorSource and it indeed has features loaded, but they are not shown.

Anyone has any clue of what this might be? Bellow is my code and a snippet of the xml response.

loadLayer: function() {
      var wfsFormat = new ol.format.WFS();
      var self = this;
      this._vectorSource = new ol.source.Vector({
        format: wfsFormat,
        url: function(extent) {
          var url = self.serviceUrl +                  '&request=GetFeature&typeName=cite:dl_3&outputFormat=gml3&srsname=EPSG:3857' +
              '&bbox=' + extent.join(',') + ',EPSG:3857';
          return url;
      },
        strategy: ol.loadingstrategy.bbox,
        projection: 'EPSG:3857',
      });

      this.inherited(arguments);
    }

This loader is in a class called WFSLayer. Bellow is the code in the main:

var wfsLayer = WFSLayer({
            serviceUrl: wfsServiceUrl,
        });
        wfsLayer.loadLayer();

        var wfsVector = new ol.layer.Vector({
            source: wfsLayer.getVectorSource(),
            style: new ol.style.Style({
                stroke: new ol.style.Stroke({
                    color: 'rgba(0, 0, 255, 1.0)',
                    width: 2,
                }),
            }),
        });

        var raster = new ol.layer.Tile({
            source: new ol.source.XYZ({
                attributions: 'Tiles © ArcGIS',
                url: 'https://server.arcgisonline.com/ArcGIS/rest/services/' +
                'World_Topo_Map/MapServer/tile/{z}/{y}/{x}',
            }),
        });

        var map = new ol.Map({
            layers: [raster, wfsVector],
            target: document.getElementById('map'),
            view: new ol.View({
                center: [705208.0811999999, 6839435.416199997],
                zoom: 8,
                projection: 'EPSG:3857',
            }),
        });

And here is a snippet of the xml response:

<wfs:FeatureCollection xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:wfs="http://www.opengis.net/wfs" xmlns:gml="http://www.opengis.net/gml" xmlns:cite="http://www.opengeospatial.net/cite" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" numberOfFeatures="10070" timeStamp="2017-06-15T15:06:48Z" xsi:schemaLocation="http://www.opengeospatial.net/cite http://geoserver:8080/geoserver/wfs?service=WFS&version=1.1.0&request=DescribeFeatureType&typeName=cite%3Adl_3 http://www.opengis.net/wfs http://geoserver:8080/geoserver/schemas/wfs/1.1.0/wfs.xsd">
<gml:featureMembers>

<gml:MultiLineString srsName="http://www.opengis.net/gml/srs/epsg.xml#3857" srsDimension="3">
<gml:lineStringMember>
<gml:LineString>
<gml:posList>
498498.93497989 6786346.91870299 43.80370511 498497.04800763 6786352.73097019 43.68967084 498495.16103228 6786358.54324726 43.83243658 498498.89640871 6786359.76200893 43.70402609 498499.33127574 6786359.90391212 43.65502487 498501.21824812 6786354.09163816 43.72265914 498503.10521781 6786348.27936783 43.7882934 498502.63037784 6786348.12447027 43.82089473 498498.93497989 6786346.91870299 43.80370511
</gml:posList>
</gml:LineString>
</gml:lineStringMember>
</gml:MultiLineString>

<gml:MultiLineString srsName="http://www.opengis.net/gml/srs/epsg.xml#3857" srsDimension="3">
<gml:lineStringMember>
<gml:LineString>
<gml:posList>
498509.86707833 6786343.314062 43.70141855 498508.02631507 6786349.10070888 43.75378441 498506.18554938 6786354.88735662 43.69115027 498509.61544357 6786355.98400546 43.67794078 498510.10837676 6786356.14156283 43.62683941 498511.94913995 6786350.35491354 43.70037356 498513.78990048 6786344.56826831 43.7912077 498513.44929737 6786344.45934742 43.78340864 498509.86707833 6786343.314062 43.70141855
</gml:posList>
</gml:LineString>
</gml:lineStringMember>
</gml:MultiLineString>

<gml:MultiLineString srsName="http://www.opengis.net/gml/srs/epsg.xml#3857" srsDimension="3">
<gml:lineStringMember>
<gml:LineString>
<gml:posList>
498513.37376869 6786275.58223307 43.95293282 498510.96125125 6786281.14230307 43.92010051 498508.54873049 6786286.70237625 43.89516819 498511.70049349 6786288.07686893 43.8335572 498514.11293161 6786282.51679254 43.84838951 498516.5253664 6786276.95671993 43.89402182 498513.70936863 6786275.72873202 43.95213165 498513.37376869 6786275.58223307 43.95293282
</gml:posList>
</gml:LineString>
</gml:lineStringMember>
</gml:MultiLineString>

<gml:MultiLineString srsName="http://www.opengis.net/gml/srs/epsg.xml#3857" srsDimension="3">
<gml:lineStringMember>
<gml:LineString>
<gml:posList>
498547.56469744 6786240.41906434 43.91062195 498546.95224789 6786240.21669251 43.91602369 498547.4916903 6786238.48738942 43.91663392 498548.12052306 6786238.67374152 43.91073226 498547.56469744 6786240.41906434 43.91062195
</gml:posList>
</gml:LineString>
</gml:lineStringMember>
</gml:MultiLineString>

<gml:MultiLineString srsName="http://www.opengis.net/gml/srs/epsg.xml#3857" srsDimension="3">
<gml:lineStringMember>
<gml:LineString>
<gml:posList>
498835.21795003 6785163.91809574 46.00415766 498829.6138097 6785161.26036719 46.02577907
</gml:posList>
</gml:LineString>
</gml:lineStringMember>
</gml:MultiLineString>


问:
How to detect slow connection in ROKU Scene Graph?
The requirement says "Switch to low definition video when connection is slow"
I'm wondering is there anyway.
Any help would be appreciated</p>

答:
You can try checking the streamInfo field of the video node.
It is an associative array, which holds some info:

measuredBItrate   (Integer)   The measured bitrate (bps) of the network when the stream was selected.

streamBitrate (Integer)   The bitrate of the stream


问:
C++0x: How can I access variadic tuple members by index at runtime?
I have written the following basic Tuple template:

```<code>template <typename... T>
class Tuple;

template <uintptr_t N, typename... T>
struct TupleIndexer;

template <typename Head, typename... Tail>
class Tuple<Head, Tail...> : public Tuple<Tail...> {

    private:
    Head element;

    public:
    template <uintptr_t N>
    typename TupleIndexer<N, Head, Tail...>::Type& Get() {
        return TupleIndexer<N, Head, Tail...>::Get(*this);
    }

    uintptr_t GetCount() const {
        return sizeof...(Tail) + 1;
    }

    private:
    friend struct TupleIndexer<0, Head, Tail...>;

};

template <>
class Tuple<> {

    public:
    uintptr_t GetCount() const {
        return 0;
    }

};

template <typename Head, typename... Tail>
struct TupleIndexer<0, Head, Tail...> {

    typedef Head& Type;

    static Type Get(Tuple<Head, Tail...>& tuple) {
        return tuple.element;
    }

};

template <uintptr_t N, typename Head, typename... Tail>
struct TupleIndexer<N, Head, Tail...> {

    typedef typename TupleIndexer<N - 1, Tail...>::Type Type;

    static Type Get(Tuple<Head, Tail...>& tuple) {
        return TupleIndexer<N - 1, Tail...>::Get(*(Tuple<Tail...>*) &tuple);
    }

};
</code>```

It works just fine, and I can access elements in array-like fashion by using tuple.Get<Index>() - but I can only do that if I know the index at compile-time.  However, I need to access elements in the tuple by index at runtime, and I won't know at compile-time which index needs to be accessed.  Example:

```<code>int chosenIndex = getUserInput();
void* chosenElement = tuple.Get(chosenIndex);
cout << "The option you chose was: " << ((MyAbstractBaseClass*) chosenElement)->getInfo() << endl;
</code>```

What's the best way to do this?

EDIT:

Hackish solution below:

Okay, I've got an idea.  I already figured out one way of doing this before I even posted this question, but it was hackish and produced warnings.  Since another solution isn't forthcoming right away, maybe you guys could help me improve my hackish one. :-)

The tuple can't normally be accessed like an array because the elements are not all necessarily of the same size.  (Hence array-style multiplication to arrive at the correct offset in the class structure will not help.)  However, I managed to work around this by creating a static table that contains a list of offsets for a tuple.  Here's the complete tuple and related templates:

```<code>#include <cstddef>

template <typename... T>
class Tuple;

template <uintptr_t N, typename... T>
struct TupleIndexer;

template <typename... T>
struct TupleOffsets;

template <typename Head, typename... Tail>
struct TupleOffsets<Head, Tail...> {

    TupleOffsets() { Init(offsets); }
    static void Init(uintptr_t* offsets);
    uintptr_t const& operator[] (uintptr_t i) const { return offsets[i]; }

    private:
    uintptr_t offsets[sizeof...(Tail) + 1];

};

template <typename Head, typename... Tail>
void TupleOffsets<Head, Tail...>::Init(uintptr_t* offsets) {

    typedef Tuple<Head, Tail...> Type;

    *offsets = offsetof(Type, element);
    TupleOffsets<Tail...>::Init(++offsets);

}

template <>
struct TupleOffsets<> {

    TupleOffsets() {}
    static void Init(uintptr_t* offsets) {}

};

template <typename Head, typename... Tail>
class Tuple<Head, Tail...> : public Tuple<Tail...> {

    private:
    Head element;

    public:
    void* Get(uintptr_t i) {
        return (uint8_t*) this + offsets[i];
    }

    template <uintptr_t N>
    typename TupleIndexer<N, Head, Tail...>::Type& Get() {
        return TupleIndexer<N, Head, Tail...>::Get(*this);
    }

    uintptr_t GetCount() const {
        return sizeof...(Tail) + 1;
    }

    private:
    static const TupleOffsets<Head, Tail...> offsets;

    friend struct TupleOffsets<Head, Tail...>;
    friend struct TupleIndexer<0, Head, Tail...>;

};

template <typename Head, typename... Tail>
const TupleOffsets<Head, Tail...> Tuple<Head, Tail...>::offsets;

template <>
class Tuple<> {

    public:
    uintptr_t GetCount() const {
        return 0;
    }

};

template <typename Head, typename... Tail>
struct TupleIndexer<0, Head, Tail...> {

    typedef Head& Type;

    static Type Get(Tuple<Head, Tail...>& tuple) {
        return tuple.element;
    }

};

template <uintptr_t N, typename Head, typename... Tail>
struct TupleIndexer<N, Head, Tail...> {

    typedef typename TupleIndexer<N - 1, Tail...>::Type Type;

    static Type Get(Tuple<Head, Tail...>& tuple) {
        return TupleIndexer<N - 1, Tail...>::Get(*(Tuple<Tail...>*) &tuple);
    }

};
</code>```

In practice it works.  However, the compiler gives me a warning for using offsetof on a non-POD data type, and I'm not sure how portable this solution is.  Anyone know how I might improve this solution?

答:
You do the exact same thing as you do with TupleIndexer, just at runtime.

Add a function like this to the Tuple class:

```<code>Head &operator[](unsigned i) {
    return i ? ((Tuple<Tail...>&)*this)[i-1] : element;
}
</code>```

and add a specialization for Tuple:

```<code>Head &operator[](unsigned i) {
    assert(!i);
    return i;
}
</code>```

(You can't put the base case into Tuple<>, since you don't have a type to return that would be compatible with every possible caller.)

Body:
I have written the following basic Tuple template:

template <typename... T>
class Tuple;

template <uintptr_t N, typename... T>
struct TupleIndexer;

template <typename Head, typename... Tail>
class Tuple : public Tuple<Tail...> {

    private:
    Head element;

    public:
    template <uintptr_t N>
    typename TupleIndexer<N, Head, Tail...>::Type& Get() {
        return TupleIndexer<N, Head, Tail...>::Get(*this);
    }

    uintptr_t GetCount() const {
        return sizeof...(Tail) + 1;
    }

    private:
    friend struct TupleIndexer<0, Head, Tail...>;

};

template <>
class Tuple<> {

    public:
    uintptr_t GetCount() const {
        return 0;
    }

};

template <typename Head, typename... Tail>
struct TupleIndexer<0, Head, Tail...> {

    typedef Head& Type;

    static Type Get(Tuple& tuple) {
        return tuple.element;
    }

};

template <uintptr_t N, typename Head, typename... Tail>
struct TupleIndexer<N, Head, Tail...> {

    typedef typename TupleIndexer<N - 1, Tail...>::Type Type;

    static Type Get(Tuple& tuple) {
        return TupleIndexer<N - 1, Tail...>::Get(*(Tuple<Tail...>*) &tuple);
    }

};

It works just fine, and I can access elements in array-like fashion by using tuple.Get<Index>() - but I can only do that if I know the index at compile-time.  However, I need to access elements in the tuple by index at runtime, and I won't know at compile-time which index needs to be accessed.  Example:

int chosenIndex = getUserInput();
void* chosenElement = tuple.Get(chosenIndex);
cout << "The option you chose was: " << ((MyAbstractBaseClass*) chosenElement)->getInfo() << endl;

What's the best way to do this?

EDIT:

Hackish solution below:

Okay, I've got an idea.  I already figured out one way of doing this before I even posted this question, but it was hackish and produced warnings.  Since another solution isn't forthcoming right away, maybe you guys could help me improve my hackish one. :-)

The tuple can't normally be accessed like an array because the elements are not all necessarily of the same size.  (Hence array-style multiplication to arrive at the correct offset in the class structure will not help.)  However, I managed to work around this by creating a static table that contains a list of offsets for a tuple.  Here's the complete tuple and related templates:

#include <cstddef>

template <typename... T>
class Tuple;

template <uintptr_t N, typename... T>
struct TupleIndexer;

template <typename... T>
struct TupleOffsets;

template <typename Head, typename... Tail>
struct TupleOffsets {

    TupleOffsets() { Init(offsets); }
    static void Init(uintptr_t* offsets);
    uintptr_t const& operator[] (uintptr_t i) const { return offsets[i]; }

    private:
    uintptr_t offsets[sizeof...(Tail) + 1];

};

template <typename Head, typename... Tail>
void TupleOffsets::Init(uintptr_t* offsets) {

    typedef Tuple Type;

    *offsets = offsetof(Type, element);
    TupleOffsets<Tail...>::Init(++offsets);

}

template <>
struct TupleOffsets<> {

    TupleOffsets() {}
    static void Init(uintptr_t* offsets) {}

};

template <typename Head, typename... Tail>
class Tuple : public Tuple<Tail...> {

    private:
    Head element;

    public:
    void* Get(uintptr_t i) {
        return (uint8_t*) this + offsets[i];
    }

    template <uintptr_t N>
    typename TupleIndexer<N, Head, Tail...>::Type& Get() {
        return TupleIndexer<N, Head, Tail...>::Get(*this);
    }

    uintptr_t GetCount() const {
        return sizeof...(Tail) + 1;
    }

    private:
    static const TupleOffsets offsets;

    friend struct TupleOffsets;
    friend struct TupleIndexer<0, Head, Tail...>;

};

template <typename Head, typename... Tail>
const TupleOffsets Tuple::offsets;

template <>
class Tuple<> {

    public:
    uintptr_t GetCount() const {
        return 0;
    }

};

template <typename Head, typename... Tail>
struct TupleIndexer<0, Head, Tail...> {

    typedef Head& Type;

    static Type Get(Tuple& tuple) {
        return tuple.element;
    }

};

template <uintptr_t N, typename Head, typename... Tail>
struct TupleIndexer<N, Head, Tail...> {

    typedef typename TupleIndexer<N - 1, Tail...>::Type Type;

    static Type Get(Tuple& tuple) {
        return TupleIndexer<N - 1, Tail...>::Get(*(Tuple<Tail...>*) &tuple);
    }

};

In practice it works.  However, the compiler gives me a warning for using offsetof on a non-POD data type, and I'm not sure how portable this solution is.  Anyone know how I might improve this solution?

Body:
You do the exact same thing as you do with TupleIndexer, just at runtime.

Add a function like this to the Tuple class:

Head &operator[](unsigned i) {
    return i ? ((Tuple<Tail...>&)*this)[i-1] : element;
}

and add a specialization for Tuple<Head>:

Head &operator[](unsigned i) {
    assert(!i);
    return i;
}

(You can't put the base case into Tuple<>, since you don't have a type to return that would be compatible with every possible caller.)


问:
Get Total Photo Count in a published post via Facebook Graph API
I am currently trying to get the total photo count in a published post via Facebook Graph API. I have tried

me/albums?fields=count,name

but this is counting the number of photos in an album. Thanks in advance

For example, total photo count is four

答:
```<code> $count =0;
 $ALLalbums = $facebook->api('/me/albums?fields=id');
 $pics = array();
 foreach ($ALLalbums['data'] as $album) {
 $pics = $facebook->api('/'.$album['id'].'/photos?fields=source,picture');
 $pics[$album['id']] = $pics['data'];
}
//Albums
foreach ($pics as $album) {
//Count Pics Inside each album
foreach ($album as $img) {
$count++;
// you can get image as well by $img['source'];
}
}
echo $count;
</code>```


问:
Giving initial value to observable from the HTML markup
I'm trying to create an HtmlHelper extension that outputs some HTML to the view. In this HTML I'm wiring up some KnockoutJS binding. I'm new to KO so I'm still struggling in getting some things done. Anyway, what I'm trying to do is generate input fields (in the server-side code) bound to observables on my client-side code, then set the initial values of the observables through the value of the hidden fields. Unfortunately, that is not working for me. So I'm wondering if there any way I could get this done (even if I have to do it completely different).

Here's what I'm basically doing:

In my client side view model I have the following:

```<code>self.dataSource = ko.observable();
self.pageSize = ko.observable();
</code>```

And my extension method outputs the following:

```<code><input type="hidden" value="/Employee/Get" data-bind="value: dataSource" />
<input type="hidden" value="30" data-bind="value: pageSize" />
</code>```

But when the page renders, when I inspect the elements I notice that the value of the input fields is being set to an empty string, which I believe is because of the way observables are being declared. But is there a way to override this behavior or something?

答:
You can simply use a custom binding and assign the values to the existing observables:

```<code>ko.bindingHandlers.yourBindingName = {
    init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
        viewModel.dataSource($(".dataSource").val());
        viewModel.pageSize($(".pageSize").val());
    }
};
</code>```

Then, just add a class, or an Id to the inputs and data-bind="yourBindingName" to the HTML element containing them.

Body:
I'm trying to create an HtmlHelper extension that outputs some HTML to the view. In this HTML I'm wiring up some KnockoutJS binding. I'm new to KO so I'm still struggling in getting some things done. Anyway, what I'm trying to do is generate input fields (in the server-side code) bound to observables on my client-side code, then set the initial values of the observables through the value of the hidden fields. Unfortunately, that is not working for me. So I'm wondering if there any way I could get this done (even if I have to do it completely different).

Here's what I'm basically doing:

In my client side view model I have the following:

self.dataSource = ko.observable();
self.pageSize = ko.observable();

And my extension method outputs the following:

<input type="hidden" value="/Employee/Get" data-bind="value: dataSource" />
<input type="hidden" value="30" data-bind="value: pageSize" />

But when the page renders, when I inspect the elements I notice that the value of the input fields is being set to an empty string, which I believe is because of the way observables are being declared. But is there a way to override this behavior or something?

Body:
You can simply use a custom binding and assign the values to the existing observables:

ko.bindingHandlers.yourBindingName = {
    init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
        viewModel.dataSource($(".dataSource").val());
        viewModel.pageSize($(".pageSize").val());
    }
};

Then, just add a class, or an Id to the inputs and data-bind="yourBindingName" to the HTML element containing them.


问:
Request.Cookies["cookieName"] is null in web service method
This is how I'am saving cookie in my code which is a web service method. I tried to change the cookie expire time but still it is not working for me. Is there any issue with Context.Response to write cookie or Context.Request to read it??

```<code>[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false)]
public void SaveInDraft(FormRootObject _forms)
{
    HttpCookie formCookie = new HttpCookie("UserData");

    formCookie.Values.Add("formid", _forms.formid);

    foreach (var item in _forms.fielddata)
    {
        formCookie.Values.Add(item.id, item.value);
    }

    formCookie.Expires = DateTime.Now.AddYears(1);
    Context.Response.Cookies.Add(formCookie);

}
</code>```

for retrieving this cookie on next page

```<code>[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false)]
public FormRootObject getDataFromCookie()
{
    FormRootObject form = new FormRootObject();
    List<formFielddata> lstFormFieldData = new List<formFielddata>();

    var getCookie=Context.Request.Cookies["UserData"];
    if (getCookie != null)
    {
        if (getCookie.Values.Count > 0)
        {
            foreach (var val in getCookie.Values)
            {
                formFielddata document = new formFielddata();

                if (val.ToString() != "formid")
                {
                    document.id = val.ToString();
                    document.value = getCookie[val.ToString()];
                    lstFormFieldData.Add(document);
                }
                else {
                    form.formid = getCookie[val.ToString()];
                }
            }

            form.fielddata = lstFormFieldData;
        }
    }

    return form;
}
</code>```

but my object getCookie is always null

答:
Rajesh, forms are only present on web applications. If you're using plain web api to create your service, no form is going to be presented to your service client.

To create a cookie:
    var resp = new HttpResponseMessage();

```<code>var cookie = new CookieHeaderValue("session-id", "12345");
cookie.Expires = DateTimeOffset.Now.AddDays(1);
cookie.Domain = Request.RequestUri.Host;
cookie.Path = "/";

resp.Headers.AddCookies(new CookieHeaderValue[] { cookie });
return resp;
</code>```

To consume cookie:

```<code>CookieHeaderValue cookie = Request.Headers.GetCookies("session-id")
</code>```

Body:
This is how I'am saving cookie in my code which is a web service method. I tried to change the cookie expire time but still it is not working for me. Is there any issue with Context.Response to write cookie or Context.Request to read it??

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false)]
public void SaveInDraft(FormRootObject _forms)
{
    HttpCookie formCookie = new HttpCookie("UserData");

    formCookie.Values.Add("formid", _forms.formid);

    foreach (var item in _forms.fielddata)
    {
        formCookie.Values.Add(item.id, item.value);
    }

    formCookie.Expires = DateTime.Now.AddYears(1);
    Context.Response.Cookies.Add(formCookie);

}

for retrieving this cookie on next page

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false)]
public FormRootObject getDataFromCookie()
{
    FormRootObject form = new FormRootObject();
    List<formFielddata> lstFormFieldData = new List<formFielddata>();

    var getCookie=Context.Request.Cookies["UserData"];
    if (getCookie != null)
    {
        if (getCookie.Values.Count > 0)
        {
            foreach (var val in getCookie.Values)
            {
                formFielddata document = new formFielddata();

                if (val.ToString() != "formid")
                {
                    document.id = val.ToString();
                    document.value = getCookie[val.ToString()];
                    lstFormFieldData.Add(document);
                }
                else {
                    form.formid = getCookie[val.ToString()];
                }
            }

            form.fielddata = lstFormFieldData;
        }
    }

    return form;
}

but my object getCookie is always null

Body:
Rajesh, forms are only present on web applications. If you're using plain web api to create your service, no form is going to be presented to your service client.

To create a cookie:
    var resp = new HttpResponseMessage();

var cookie = new CookieHeaderValue("session-id", "12345");
cookie.Expires = DateTimeOffset.Now.AddDays(1);
cookie.Domain = Request.RequestUri.Host;
cookie.Path = "/";

resp.Headers.AddCookies(new CookieHeaderValue[] { cookie });
return resp;

To consume cookie:

CookieHeaderValue cookie = Request.Headers.GetCookies("session-id")


问:
How do I restore my position in a CoordinatorLayout after rotation?
When I scroll to the bottom of my NestedScrollView and rotate the device my position in the list is saved but when I rotate back to portrait mode the ImageView in the AppBarLayout is expanded instead of collapsed like it was when I originally rotated the screen. I want to return to how it was prior to rotation, with the image either partially collapsed or completely collapsed.

Prior to device rotation

After device rotation

XML File:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/coordinator_layout"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:id="@+id/album_art"
                android:layout_width="match_parent"
                android:layout_height="300dp"
                android:scaleType="fitXY"
                app:layout_collapseMode="parallax"
                app:layout_collapseParallaxMultiplier="0.7"
                android:src="@drawable/the_getaway_album"
                android:contentDescription="@string/album_art_description" />

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
        android:id="@+id/scroll_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:padding="@dimen/standard_padding" >

                <TextView
                    android:id="@+id/album_title"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:maxLines="3"
                    android:textSize="@dimen/large_text_size"
                    android:textStyle="bold" />

                <TextView
                    android:id="@+id/explicitness"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="@dimen/standard_padding"
                    android:background="@drawable/rounded_border_filled"
                    android:text="@string/explicit_tag"
                    android:textAlignment="center"
                    android:textColor="@android:color/white"
                    android:textSize="@dimen/standard_text_size"
                    android:textStyle="bold"
                    android:visibility="invisible"/>

                <TextView
                    android:id="@+id/artist"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"/>

                <TextView
                    android:id="@+id/release_date"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

            </LinearLayout>

            <TextView
                android:id="@+id/album_price"
                android:layout_width="@dimen/large_price_bubble_length"
                android:layout_height="wrap_content"
                android:layout_marginBottom="@dimen/activity_vertical_margin"
                android:layout_gravity="center_horizontal"
                android:background="@drawable/rounded_border"
                android:textAlignment="center"
                android:textColor="@color/colorAccent"
                android:textSize="@dimen/standard_text_size"/>

            <TextView
                android:id="@+id/copyright"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:maxLines="2"
                android:ellipsize="end"
                android:textSize="12sp"
                android:textColor="@android:color/secondary_text_dark"
                android:textAlignment="center"/>

            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:layout_margin="@dimen/activity_horizontal_margin"
                android:background="@android:color/darker_gray"/>

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/track_list_title"
                android:textSize="@dimen/standard_text_size"
                android:textStyle="bold"
                android:textAlignment="center"/>

            <LinearLayout
                android:id="@+id/track_list"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">
            </LinearLayout>

        </LinearLayout>

    </android.support.v4.widget.NestedScrollView>

</android.support.design.widget.CoordinatorLayout>
</code>```

答:
Add configChanges param to manifest file it worked for me,</p>

```<code><activity
            android:name=".MainActivity"
            android:configChanges="orientation|screenSize"/>
</code>```

Body:
When I scroll to the bottom of my NestedScrollView and rotate the device my position in the list is saved but when I rotate back to portrait mode the ImageView in the AppBarLayout is expanded instead of collapsed like it was when I originally rotated the screen. I want to return to how it was prior to rotation, with the image either partially collapsed or completely collapsed.

Prior to device rotation

After device rotation

XML File:

    <?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/coordinator_layout"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:id="@+id/album_art"
                android:layout_width="match_parent"
                android:layout_height="300dp"
                android:scaleType="fitXY"
                app:layout_collapseMode="parallax"
                app:layout_collapseParallaxMultiplier="0.7"
                android:src="@drawable/the_getaway_album"
                android:contentDescription="@string/album_art_description" />

        </android.support.design.widget.CollapsingToolbarLayout>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
        android:id="@+id/scroll_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:padding="@dimen/standard_padding" >

                <TextView
                    android:id="@+id/album_title"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:maxLines="3"
                    android:textSize="@dimen/large_text_size"
                    android:textStyle="bold" />

                <TextView
                    android:id="@+id/explicitness"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="@dimen/standard_padding"
                    android:background="@drawable/rounded_border_filled"
                    android:text="@string/explicit_tag"
                    android:textAlignment="center"
                    android:textColor="@android:color/white"
                    android:textSize="@dimen/standard_text_size"
                    android:textStyle="bold"
                    android:visibility="invisible"/>

                <TextView
                    android:id="@+id/artist"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"/>

                <TextView
                    android:id="@+id/release_date"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />

            </LinearLayout>

            <TextView
                android:id="@+id/album_price"
                android:layout_width="@dimen/large_price_bubble_length"
                android:layout_height="wrap_content"
                android:layout_marginBottom="@dimen/activity_vertical_margin"
                android:layout_gravity="center_horizontal"
                android:background="@drawable/rounded_border"
                android:textAlignment="center"
                android:textColor="@color/colorAccent"
                android:textSize="@dimen/standard_text_size"/>

            <TextView
                android:id="@+id/copyright"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:maxLines="2"
                android:ellipsize="end"
                android:textSize="12sp"
                android:textColor="@android:color/secondary_text_dark"
                android:textAlignment="center"/>

            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:layout_margin="@dimen/activity_horizontal_margin"
                android:background="@android:color/darker_gray"/>

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/track_list_title"
                android:textSize="@dimen/standard_text_size"
                android:textStyle="bold"
                android:textAlignment="center"/>

            <LinearLayout
                android:id="@+id/track_list"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">
            </LinearLayout>

        </LinearLayout>

    </android.support.v4.widget.NestedScrollView>

</android.support.design.widget.CoordinatorLayout>

Body:
Add configChanges param to manifest file it worked for me,

<activity
            android:name=".MainActivity"
            android:configChanges="orientation|screenSize"/>


问:
Jquery counter on scroll
I am trying to make number counter which will work on scroll. When you scroll down, then counter is going from 0 to some number, and when you scroll up, from some number to zero. Numbers are changing during the scroll (if there is no scroll, number stay where it is in that time). Any ideas?
Thanks.</p>

答:
Using this answer to determin if the scroll goes up or down:</p>

```<code>var lastScrollTop = 0;
var counter = 0;
$(window).scroll(function(event){
   var st = $(this).scrollTop();
   if (st > lastScrollTop){
     counter++;
   } else {
     counter--;
   }
   lastScrollTop = st;
});
</code>```

Title: Jquery counter on scroll

Body:
Using this answer to determin if the scroll goes up or down:

var lastScrollTop = 0;
var counter = 0;
$(window).scroll(function(event){
   var st = $(this).scrollTop();
   if (st > lastScrollTop){
     counter++;
   } else {
     counter--;
   }
   lastScrollTop = st;
});


问:
vscode jshint configuration
I want to exclude some diretory in my project and configure vscode jshint in setting.json

```<code>{
    "jslint.exclude": "C:\\Users\\Administrator\\Desktop\\tmp"
}
</code>```

However a object is ecpected, so what is the key of object?

答:
jslint.exclude maps paths (which possibly contain globs) to true or false to indicate if the path should be excluded

```<code>"jslint.exclude": {
     "C:\\Users\\Administrator\\Desktop\\tmp": true,
     "**\\*.es6": true
}
</code>```

Title: vscode jshint configuration

Body:
I want to exclude some diretory in my project and configure vscode jshint in setting.json

{
    "jslint.exclude": "C:\\Users\\Administrator\\Desktop\\tmp"
}

However a object is ecpected, so what is the key of object?

Body:
jslint.exclude maps paths (which possibly contain globs) to true or false to indicate if the path should be excluded

"jslint.exclude": {
     "C:\\Users\\Administrator\\Desktop\\tmp": true,
     "**\\*.es6": true
}


答:
Try this and check your console

HTML

```<code><div class="body">

</div>
</code>```

jquery

```<code>$(window).scroll(function(){
    console.log($(window).scrollTop());
});
</code>```

css

```<code>.body{
    height:900px;
}
</code>```

Title: Jquery counter on scroll

Body:
I am trying to make number counter which will work on scroll. When you scroll down, then counter is going from 0 to some number, and when you scroll up, from some number to zero. Numbers are changing during the scroll (if there is no scroll, number stay where it is in that time). Any ideas?
Thanks.

Body:
Try this and check your console

HTML

<div class="body">

</div>

jquery

$(window).scroll(function(){
    console.log($(window).scrollTop());
});

css

.body{
    height:900px;
}


问:
Looking for good solutions for blocking TOR
I am running an asp.net mvc website, and i want to block every user that reaches my site through TOR. By now i have two solutions:

Download list of TOR exit nodes once every hour, store that list in
memory, and check every request IP address with that list.

Try to block TOR exit nodes with windows firewall - i think that this would
be better, but i don't know how to do that.

Is there any other possible solution? Have any of you maybe had a similar problem to mine? How did you solve it?

Body:
Here(https://github.com/RD17/DeTor) is a simple REST API which use TorDNSEl to determine whether a request was made from TOR network or not. I think it will be pretty simple to use it from C# with RESTSharp for example.

The request is:
curl -X GET http://detor.ambar.cloud/.

The response is

{
  "sourceIp": "104.200.20.46",
  "destIp": "89.207.89.82",
  "destPort": "8080",
  "found": true
}

As a bonus you can add a badge to your site to detect whether a user comes from TOR or not:

<img src='http://detor.ambar.cloud/badge' />


问:
div with display: flex is not centering child div
I have a div with a display: flex, and I would like to display the output in a row center. For some reason it is displaying left. I want the imgBoxBot to be centered inside the imgBot div. But text-align: center is only centering the text inside the imgBoxBot, how do I center the actual div?

#imgBot {
  position: absolute;
  height: 100px;
  width: 100%;
  bottom: 0;
  display: flex;
  flex-direction: row;
  text-align: center;
}

#imgBoxBot {
  height: 100px;
  width: 100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="imgBot">
  <div id="imgBoxBot">
    test
  </div>
  <div id="imgBoxBot">
    test
  </div>
</div></code>```

答:
Use justify-content: center. You can find more information here

#imgBot {
  position: absolute;
  height: 100px;
  width: 100%;
  bottom: 0;
  display: flex;
  flex-direction: row;
  justify-content: center;
}

.imgBoxBot {
  height: 100px;
  width: 100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="imgBot">
  <div class="imgBoxBot">
    test
  </div>
  <div class="imgBoxBot">
    test
  </div>
</div></code>```

Body:
I have a div with a display: flex, and I would like to display the output in a row center. For some reason it is displaying left. I want the imgBoxBot to be centered inside the imgBot div. But text-align: center is only centering the text inside the imgBoxBot, how do I center the actual div?

#imgBot {
  position: absolute;
  height: 100px;
  width: 100%;
  bottom: 0;
  display: flex;
  flex-direction: row;
  text-align: center;
}

#imgBoxBot {
  height: 100px;
  width: 100px;
}

    test

    test

Body:
Use justify-content: center. You can find more information here

#imgBot {
  position: absolute;
  height: 100px;
  width: 100%;
  bottom: 0;
  display: flex;
  flex-direction: row;
  justify-content: center;
}

.imgBoxBot {
  height: 100px;
  width: 100px;
}

<div id="imgBot">
  <div class="imgBoxBot">
    test
  </div>
  <div class="imgBoxBot">
    test
  </div>
</div>


问:
cout value without touching variable C++
When I run the program, it prints the value of variable a. But when I comment the line 'cout<<&b<<endl<<&a<<endl;' it prints a garbage value.
What can be the explanation behind it?

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

int main()
{
    int a = 9;
    int b = 10;
    int *pb = &b;
    cout<<&b<<endl<<&a<<endl;
    cout<<*(pb+1);
}
</code>```

答:
There are two spots where you could get "gibberish" values however only one of them is actualy where garbage is printed out.

This cout << &b << endl << &a << endl; will print the addresses of a and b by using the address-of-operator. What you see there are not the values of a and b rather there locations where they are stored in memory. Those are hex values and they will probably change each time you run the program. This is the expected behaviour.

Then there is this construct: *(pb + 1) which is actually invoking undefined behaviour. But why is this? First of all pb is a pointer so it stores an adress, more specifically the memory address where b is stored. You can either print out pb directly which will result in the same thing as cout << &b or dereference it using the dereference operator *. So this cout << *pb would print the value not the address pb is pointing to (10 btw). Now to what is wrong with your statement - (pb + 1) is not increasing the value pb is pointing but the address stored in pb. So it no longer points to the value of b but to some other value somewhere in the memory. Then you dereference this address and read some random value - this is your "garbage" value.

What you probably want is to increase the value pb is pointing to. So cout << (*pb + 1) will print 11 (note where the brackets are placed). But cout << b would still result in 10. If you want to actually alter the value of b you could do this:

```<code>int b = 10;
int *pb = &b;
*pb += 1;
cout << b;
</code>```

Now b was increased by one without touching b itself.

Body:
When I run the program, it prints the value of variable a. But when I comment the line 'cout<<&b<<endl<<&a<<endl;' it prints a garbage value.
What can be the explanation behind it?

#include<iostream>
using namespace std;

int main()
{
    int a = 9;
    int b = 10;
    int *pb = &b;
    cout<<&b<<endl<<&a<<endl;
    cout<<*(pb+1);
}

Body:
There are two spots where you could get "gibberish" values however only one of them is actualy where garbage is printed out.

This cout << &b << endl << &a << endl; will print the addresses of a and b by using the address-of-operator. What you see there are not the values of a and b rather there locations where they are stored in memory. Those are hex values and they will probably change each time you run the program. This is the expected behaviour.

Then there is this construct: *(pb + 1) which is actually invoking undefined behaviour. But why is this? First of all pb is a pointer so it stores an adress, more specifically the memory address where b is stored. You can either print out pb directly which will result in the same thing as cout << &b or dereference it using the dereference operator *. So this cout << *pb would print the value not the address pb is pointing to (10 btw). Now to what is wrong with your statement - (pb + 1) is not increasing the value pb is pointing but the address stored in pb. So it no longer points to the value of b but to some other value somewhere in the memory. Then you dereference this address and read some random value - this is your "garbage" value.

What you probably want is to increase the value pb is pointing to. So cout << (*pb + 1) will print 11 (note where the brackets are placed). But cout << b would still result in 10. If you want to actually alter the value of b you could do this:

int b = 10;
int *pb = &b;
*pb += 1;
cout << b;

Now b was increased by one without touching b itself.


问:
How to show approved comments in Laravel
I want to show post's comments (approved = true) We have a single post with a random slug/id, But the problem is: How can I show approved comments with that specific post id !?

I think i have to use something like this following example :

```<code>Post::find($id)->Comments()->whereApproved(true)->get()
</code>```

Comments Table :

答:
As I understand from the description, approved column is in the comments table. You can get comments with just one query since you know post ID:

```<code>Comment::where('post_id', $postId)
       ->where('approved', true)
       ->get();
</code>```

If you want to get the post with approved comments, do this:

```<code>Post::with(['comments' => function ($q) {
    $q->where('approved', true);
}])->find($postId);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to show post's comments (approved = true) We have a single post with a random slug/id, But the problem is: How can I show approved comments with that specific post id !?

I think i have to use something like this following example :

Post::find($id)->Comments()->whereApproved(true)->get()

Comments Table :

Body:
As I understand from the description, approved column is in the comments table. You can get comments with just one query since you know post ID:

Comment::where('post_id', $postId)
       ->where('approved', true)
       ->get();

If you want to get the post with approved comments, do this:

Post::with(['comments' => function ($q) {
    $q->where('approved', true);
}])->find($postId);


问:
Image preprocessing in deep learning
I am experimenting with deep learning on images. I have about ~4000 images from different cameras with different light conditions, image resolutions and view angle.

My question is: What kind of image preprocessing would be helpful for improving object detection? (For example: contrast/color normalization, denoising, etc.)

答:
For pre-processing of images before feeding them into the Neural Networks. It is better to make the data Zero Centred. Then try out normalization technique. It certainly will increase the accuracy as the data is scaled in a range than arbitrarily large values or too small values.

An example image will be: -

Here is a explanation of it from Stanford CS231n 2016 Lectures.

*

Normalization  refers to normalizing the data dimensions so that they are of approximately the same scale. For Image data There are two common ways of achieving this normalization. One is to divide each dimension by its standard deviation, once it has been zero-centered:

    (X /= np.std(X, axis = 0)). Another form of this preprocessing normalizes each dimension so that the min and max along the dimension is -1 and 1 respectively. It only makes sense to apply this preprocessing if you have a reason to believe that different input features have different scales (or units), but they should be of approximately equal importance to the learning algorithm. In case of images, the relative scales of pixels are already approximately equal (and in range from 0 to 255), so it is not strictly necessary to perform this additional preprocessing step.

*

Link for the above extract:- http://cs231n.github.io/neural-networks-2/

Title: Image preprocessing in deep learning


问:
How to save .mat files of multiple files with their respective name
```<code>filename = ((fname{ind}) ,'.mat');
save((fname(ind)),'*.mat');
</code>```

where 'ind' is index of file name.I want to store result of each .wav file from workspace into .mat with respective .wav file name.

答: If you mean you are going to store a series of names in an array and then want to go down that array as you go through corresponding variables (based on your fname{ind}, then filename = [fname{ind},'.mat'] should be the only fix you need for the filename assignment (notice changing the parenthesis to brackets). As for the save line, if you don't specify the specific variables, everything in the workspace will be saved. More context is needed for a more complete answer.

Body:
filename = ((fname{ind}) ,'.mat');
save((fname(ind)),'*.mat');

where 'ind' is index of file name.I want to store result of each .wav file from workspace into .mat with respective .wav file name.