问:
How can I initialize a std::vector with a size parameter and have each object constructed independently?
I like creating vectors with a given size and value, for example like this:

```<code>std::vector<std::string> names(10);
</code>```

However, this a few times this led to unexpected results. For example in the following code each UniqueNumber turns out to have the same value:

```<code>#include <iostream>
#include <string>
#include <vector>

struct UniqueNumber
{
    UniqueNumber() : mValue(sInstanceCount++)
    {
    }

    inline unsigned int value() const
    {
        return mValue;
    }

private:
    static unsigned int sInstanceCount;
    unsigned int mValue;
};

int UniqueNumber::sInstanceCount(0);

int main()
{
    std::vector<UniqueNumber> numbers(10);
    for (size_t i = 0; i < numbers.size(); ++i)
    {
        std::cout << numbers[i].value() << " ";
    }
}
</code>```

Console output:

```<code>0 0 0 0 0 0 0 0 0 0
</code>```

It does make sense when looking at std::vector's constructor:

```<code>explicit vector(size_type __n,
                const value_type& __value = value_type(),
                const allocator_type& __a = allocator_type());
</code>```

Apparently the vector was initialized with copies of the same object.

Is there also a way to have each object default constructed?

答:
You need to add a copy constructor:

```<code>UniqueNumber(const UniqueNumber& un) : mValue(sInstanceCount++)
{ }
</code>```

The fill constructor of std::vector is not calling your default constructor.  Rather, it's calling the default copy constructor which exists implicitly.  That constructor of course will not increment your internal static counter variable.

You also need to define an assignment operator as well.

However, using an object that has an internal static counter with an std::vector is going to produce unexpected results, because the vector can internally copy-construct/assign your object as much as it sees fit.  So this may interfere with the copy-semantics you require here.

Body:
I like creating vectors with a given size and value, for example like this:

std::vector<std::string> names(10);

However, this a few times this led to unexpected results. For example in the following code each UniqueNumber turns out to have the same value:

#include <iostream>
#include <string>
#include <vector>

struct UniqueNumber
{
    UniqueNumber() : mValue(sInstanceCount++)
    {
    }

    inline unsigned int value() const
    {
        return mValue;
    }

private:
    static unsigned int sInstanceCount;
    unsigned int mValue;
};

int UniqueNumber::sInstanceCount(0);

int main()
{
    std::vector<UniqueNumber> numbers(10);
    for (size_t i = 0; i < numbers.size(); ++i)
    {
        std::cout << numbers[i].value() << " ";
    }
}

Console output:

0 0 0 0 0 0 0 0 0 0

It does make sense when looking at std::vector's constructor:

explicit vector(size_type __n,
                const value_type& __value = value_type(),
                const allocator_type& __a = allocator_type());

Apparently the vector was initialized with copies of the same object.

Is there also a way to have each object default constructed?

Body:
You need to add a copy constructor:

UniqueNumber(const UniqueNumber& un) : mValue(sInstanceCount++)
{ }

The fill constructor of std::vector is not calling your default constructor.  Rather, it's calling the default copy constructor which exists implicitly.  That constructor of course will not increment your internal static counter variable.

You also need to define an assignment operator as well.

However, using an object that has an internal static counter with an std::vector is going to produce unexpected results, because the vector can internally copy-construct/assign your object as much as it sees fit.  So this may interfere with the copy-semantics you require here.


来源: stackexchange

问:
Passing params from one controller to another AngularJS
I have a controller which fetches a list of airports, this feeds a single input component which I use for Departing and then again for Arrival. The autocomplete component works great for each case. I am trying to figure out how to pass each inputs selected airports as a individual param to another controller which fetches prices from a second url. Any ideas on how to do this with one component?

This is the controller for the initial fetch

```<code> $scope.airport_list = null;

 $http({
  url: 'someUrl.com',
  method: 'GET'
 })
  .then((response) => {
    $scope.airport_list = response.data.airports;
 });

 $scope.searchFor = function(airportName) {
  $scope.hidelist = false;
  const output = [];
  angular.forEach($scope.airport_list, function(airport) {
    if (airport.name.toLowerCase() === airportName) {
      output.push(airport);
    }
  });
  $scope.airports = output;
 };

 $scope.selectAirport = function(airportName) {
   $scope.airportSearch.name = airportName.name;
   $scope.state = !$scope.state;
 };
</code>```

This is the single input component which is used multiple times.

```<code><div class="control" ng-controller="selectCtrl">
  <div>
    <input type="text" name="airport"
      id="airport" ng-model="airportSearch.name" />
      <div class="airport-container-dropdown" ng-
        hide="!airportSearch.name">
      <div class="airport-list"
        ng-repeat="airport in airport_list | filter:airportSearch"
        ng-show="!state"
        ng-click="selectAirport(airport)">
       {{ airport.name }}
      </div>
    </div>
  </div>
</div>
</code>```

This is how the component is passed for use in the view

```<code>  <div class="control">
    <label for="from">From:</label>
    <selector-component id="from"></selector-component>
  </div>
  <div class="control">
    <label for="to">To:</label>
    <selector-component id="to"></selector-component>
  </div>
</code>```

This is the airport selector component, not anything really going on with it.

```<code>import template from './airport-selector.html';

export const AirportSelectorComponent = {
  template
};
</code>```

答:
If selector-component is your directive then

```<code>app.directive('directiveName', function(){
   return {
      restrict:'E',
      scope: {
         title: '@'
      },
      template:'<div class="title"><h2>{{title}}</h2></div>'
   };
});
</code>```

Depending on how/what you want to bind, you have different options:

= is two-way binding

@ simply reads the value (one-way binding)

& is used to bind functions

You should go for more research here

ContentLicense: CC BY-SA 3.0

Body:
I have a controller which fetches a list of airports, this feeds a single input component which I use for Departing and then again for Arrival. The autocomplete component works great for each case. I am trying to figure out how to pass each inputs selected airports as a individual param to another controller which fetches prices from a second url. Any ideas on how to do this with one component?

This is the controller for the initial fetch

 $scope.airport_list = null;

 $http({
  url: 'someUrl.com',
  method: 'GET'
 })
  .then((response) => {
    $scope.airport_list = response.data.airports;
 });

 $scope.searchFor = function(airportName) {
  $scope.hidelist = false;
  const output = [];
  angular.forEach($scope.airport_list, function(airport) {
    if (airport.name.toLowerCase() === airportName) {
      output.push(airport);
    }
  });
  $scope.airports = output;
 };

 $scope.selectAirport = function(airportName) {
   $scope.airportSearch.name = airportName.name;
   $scope.state = !$scope.state;
 };

This is the single input component which is used multiple times.

    <input type="text" name="airport"
      id="airport" ng-model="airportSearch.name" />

       {{ airport.name }}

This is how the component is passed for use in the view

    From:
    <selector-component id="from"></selector-component>

    To:
    <selector-component id="to"></selector-component>

This is the airport selector component, not anything really going on with it.

import template from './airport-selector.html';

export const AirportSelectorComponent = {
  template
};

Body:
If selector-component is your directive then

app.directive('directiveName', function(){
   return {
      restrict:'E',
      scope: {
         title: '@'
      },
      template:'<div class="title"><h2>{{title}}</h2></div>'
   };
});

Depending on how/what you want to bind, you have different options:

= is two-way binding

@ simply reads the value (one-way binding)

& is used to bind functions

You should go for more research here


问:
Getting input from form to use in JSON
So, I am pretty new when it comes to messing with JSON, AJAX and that kind of stuff...
I have this one assignment which I am supposed to have 4 input fields: "Start city", "Start state", "Destination city" and "Destination state".
It is basically supposed to get the distance between city A to city B. It was given a file with the information behind that, the thing I need to do is get the inputs, and get the data from the file if that makes sense.

I thought about having a javascript function something like this:

```<code>function getData()
{
    var xhttpData = new XMLHttpRequest();
    var url = "http://localhost/cgi-
        bin/ercanbracks/mileage/mileageAjaxJSON";

    xhttpData.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            var parseData = this.responseText;
            console.log(parseData);
            var trip = parseData.trip;
            document.getElementsByName("startCity")[0].value =
                trip.startcity;
            document.getElementsByName("startState")[0].value =
                trip.startstate;
            document.getElementsByName("endCity")[0].value =  trip.endcity;
            document.getElementsByName("endState")[0].value =
                trip.endstate;

            document.getElementById("demo").innerHTML =  trip.startcity + ",
                " + trip.startstate + ", " + trip.miles + " miles to " +
                trip.endcity + ", " + trip.endstate + ".";
        }
    };

    xhttpData.open("GET", url, true);
    xhttpData.send();
}
document.addEventListener("DOMContentLoaded", function(event) { getData();
});
</code>```

Here is the form:

```<code><!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript"
            src="http://localhost/~arthurfig/week11.js"></script>
        <title></title>

    </head>
    <body>
        <form action="" onsubmit="getData()">
            <p>Start City: </p>
            <input type="text" name="startCity">
            <p>Start State: </p>
            <input type="text" name="startState">
            <p>Destination City: </p>
            <input type="text" name="endCity">
            <p>Destination State: </p>
            <input type="text" name="endState">
            <input type="submit" value="Check">
        </form>
        <p id="demo"></p>
    </body>
</html>
</code>```

And here is what is in the file:

```<code>{"trip" :
  { "startcity" : "",
    "startstate" : "",
    "endcity" : "",
    "endstate" : "",
    "miles" : "Unknown"
  }
}
</code>```

My problem is that I'm not sure how to get the value of the text fields from the form to set as the value of the variables and make it get the distance(miles) using these values.

答:
Try this:</p>

```<code>function getData() {
    var xhttpData = new XMLHttpRequest();
    var url = "http://localhost/cgi-bin/ercanbracks/mileage/mileageAjaxJSON";

    xhttpData.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            var parseData = JSON.parse(this.responseText);
            var trip = parseData.trip;
            document.getElementsByName("startCity")[0].value =  trip.startcity;
            document.getElementsByName("startState")[0].value =  trip.startstate;
            document.getElementsByName("endCity")[0].value =  trip.endcity;
            document.getElementsByName("endState")[0].value =  trip.endstate;

            var text = trip.startcity + ", " trip.startstate + ", " + trip.miles + " miles to " + trip.endcity + ", " + trip.endstate + ".";
            document.getElementById("demo").innerHTML = text;
        }
    };

    xhttpData.open("GET", url, true);
    xhttpData.send();
}
</code>```

Title: Getting input from form to use in JSON

Body:
So, I am pretty new when it comes to messing with JSON, AJAX and that kind of stuff...
I have this one assignment which I am supposed to have 4 input fields: "Start city", "Start state", "Destination city" and "Destination state".
It is basically supposed to get the distance between city A to city B. It was given a file with the information behind that, the thing I need to do is get the inputs, and get the data from the file if that makes sense.

I thought about having a javascript function something like this:

function getData()
{
    var xhttpData = new XMLHttpRequest();
    var url = "http://localhost/cgi-
        bin/ercanbracks/mileage/mileageAjaxJSON";

    xhttpData.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            var parseData = this.responseText;
            console.log(parseData);
            var trip = parseData.trip;
            document.getElementsByName("startCity")[0].value =
                trip.startcity;
            document.getElementsByName("startState")[0].value =
                trip.startstate;
            document.getElementsByName("endCity")[0].value =  trip.endcity;
            document.getElementsByName("endState")[0].value =
                trip.endstate;

            document.getElementById("demo").innerHTML =  trip.startcity + ",
                " + trip.startstate + ", " + trip.miles + " miles to " +
                trip.endcity + ", " + trip.endstate + ".";
        }
    };

    xhttpData.open("GET", url, true);
    xhttpData.send();
}
document.addEventListener("DOMContentLoaded", function(event) { getData();
});

Here is the form:

<!DOCTYPE html>

        <title></title>

        <form action="" onsubmit="getData()">

Start City:

            <input type="text" name="startCity">

Start State:

            <input type="text" name="startState">

Destination City:

            <input type="text" name="endCity">

Destination State:

            <input type="text" name="endState">
            <input type="submit" value="Check">
        </form>

And here is what is in the file:

{"trip" :
  { "startcity" : "",
    "startstate" : "",
    "endcity" : "",
    "endstate" : "",
    "miles" : "Unknown"
  }
}

My problem is that I'm not sure how to get the value of the text fields from the form to set as the value of the variables and make it get the distance(miles) using these values.

Body:
Try this:

function getData() {
    var xhttpData = new XMLHttpRequest();
    var url = "http://localhost/cgi-bin/ercanbracks/mileage/mileageAjaxJSON";

    xhttpData.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            var parseData = JSON.parse(this.responseText);
            var trip = parseData.trip;
            document.getElementsByName("startCity")[0].value =  trip.startcity;
            document.getElementsByName("startState")[0].value =  trip.startstate;
            document.getElementsByName("endCity")[0].value =  trip.endcity;
            document.getElementsByName("endState")[0].value =  trip.endstate;

            var text = trip.startcity + ", " trip.startstate + ", " + trip.miles + " miles to " + trip.endcity + ", " + trip.endstate + ".";
            document.getElementById("demo").innerHTML = text;
        }
    };

    xhttpData.open("GET", url, true);
    xhttpData.send();
}


问:
How do I create a query that list the name of students who took fewer than three classes or have a null value for class
I have a "database" with two tables a student,and enroll. The student table has stuid, lastname, firstname. The enroll table has stuid classnumber and grade.

I have to return a list that looks like this

Last Name

Burns
Jones
Lee
McCarthy
Rivera
Smith

First Name

Edward
Mary
Perry
Owen
Jane
Tom

I attempted to do a statement like this

Select lastname, firstname
Where Not exists (Select stuid from enroll e where e.stuid = s.stuid)
Having count(*) < 3
Group By lastname, firstname;

I understand that I need two merge the two tables basically so that I get the results of people who have classes < 3 and people who are also not currently enrolled in a class.

答:
Try like this:</p>

```<code>SELECT lastname, firstname FROM student st LEFT JOIN enroll el
ON st.stuid = el.stid
WHERE (el.classnumber < 3 OR el.classnumber IS NULL)
</code>```

Body:
Try like this:

SELECT lastname, firstname FROM student st LEFT JOIN enroll el
ON st.stuid = el.stid
WHERE (el.classnumber < 3 OR el.classnumber IS NULL)


问:
create binary plist in Java?
is there a way to create binary plist in Java?

I can only find the open sourced C implementation at: http://opensource.apple.com/source/CF/CF-550/CFBinaryPList.c

thx

答: If you're familiar with Objective-C then check out Rococoa. Can't say specifically that it does it but I ran into a while back and it looked like it had some promise.</p>

ContentLicense: CC BY-SA 2.5

Title: create binary plist in Java?


问:
Bootstrap modal-open causing body to have style="padding-right: 15px;"
On my bootstrap 3.3.7 website, the entire body gets a 'style="15px"' when the modal is opened. This is moving my top navigation (fixed nav) 15px right when I open my modal. I cannot use CSS to remove the padding since it is an element.

I have tried to use 'left: 15px' on the body for modal-open class (and various other CSS options) to no avail. I did not add this to my HTML so it's a bootstrap thing. The link to the modal is within the top navigation, but when the link is clicked the modal popup HTML shows up below the nav div when I inspect element.

Here's the page, click on 'Log In' button in top right.I expect the navigation to stay put when I click the modal. I don't want it to move. Please help

答:
Bootstrap also add class on body <code>.modal-open</code> u can play with this class </p>

```<code>   .modal-open .navbar-fixed-top {
        right: 15px;
    }
</code>```

Body:
Bootstrap also add class on body .modal-open u can play with this class

   .modal-open .navbar-fixed-top {
        right: 15px;
    }


问:
How to store a state in localstorage for react?
I'm trying to store my checkbox checked value into the localstorage in my react app. But everytime I store, it will store a previous state. Below is my code:

For render side:

```<code>  render () {
    return (
                      <Checkbox
                        checked={this.state.checkedCheckpoint}
                        onChange={() => this.onChange('checkpoint')}
                      >
                      </Checkbox>
          )
</code>```

For the onchange method:

```<code>  onChange (value){
    const { checkedCheckpoint } = this.state

    if (value === 'checkpoint')
    {
      if (checkedCheckpoint)
      {
        this.setState({checkedCheckpoint : false})
        console.log(checkedCheckpoint)
      }
      else
      {
        this.setState({checkedCheckpoint : true})
        console.log(checkedCheckpoint)
      }
    }
    localStorage.setObject('checkedCheckpoint', checkedCheckpoint)
</code>```

What I mean by previous state is:
If I initialize my checkpoint to be true, after I unchecked, I should get checkpoint: false right? But I get checkedCheckpoint: true. If I checked it, I should get checkedCheckpoint: true right? I will get checkedCheckpoint: false. Seems like it will always follow the previous state in localstorage. Anyone knows what's wrong?

答:
React tries to batch the setState command. It is more like an asynchronous task. So when you execute  this.setState({checkedCheckpoint : true}) it only tells react to set the state of 'checkedCheckpoint' to true but it does not execute that command at that moment. So basically when you are trying to set your localStorage variable it is still the previous state.

Try setting your new state in a variable like this.

```<code>onChange (value){
var newState;
const { checkedCheckpoint } = this.state

if (value === 'checkpoint') {
  if (checkedCheckpoint) {
    newState = false;
    console.log(newState);
  }
  else {
    newState = true;
    console.log(newState);
  }
  this.setState({checkedCheckpoint : newState});
  localStorage.setObject('checkedCheckpoint', newState);
}
</code>```

Body:
I'm trying to store my checkbox checked value into the localstorage in my react app. But everytime I store, it will store a previous state. Below is my code:

For render side:

  render () {
    return (
                      <Checkbox
                        checked={this.state.checkedCheckpoint}
                        onChange={() => this.onChange('checkpoint')}
                      >
                      </Checkbox>
          )

For the onchange method:

  onChange (value){
    const { checkedCheckpoint } = this.state

    if (value === 'checkpoint')
    {
      if (checkedCheckpoint)
      {
        this.setState({checkedCheckpoint : false})
        console.log(checkedCheckpoint)
      }
      else
      {
        this.setState({checkedCheckpoint : true})
        console.log(checkedCheckpoint)
      }
    }
    localStorage.setObject('checkedCheckpoint', checkedCheckpoint)

What I mean by previous state is:
If I initialize my checkpoint to be true, after I unchecked, I should get checkpoint: false right? But I get checkedCheckpoint: true. If I checked it, I should get checkedCheckpoint: true right? I will get checkedCheckpoint: false. Seems like it will always follow the previous state in localstorage. Anyone knows what's wrong?

Body:
React tries to batch the setState command. It is more like an asynchronous task. So when you execute  this.setState({checkedCheckpoint : true}) it only tells react to set the state of 'checkedCheckpoint' to true but it does not execute that command at that moment. So basically when you are trying to set your localStorage variable it is still the previous state.

Try setting your new state in a variable like this.

onChange (value){
var newState;
const { checkedCheckpoint } = this.state

if (value === 'checkpoint') {
  if (checkedCheckpoint) {
    newState = false;
    console.log(newState);
  }
  else {
    newState = true;
    console.log(newState);
  }
  this.setState({checkedCheckpoint : newState});
  localStorage.setObject('checkedCheckpoint', newState);
}


问:
How to get AJAX posted JSON in flask?
I am following this flask tutorial to learn about building an app in Python.

The tutorial (close to the end) talks about how to get a AJAX posted JSON inside python as follows:

HTML code:

This will send data using AJAX to Python:

Click Me```
</div>
</div>
</p>
<p>Python Code:</p>
```import sys

from flask import Flask, render_template, request, redirect, Response
import random, json

app = Flask(__name__)

@app.route('/')
def output():
    return render_template('index.html')

@app.route('/receiver', methods = ['POST'])
def worker():
    # read json + reply
    data = request.get_json()
    result = ''

    for item in data:
        # loop over every row
        result += str(item['make']) + '\n'

    return result

if __name__ == '__main__':
    app.run()
```

When I run the script and click on the button 'Click me' in the browser, I get the 500 Internal Server Error when I examine the Response in the browser. If I print the data variable, it prints out None in the terminal on the click event. I tried the suggestions given in the comments to use get_json(forced=true) in Python script and stringify the 'cars' JSON in HTML file but in vain.

答:
It looks like you didn't specify the content type of your post request look what is said in the official documentation:

By default this function will return None if the mimetype is not
  application/json but this can be overridden by the force parameter.

you need also to serialize you cars object to json object .

you can do something like this :

```<code>function doWork() {
    // ajax the JSON to the server
    $.ajax({
        type: 'POST',
        url: '/receiver',
        data: JSON.stringify (cars),
        success: function(data) { alert('data: ' + data); },
        contentType: "application/json",
        dataType: 'json'
    });
    // stop link reloading the page
    event.preventDefault();
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to get AJAX posted JSON in flask?

Body:
I am following this flask tutorial to learn about building an app in Python.

The tutorial (close to the end) talks about how to get a AJAX posted JSON inside python as follows:

HTML code:

This will send data using AJAX to Python:

Click Me

Python Code:

import sys

from flask import Flask, render_template, request, redirect, Response
import random, json

app = Flask(__name__)

@app.route('/')
def output():
    return render_template('index.html')

@app.route('/receiver', methods = ['POST'])
def worker():
    # read json + reply
    data = request.get_json()
    result = ''

    for item in data:
        # loop over every row
        result += str(item['make']) + '\n'

    return result

if __name__ == '__main__':
    app.run()

When I run the script and click on the button 'Click me' in the browser, I get the 500 Internal Server Error when I examine the Response in the browser. If I print the data variable, it prints out None in the terminal on the click event. I tried the suggestions given in the comments to use get_json(forced=true) in Python script and stringify the 'cars' JSON in HTML file but in vain.

Body:
It looks like you didn't specify the content type of your post request look what is said in the official documentation:

By default this function will return None if the mimetype is not
  application/json but this can be overridden by the force parameter.

you need also to serialize you cars object to json object .

you can do something like this :

function doWork() {
    // ajax the JSON to the server
    $.ajax({
        type: 'POST',
        url: '/receiver',
        data: JSON.stringify (cars),
        success: function(data) { alert('data: ' + data); },
        contentType: "application/json",
        dataType: 'json'
    });
    // stop link reloading the page
    event.preventDefault();
}


问:
Databinding a ObservableCollection<T> in MVVM
I have a ListView with a Datatemplate that holds a list of Movies. It is databinded to a ObservableColection but whenever I edit the Movie.Name it does not update the ListView even though "Name" is called in my PropertyChangedEventHandler is called with "Name".

I add 2 "Movie"s to my collection in my initializer and these are shown correct (Klovn the Movie, Taken)

So when I click Edit it should change the text of the selected movie and change the Name of it to "Test" and is is changed but the change is not shown in the ListView but if I output Collection with a foreach then Name is Test.

View.xaml

<Window x:Class="MovieDB3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <DockPanel>
        <Menu DockPanel.Dock="Top">
            <MenuItem Header="File">
                <MenuItem Header="Edit" Click="MenuEditClick"/>
            </MenuItem>
        </Menu>
        <Grid DockPanel.Dock="Top">
            <Grid.ColumnDefinitions>
                <ColumnDefinition/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition/>
            </Grid.RowDefinitions>
            <ListView VerticalAlignment="Stretch" Name="ListViewMovies" ItemsSource="{Binding Path=Collection}" IsSynchronizedWithCurrentItem="True" >
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <WrapPanel>
                            <TextBlock Text="{Binding Path=Name}"/>
                        </WrapPanel>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </Grid>
    </DockPanel>
</Window>
```

<p>View.cs</p>

```using System;
using System.Windows;
using MovieDB3.Models;
using MovieDB3.ViewModels;

namespace MovieDB3
{
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {
        private MainViewModel MVM;
        public MainWindow()
        {
            InitializeComponent();
            MVM = new MainViewModel();
            DataContext = MVM;
        }

        private void MenuEditClick(object sender, RoutedEventArgs e)
        {
            MVM.setMovieName((Movie)ListViewMovies.SelectedItem, "test");
        }
    }
}
```

<p>The ViewModel</p>

```using System;
using System.ComponentModel;
using MovieDB3.Models;
using System.Collections.ObjectModel;

namespace MovieDB3.ViewModels
{
    class MainViewModel : INotifyPropertyChanged
    {
        public ObservableCollection<Movie> Collection {get; set;}

        public MainViewModel()
        {
            Collection = new ObservableCollection<Movie>();

            //Test kode
            Movie movie = new Movie();
            movie.Name = "Klovn The Movie";
            Collection.Add(movie);
            movie = new Movie();
            movie.Name = "Taken";
            Collection.Add(movie);
        }

        public void setMovieName(Movie movie, string newName)
        {
            //movie.Name = newName;
            Console.WriteLine("CurrentName: " + movie.Name);
            int i = Collection.IndexOf(movie);
            Collection[i].Name = newName;
            Console.WriteLine("NewName: " + movie.Name);
            NotifyPropertyChanged("Name");
        }

        public void setMovieName(string currentName, string newName)
        {
            foreach (Movie movie in Collection)
            {
                if (movie.Name.Equals(currentName))
                {
                    movie.Name = newName;
                    NotifyPropertyChanged("Name");
                    return;
                }
            }
        }

        //public string MovieName
        //{
        //    set
        //    {

        //        NotifyPropertyChanged("MovieName");
        //    }
        //}

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }
    }
}
```

<p>Movie.cs</p>

```using System;

namespace MovieDB3.Models
{
    class Movie
    {
        public string Name { get; set; }
        public int Id { get; set; }
        public double Rating { get; set; }
        public DateTime Release { get; set; }
        public TimeSpan Runtime { get; set; }
        public String Trailer { get; set; }
    }
}
```

答: Currently, you're having your MainViewModel raise the NotifyPropertyChanged event for Name changing.  Instead, your Movie instances should be raising those events, since your Movie objects are what have that property bound.

Body:
I have a ListView with a Datatemplate that holds a list of Movies. It is databinded to a ObservableColection but whenever I edit the Movie.Name it does not update the ListView even though "Name" is called in my PropertyChangedEventHandler is called with "Name".

I add 2 "Movie"s to my collection in my initializer and these are shown correct (Klovn the Movie, Taken)

So when I click Edit it should change the text of the selected movie and change the Name of it to "Test" and is is changed but the change is not shown in the ListView but if I output Collection with a foreach then Name is Test.

View.xaml

<Window x:Class="MovieDB3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <DockPanel>
        <Menu DockPanel.Dock="Top">
            <MenuItem Header="File">
                <MenuItem Header="Edit" Click="MenuEditClick"/>
            </MenuItem>
        </Menu>
        <Grid DockPanel.Dock="Top">
            <Grid.ColumnDefinitions>
                <ColumnDefinition/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition/>
            </Grid.RowDefinitions>
            <ListView VerticalAlignment="Stretch" Name="ListViewMovies" ItemsSource="{Binding Path=Collection}" IsSynchronizedWithCurrentItem="True" >
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <WrapPanel>
                            <TextBlock Text="{Binding Path=Name}"/>
                        </WrapPanel>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </Grid>
    </DockPanel>
</Window>

View.cs

using System;
using System.Windows;
using MovieDB3.Models;
using MovieDB3.ViewModels;

namespace MovieDB3
{
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {
        private MainViewModel MVM;
        public MainWindow()
        {
            InitializeComponent();
            MVM = new MainViewModel();
            DataContext = MVM;
        }

        private void MenuEditClick(object sender, RoutedEventArgs e)
        {
            MVM.setMovieName((Movie)ListViewMovies.SelectedItem, "test");
        }
    }
}

The ViewModel

using System;
using System.ComponentModel;
using MovieDB3.Models;
using System.Collections.ObjectModel;

namespace MovieDB3.ViewModels
{
    class MainViewModel : INotifyPropertyChanged
    {
        public ObservableCollection<Movie> Collection {get; set;}

        public MainViewModel()
        {
            Collection = new ObservableCollection<Movie>();

            //Test kode
            Movie movie = new Movie();
            movie.Name = "Klovn The Movie";
            Collection.Add(movie);
            movie = new Movie();
            movie.Name = "Taken";
            Collection.Add(movie);
        }

        public void setMovieName(Movie movie, string newName)
        {
            //movie.Name = newName;
            Console.WriteLine("CurrentName: " + movie.Name);
            int i = Collection.IndexOf(movie);
            Collection[i].Name = newName;
            Console.WriteLine("NewName: " + movie.Name);
            NotifyPropertyChanged("Name");
        }

        public void setMovieName(string currentName, string newName)
        {
            foreach (Movie movie in Collection)
            {
                if (movie.Name.Equals(currentName))
                {
                    movie.Name = newName;
                    NotifyPropertyChanged("Name");
                    return;
                }
            }
        }

        //public string MovieName
        //{
        //    set
        //    {

        //        NotifyPropertyChanged("MovieName");
        //    }
        //}

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }
    }
}

Movie.cs

using System;

namespace MovieDB3.Models
{
    class Movie
    {
        public string Name { get; set; }
        public int Id { get; set; }
        public double Rating { get; set; }
        public DateTime Release { get; set; }
        public TimeSpan Runtime { get; set; }
        public String Trailer { get; set; }
    }
}


问:
Use ssh credentials in jenkins pipeline with ssh, scp or sftp
I want to use scp/ssh to upload some files to a server. I discover that I need to use certificate-based authentication, but the question is how? Really what I want to do is to use the same sort of credentials I use with git - passworded ssh cert stored in Jenkins. However, I can't work out how to - the snippet generator has no obvious option for that.

What do others do? Is there an undocumented feature that would do this?

答:
```<code>    withCredentials([sshUserPrivateKey(credentialsId: "yourkeyid", keyFileVariable: 'keyfile')]) {
       stage('scp-f/b') {
        sh 'scp -i ${keyfile} do sth here'
       }
   }
</code>```

Maybe this is what you want. Install Credentials Plugin and

Credentials Binding Plugin. Add some credentials and then you will get "yourkeyid", bind this credentials to keyFileVariable, passphraseVariable etc.

More details and documentation can be found on the Github site of the Jenkins Credentials Binding Plugin, Credentials Binding Plugin docs, Credentials Plugin, SSH Pipeline Steps plugin

Body:
    withCredentials([sshUserPrivateKey(credentialsId: "yourkeyid", keyFileVariable: 'keyfile')]) {
       stage('scp-f/b') {
        sh 'scp -i ${keyfile} do sth here'
       }
   }

Maybe this is what you want. Install Credentials Plugin and

Credentials Binding Plugin. Add some credentials and then you will get "yourkeyid", bind this credentials to keyFileVariable, passphraseVariable etc.

More details and documentation can be found on the Github site of the Jenkins Credentials Binding Plugin, Credentials Binding Plugin docs, Credentials Plugin, SSH Pipeline Steps plugin


问:
angular - store and use data in multiple components
I'm trying to build a admin panel using Angular. Please do note that, this is my first time using Angular and first time on OOP constructs.

I have a page where I list all the product types, by selecting or rather clicking on any of the product type. I redirect them to another page with the brands for the respective product.

So, when I searched the internet to check what is the best way of sharing data across multiple components, I found BehaviourSubject, and I did successfully manage to redirect the user from the products page to the brands page. Now I wanted to route the user to a new page from the brands page after they select the brands.

So far, I managed to do the BehaviourSubject with just one variable of type string which is selecting one product from the products page. Now I have an option for my users to select multiple brands.

How can I pass this data to the next page? And when I select the brands, will I still be able to access my product value using the BehaviouSubject. I was thinking to create a class and update the last value to the class, which I couldn't do it unfortunately.

CODE

```<code>@Injectable()
export class UserActionService {

    private product;
    private currentProduct;

    constructor() {
        this.product = new BehaviorSubject<UserActions>(null);
        this.currentProduct = this.product.asObservable();
    }

    changeProduct(product: UserActions) {
        this.product.lastProduct.next(product);
    }
}

export class UserActions {
    private lastProduct: string;
    private lastBrands: Array<string>;
}
</code>```

This code didn't throw me any error on the tslint, but on the browser it throws me an error:

```<code>Cannot read property 'next' of undefined
</code>```

I don't know if I'm doing the right thing, any help will be much appreciated.

答:
I think what you need is a GetCurrentValue after redirect to a new page. Referring to Simple way to get the current value of a BehaviorSubject with rxjs5, you can do this:

```<code>getProduct() : UserActions {
    return this.product.value;
}
changeProduct(product: UserActions) {
    this.product.next(product);
}
</code>```

Body:
I'm trying to build a admin panel using Angular. Please do note that, this is my first time using Angular and first time on OOP constructs.

I have a page where I list all the product types, by selecting or rather clicking on any of the product type. I redirect them to another page with the brands for the respective product.

So, when I searched the internet to check what is the best way of sharing data across multiple components, I found BehaviourSubject, and I did successfully manage to redirect the user from the products page to the brands page. Now I wanted to route the user to a new page from the brands page after they select the brands.

So far, I managed to do the BehaviourSubject with just one variable of type string which is selecting one product from the products page. Now I have an option for my users to select multiple brands.

How can I pass this data to the next page? And when I select the brands, will I still be able to access my product value using the BehaviouSubject. I was thinking to create a class and update the last value to the class, which I couldn't do it unfortunately.

CODE

@Injectable()
export class UserActionService {

    private product;
    private currentProduct;

    constructor() {
        this.product = new BehaviorSubject<UserActions>(null);
        this.currentProduct = this.product.asObservable();
    }

    changeProduct(product: UserActions) {
        this.product.lastProduct.next(product);
    }
}

export class UserActions {
    private lastProduct: string;
    private lastBrands: Array<string>;
}

This code didn't throw me any error on the tslint, but on the browser it throws me an error:

Cannot read property 'next' of undefined

I don't know if I'm doing the right thing, any help will be much appreciated.

Body:
I think what you need is a GetCurrentValue after redirect to a new page. Referring to Simple way to get the current value of a BehaviorSubject with rxjs5, you can do this:

getProduct() : UserActions {
    return this.product.value;
}
changeProduct(product: UserActions) {
    this.product.next(product);
}


问:
How to keep the login token so that it can be used by other components?
Let's say, I make a post request to create my token.

```<code>public tokenInfo: TokenInfo;

public login(creds){
   return this.http.post<TokenInfo>(this.baseUrl + "Account/CreateToken", creds)
          .map(res =>{
                this.tokenInfo = res;
                return true;
          })
  }
</code>```

I get back my token and the expiration date. something like:

{token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ...", expiration: "2017-12-04T03:40:55Z"}

How do I keep it around so that other component can take advantage of it? The first thing that comes to mind is to display the name of the logged user at the left corner of the menu bar and hide the Login item.

Thanks for helping

答:
I would use a service for this purpose:</p>

```<code>@Injectable()
export class AuthService {
  authToken: TokenInfo;

  public login(creds) {
    // You could store the auth token in local storage here instead.
    return this.http.post('/login').subscribe((res) => this.authToken = res);
  }

  public getAuthToken() {
    return this.authToken;
  }
}

export class YourComponent {
  constructor(private authService: AuthService) { }

  login() {
    this.authService.login({ /* Your credentials. */ });
  }

  displayToken() {
     alert(this.authService.getAuthToken());
  }
}
</code>```

Body:
Let's say, I make a post request to create my token.

public tokenInfo: TokenInfo;

public login(creds){
   return this.http.post<TokenInfo>(this.baseUrl + "Account/CreateToken", creds)
          .map(res =>{
                this.tokenInfo = res;
                return true;
          })
  }

I get back my token and the expiration date. something like:

{token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ...", expiration: "2017-12-04T03:40:55Z"}

How do I keep it around so that other component can take advantage of it? The first thing that comes to mind is to display the name of the logged user at the left corner of the menu bar and hide the Login item.

Thanks for helping

Body:
I would use a service for this purpose:

@Injectable()
export class AuthService {
  authToken: TokenInfo;

  public login(creds) {
    // You could store the auth token in local storage here instead.
    return this.http.post('/login').subscribe((res) => this.authToken = res);
  }

  public getAuthToken() {
    return this.authToken;
  }
}

export class YourComponent {
  constructor(private authService: AuthService) { }

  login() {
    this.authService.login({ /* Your credentials. */ });
  }

  displayToken() {
     alert(this.authService.getAuthToken());
  }
}


问:
llvm - get the first instruction of the basic block referred to in the label field of instruction of type br
I'm trying to write a pass that will check the control flow of a code. Given a br instruction, I need to access the basic blocks referred to in the label fields.

For example, for the code:

```<code> for(i = 0; i < count; i++){
    sum = add(sum, array[i]);
  }
</code>```

I get the IR representation

```<code>br i1 %cmp, label %for.body, label %for.end
</code>```

Now when I come across this instruction in the pass, I need to know exactly where these labels are pointing to. Can anybody please tell me how I can do that?

答: Call ->getOperand(1) and ->getOperand(2) methods for that instruction. This would give you 1st and 2nd BB respectively. See http://llvm.org/doxygen/classllvm_1_1User.html#abe1de1520a21f77ac57cc210bf0fb0b4

Body:
I'm trying to write a pass that will check the control flow of a code. Given a br instruction, I need to access the basic blocks referred to in the label fields.

For example, for the code:

 for(i = 0; i < count; i++){
    sum = add(sum, array[i]);
  }

I get the IR representation

br i1 %cmp, label %for.body, label %for.end

Now when I come across this instruction in the pass, I need to know exactly where these labels are pointing to. Can anybody please tell me how I can do that?


问:
Why in this program BufferedReader taking infinite input
Why is in this program BufferedReader taking infinite input?

Below is the code which is taking  input infinitely. To avoid this I have added condition

```<code>    while((!(s1=br.readLine().trim()).equals(null))&&(!s1.isEmpty())){
</code>```

but it didn't  work out.

```<code>import java.io.*;
import java.util.*;
public class skylerStudent {
public static void main(String []args)throws IOException{
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    String s1="";String s="";
    while((!(s1=br.readLine().trim()).equals(null))&&(!s1.isEmpty())){
        s+=s1.trim()+" ";

    }
    StringTokenizer st=new StringTokenizer(s.trim());
    int i=0,n=0,q=0;
    while(st.hasMoreTokens()){
        if(i==0)n=Integer.parseInt(st.nextToken());
        if(i==1)q=Integer.parseInt(st.nextToken());

        i++;
    }
    int ar[]=new int[n];i=0;
    while(st.hasMoreTokens()){
    if(i<n)ar[i]=Integer.parseInt(st.nextToken());

        i++;
    }
    i=0;
    while(st.hasMoreTokens()){
        StringTokenizer st1=new StringTokenizer(st.nextToken());

        while(st.hasMoreTokens()){
            if(i<q){
    int a=Integer.parseInt(st1.nextToken());
    int b=Integer.parseInt(st1.nextToken());
    System.out.println(a);System.out.println(b);}
    i++;
        }
    }

}
}
</code>```

答:
The condition !(s1 = br.readLine().trim()).equals(null) is not correct. If you can call .trim on string then it can never be null. You can check

```<code>(s1 = br.readLine()) != null
</code>```

Also the infinite loop is not in the reading the input, its in the one of the later loops of the code.

```<code>while (st.hasMoreTokens()) {
            if (i == 0)
                n = Integer.parseInt(st.nextToken());
            if (i == 1)
                q = Integer.parseInt(st.nextToken());

            i++;
        }
</code>```

You are not moving forward to nextToken() if the i is not in (0,1). That's why it would never exit the loop.

Body:
Why is in this program BufferedReader taking infinite input?

Below is the code which is taking  input infinitely. To avoid this I have added condition

    while((!(s1=br.readLine().trim()).equals(null))&&(!s1.isEmpty())){

but it didn't  work out.

import java.io.*;
import java.util.*;
public class skylerStudent {
public static void main(String []args)throws IOException{
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    String s1="";String s="";
    while((!(s1=br.readLine().trim()).equals(null))&&(!s1.isEmpty())){
        s+=s1.trim()+" ";

    }
    StringTokenizer st=new StringTokenizer(s.trim());
    int i=0,n=0,q=0;
    while(st.hasMoreTokens()){
        if(i==0)n=Integer.parseInt(st.nextToken());
        if(i==1)q=Integer.parseInt(st.nextToken());

        i++;
    }
    int ar[]=new int[n];i=0;
    while(st.hasMoreTokens()){
    if(i<n)ar[i]=Integer.parseInt(st.nextToken());

        i++;
    }
    i=0;
    while(st.hasMoreTokens()){
        StringTokenizer st1=new StringTokenizer(st.nextToken());

        while(st.hasMoreTokens()){
            if(i<q){
    int a=Integer.parseInt(st1.nextToken());
    int b=Integer.parseInt(st1.nextToken());
    System.out.println(a);System.out.println(b);}
    i++;
        }
    }

}
}

Body:
The condition !(s1 = br.readLine().trim()).equals(null) is not correct. If you can call .trim on string then it can never be null. You can check

(s1 = br.readLine()) != null

Also the infinite loop is not in the reading the input, its in the one of the later loops of the code.

while (st.hasMoreTokens()) {
            if (i == 0)
                n = Integer.parseInt(st.nextToken());
            if (i == 1)
                q = Integer.parseInt(st.nextToken());

            i++;
        }

You are not moving forward to nextToken() if the i is not in (0,1). That's why it would never exit the loop.


问:
Swift 3 draw a simple png image with transparency
I need to draw no more than 9 of the same image around an arc. I subclassed UiView already to draw a circle and several arcs with CoreGraphics. Now i need to draw these marker objects around it like a clock. I have already done this once in Android Java but have been having a hell of a time so far in Swift.
I cobbled together this code from another answer and it draws the image but doesnt keep the transparency:

```<code>let imageName = "single_marker_vertical_high_res.png";
let image = UIImage(named: imageName);
let imageView = UIImageView(image: image!);
imageView.frame = CGRect(x: 0, y: 0, width: 25, height: 75);
imageView.draw(rect)
</code>```

and this is called on the overridden draw function of the class.

I am a noob when it comes to Swift as well, I have yet to find an example that shows the code and how to utilize it. For reference, this is what I need:

As it looks on Android
The tick marks on the top widget is what I need to draw, with transparency.

答: You don't need to write xml explicitly, while you can write code for custom & reusable views, but a better approach is to use storyboard, it takes care of the constraints, which are relatively very easy to handle. After adding your wanted object in storyboard. e.g you want to add a circle, you can drag the view, place it wherever you want and then make it a circle with properties like view.layer.cornerRadius = half of your height, you can also hide/show via properties like isHidden, opaque and do a bunch of stuff. if you need any help just ask.

Body:
I need to draw no more than 9 of the same image around an arc. I subclassed UiView already to draw a circle and several arcs with CoreGraphics. Now i need to draw these marker objects around it like a clock. I have already done this once in Android Java but have been having a hell of a time so far in Swift.
I cobbled together this code from another answer and it draws the image but doesnt keep the transparency:

let imageName = "single_marker_vertical_high_res.png";
let image = UIImage(named: imageName);
let imageView = UIImageView(image: image!);
imageView.frame = CGRect(x: 0, y: 0, width: 25, height: 75);
imageView.draw(rect)

and this is called on the overridden draw function of the class.

I am a noob when it comes to Swift as well, I have yet to find an example that shows the code and how to utilize it. For reference, this is what I need:

As it looks on Android
The tick marks on the top widget is what I need to draw, with transparency.


问:
Ruby array reverse_each_with_index
I would like to use something like reverse_each_with_index on an array.

Example:

```<code>array.reverse_each_with_index do |node,index|
  puts node
  puts index
end
</code>```

I see that Ruby has each_with_index but it doesn’t seem to have an opposite. Is there another way to do this?

答:
Without copying array:</p>

```<code>(array.size - 1).downto(0) do |index|
  node = array[index]
  # ...
end
</code>```

Title: Ruby array reverse_each_with_index

Body:
I would like to use something like reverse_each_with_index on an array.

Example:

array.reverse_each_with_index do |node,index|
  puts node
  puts index
end

I see that Ruby has each_with_index but it doesn’t seem to have an opposite. Is there another way to do this?

Body:
Without copying array:

(array.size - 1).downto(0) do |index|
  node = array[index]
  # ...
end


问:
Spring Batch: How to set the first line columns (header), of the csv file to token name for my file reader
I have a csv file to consume through spring batch. The column header (names) can differ based on the customer. When reading the data using FlatFileItemReader, how would i set the token name(s) to be the first line (header) column name(s) ? I am using Java Configuration to setup the flow.

Appreciate any comments/suggestions

答:
You should set LineToSkip Property :</p>

```<code>    @Component
    @JobScope
    public class CsvToDbItemReader extends FlatFileItemReader<BillDTO> {
            public CsvToDbItemReader(@Value("#{jobParameters}") Map jobParameters)
    {
                String uploadDate = (String) jobParameters.get("uploadDate");
                this.setResource(new FileSystemResource(getFileName(uploadDate)));
                this.setLinesToSkip(1); //set header line
                LineMapper<BillDTO> lineMapper = createBillLineMapper();
                this.setLineMapper(lineMapper);
            }
     }
</code>```

Body:
You should set LineToSkip Property :

    @Component
    @JobScope
    public class CsvToDbItemReader extends FlatFileItemReader<BillDTO> {
            public CsvToDbItemReader(@Value("#{jobParameters}") Map jobParameters)
    {
                String uploadDate = (String) jobParameters.get("uploadDate");
                this.setResource(new FileSystemResource(getFileName(uploadDate)));
                this.setLinesToSkip(1); //set header line
                LineMapper<BillDTO> lineMapper = createBillLineMapper();
                this.setLineMapper(lineMapper);
            }
     }


问:
Grabing first object for each item related to items in an array - DJango
I have a django project I am working on. I have two tables which are groups and group activities. Groups store information about the group that is created. GroupActivity stores all of the activities that are related to a group. for instance a group called Welcome would be stored in the group table with info about the group. if a member is added to the group there would be a record of the activity in the group activity table. I want to create a system that allows me to grab all of the groups someone is a part of and for each group, grab the last activity that happened for each of the groups that the user is a member of. I tried using two different queries and use two for loops but it is not working at all. Can anyone help me with this.. here is the code I have

Here are the tables:

```<code>class Group(models.Model):
    name = models.CharField(max_length = 25)
    description = models.CharField(max_length = 250, null=True)
    created_by = models.ForeignKey(User, default=1, on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add=True)

class GroupActivity(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    group = models.ForeignKey(Group, on_delete=models.CASCADE)
    expense = models.ForeignKey(Expense, null=True, on_delete=models.CASCADE)
    bundle = models.ForeignKey(Bundle, on_delete=models.CASCADE, null=True)
    description = models.CharField(max_length=200, default='some action')
    host = models.CharField(max_length=100, null=True)
    reference = models.IntegerField(default=0)
    category = models.SmallIntegerField(default = 1)
    created = models.DateTimeField(auto_now_add=True)
</code>```

Here is what i have in the views.py file:

```<code># ensure someone is logged in
@login_required(login_url='/login/')
# groups home page
def groups_home(request):
    # grab the logged in user
    user = request.user
    # grab all of the groups you are a member of
    groups = Member.objects.filter(user = user).all()
    # everythin that is going to be passed to the html template
    activities = GroupActivity.ojects.order_by('group').desc()
    parameters = {
        'groups':groups,
        'activities':activities,
    }
    return render(request, 'groups/groups.html', parameters)
</code>```

Here is the html template :

```<code>      {% for group in groups %}
        <p>
          <a href="{% url 'group_home' group.group.name|slugify group.group.id %}">{{ group.group.name }}</a>
        </p>
      {% endfor %}
</code>```

Example:

```<code>two groups = Bros and Sisters
activity = Bros => josh was added
                => steve was added
                => josh sent steve a message
           Sisters => jessica added jenny
                   => jessica added julie
                   => jessica added stephanie

I want to grab the two groups = Bros and Girls
I want to grab the actviities = josh sent steve a message
                              = jessica added stephanie
</code>```

I want to display the group and the last activity together like a whatsapp group from the main screen of the applicaiton.

Can anyone help me.

答:
instead of directly querying activities you can use backward relations, use something like this in your template

```<code>{% for group in groups %}
    <p>
      <a href="{% url 'group_home' group.group.name|slugify group.group.id %}">{{ group.group.name }}</a>
    </p>
    {% for act in group.activity_set.all %}
        {{ act.description }}
    {% endfor %}
  {% endfor %}
</code>```

for more info check this page in django docs.

Body:
I have a django project I am working on. I have two tables which are groups and group activities. Groups store information about the group that is created. GroupActivity stores all of the activities that are related to a group. for instance a group called Welcome would be stored in the group table with info about the group. if a member is added to the group there would be a record of the activity in the group activity table. I want to create a system that allows me to grab all of the groups someone is a part of and for each group, grab the last activity that happened for each of the groups that the user is a member of. I tried using two different queries and use two for loops but it is not working at all. Can anyone help me with this.. here is the code I have

Here are the tables:

class Group(models.Model):
    name = models.CharField(max_length = 25)
    description = models.CharField(max_length = 250, null=True)
    created_by = models.ForeignKey(User, default=1, on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add=True)

class GroupActivity(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    group = models.ForeignKey(Group, on_delete=models.CASCADE)
    expense = models.ForeignKey(Expense, null=True, on_delete=models.CASCADE)
    bundle = models.ForeignKey(Bundle, on_delete=models.CASCADE, null=True)
    description = models.CharField(max_length=200, default='some action')
    host = models.CharField(max_length=100, null=True)
    reference = models.IntegerField(default=0)
    category = models.SmallIntegerField(default = 1)
    created = models.DateTimeField(auto_now_add=True)

Here is what i have in the views.py file:

# ensure someone is logged in
@login_required(login_url='/login/')
# groups home page
def groups_home(request):
    # grab the logged in user
    user = request.user
    # grab all of the groups you are a member of
    groups = Member.objects.filter(user = user).all()
    # everythin that is going to be passed to the html template
    activities = GroupActivity.ojects.order_by('group').desc()
    parameters = {
        'groups':groups,
        'activities':activities,
    }
    return render(request, 'groups/groups.html', parameters)

Here is the html template :

      {% for group in groups %}

          {{ group.group.name }}

      {% endfor %}

Example:

two groups = Bros and Sisters
activity = Bros => josh was added
                => steve was added
                => josh sent steve a message
           Sisters => jessica added jenny
                   => jessica added julie
                   => jessica added stephanie

I want to grab the two groups = Bros and Girls
I want to grab the actviities = josh sent steve a message
                              = jessica added stephanie

I want to display the group and the last activity together like a whatsapp group from the main screen of the applicaiton.

Can anyone help me.

Body:
instead of directly querying activities you can use backward relations, use something like this in your template

{% for group in groups %}
    <p>
      <a href="{% url 'group_home' group.group.name|slugify group.group.id %}">{{ group.group.name }}</a>
    </p>
    {% for act in group.activity_set.all %}
        {{ act.description }}
    {% endfor %}
  {% endfor %}

for more info check this page in django docs.


问:
JSONArray Parsing in RecyclerView using volley android
I am trying to parse JSONArray in RecyclerView using volley in android,  i have 10 data per page, how can I call next page url when we scroll down recyclerview every time?

My JsonArray

```<code>"data": {
    "total": 146,
    "per_page": 10,
    "current_page": 1,
    "last_page": 15,
    "next_page_url": "http://www.xxxxxxxxxx.com/api/v1/auth/deal?page=2",
    "prev_page_url": null,
    "from": 1,
    "to": 10,
    "data": [
        {
            "id": "209",
            "ref": "101hd-209",
            "pid": "437",
            "name": "Office For Rent",
            "deal_mode": {
                "id": "128",
                "category_name": "Lease"
            },
</code>```

My recyclerview load 1st page data at a time, now on scroll down how i call next page url to load next page data.

答:
I create interface onbottom and check if the recyclerview is on bottom then load more data. means count will post into the API first it loaded 1st page data means count=1 then when will reach onbottom call function again with count++ to load second page data

Its a same structure which i faced and this helped me fine.

interface:

```<code>public interface OnBottomReachedListener {
    void onBottomReached(int position);

}
</code>```

adapter:

```<code>OnBottomReachedListener onBottomReachedListener;
 public void setOnBottomReachedListener(OnBottomReachedListener onBottomReachedListener){

        this.onBottomReachedListener = onBottomReachedListener;
    }
 @Override
    public void onBindViewHolder(final MyViewHolder holder, int position) {
       final PropertyInfo propertyInfo = propertyInfoList.get(position);

        if (position == propertyInfoList.size() - 1  ){

            onBottomReachedListener.onBottomReached(position);

        }
}
</code>```

Activity:

```<code>adapter.setOnBottomReachedListener(new OnBottomReachedListener() {
            @Override
            public void onBottomReached(int position) {
                count++;
                String URl="http://www.xxxxxxxxxx.com/api/v1/auth/deal?

                page="+count;

            }
        });
</code>```

Body:
I am trying to parse JSONArray in RecyclerView using volley in android,  i have 10 data per page, how can I call next page url when we scroll down recyclerview every time?

My JsonArray

"data": {
    "total": 146,
    "per_page": 10,
    "current_page": 1,
    "last_page": 15,
    "next_page_url": "http://www.xxxxxxxxxx.com/api/v1/auth/deal?page=2",
    "prev_page_url": null,
    "from": 1,
    "to": 10,
    "data": [
        {
            "id": "209",
            "ref": "101hd-209",
            "pid": "437",
            "name": "Office For Rent",
            "deal_mode": {
                "id": "128",
                "category_name": "Lease"
            },

My recyclerview load 1st page data at a time, now on scroll down how i call next page url to load next page data.

Body:
I create interface onbottom and check if the recyclerview is on bottom then load more data. means count will post into the API first it loaded 1st page data means count=1 then when will reach onbottom call function again with count++ to load second page data

Its a same structure which i faced and this helped me fine.

interface:

public interface OnBottomReachedListener {
    void onBottomReached(int position);

}

adapter:

OnBottomReachedListener onBottomReachedListener;
 public void setOnBottomReachedListener(OnBottomReachedListener onBottomReachedListener){

        this.onBottomReachedListener = onBottomReachedListener;
    }
 @Override
    public void onBindViewHolder(final MyViewHolder holder, int position) {
       final PropertyInfo propertyInfo = propertyInfoList.get(position);

        if (position == propertyInfoList.size() - 1  ){

            onBottomReachedListener.onBottomReached(position);

        }
}

Activity:

adapter.setOnBottomReachedListener(new OnBottomReachedListener() {
            @Override
            public void onBottomReached(int position) {
                count++;
                String URl="http://www.xxxxxxxxxx.com/api/v1/auth/deal?

                page="+count;

            }
        });


问:
Change servo angle based on Bluetooth input
I'm using an app to either turn on an LED or change the angle of a micro servo depending on which button is pressed (using Arduino). My code works for the LED (while the button is pressed, the LED is on) but nothing happens when I press the button meant to change the angle of the servo to 40.

// Bluetooth serial:
#include <SoftwareSerial.h> // import the serial library

// setup the bluetooth coms
SoftwareSerial BTSerial(8,7);

#include <Servo.h>

int servoPin = 0;

Servo servo;

int angle = 0; // servo position in degrees
int input = 0;
int led2 = 13;

void setup() {
  // put your setup code here, to run once:
  servo.attach(servoPin);
  Serial.begin(9600);   // coms w/ computer
  BTSerial.begin(9600); // coms w/ Bluetooth
  pinMode(led2, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:

  if (BTSerial.available())
  {
    input = BTSerial.read();
    digitalWrite(led2, LOW);

    switch(input) {
      case 'E':
        angle = 40;
        break;

      case 'C':
        digitalWrite(led2, HIGH);
        break;
    }

    servo.write(angle);
  }
}
```

<p>The input is right as I checked by also turning the LED on in case 'E' where it worked as normal. I had also tried using servo.write() within the case function as well but this didn't work either.</p>

```case 'E':
   servo.write(40);
   break;
```

答:
You cannot use digital pins 0 or 1 as input:

As mentioned, those are serial send and receive pins. If you power your computer through USB, it can interfere if you try to use them, since it's reading from both the USB to Serial and the pin. Also you have an issue with anything connected (well, not anything, but remove it just to be safe) when you're trying to program. If you use the pins as intended, and program then run it off battery, it should be no problem at all.

Most of us stay away from it because it's a bit of a hassle

Depending on your Arduino model, servo.attach only supports pins 9 and 10:

Note that in Arduino 0016 and earlier, the Servo library supports only servos on only two pins: 9 and 10.

Or you could just use one of those anyway.

Body:
I'm using an app to either turn on an LED or change the angle of a micro servo depending on which button is pressed (using Arduino). My code works for the LED (while the button is pressed, the LED is on) but nothing happens when I press the button meant to change the angle of the servo to 40.

// Bluetooth serial:
#include <SoftwareSerial.h> // import the serial library

// setup the bluetooth coms
SoftwareSerial BTSerial(8,7);

#include <Servo.h>

int servoPin = 0;

Servo servo;

int angle = 0; // servo position in degrees
int input = 0;
int led2 = 13;

void setup() {
  // put your setup code here, to run once:
  servo.attach(servoPin);
  Serial.begin(9600);   // coms w/ computer
  BTSerial.begin(9600); // coms w/ Bluetooth
  pinMode(led2, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:

  if (BTSerial.available())
  {
    input = BTSerial.read();
    digitalWrite(led2, LOW);

    switch(input) {
      case 'E':
        angle = 40;
        break;

      case 'C':
        digitalWrite(led2, HIGH);
        break;
    }

    servo.write(angle);
  }
}

The input is right as I checked by also turning the LED on in case 'E' where it worked as normal. I had also tried using servo.write() within the case function as well but this didn't work either.

case 'E':
   servo.write(40);
   break;


问:
Instagram iPhone hooks url schemes
I have developed an app to test the use of Instagram iPhone hooks, which is quite well explained on this site, but, to my opinion, not so on the Instagram developer site. The reason for this post is to see if there are developers better informed than I am about the url scheme and parameters in the iPhone hooks than I am.

According to Instagram you can use the following urls:

However, it is not clear to me what the Instagram app does depending on the url. The reason is that I first, of course, used the scheme and url:

```<code>let instagramURL = URL.init(string: "instagram://app")
</code>```

Then I tried tho use:

```<code>let instagramURL = URL.init(string: "instagram://location?id=1")
</code>```

Same behavior. So, I went further and used:

```<code>let instagramURL = URL.init(string: "instagram://location")
let instagramURL = URL.init(string: "instagram://layout")
let instagramURL = URL.init(string: "instagram://crap")
</code>```

All delivering the same successful behavior in being able to post a picture on Instagram. I reported the issue with this question on the developers site, but haven't gotten a response yet.

Is there someone with a better understanding of the url schemes used in the iPhone hooks?

答:
Well I don't get what exactly you are looking for but,
Using these schemes you can open a specific location , tag or username's page directly on instagram app
try this for example : "instagram://user?username=amirzakeri" :)</p>

Title: Instagram iPhone hooks url schemes

Body:
I have developed an app to test the use of Instagram iPhone hooks, which is quite well explained on this site, but, to my opinion, not so on the Instagram developer site. The reason for this post is to see if there are developers better informed than I am about the url scheme and parameters in the iPhone hooks than I am.

According to Instagram you can use the following urls:

However, it is not clear to me what the Instagram app does depending on the url. The reason is that I first, of course, used the scheme and url:

let instagramURL = URL.init(string: "instagram://app")

Then I tried tho use:

let instagramURL = URL.init(string: "instagram://location?id=1")

Same behavior. So, I went further and used:

let instagramURL = URL.init(string: "instagram://location")
let instagramURL = URL.init(string: "instagram://layout")
let instagramURL = URL.init(string: "instagram://crap")

All delivering the same successful behavior in being able to post a picture on Instagram. I reported the issue with this question on the developers site, but haven't gotten a response yet.

Is there someone with a better understanding of the url schemes used in the iPhone hooks?


问:
How do I merge two csv files based on the words in a given list?
I have two csv files, each of them are in this format,

```<code>file1
zip     name    score
23431   david   12
23231   rob     45
33441   hary    23
98901   rgrg    55

file2
zip1    name1   score1
23433   david   12
23245   stel    45
33478   hary    23
98988   rob     55
12121   jass    33
</code>```

and I have a list that has the names, like this

```<code>lista = ['harry', 'rob', 'wine', 'david', 'jass']
</code>```

The final csv file should look like this:

```<code>name    zip     score       zip1     score1
harry   x       x           x           x
rob     23231   45          98988       55
wine    x       x           x           x
david   23431   12          23433       12
jass    x       x           12121       33
</code>```

that means, if any name from the list lies in either of the csv files, than we should include it in the new csv file along with its zip and score. Otherwise we should print 'x' in it.

This is what I have done so far:

```<code>import csv
with open('file1.csv', 'r') as input1, open('file2.csv', 'r') as input2, open('merge_final.csv', 'w') as output:
    writer = csv.writer(output)
    reader1 = csv.reader(input1)
    eader2 = csv.reader(input2)

    lista = ['harry', 'rob', 'wine', 'david', 'jass']
    writer.writerow(['name','zip','score','zip1','score'])

        for i in lista:
            for row in list(reader1):
                rev = row[1]
                if i in rev:
                    score = row[2]
                    zip = row[0]
                else:
                    score = 'x'
                    zip = 'x'
            for row in list(reader2):
                rev = row[1]
                if i in rev:
                    score1 = row[2]
                    zip1 = row[0]
                else:
                    score1 = 'x'
                    zip1 = 'x'
            writer.writerow([i, score, zip, score1, zip1])
</code>```

This code is not working as expected. This is the output I got using this code.

```<code>name    zip     score       zip1     score1
harry   x       x           x           x
rob     x      x            x            x
wine    x       x           x           x
david   x       x           x           x
jass    x       x           x           x
</code>```

Even thought there are many common words, only 'x' gets printed in the final merged csv file. I think the problem is with the loops. But, I don't seem to figure out the issue.

答:
The errors in above code:

The first loop of list(reader1) exhausts the iterator that is the file handle. So when the next iteration for 'lista' starts the reader1 is empty with len=0.

Instead of repeatedly iterating the file handle store data in a list or dictionary.

When the i matches with rev in case of if(i in rev) you are continuing to iterate over rest of the file which causes the value of zip and score to be reset to 'x' as for the next iteration "i in rev" will give False. You need to remove the else part to rectify this. Instead declare zip,score as 'x' just after for i in lista:

Body:
I have two csv files, each of them are in this format,

file1
zip     name    score
23431   david   12
23231   rob     45
33441   hary    23
98901   rgrg    55

file2
zip1    name1   score1
23433   david   12
23245   stel    45
33478   hary    23
98988   rob     55
12121   jass    33

and I have a list that has the names, like this

lista = ['harry', 'rob', 'wine', 'david', 'jass']

The final csv file should look like this:

name    zip     score       zip1     score1
harry   x       x           x           x
rob     23231   45          98988       55
wine    x       x           x           x
david   23431   12          23433       12
jass    x       x           12121       33

that means, if any name from the list lies in either of the csv files, than we should include it in the new csv file along with its zip and score. Otherwise we should print 'x' in it.

This is what I have done so far:

import csv
with open('file1.csv', 'r') as input1, open('file2.csv', 'r') as input2, open('merge_final.csv', 'w') as output:
    writer = csv.writer(output)
    reader1 = csv.reader(input1)
    eader2 = csv.reader(input2)

    lista = ['harry', 'rob', 'wine', 'david', 'jass']
    writer.writerow(['name','zip','score','zip1','score'])

        for i in lista:
            for row in list(reader1):
                rev = row[1]
                if i in rev:
                    score = row[2]
                    zip = row[0]
                else:
                    score = 'x'
                    zip = 'x'
            for row in list(reader2):
                rev = row[1]
                if i in rev:
                    score1 = row[2]
                    zip1 = row[0]
                else:
                    score1 = 'x'
                    zip1 = 'x'
            writer.writerow([i, score, zip, score1, zip1])

This code is not working as expected. This is the output I got using this code.

name    zip     score       zip1     score1
harry   x       x           x           x
rob     x      x            x            x
wine    x       x           x           x
david   x       x           x           x
jass    x       x           x           x

Even thought there are many common words, only 'x' gets printed in the final merged csv file. I think the problem is with the loops. But, I don't seem to figure out the issue.


问:
Java Regex to extract a word from given String
I need to extract a word from a given string. The String might come in different ways in this case. e.g:

"The Signature refers to test id 69043 abcd. The Signature refers to test id 1001"

"The Signature refers to test id

69043 defg. The Signature refers to test id
1001"

"The Signature refers to test

id 69043."

Also test id might not be in lower case always. it would be better if i could ignore whether it is lower case or upper case. it might come as Test ID, TEST ID as well

I wrote this for the moment ' test id ([0-9]+) '

i want to extract 'test id number' from these given strings. sometimes it can have multiple 'test id number' in the string. some time string has multi lines because it comes in a paragraph.

答:
You can use a formal Java pattern matcher here, using the following case insensitive pattern:

```<code>(?i)test\s+id\s+(\d+)
</code>```

Consider the following code snippet:

```<code>String input = "The Signature refers to test id 69043 abcd. ";
input += "The Signature refers to test id 1001";
String pattern = "(?i)test\\s+id\\s+(\\d+)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(input);

while (m.find()) {
   System.out.println("Found value: " + m.group(1) );
}
</code>```

This correctly outputs the two ids:

```<code>Found value: 69043
Found value: 1001
</code>```

Demo

Body:
You can use a formal Java pattern matcher here, using the following case insensitive pattern:

(?i)test\s+id\s+(\d+)

Consider the following code snippet:

String input = "The Signature refers to test id 69043 abcd. ";
input += "The Signature refers to test id 1001";
String pattern = "(?i)test\\s+id\\s+(\\d+)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(input);

while (m.find()) {
   System.out.println("Found value: " + m.group(1) );
}

This correctly outputs the two ids:

Found value: 69043
Found value: 1001

Demo


问:
ASP.Net Core 2.0 - Referencing 'Microsoft.NET.Sdk.Web' and the 'PreserveCompilationContext' property is not set to false
I'm getting the following error in the _ViewImports.cshtml file.

One or more compilation references are missing. Ensure that your project is referencing 'Microsoft.NET.Sdk.Web' and the 'PreserveCompilationContext' property is not set to false.

Stack trace:

```<code>fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[0]
      An unhandled exception has occurred while executing the request
Microsoft.AspNetCore.Mvc.Razor.Compilation.CompilationFailedException: One or more compilation failures occurred:
C:\src\LunchVoting\Web\Views\_ViewImports.cshtml(1,7): error CS0246: The type or namespace name 'LunchVoting' could not be found (are you missing a using directive or an assembly reference?)
   at Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler.CompileAndEmit(RazorCodeDocument codeDocument, String generatedCode)
   at Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler.CompileAndEmit(String relativePath)
   at Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler.CreateCacheEntry(String normalizedPath)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.AspNetCore.Mvc.Razor.Internal.DefaultRazorPageFactoryProvider.CreateFactory(String relativePath)
   at Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.CreateCacheResult(HashSet`1 expirationTokens, String relativePath, Boolean isMainPage)
   at Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.OnCacheMiss(ViewLocationExpanderContext expanderContext, ViewLocationCacheKey cacheKey)
   at Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.LocatePageFromViewLocations(ActionContext actionContext, String pageName, Boolean isMainPage)
   at Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.FindView(ActionContext context, String viewName, Boolean isMainPage)
   at Microsoft.AspNetCore.Mvc.ViewEngines.CompositeViewEngine.FindView(ActionContext context, String viewName, Boolean isMainPage)
   at Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.ViewResultExecutor.FindView(ActionContext actionContext, ViewResult viewResult)
   at Microsoft.AspNetCore.Mvc.ViewResult.<ExecuteResultAsync>d__26.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeResultAsync>d__19.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeNextResultFilterAsync>d__24.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResultExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeNextResourceFilter>d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeFilterPipelineAsync>d__17.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeAsync>d__15.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.SpaServices.Webpack.ConditionalProxyMiddleware.<Invoke>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.SpaServices.Webpack.ConditionalProxyMiddleware.<Invoke>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__7.MoveNext()
</code>```

答:
So it turns out that I renamed my web project and it's namespaces but forgot to do the rename in the _ViewImports.cshtml file.

I feel really stupid.

Body:
I'm getting the following error in the _ViewImports.cshtml file.

One or more compilation references are missing. Ensure that your project is referencing 'Microsoft.NET.Sdk.Web' and the 'PreserveCompilationContext' property is not set to false.

Stack trace:

fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[0]
      An unhandled exception has occurred while executing the request
Microsoft.AspNetCore.Mvc.Razor.Compilation.CompilationFailedException: One or more compilation failures occurred:
C:\src\LunchVoting\Web\Views\_ViewImports.cshtml(1,7): error CS0246: The type or namespace name 'LunchVoting' could not be found (are you missing a using directive or an assembly reference?)
   at Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler.CompileAndEmit(RazorCodeDocument codeDocument, String generatedCode)
   at Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler.CompileAndEmit(String relativePath)
   at Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler.CreateCacheEntry(String normalizedPath)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.AspNetCore.Mvc.Razor.Internal.DefaultRazorPageFactoryProvider.CreateFactory(String relativePath)
   at Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.CreateCacheResult(HashSet`1 expirationTokens, String relativePath, Boolean isMainPage)
   at Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.OnCacheMiss(ViewLocationExpanderContext expanderContext, ViewLocationCacheKey cacheKey)
   at Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.LocatePageFromViewLocations(ActionContext actionContext, String pageName, Boolean isMainPage)
   at Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.FindView(ActionContext context, String viewName, Boolean isMainPage)
   at Microsoft.AspNetCore.Mvc.ViewEngines.CompositeViewEngine.FindView(ActionContext context, String viewName, Boolean isMainPage)
   at Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.ViewResultExecutor.FindView(ActionContext actionContext, ViewResult viewResult)
   at Microsoft.AspNetCore.Mvc.ViewResult.<ExecuteResultAsync>d__26.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeResultAsync>d__19.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeNextResultFilterAsync>d__24.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResultExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeNextResourceFilter>d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeFilterPipelineAsync>d__17.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeAsync>d__15.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.SpaServices.Webpack.ConditionalProxyMiddleware.<Invoke>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.SpaServices.Webpack.ConditionalProxyMiddleware.<Invoke>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__7.MoveNext()


问:
How to call a function variable in another function having the same class in core php
```<code>class DB_conn{
    function getConnected($servername,$useranem,$pass,$db) {
    $mysqli = new mysqli($servername, $useranem, $pass, $db);
    if($mysqli->connect_error)
        die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
    return $mysqli;
    }
</code>```

This is my connection string function, I am using mysqli. I have to use two parameters for the mysqli query. How to call $mysqli in the next function? When I am using $mysqli in the fetch_login function, it's giving me an error of undefined variable.

Notice: Undefined property: DB_conn::$mysqli in
     D:\xampp\htdocs\mysqli\connect.php on line 44

```<code>public function fetch_login(){
    //$mysqli;
    $sql = mysqli_query($mysqli,"select * from login");
    return $sql;
}
</code>```

答:
Try to use $this keyword before variable and function to access class members</p>

```<code>class DB_conn
{
    private $mysqli;

    public function getConnected($servername,$useranem,$pass,$db)
    {
        $mysqli = new mysqli($servername, $useranem, $pass, $db);
        if($mysqli->connect_error)
            die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
        return $mysqli;
    }
    public function fetch_login()
    {
      //$mysqli;
       $sql = mysqli_query($this->$mysqli,"select * from login");
       return $sql;
    }
}
</code>```

Body:
class DB_conn{
    function getConnected($servername,$useranem,$pass,$db) {
    $mysqli = new mysqli($servername, $useranem, $pass, $db);
    if($mysqli->connect_error)
        die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
    return $mysqli;
    }

This is my connection string function, I am using mysqli. I have to use two parameters for the mysqli query. How to call $mysqli in the next function? When I am using $mysqli in the fetch_login function, it's giving me an error of undefined variable.

Notice: Undefined property: DB_conn::$mysqli in
     D:\xampp\htdocs\mysqli\connect.php on line 44

public function fetch_login(){
    //$mysqli;
    $sql = mysqli_query($mysqli,"select * from login");
    return $sql;
}

Body:
Try to use $this keyword before variable and function to access class members

class DB_conn
{
    private $mysqli;

    public function getConnected($servername,$useranem,$pass,$db)
    {
        $mysqli = new mysqli($servername, $useranem, $pass, $db);
        if($mysqli->connect_error)
            die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
        return $mysqli;
    }
    public function fetch_login()
    {
      //$mysqli;
       $sql = mysqli_query($this->$mysqli,"select * from login");
       return $sql;
    }
}


问:
VSTS build definition using npm task for angular cli build - where's the output?
I've created a build definition in Visual Studio Team Services with a hosted agent, and I'm trying to build an Angular 4 project via an npm task, but when I use a Copy File or Publish Artifact task, the places I look for output are always empty.  The npm task looks like this:

```<code>Version: 1.*
Command: custom
Working folder with package.json: $/teamproj/soln/proj
Command and arguments: run vsts-build-dev -op $(BuildArtifactStagingDirectory)\wwwroot
</code>```

I've tried controlling the output and retrieving the compiled code via a number of methods...the npm step usually completes, but I'm never able to find the output.  Currently I have a custom function called "vsts-build-dev" which just runs "ng build -dev".  I wasn't sure whether I could build directly to a subfolder of the BuildArtifactStagingDirectory...the npm task works, but a later zip of the build files is empty.

The logs don't always give the full picture of where the files are being generated and I've found debugging these tedious as they're always taking 6-10 minutes before failing...what's the best way to troubleshoot file paths with a hosted agent?

答:
The syntax is: npm run <command> [-- <args>]

For example, Command and arguments: run vsts-build-dev -- -op ..\a\wwwroot. (can’t use build variable, using relative path instead)

Body:
I've created a build definition in Visual Studio Team Services with a hosted agent, and I'm trying to build an Angular 4 project via an npm task, but when I use a Copy File or Publish Artifact task, the places I look for output are always empty.  The npm task looks like this:

Version: 1.*
Command: custom
Working folder with package.json: $/teamproj/soln/proj
Command and arguments: run vsts-build-dev -op $(BuildArtifactStagingDirectory)\wwwroot

I've tried controlling the output and retrieving the compiled code via a number of methods...the npm step usually completes, but I'm never able to find the output.  Currently I have a custom function called "vsts-build-dev" which just runs "ng build -dev".  I wasn't sure whether I could build directly to a subfolder of the BuildArtifactStagingDirectory...the npm task works, but a later zip of the build files is empty.

The logs don't always give the full picture of where the files are being generated and I've found debugging these tedious as they're always taking 6-10 minutes before failing...what's the best way to troubleshoot file paths with a hosted agent?


问:
How to produce Live video and audio streaming (not VoD) with ffmpeg?
I want to produce a Live audio/video stream from local file.

I tried the following:

ffmpeg -re -thread_queue_size 4 -i source_video_file.ts -strict -2
  -vcodec copy -an -f rtp rtp://localhost:10000 -acodec copy -vn -sdp_file saved_sdp_file -f rtp rtp://localhost:20000

and then:

ffplay saved_sdp_file

It seems to work fine, but it looks like a Video on Demand, cause I can replay this file with ffplay whenever I want.

But I need ffplay to show video/audio only during ffmpeg streaming instance is running (the first command above).

How do I achieve this?

Thanks!

答:
This  code works for live video streaming :

```<code>proc liveStreaming {} {

    #ffmpeg command to capture live streaming in background
    exec ffplay -f dshow -i video="Integrated Webcam" >& $logFile &

}
liveStreaming
</code>```

Make use of fmmpeg using  following code, this also works :

```<code>proc liveStreaming {} {

    #ffmpeg command to capture live streaming
    exec ffmpeg -f dshow -i video="Integrated Webcam" -f sdl2 -

}
liveStreaming
</code>```

You can also make use of "sdl" if sdl2 doesn't work.

Body:
This  code works for live video streaming :

proc liveStreaming {} {

    #ffmpeg command to capture live streaming in background
    exec ffplay -f dshow -i video="Integrated Webcam" >& $logFile &

}
liveStreaming

Make use of fmmpeg using  following code, this also works :

proc liveStreaming {} {

    #ffmpeg command to capture live streaming
    exec ffmpeg -f dshow -i video="Integrated Webcam" -f sdl2 -

}
liveStreaming

You can also make use of "sdl" if sdl2 doesn't work.