答:
InputStream, OutputStream, byte[], ByteBuffer are for binary data.

Reader, Writer, String, char are for text, internally Unicode, so that all scripts in the world may be combined (say Greek and Arabic).

InputStreamReader and OutputStreamWriter form a bridge between both. If you have some InputStream and know that its bytes is actually text in some encoding, Charset, then you can wrap the InputStream:

```<code>try (InputStreamReader reader =
        new InputStreamReader(stream, StandardCharsets.UTF_8)) {
     ... read text ...
}
</code>```

There is a constructor without Charset, but that is not portable, as it uses the default platform encoding.

On Android StandardCharset may not exist, use "UTF-8".

The derived classes FileInputStream and BufferedReader add something to the parent InputStream resp. Reader.

A FileInputStream is for input from a File, and BufferedReader uses a memory buffer, so the actual physical reading does not does not read character wise (inefficient). With new BufferedReader(otherReader) you add buffering to your original reader.

All this understood, there is the utility class Files with methods like newBufferedReader(Path, Charset) which add additional brevity.

Title: How do an InputStream, InputStreamReader and BufferedReader work together in Java?

Body:
I am studying Android development (I'm a beginner in programming in general) and learning about HTTP networking and saw this code in the lesson:

private String readFromStream(InputStream inputStream) throws IOException {
  StringBuilder output = new StringBuilder();
  if (inputStream != null) {
    InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
    BufferedReader reader = new BufferedReader(inputStreamReader);
    String line = reader.readLine();
    while (line != null) {
      output.append(line);
      line = reader.readLine();
    }
  }
  return output.toString();
}

I don't understand exactly what InputStream, InputStreamReader and BufferedReader do. All of them have a read() method and also readLine() in the case of the BufferedReader.Why can't I only use the InputStream or only add the InputStreamReader? Why do I need to add the BufferedReader? I know it has to do with efficiency but I don't understand how.

I've been researching and the documentation for the BufferedReader tries to explain this but I still don't get who is doing what:

In general, each read request made of a Reader causes a corresponding
  read request to be made of the underlying character or byte stream. It
  is therefore advisable to wrap a BufferedReader around any Reader
  whose read() operations may be costly, such as FileReaders and
  InputStreamReaders. For example,

BufferedReader in    = new BufferedReader(new FileReader("foo.in"));
  will buffer the input from the specified file. Without buffering, each
  invocation of read() or readLine() could cause bytes to be read from
  the file, converted into characters, and then returned, which can be
  very inefficient.

So, I understand that the InputStream can only read one byte, the InputStreamReader a single character, and the BufferedReader a whole line and that it also does something about efficiency which is what I don't get. I would like to have a better understanding of who is doing what, so as to understand why I need all three of them and what the difference would be without one of them.

I've researched a lot here and elsewhere on the web and don't seem to find any explanation about this that I can understand, almost all tutorials just repeat the documentation info. Here are some related questions that maybe begin to explain this but don't go deeper and solve my confusion: Q1, Q2, Q3, Q4. I think it may have to do with this last question's explanation about system calls and returning. But I would like to understand what is meant by all this.

Could it be that the BufferedReader's readLine() calls the InputStreamReader's read() method which in turn calls the InputStream's read() method? And the InputStream returns bytes converted to int, returning a single byte at a time, the InputStreamReader reads enough of these to make a single character and converts it to int and returns a single character at a time, and the BufferedReader reads enough of these characters represented as integers to make up a whole line? And returns the whole line as a String, returning only once instead of several times? I don't know, I'm just trying to get how things work.

Lots of thanks in advance!

Body:
InputStream, OutputStream, byte[], ByteBuffer are for binary data.

Reader, Writer, String, char are for text, internally Unicode, so that all scripts in the world may be combined (say Greek and Arabic).

InputStreamReader and OutputStreamWriter form a bridge between both. If you have some InputStream and know that its bytes is actually text in some encoding, Charset, then you can wrap the InputStream:

try (InputStreamReader reader =
        new InputStreamReader(stream, StandardCharsets.UTF_8)) {
     ... read text ...
}

There is a constructor without Charset, but that is not portable, as it uses the default platform encoding.

On Android StandardCharset may not exist, use "UTF-8".

The derived classes FileInputStream and BufferedReader add something to the parent InputStream resp. Reader.

A FileInputStream is for input from a File, and BufferedReader uses a memory buffer, so the actual physical reading does not does not read character wise (inefficient). With new BufferedReader(otherReader) you add buffering to your original reader.

All this understood, there is the utility class Files with methods like newBufferedReader(Path, Charset) which add additional brevity.


来源: stackexchange

问:
Android TextView Justify Text
How do you get the text of a TextView to be Justified (with text flush on the left- and right- hand sides)?

I found a possible solution here, but it does not work (even if you change vertical-center to center_vertical, etc).

答:
To justify text in android I used WebView

```<code>    setContentView(R.layout.main);

    WebView view = new WebView(this);
    view.setVerticalScrollBarEnabled(false);

    ((LinearLayout)findViewById(R.id.inset_web_view)).addView(view);

    view.loadData(getString(R.string.hello), "text/html; charset=utf-8", "utf-8");
</code>```

and html.

```<code><string name="hello">
<![CDATA[
<html>
 <head></head>
 <body style="text-align:justify;color:gray;background-color:black;">
  Lorem ipsum dolor sit amet, consectetur
  adipiscing elit. Nunc pellentesque, urna
  nec hendrerit pellentesque, risus massa
 </body>
</html>
]]>
</string>
</code>```

I can't yet upload images to prove it but "it works for me".

ContentLicense: CC BY-SA 3.0

Title: Android TextView Justify Text

Body:
To justify text in android I used WebView

    setContentView(R.layout.main);

    WebView view = new WebView(this);
    view.setVerticalScrollBarEnabled(false);

    ((LinearLayout)findViewById(R.id.inset_web_view)).addView(view);

    view.loadData(getString(R.string.hello), "text/html; charset=utf-8", "utf-8");

and html.

<string name="hello">
<![CDATA[
<html>
 <head></head>
 <body style="text-align:justify;color:gray;background-color:black;">
  Lorem ipsum dolor sit amet, consectetur
  adipiscing elit. Nunc pellentesque, urna
  nec hendrerit pellentesque, risus massa
 </body>
</html>
]]>
</string>

I can't yet upload images to prove it but "it works for me".


问:
about synchronization with two threads
Say one singleton instance accessed by two threads. Two threads are accessing the same function called doTask().

```<code>public class MySingleton {
    Object lock = new Object();
    // I omit the constructor here.

    public void doTask() {
         //first non-synchronized code

         synchronize(lock) {
             //some heavy task
         }

         //final non-synchronized code
    }
}
</code>```

If thread B is doing the heavy task, when thread A access doTask(), I know Thread A will run the //first non-synchronized code, then thread A noticed the lock is acquired by Thread B, so it can't run synchronized //some heavy task. But would thread A skip the synchronized heavy task continue run //final non-synchronized code or will thread A wait for the lock without even executing the //final non-synchronized code?

(I know I can try it out, but currently I don't have a proper development environment...)

答:
Thread A will always wait indefinitely until Thread B releases the lock.

In the extreme case, if the lock is never released, Thread A will be stuck forever.

Sometimes this is good enough but often you will need better control over things, this is when classes like ReentrantLock come handy.

This can do everything synchronized offers, but can also do things like checking whether the lock is owned by the current thread already, attempting to acquire the lock without waiting (failing instantly if the lock is already taken by another thread), or limit its waiting to a certain amount of time.

Please also note that while these solutions can be used to control mutual exclusion, this isn't their only function, they also play an important role in visibility.

Title: about synchronization with two threads

Body:
Say one singleton instance accessed by two threads. Two threads are accessing the same function called doTask().

public class MySingleton {
    Object lock = new Object();
    // I omit the constructor here.

    public void doTask() {
         //first non-synchronized code

         synchronize(lock) {
             //some heavy task
         }

         //final non-synchronized code
    }
}

If thread B is doing the heavy task, when thread A access doTask(), I know Thread A will run the //first non-synchronized code, then thread A noticed the lock is acquired by Thread B, so it can't run synchronized //some heavy task. But would thread A skip the synchronized heavy task continue run //final non-synchronized code or will thread A wait for the lock without even executing the //final non-synchronized code?

(I know I can try it out, but currently I don't have a proper development environment...)


问:
How to change a list of hashtags into strings separated by commas?
I have a list of instagram hashtags that go like this

#love #life #instagram #cool

but I want them to look like this

'love', 'life', 'instagram', 'cool'

is there any way to make that happen using javascript, or is there an existing program that does that? I want to have a small code that takes those hashtags as input, and outputs in the format that I want. I only know JavaScript so I doubt any other programming language advice will be useful, unless there's a program that does that already.

答:
you can do this:

let input = $('#my_input').text().split('#');
let output = '';
$.each( input, function( key, value ) {
 if(value != ''){
  if(input.length-1 != key){
     output += "'" + value + "', "
  }else{
   output += "'" + value + "'"
  }
 }
});

$('#my_input').text(output)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!-- 'love', 'life', 'instagram', 'cool' -->
<div id='my_input'>#love #life #instagram #cool</div></code>```

or something like this (from nullqube but added some changes):

let strData = $('#my_input').text();

let list = strData.split("#");
//remove first item
list.shift();
let res = list.map(function(item){
 if(item != ''){
     return "'" + item + "'";
  }
}).join(", ");

$('#my_input').text(res)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!-- 'love', 'life', 'instagram', 'cool' -->
<div id='my_input'>#love #life #instagram #cool</div></code>```

Body:
you can do this:

let input = $('#my_input').text().split('#');
let output = '';
$.each( input, function( key, value ) {
 if(value != ''){
  if(input.length-1 != key){
     output += "'" + value + "', "
  }else{
   output += "'" + value + "'"
  }
 }
});

$('#my_input').text(output)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!-- 'love', 'life', 'instagram', 'cool' -->
<div id='my_input'>#love #life #instagram #cool</div>

or something like this (from nullqube but added some changes):

let strData = $('#my_input').text();

let list = strData.split("#");
//remove first item
list.shift();
let res = list.map(function(item){
 if(item != ''){
     return "'" + item + "'";
  }
}).join(", ");

$('#my_input').text(res)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!-- 'love', 'life', 'instagram', 'cool' -->
<div id='my_input'>#love #life #instagram #cool</div>


问:
Django: Initializing a FormSet of custom forms with instances
Given the following models:

```<code>class Graph(models.Model):
    owner = models.ForeignKey(User)

    def __unicode__(self):
        return u'%d' % self.id

class Point(models.Model):
    graph = models.ForeignKey(Graph)
    date  = models.DateField(primary_key = True)
    abs   = models.FloatField(null = True)
    avg   = models.FloatField(null = True)

    def __unicode__(self):
        return u'%s' % self.date
</code>```

I am trying to create a form for editing lists of Points.
The HTML input tags require additional attributes to be set, so I am using the following custom form:

```<code>class PointForm(forms.ModelForm):
    graph = forms.ModelChoiceField(queryset = Graph.objects.all(),
                                   widget   = forms.HiddenInput())
    date  = forms.DateField(widget = forms.HiddenInput(), label = 'date')
    abs   = forms.FloatField(widget = forms.TextInput(
                                      attrs = {'class': 'abs-field'}),
                            required = False)

    class Meta:
        model  = Point
        fields = ('graph', 'date', 'abs')  # Other fields are not edited.

    def pretty_date(self):
        return self.data.strftime('%B')
</code>```

At this point I do not know how to pass instances of the Point class to a FormSet:

```<code>def edit(request):
    PointFormSet = forms.formsets.formset_factory(PointForm, extra = 0)
    if request.method == 'POST':
        return

    # Receive 3 points to edit from the database.
    graph, res = Graph.objects.get_or_create(id = 1)
    one_day    = datetime.timedelta(days = 1)
    today      = datetime.date.today()
    do_edit    = []
    for date in [today - (x * one_day) for x in range(3)]:
        point, res = Point.objects.get_or_create(graph = graph, date = date)
        do_edit.append(point)

    formset = PointFormSet(????) # How is this initialized with the points?
</code>```

I found a hack that somewhat works, but it leads to errors later on when trying to process the resulting POST data:

```<code>do_edit = []
for date in [today - (x * one_day) for x in range(3)]:
    point, res    = Point.objects.get_or_create(graph = graph, date = date)
    data          = point.__dict__.copy()
    data['graph'] = graph
    do_edit.append(data)

formset = PointFormSet(initial = do_edit)
</code>```

How is this done correctly?

For the reference, my template looks like this:

```<code><form action="" method="post">
{{ formset.management_form }}
<table>
    <tbody>
    {% for form in formset.forms %}
        <tr>
            <td>{{ form.graph }} {{ form.date }} {{ form.pretty_date }}:</td>
            <td width="100%">{{ form.abs }}</td>
        </tr>
    {% endfor %}
    </tbody>
</table>
</form>
</code>```

答:
If you only have one possible value which you want to set, or perhaps a closed of values, it is possible to set them after the user POSTS the data to your server using commit=False

Please consider the following code:

```<code>class UserReferralView(View):
    ReferralFormSet = modelformset_factory(ReferralCode,
                                           form=ReferralTokenForm, extra=1)

    def get(self, request):
        pass

    def post(self, request):
        referral_formset = UserUpdateView.ReferralFormSet(request.POST)

        if referral_formset.is_valid():
            instances = referral_formset.save(commit=False)
            for instance in instances:
                instance.user = request.user
                instance.save()
            return redirect(reverse('referrals.success_view'))
         else:
            return redirect(reverse('referrals.failure_view'))
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Given the following models:

class Graph(models.Model):
    owner = models.ForeignKey(User)

    def __unicode__(self):
        return u'%d' % self.id

class Point(models.Model):
    graph = models.ForeignKey(Graph)
    date  = models.DateField(primary_key = True)
    abs   = models.FloatField(null = True)
    avg   = models.FloatField(null = True)

    def __unicode__(self):
        return u'%s' % self.date

I am trying to create a form for editing lists of Points.
The HTML input tags require additional attributes to be set, so I am using the following custom form:

class PointForm(forms.ModelForm):
    graph = forms.ModelChoiceField(queryset = Graph.objects.all(),
                                   widget   = forms.HiddenInput())
    date  = forms.DateField(widget = forms.HiddenInput(), label = 'date')
    abs   = forms.FloatField(widget = forms.TextInput(
                                      attrs = {'class': 'abs-field'}),
                            required = False)

    class Meta:
        model  = Point
        fields = ('graph', 'date', 'abs')  # Other fields are not edited.

    def pretty_date(self):
        return self.data.strftime('%B')

At this point I do not know how to pass instances of the Point class to a FormSet:

def edit(request):
    PointFormSet = forms.formsets.formset_factory(PointForm, extra = 0)
    if request.method == 'POST':
        return

    # Receive 3 points to edit from the database.
    graph, res = Graph.objects.get_or_create(id = 1)
    one_day    = datetime.timedelta(days = 1)
    today      = datetime.date.today()
    do_edit    = []
    for date in [today - (x * one_day) for x in range(3)]:
        point, res = Point.objects.get_or_create(graph = graph, date = date)
        do_edit.append(point)

    formset = PointFormSet(????) # How is this initialized with the points?

I found a hack that somewhat works, but it leads to errors later on when trying to process the resulting POST data:

do_edit = []
for date in [today - (x * one_day) for x in range(3)]:
    point, res    = Point.objects.get_or_create(graph = graph, date = date)
    data          = point.__dict__.copy()
    data['graph'] = graph
    do_edit.append(data)

formset = PointFormSet(initial = do_edit)

How is this done correctly?

For the reference, my template looks like this:

<form action="" method="post">
{{ formset.management_form }}

    {% for form in formset.forms %}

            {{ form.graph }} {{ form.date }} {{ form.pretty_date }}:
            {{ form.abs }}

    {% endfor %}

</form>

Body:
If you only have one possible value which you want to set, or perhaps a closed of values, it is possible to set them after the user POSTS the data to your server using commit=False

Please consider the following code:

class UserReferralView(View):
    ReferralFormSet = modelformset_factory(ReferralCode,
                                           form=ReferralTokenForm, extra=1)

    def get(self, request):
        pass

    def post(self, request):
        referral_formset = UserUpdateView.ReferralFormSet(request.POST)

        if referral_formset.is_valid():
            instances = referral_formset.save(commit=False)
            for instance in instances:
                instance.user = request.user
                instance.save()
            return redirect(reverse('referrals.success_view'))
         else:
            return redirect(reverse('referrals.failure_view'))


问:
ASP.net MVC missing a using directive or an assembly reference
Hi I am following a guide to learn Asp.net MVC5.
I have created solution with three project and with NuGet i have installed this library:

Install-Package Ninject -projectname SportsStore.WebUI

Install-Package Ninject.Web.Common -projectname SportsStore.WebUI

Install-Package Ninject.MVC5 -projectname SportsStore.WebUI

Install-Package Ninject -projectname SportsStore.UnitTests

Install-Package Ninject.Web.Common -projectname SportsStore.UnitTests

Install-Package Ninject.MVC5 -projectname SportsStore.UnitTests

Install-Package Moq -projectname SportsStore.WebUI

Install-Package Moq -projectname SportsStore.UnitTests

Install-Package Microsoft.Aspnet.Mvc -projectname SportsStore.Domain

Install-Package Microsoft.Aspnet.Mvc -projectname
  SportsStore.UnitTests

Then i have added reference and i had this:

I have problem with class NinjectDependencyResolver.cs precisly into method AddBindings():

```<code>private void AddBindings() {
        Mock<IProductRepository> mock = new Mock<IProductRepository>();
        mock.Setup(m => m.Products).Returns(new List<Product> {
                    new Product { Name = "Football", Price = 25 },
                    new Product { Name = "Surf board", Price = 179 },
                    new Product { Name = "Running shoes", Price = 95 }
                    });
        kernel.Bind<IProductRepository>().ToConstant(mock.Object);

    }
</code>```

where I have binded my Interface IProductRepository and my class Products to Mock. I reiceived this error:

missing a using directive or an assembly reference

I have checked into reference of SportsStore and I noticed that the reference were already there.

I have tried to import class with using:

```<code>using SportsStore.Domain.Abstract;
using SportsStore.Domain.Entities;
</code>```

but didn't work, furthermore when i typed SportsStore intellisense suggested me the folder Abstract, therefore i had SportsStore.Abstract but then intellisense when I have put dot after Abstract it didn't suggest me nothing, it seemed like intellisense didn't find Interface IProductRepository. The same thing is happened when i have typed SportStore.Entities, intellisense didn't suggest me class Product why?
Why i had error:  missing a using directive or an assembly reference?

I have tried:

Clean Project and then Build or Rebuild project but didn't work.

答:
Edit: I have solved the problem was:

The class Product into folder Entities wasn't public therefore i have changed to public, after the change i could enter to class. Then i have tried to change Interface into folder Abstract to Public but despite everything i could not access from an other projec to class, therefore i have created a new public class and then i have changed the attribute class to Interface and now work all.

Body:
Hi I am following a guide to learn Asp.net MVC5.
I have created solution with three project and with NuGet i have installed this library:

Install-Package Ninject -projectname SportsStore.WebUI

Install-Package Ninject.Web.Common -projectname SportsStore.WebUI

Install-Package Ninject.MVC5 -projectname SportsStore.WebUI

Install-Package Ninject -projectname SportsStore.UnitTests

Install-Package Ninject.Web.Common -projectname SportsStore.UnitTests

Install-Package Ninject.MVC5 -projectname SportsStore.UnitTests

Install-Package Moq -projectname SportsStore.WebUI

Install-Package Moq -projectname SportsStore.UnitTests

Install-Package Microsoft.Aspnet.Mvc -projectname SportsStore.Domain

Install-Package Microsoft.Aspnet.Mvc -projectname
  SportsStore.UnitTests

Then i have added reference and i had this:

I have problem with class NinjectDependencyResolver.cs precisly into method AddBindings():

private void AddBindings() {
        Mock<IProductRepository> mock = new Mock<IProductRepository>();
        mock.Setup(m => m.Products).Returns(new List<Product> {
                    new Product { Name = "Football", Price = 25 },
                    new Product { Name = "Surf board", Price = 179 },
                    new Product { Name = "Running shoes", Price = 95 }
                    });
        kernel.Bind<IProductRepository>().ToConstant(mock.Object);

    }

where I have binded my Interface IProductRepository and my class Products to Mock. I reiceived this error:

missing a using directive or an assembly reference

I have checked into reference of SportsStore and I noticed that the reference were already there.

I have tried to import class with using:

using SportsStore.Domain.Abstract;
using SportsStore.Domain.Entities;

but didn't work, furthermore when i typed SportsStore intellisense suggested me the folder Abstract, therefore i had SportsStore.Abstract but then intellisense when I have put dot after Abstract it didn't suggest me nothing, it seemed like intellisense didn't find Interface IProductRepository. The same thing is happened when i have typed SportStore.Entities, intellisense didn't suggest me class Product why?
Why i had error:  missing a using directive or an assembly reference?

I have tried:

Clean Project and then Build or Rebuild project but didn't work.


Title: Partition a table and get first and last records in google big query

Body:
From the below table, I am trying to find the starttime and stoptime for each Id1.
For example, for Id1 = 103, it started on 2016-11-01 10:50:28 UTC and the stoptime of the vehicle on the same day is on 2016-11-01 11:23:55 UTC.
Similary for id1 = 103, on 2016-12-01, it started on 2016-12-01 10:51:28 UTC and ended on 2016-12-01 11:28:55 UTC.

        Id1 Id2 StartTime                 StartDate   StopTime                StopDate    DateTime
    1   103 314 2016-11-01 10:50:28 UTC 2016-11-01  2016-11-01 11:22:35 UTC 2016-11-01  2016-11-01 10:50:32 UTC
    2   103 315 2016-11-01 10:50:28 UTC 2016-11-01  2016-11-01 11:22:48 UTC 2016-11-01  2016-11-01 10:50:49 UTC
    3   103 316 2016-11-01 10:50:28 UTC 2016-11-01  2016-11-01 11:22:55 UTC 2016-11-01  2016-11-01 10:50:54 UTC
    4   103 317 2016-11-01 10:50:28 UTC 2016-11-01  2016-11-01 11:23:55 UTC 2016-11-01  2016-11-01 10:51:03 UTC
    5   103 318 2016-12-01 10:51:28 UTC 2016-12-01  2016-12-01 11:24:15 UTC 2016-12-01  2016-12-01 10:51:19 UTC
    6   103 319 2016-12-01 10:52:28 UTC 2016-12-01  2016-12-01 11:25:55 UTC 2016-12-01  2016-12-01 10:51:24 UTC
    7   103 320 2016-12-01 10:53:28 UTC 2016-12-01  2016-12-01 11:26:55 UTC 2016-12-01  2016-12-01 10:51:31 UTC
    8   103 321 2016-12-01 10:54:28 UTC 2016-12-01  2016-12-01 11:27:55 UTC 2016-12-01  2016-12-01 10:51:40 UTC
    9   103 322 2016-12-01 10:55:28 UTC 2016-12-01  2016-12-01 11:28:55 UTC 2016-12-01  2016-12-01 10:51:43 UTC

    Output:
        Id1 StartTime                 StartDate   StopTime                StopDate
    1   103 2016-11-01 10:50:28 UTC 2016-11-01  2016-11-01 11:23:55 UTC 2016-11-01
    5   103 2016-12-01 10:51:28 UTC 2016-12-01  2016-12-01 11:28:55 UTC 2016-12-01

I tried with the below query, but not sure why it does not work:

          SELECT Id1, Date, StartTime, StopTime
          FROM(
          SELECT
            Id1,
            DATE(DateTime) AS Date,
            FIRST_VALUE(StartTime) OVER (PARTITION BY Id1, DATE(DateTime)  ORDER BY DateTime) AS StartTime,
            LAST_VALUE(StopTime) OVER (PARTITION BY Id1, DATE(DateTime) ORDER BY DateTime ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) AS StopTime,
          FROM
            TestSridevi.ET_Time_Leaving)
          GROUP BY Id1, Date, StartTime, StopTime
          ORDER BY Id1

Body:
Try below

#standardSQL
WITH yourTable AS (
  SELECT 103 AS Id1, 314 AS Id2, '2016-11-01 10:50:28 UTC' AS StartTime, '2016-11-01' AS StartDate, '2016-11-01 11:22:35 UTC' AS StopTime, '2016-11-01' AS StopDate, '2016-11-01 10:50:32 UTC' AS DateTime UNION ALL
  SELECT 103, 315, '2016-11-01 10:50:28 UTC', '2016-11-01', '2016-11-01 11:22:48 UTC', '2016-11-01', '2016-11-01 10:50:49 UTC' UNION ALL
  SELECT 103, 316, '2016-11-01 10:50:28 UTC', '2016-11-01', '2016-11-01 11:22:55 UTC', '2016-11-01', '2016-11-01 10:50:54 UTC' UNION ALL
  SELECT 103, 317, '2016-11-01 10:50:28 UTC', '2016-11-01', '2016-11-01 11:23:55 UTC', '2016-11-01', '2016-11-01 10:51:03 UTC' UNION ALL
  SELECT 103, 318, '2016-12-01 10:51:28 UTC', '2016-12-01', '2016-12-01 11:24:15 UTC', '2016-12-01', '2016-12-01 10:51:19 UTC' UNION ALL
  SELECT 103, 319, '2016-12-01 10:52:28 UTC', '2016-12-01', '2016-12-01 11:25:55 UTC', '2016-12-01', '2016-12-01 10:51:24 UTC' UNION ALL
  SELECT 103, 320, '2016-12-01 10:53:28 UTC', '2016-12-01', '2016-12-01 11:26:55 UTC', '2016-12-01', '2016-12-01 10:51:31 UTC' UNION ALL
  SELECT 103, 321, '2016-12-01 10:54:28 UTC', '2016-12-01', '2016-12-01 11:27:55 UTC', '2016-12-01', '2016-12-01 10:51:40 UTC' UNION ALL
  SELECT 103, 322, '2016-12-01 10:55:28 UTC', '2016-12-01', '2016-12-01 11:28:55 UTC', '2016-12-01', '2016-12-01 10:51:43 UTC'
)
SELECT
  Id1,
  MIN(StartTime) AS StartTime,
  StartDate,
  MAX(StopTime) AS StopTime,
  StopDate
FROM yourTable
GROUP BY Id1, StartDate, StopDate
ORDER BY Id1, StartDate, StopDate

result is

Id1               StartTime  StartDate                 StopTime   stopDate
103 2016-11-01 10:50:28 UTC 2016-11-01  2016-11-01 11:23:55 UTC 2016-11-01
103 2016-12-01 10:51:28 UTC 2016-12-01  2016-12-01 11:28:55 UTC 2016-12-01


问:
How to get rid of duplicates in a graph
I'm building a social graph from a list of tuples 'friends' like this:

```<code>(4118181 {'last_name': 'Belousov', 'first_name': 'Mikhail'})
</code>```

Here's the function:

```<code>def addToGraph (g, start, friends):
    g.add_nodes_from(friends)
    egdes_to_add = [(start, entry[0]) for entry in friends]
    g.add_edges_from(edges_to_add)
    return g
</code>```

As a result I get a graph with duplicated amount of nodes, the 1st with attributes, coming from

```<code>g.add_nodes_from(friends)
</code>```

and the second is from

```<code> g.add_edges_from(edges_to_add)
</code>```

I read the docs, but can't figure out, how can I add both nodes with attributes and edges between those nodes?

答:
Your nodes are integers.  Your edges are strings.  When you add the nodes, it adds a bunch of nodes whose names are integers.  When it adds an edge, it sees a new edge between the strings '4118181'and '340559596'.  Python sees those as distinct from the integers, so it creates new nodes with the new names and puts an edge between them.

To fix this, you'll need to convert the strings to integers before adding the edges.

Title: How to get rid of duplicates in a graph

Body:
I'm building a social graph from a list of tuples 'friends' like this:

(4118181 {'last_name': 'Belousov', 'first_name': 'Mikhail'})

Here's the function:

def addToGraph (g, start, friends):
    g.add_nodes_from(friends)
    egdes_to_add = [(start, entry[0]) for entry in friends]
    g.add_edges_from(edges_to_add)
    return g

As a result I get a graph with duplicated amount of nodes, the 1st with attributes, coming from

g.add_nodes_from(friends)

and the second is from

 g.add_edges_from(edges_to_add)

I read the docs, but can't figure out, how can I add both nodes with attributes and edges between those nodes?


问:
moq 4.5.29 -getting error " type initializer for 'Moq.Proxy.CastleProxyFactory' threw an exception."
I am using xUnit 2.x and moq 4.5 and castle.core 3.3.0.0 . I have the IAssessmentsRepository interface in a different assembly ( but part of same solution) than my unit test are. I am giving reference to the assembly where IAssessmentsRepository reside. But when I try to mock, it gets error of "Type initilization"  which means that moq is not able to load the type i.e. IAssessmentsRepository .  Now I do not understand why ?? kindly suggest if anyone faced the same issue.

```<code>  [Fact]
            [UnitTest]
            public void DeleteAssessment_ShouldCall_AssessmentsRepository_DeleteAssessment_Method()
            {
                //Arrange
                var assessmentRepoMock = new Mock<Data.Assessments.IAssessmentsRepository>();
                assessmentRepoMock.Setup(x => x.DeleteAssessment(It.IsAny<int>(), It.IsAny<string>())).Returns(true);

                var assessmentService = new AssessmentService(assessmentRepoMock.Object);

                //Act
                var testResult = assessmentService.DeleteAssessment(It.IsAny<int>(), It.IsAny<string>());

                //Assert

                assessmentRepoMock.Verify(r => r.DeleteAssessment(It.IsAny<int>(), It.IsAny<string>()), Times.Once);

            }
</code>```

following is the stack trace of the error,

```<code> UHCNV.Web.Services.Icm.Services.Tests.UnitTests.AssessmentServiceTests.DeleteAssessment_ShouldCall_AssessmentsRepository_DeleteAssessment_Method [FAIL]
[xUnit.net 00:00:07.6027020]       System.TypeInitializationException : The type initializer for 'Moq.Mock`1' threw an exception.
[xUnit.net 00:00:07.6033988]       ---- System.TypeInitializationException : The type initializer for 'Moq.Proxy.CastleProxyFactory' threw an exception.
[xUnit.net 00:00:07.6038240]       -------- System.Configuration.ConfigurationErrorsException : Configuration system failed to initialize
[xUnit.net 00:00:07.6042223]       ------------ System.Configuration.ConfigurationErrorsException : Only one <configSections> element allowed per config file and if present must be the first child of the root <configuration> element. (C:\DEV2\LouisFinal\UpdatedOne\UHCNV.WEB.SERVICES.ICM\test\UHCNV.Web.Services.Icm.Services.Tests\bin\x86\Debug\UHCNV.Web.Services.Icm.Services.Tests.dll.config line 23)
[xUnit.net 00:00:07.6113488]       Stack Trace:
[xUnit.net 00:00:07.6119217]            at Moq.Mock`1.<InitializeInstance>b__24_0()
[xUnit.net 00:00:07.6123448]            at Moq.PexProtector.Invoke(Action action)
[xUnit.net 00:00:07.6127299]            at Moq.Mock`1.InitializeInstance()
[xUnit.net 00:00:07.6131116]            at Moq.Mock`1.OnGetObject()
[xUnit.net 00:00:07.6134937]            at Moq.Mock.GetObject()
[xUnit.net 00:00:07.6138850]            at Moq.Mock.get_Object()
[xUnit.net 00:00:07.6142657]            at Moq.Mock`1.get_Object()
[xUnit.net 00:00:07.6146855]         test\UHCNV.Web.Services.Icm.Services.Tests\UnitTests\AssessmentServiceTests.cs(20,0): at UHCNV.Web.Services.Icm.Services.Tests.UnitTests.AssessmentServiceTests.DeleteAssessment_ShouldCall_AssessmentsRepository_DeleteAssessment_Method()
[xUnit.net 00:00:07.6150651]         ----- Inner Stack Trace -----
[xUnit.net 00:00:07.6154568]            at Moq.Proxy.CastleProxyFactory..ctor()
[xUnit.net 00:00:07.6158157]            at Moq.Mock`1..cctor()
[xUnit.net 00:00:07.6161683]         ----- Inner Stack Trace -----
[xUnit.net 00:00:07.6165556]            at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
[xUnit.net 00:00:07.6169380]            at System.Configuration.ClientConfigurationSystem.PrepareClientConfigSystem(String sectionName)
[xUnit.net 00:00:07.6173346]            at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String sectionName)
[xUnit.net 00:00:07.6177103]            at System.Configuration.ConfigurationManager.GetSection(String sectionName)
[xUnit.net 00:00:07.6180813]            at System.Configuration.PrivilegedConfigurationManager.GetSection(String sectionName)
[xUnit.net 00:00:07.6184595]            at System.Diagnostics.DiagnosticsConfiguration.Initialize()
[xUnit.net 00:00:07.6188321]            at System.Diagnostics.DiagnosticsConfiguration.get_Sources()
[xUnit.net 00:00:07.6191972]            at System.Diagnostics.TraceSource.Initialize()
[xUnit.net 00:00:07.6195693]            at Castle.Core.Logging.TraceLogger.IsSourceConfigured(TraceSource source)
[xUnit.net 00:00:07.6199486]            at Castle.Core.Logging.TraceLogger.Initialize()
[xUnit.net 00:00:07.6204199]            at Castle.Core.Logging.TraceLogger..ctor(String name, LoggerLevel level)
[xUnit.net 00:00:07.6208012]            at Castle.DynamicProxy.ProxyGenerator..ctor(IProxyBuilder builder)
[xUnit.net 00:00:07.6211584]            at Castle.DynamicProxy.ProxyGenerator..ctor()
[xUnit.net 00:00:07.6215447]            at Moq.Proxy.CastleProxyFactory.CreateProxyGenerator()
[xUnit.net 00:00:07.6219298]            at Moq.Proxy.CastleProxyFactory..cctor()
[xUnit.net 00:00:07.6222921]         ----- Inner Stack Trace -----
[xUnit.net 00:00:07.6226725]            at System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean ignoreLocal)
[xUnit.net 00:00:07.6230535]            at System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(ConfigurationSchemaErrors schemaErrors)
[xUnit.net 00:00:07.6242699]            at System.Configuration.BaseConfigurationRecord.ThrowIfInitErrors()
[xUnit.net 00:00:07.6247423]            at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
[xUnit.net 00:00:07.6633781]     UHCNV.Web.Services.Icm.Services.Tests.UnitTests.AssessmentServiceTests.GenerateAssessmentForm_ShouldCall_AssessmentsRepository_GenerateAssessmentForm_Method [FAIL]
[xUnit.net 00:00:07.6715323]       System.TypeInitializationException : The type initializer for 'Moq.Mock`1' threw an exception.
[xUnit.net 00:00:07.6719637]       ---- System.TypeInitializationException : The type initializer for 'Moq.Proxy.CastleProxyFactory' threw an exception.
[xUnit.net 00:00:07.6723726]       -------- System.Configuration.ConfigurationErrorsException : Configuration system failed to initialize
[xUnit.net 00:00:07.6727605]       ------------ System.Configuration.ConfigurationErrorsException : Only one <configSections> element allowed per config file and if present must be the first child of the root <configuration> element. (C:\DEV2\LouisFinal\UpdatedOne\UHCNV.WEB.SERVICES.ICM\test\UHCNV.Web.Services.Icm.Services.Tests\bin\x86\Debug\UHCNV.Web.Services.Icm.Services.Tests.dll.config line 23)
[xUnit.net 00:00:07.6796134]       Stack Trace:
[xUnit.net 00:00:07.6801181]            at Moq.Mock`1.<InitializeInstance>b__24_0()
[xUnit.net 00:00:07.6805315]            at Moq.PexProtector.Invoke(Action action)
[xUnit.net 00:00:07.6809086]            at Moq.Mock`1.InitializeInstance()
[xUnit.net 00:00:07.6813035]            at Moq.Mock`1.OnGetObject()
[xUnit.net 00:00:07.6816928]            at Moq.Mock.GetObject()
[xUnit.net 00:00:07.6820733]            at Moq.Mock.get_Object()
[xUnit.net 00:00:07.6824593]            at Moq.Mock`1.get_Object()
[xUnit.net 00:00:07.6828478]         test\UHCNV.Web.Services.Icm.Services.Tests\UnitTests\AssessmentServiceTests.cs(40,0): at UHCNV.Web.Services.Icm.Services.Tests.UnitTests.AssessmentServiceTests.GenerateAssessmentForm_ShouldCall_AssessmentsRepository_GenerateAssessmentForm_Method()
[xUnit.net 00:00:07.6832594]         ----- Inner Stack Trace -----
[xUnit.net 00:00:07.6836425]            at Moq.Proxy.CastleProxyFactory..ctor()
[xUnit.net 00:00:07.6841577]            at Moq.Mock`1..cctor()
[xUnit.net 00:00:07.6845556]         ----- Inner Stack Trace -----
[xUnit.net 00:00:07.6856442]            at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
[xUnit.net 00:00:07.6860674]            at System.Configuration.ClientConfigurationSystem.PrepareClientConfigSystem(String sectionName)
[xUnit.net 00:00:07.6864632]            at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String sectionName)
[xUnit.net 00:00:07.6869201]            at System.Configuration.ConfigurationManager.GetSection(String sectionName)
[xUnit.net 00:00:07.6873166]            at System.Configuration.PrivilegedConfigurationManager.GetSection(String sectionName)
[xUnit.net 00:00:07.6877093]            at System.Diagnostics.DiagnosticsConfiguration.Initialize()
[xUnit.net 00:00:07.6881252]            at System.Diagnostics.DiagnosticsConfiguration.get_Sources()
[xUnit.net 00:00:07.6885259]            at System.Diagnostics.TraceSource.Initialize()
[xUnit.net 00:00:07.6889303]            at Castle.Core.Logging.TraceLogger.IsSourceConfigured(TraceSource source)
[xUnit.net 00:00:07.6893368]            at Castle.Core.Logging.TraceLogger.Initialize()
[xUnit.net 00:00:07.6897193]            at Castle.Core.Logging.TraceLogger..ctor(String name, LoggerLevel level)
[xUnit.net 00:00:07.6901234]            at Castle.DynamicProxy.ProxyGenerator..ctor(IProxyBuilder builder)
[xUnit.net 00:00:07.6905143]            at Castle.DynamicProxy.ProxyGenerator..ctor()
[xUnit.net 00:00:07.6909231]            at Moq.Proxy.CastleProxyFactory.CreateProxyGenerator()
[xUnit.net 00:00:07.6913291]            at Moq.Proxy.CastleProxyFactory..cctor()
[xUnit.net 00:00:07.6917210]         ----- Inner Stack Trace -----
[xUnit.net 00:00:07.6921119]            at System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean ignoreLocal)
[xUnit.net 00:00:07.6925092]            at System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(ConfigurationSchemaErrors schemaErrors)
[xUnit.net 00:00:07.6929139]            at System.Configuration.BaseConfigurationRecord.ThrowIfInitErrors()
[xUnit.net 00:00:07.6933131]            at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
[xUnit.net 00:00:07.7185612]   Finished:    UHCNV.Web.Services.Icm.Services.Tests
</code>```

答:
I found the root cause of the issue which is kind of weird. It was related to my app.config file in the test project. My app.config was as below when I was facing the issue:

<configuration>
    <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
                <bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0" />
            </dependentAssembly>
        </assemblyBinding>
    </runtime>
    <configSections>
    </configSections>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>
</configuration>
```

<p>All I needed to do was to make sure <code>configSections</code> tag would be the first child of my root element so I updated my <code>app.config</code> file as below:</p>

<pre class="lang-xml prettyprint-override"><code><configuration>
    <configSections>
    </configSections>
    <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
                <bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0" />
            </dependentAssembly>
        </assemblyBinding>
    </runtime>

    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>
</configuration>
</code>```

And voila, problem resolved. The error message was so confusing.

Body:
I am using xUnit 2.x and moq 4.5 and castle.core 3.3.0.0 . I have the IAssessmentsRepository interface in a different assembly ( but part of same solution) than my unit test are. I am giving reference to the assembly where IAssessmentsRepository reside. But when I try to mock, it gets error of "Type initilization"  which means that moq is not able to load the type i.e. IAssessmentsRepository .  Now I do not understand why ?? kindly suggest if anyone faced the same issue.

  [Fact]
            [UnitTest]
            public void DeleteAssessment_ShouldCall_AssessmentsRepository_DeleteAssessment_Method()
            {
                //Arrange
                var assessmentRepoMock = new Mock<Data.Assessments.IAssessmentsRepository>();
                assessmentRepoMock.Setup(x => x.DeleteAssessment(It.IsAny<int>(), It.IsAny<string>())).Returns(true);

                var assessmentService = new AssessmentService(assessmentRepoMock.Object);

                //Act
                var testResult = assessmentService.DeleteAssessment(It.IsAny<int>(), It.IsAny<string>());

                //Assert

                assessmentRepoMock.Verify(r => r.DeleteAssessment(It.IsAny<int>(), It.IsAny<string>()), Times.Once);

            }

following is the stack trace of the error,

 UHCNV.Web.Services.Icm.Services.Tests.UnitTests.AssessmentServiceTests.DeleteAssessment_ShouldCall_AssessmentsRepository_DeleteAssessment_Method [FAIL]
[xUnit.net 00:00:07.6027020]       System.TypeInitializationException : The type initializer for 'Moq.Mock`1' threw an exception.
[xUnit.net 00:00:07.6033988]       ---- System.TypeInitializationException : The type initializer for 'Moq.Proxy.CastleProxyFactory' threw an exception.
[xUnit.net 00:00:07.6038240]       -------- System.Configuration.ConfigurationErrorsException : Configuration system failed to initialize
[xUnit.net 00:00:07.6042223]       ------------ System.Configuration.ConfigurationErrorsException : Only one <configSections> element allowed per config file and if present must be the first child of the root <configuration> element. (C:\DEV2\LouisFinal\UpdatedOne\UHCNV.WEB.SERVICES.ICM\test\UHCNV.Web.Services.Icm.Services.Tests\bin\x86\Debug\UHCNV.Web.Services.Icm.Services.Tests.dll.config line 23)
[xUnit.net 00:00:07.6113488]       Stack Trace:
[xUnit.net 00:00:07.6119217]            at Moq.Mock`1.<InitializeInstance>b__24_0()
[xUnit.net 00:00:07.6123448]            at Moq.PexProtector.Invoke(Action action)
[xUnit.net 00:00:07.6127299]            at Moq.Mock`1.InitializeInstance()
[xUnit.net 00:00:07.6131116]            at Moq.Mock`1.OnGetObject()
[xUnit.net 00:00:07.6134937]            at Moq.Mock.GetObject()
[xUnit.net 00:00:07.6138850]            at Moq.Mock.get_Object()
[xUnit.net 00:00:07.6142657]            at Moq.Mock`1.get_Object()
[xUnit.net 00:00:07.6146855]         test\UHCNV.Web.Services.Icm.Services.Tests\UnitTests\AssessmentServiceTests.cs(20,0): at UHCNV.Web.Services.Icm.Services.Tests.UnitTests.AssessmentServiceTests.DeleteAssessment_ShouldCall_AssessmentsRepository_DeleteAssessment_Method()
[xUnit.net 00:00:07.6150651]         ----- Inner Stack Trace -----
[xUnit.net 00:00:07.6154568]            at Moq.Proxy.CastleProxyFactory..ctor()
[xUnit.net 00:00:07.6158157]            at Moq.Mock`1..cctor()
[xUnit.net 00:00:07.6161683]         ----- Inner Stack Trace -----
[xUnit.net 00:00:07.6165556]            at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
[xUnit.net 00:00:07.6169380]            at System.Configuration.ClientConfigurationSystem.PrepareClientConfigSystem(String sectionName)
[xUnit.net 00:00:07.6173346]            at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String sectionName)
[xUnit.net 00:00:07.6177103]            at System.Configuration.ConfigurationManager.GetSection(String sectionName)
[xUnit.net 00:00:07.6180813]            at System.Configuration.PrivilegedConfigurationManager.GetSection(String sectionName)
[xUnit.net 00:00:07.6184595]            at System.Diagnostics.DiagnosticsConfiguration.Initialize()
[xUnit.net 00:00:07.6188321]            at System.Diagnostics.DiagnosticsConfiguration.get_Sources()
[xUnit.net 00:00:07.6191972]            at System.Diagnostics.TraceSource.Initialize()
[xUnit.net 00:00:07.6195693]            at Castle.Core.Logging.TraceLogger.IsSourceConfigured(TraceSource source)
[xUnit.net 00:00:07.6199486]            at Castle.Core.Logging.TraceLogger.Initialize()
[xUnit.net 00:00:07.6204199]            at Castle.Core.Logging.TraceLogger..ctor(String name, LoggerLevel level)
[xUnit.net 00:00:07.6208012]            at Castle.DynamicProxy.ProxyGenerator..ctor(IProxyBuilder builder)
[xUnit.net 00:00:07.6211584]            at Castle.DynamicProxy.ProxyGenerator..ctor()
[xUnit.net 00:00:07.6215447]            at Moq.Proxy.CastleProxyFactory.CreateProxyGenerator()
[xUnit.net 00:00:07.6219298]            at Moq.Proxy.CastleProxyFactory..cctor()
[xUnit.net 00:00:07.6222921]         ----- Inner Stack Trace -----
[xUnit.net 00:00:07.6226725]            at System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean ignoreLocal)
[xUnit.net 00:00:07.6230535]            at System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(ConfigurationSchemaErrors schemaErrors)
[xUnit.net 00:00:07.6242699]            at System.Configuration.BaseConfigurationRecord.ThrowIfInitErrors()
[xUnit.net 00:00:07.6247423]            at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
[xUnit.net 00:00:07.6633781]     UHCNV.Web.Services.Icm.Services.Tests.UnitTests.AssessmentServiceTests.GenerateAssessmentForm_ShouldCall_AssessmentsRepository_GenerateAssessmentForm_Method [FAIL]
[xUnit.net 00:00:07.6715323]       System.TypeInitializationException : The type initializer for 'Moq.Mock`1' threw an exception.
[xUnit.net 00:00:07.6719637]       ---- System.TypeInitializationException : The type initializer for 'Moq.Proxy.CastleProxyFactory' threw an exception.
[xUnit.net 00:00:07.6723726]       -------- System.Configuration.ConfigurationErrorsException : Configuration system failed to initialize
[xUnit.net 00:00:07.6727605]       ------------ System.Configuration.ConfigurationErrorsException : Only one <configSections> element allowed per config file and if present must be the first child of the root <configuration> element. (C:\DEV2\LouisFinal\UpdatedOne\UHCNV.WEB.SERVICES.ICM\test\UHCNV.Web.Services.Icm.Services.Tests\bin\x86\Debug\UHCNV.Web.Services.Icm.Services.Tests.dll.config line 23)
[xUnit.net 00:00:07.6796134]       Stack Trace:
[xUnit.net 00:00:07.6801181]            at Moq.Mock`1.<InitializeInstance>b__24_0()
[xUnit.net 00:00:07.6805315]            at Moq.PexProtector.Invoke(Action action)
[xUnit.net 00:00:07.6809086]            at Moq.Mock`1.InitializeInstance()
[xUnit.net 00:00:07.6813035]            at Moq.Mock`1.OnGetObject()
[xUnit.net 00:00:07.6816928]            at Moq.Mock.GetObject()
[xUnit.net 00:00:07.6820733]            at Moq.Mock.get_Object()
[xUnit.net 00:00:07.6824593]            at Moq.Mock`1.get_Object()
[xUnit.net 00:00:07.6828478]         test\UHCNV.Web.Services.Icm.Services.Tests\UnitTests\AssessmentServiceTests.cs(40,0): at UHCNV.Web.Services.Icm.Services.Tests.UnitTests.AssessmentServiceTests.GenerateAssessmentForm_ShouldCall_AssessmentsRepository_GenerateAssessmentForm_Method()
[xUnit.net 00:00:07.6832594]         ----- Inner Stack Trace -----
[xUnit.net 00:00:07.6836425]            at Moq.Proxy.CastleProxyFactory..ctor()
[xUnit.net 00:00:07.6841577]            at Moq.Mock`1..cctor()
[xUnit.net 00:00:07.6845556]         ----- Inner Stack Trace -----
[xUnit.net 00:00:07.6856442]            at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
[xUnit.net 00:00:07.6860674]            at System.Configuration.ClientConfigurationSystem.PrepareClientConfigSystem(String sectionName)
[xUnit.net 00:00:07.6864632]            at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String sectionName)
[xUnit.net 00:00:07.6869201]            at System.Configuration.ConfigurationManager.GetSection(String sectionName)
[xUnit.net 00:00:07.6873166]            at System.Configuration.PrivilegedConfigurationManager.GetSection(String sectionName)
[xUnit.net 00:00:07.6877093]            at System.Diagnostics.DiagnosticsConfiguration.Initialize()
[xUnit.net 00:00:07.6881252]            at System.Diagnostics.DiagnosticsConfiguration.get_Sources()
[xUnit.net 00:00:07.6885259]            at System.Diagnostics.TraceSource.Initialize()
[xUnit.net 00:00:07.6889303]            at Castle.Core.Logging.TraceLogger.IsSourceConfigured(TraceSource source)
[xUnit.net 00:00:07.6893368]            at Castle.Core.Logging.TraceLogger.Initialize()
[xUnit.net 00:00:07.6897193]            at Castle.Core.Logging.TraceLogger..ctor(String name, LoggerLevel level)
[xUnit.net 00:00:07.6901234]            at Castle.DynamicProxy.ProxyGenerator..ctor(IProxyBuilder builder)
[xUnit.net 00:00:07.6905143]            at Castle.DynamicProxy.ProxyGenerator..ctor()
[xUnit.net 00:00:07.6909231]            at Moq.Proxy.CastleProxyFactory.CreateProxyGenerator()
[xUnit.net 00:00:07.6913291]            at Moq.Proxy.CastleProxyFactory..cctor()
[xUnit.net 00:00:07.6917210]         ----- Inner Stack Trace -----
[xUnit.net 00:00:07.6921119]            at System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean ignoreLocal)
[xUnit.net 00:00:07.6925092]            at System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(ConfigurationSchemaErrors schemaErrors)
[xUnit.net 00:00:07.6929139]            at System.Configuration.BaseConfigurationRecord.ThrowIfInitErrors()
[xUnit.net 00:00:07.6933131]            at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
[xUnit.net 00:00:07.7185612]   Finished:    UHCNV.Web.Services.Icm.Services.Tests

Body:
I found the root cause of the issue which is kind of weird. It was related to my app.config file in the test project. My app.config was as below when I was facing the issue:

<configuration>
    <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
                <bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0" />
            </dependentAssembly>
        </assemblyBinding>
    </runtime>
    <configSections>
    </configSections>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>
</configuration>

All I needed to do was to make sure configSections tag would be the first child of my root element so I updated my app.config file as below:

<configuration>
    <configSections>
    </configSections>
    <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
            <dependentAssembly>
                <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
                <bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0" />
            </dependentAssembly>
        </assemblyBinding>
    </runtime>

    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>
</configuration>

And voila, problem resolved. The error message was so confusing.

ContentLicense: CC BY-SA 4.0


问:
Decorate GET URL using forms
I have some question:

I use django form, and fields like MultipleChoiceField

in view.py I clean data and get GET URL like this

http://localhost:8000/?category=&style=&sex=&brand=ASICS&brand=Be+Positive&low_price=&high_price=

Give me advise, can I regroup brand field and hide empty.

I want getting something like this:

http://localhost:8000/?brand=1+2

And else one question:

How can I set empty value(empty_label) for forms.ModelMultipleChoiceFIeld

forms.py:

```<code>brand = forms.MultipleChoiceField(required=False,
                                  widget=forms.SelectMultiple(attrs={'size':1})
                                  )
def __init__(self,app_label=None, *args, **kwargs):
    super(Search, self).__init__(*args, **kwargs)
    self.fields['brand'].choices = [('', 'All brands')]+[(brand.name, brand) for brand in Brand.objects.all() ]
</code>```

views.py:

```<code> if request.method == 'GET' and request.GET:
     form = SearchForm(app_label, request.GET)
     if form.is_valid():
        brands = form.cleaned_data['brand']
        kwargs.update({"brand__name__in": brands})
</code>```

答:
This is how the browser submits multiple data. It's part of the HTML specification, trying to change it would be folly and technically I can't understand why you would try to care about how your url GET data looks.

That being said, if you want to change the way it submits you'll need javascript to transform the data on form submit. Django has nothing to do with the matter.

Using jQuery for example:

```<code>$('#form').submit(function(){
    //Get form data
    //Transform into my custom set of vars
    //Redirect to form's ACTION with my querystring appended.
});
</code>```

Please keep in mind you will not get any automatic parsing of the values on the Django side. Normally it would turn it into a list for you, but now you're responsible for parsing the 'value+value+value' yourself.

Title: Decorate GET URL using forms

Body:
I have some question:

I use django form, and fields like MultipleChoiceField

in view.py I clean data and get GET URL like this

http://localhost:8000/?category=&style=&sex=&brand=ASICS&brand=Be+Positive&low_price=&high_price=

Give me advise, can I regroup brand field and hide empty.

I want getting something like this:

http://localhost:8000/?brand=1+2

And else one question:

How can I set empty value(empty_label) for forms.ModelMultipleChoiceFIeld

forms.py:

brand = forms.MultipleChoiceField(required=False,
                                  widget=forms.SelectMultiple(attrs={'size':1})
                                  )
def __init__(self,app_label=None, *args, **kwargs):
    super(Search, self).__init__(*args, **kwargs)
    self.fields['brand'].choices = [('', 'All brands')]+[(brand.name, brand) for brand in Brand.objects.all() ]

views.py:

 if request.method == 'GET' and request.GET:
     form = SearchForm(app_label, request.GET)
     if form.is_valid():
        brands = form.cleaned_data['brand']
        kwargs.update({"brand__name__in": brands})

Body:
This is how the browser submits multiple data. It's part of the HTML specification, trying to change it would be folly and technically I can't understand why you would try to care about how your url GET data looks.

That being said, if you want to change the way it submits you'll need javascript to transform the data on form submit. Django has nothing to do with the matter.

Using jQuery for example:

$('#form').submit(function(){
    //Get form data
    //Transform into my custom set of vars
    //Redirect to form's ACTION with my querystring appended.
});

Please keep in mind you will not get any automatic parsing of the values on the Django side. Normally it would turn it into a list for you, but now you're responsible for parsing the 'value+value+value' yourself.


问:
Is each Javascript function of a webpage supposed to be defined in its own separate .js file?
I'm creating a website as a personal project to learn my way around the DOM and javascript. After several hours of annoyance, I discovered that if I comment out a portion of my HTML ("Animated Landing Page" in the HTML below) that has a javascript function (the btnEnter.addEventListener sequence in the JS) tied to it, anything after that function in my .js file ceases to work (such as the test.addEventListener sequence in the JS). Am I supposed to be separating my javascript functions into their own individual files? At the moment, I want to stick with javascript solutions, as I'd like to grasp the details of javascript before moving on to jQuery. I've included my HTML and JS below:

HTML

```<code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>My Webpage</title>
<!-- Add Javascript for enabled browsers -->
<script>document.documentElement.className += " js";</script>
<!-- Latest Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Bootstrap optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest Bootstrap Javascript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<!-- Personal stylesheet -->
<link rel="stylesheet" type="text/css" href="MyStyle.css">
</head>
<body>

<!-- Animated landing page -->
<div id="cover-image">
    <button id="entry-btn">Enter</button>
</div>

<!-- Main site -->
<!-- Banner -->
<h1 class="center-content" id="banner">Banner</h1>

<!-- Navigation bar -->
<nav class="nav-bar">
    <div class="container-fluid">
        <ul class="nav-list">
            <li class="divider-vertical"></li>
            <li><a class="navbar-link" id="link1" href="#home">Home</a></li>
            <li class="divider-vertical"></li>
            <li><a class="navbar-link" id="link2" href="#page1">Page 1</a></li>
            <li class="divider-vertical"></li>
            <li><a class="navbar-link" id="link3" href="#page2">Page 2</a></li>
            <li class="divider-vertical"></li>
            <li><a class="navbar-link" id="link4" href="#page3">Page 3</a></li>
            <li class="divider-vertical"></li>
        </ul>
    </div>
</nav>

<!-- Content -->
<div id="home">HOME</div>
<br/>
<div id="page1">PAGE1</div>
<br/>
<div id="page2">PAGE2</div>
<br/>
<div id="page3">PAGE3</div>

<!-- Personal JavaScript file -->
<script src="MyScript.js"></script>
</body>
</html>
</code>```

JS

```<code>var btnEnter = document.getElementById("entry-btn");
var test = document.getElementById("link1");

btnEnter.addEventListener("click", coverFadeOut);

test.addEventListener("click", testFunc);

function coverFadeOut() {
    var coverimg = document.getElementById("cover-image");
    coverimg.classList.toggle("fadeout");
    coverimg.addEventListener("transitionend", setTimeout(coverHide, 1000), false);
}

function coverHide() {
    var coverimg = document.getElementById("cover-image");
    coverimg.classList.toggle("hide");
}

function testFunc(){
    alert("Test");
}
</code>```

To clarify, I'm asking why my testFunc is not working when I comment out the HTML section "Animated Landing Page"?

答:
When you select an element you need to make sure it's not undefined before doing something with it. Your javascript will break if you try to access a method or property on undefined (in this case the method addEventListener).

```<code>var btnEnter = document.getElementById("entry-btn");
var test = document.getElementById("link1");

if (btnEnter) {
    btnEnter.addEventListener("click", coverFadeOut);
}

if (test) {
    test.addEventListener("click", testFunc);
}
</code>```

Body:
I'm creating a website as a personal project to learn my way around the DOM and javascript. After several hours of annoyance, I discovered that if I comment out a portion of my HTML ("Animated Landing Page" in the HTML below) that has a javascript function (the btnEnter.addEventListener sequence in the JS) tied to it, anything after that function in my .js file ceases to work (such as the test.addEventListener sequence in the JS). Am I supposed to be separating my javascript functions into their own individual files? At the moment, I want to stick with javascript solutions, as I'd like to grasp the details of javascript before moving on to jQuery. I've included my HTML and JS below:

HTML

<!DOCTYPE html>

<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>My Webpage</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<link rel="stylesheet" type="text/css" href="MyStyle.css">

    <button id="entry-btn">Enter</button>

Banner

Home

Page 1

Page 2

Page 3

HOME

PAGE1

PAGE2

PAGE3

JS

var btnEnter = document.getElementById("entry-btn");
var test = document.getElementById("link1");

btnEnter.addEventListener("click", coverFadeOut);

test.addEventListener("click", testFunc);

function coverFadeOut() {
    var coverimg = document.getElementById("cover-image");
    coverimg.classList.toggle("fadeout");
    coverimg.addEventListener("transitionend", setTimeout(coverHide, 1000), false);
}

function coverHide() {
    var coverimg = document.getElementById("cover-image");
    coverimg.classList.toggle("hide");
}

function testFunc(){
    alert("Test");
}

To clarify, I'm asking why my testFunc is not working when I comment out the HTML section "Animated Landing Page"?

Body:
When you select an element you need to make sure it's not undefined before doing something with it. Your javascript will break if you try to access a method or property on undefined (in this case the method addEventListener).

var btnEnter = document.getElementById("entry-btn");
var test = document.getElementById("link1");

if (btnEnter) {
    btnEnter.addEventListener("click", coverFadeOut);
}

if (test) {
    test.addEventListener("click", testFunc);
}


问:
php not logging errors log_errors=on, error_log path exists
Using php5.6 (legacy codebase), apache, ubuntu16.

phpinfo() says that:
log_errors is on
error_log = /var/log/apache2/php_errors.log

When display_errors is on there is output.
But /var/log/apache2/ does not contain a php_errors.log file.

Have restarted apache (/etc/init.d/apache2 restart).

log_errors_max_len is 1024.

```<code>ls -ld /var/log/apache2
drwxr-x--- 2 root   adm    4096 Mar 30 18:47 apache2

ls -l /var/log/apache2
-rw-r----- 1 root adm        0 Mar 30 06:25 access.log
-rw-r----- 1 root adm     5967 Mar 30 01:47 access.log.1
-rw-r----- 1 root adm    11618 Mar 31 04:07 error.log
-rw-r----- 1 root adm    11742 Mar 30 06:25 error.log.1
</code>```

What am I missing?

答:
From above comments. When using Apache2, each VirtualHost can have it's own log files.

So the /etc/apache2/ directory would have a sites-available directory along these lines:

```<code>├── sites-available
│   ├── 000-default.conf
│   ├── default-ssl.conf
│   ├── default-tls.conf
│   ├── www.domain.com.conf
│   └── www.domain.com-le-ssl.conf
</code>```

And the www. files might look like the following example.

To set up specific php log file, separate from Apache logs, follow this answer:

```<code><VirtualHost *:80>
    ServerName example.com
    DocumentRoot /var/www/domains/example.com/html
    ErrorLog /var/www/domains/example.com/apache.error.log
    CustomLog /var/www/domains/example.com/apache.access.log common
    php_flag log_errors on
    php_flag display_errors on
    php_value error_reporting 2147483647
    php_value error_log /var/www/domains/example.com/php.error.log
</VirtualHost>
</code>```

Body:
Using php5.6 (legacy codebase), apache, ubuntu16.

phpinfo() says that:
log_errors is on
error_log = /var/log/apache2/php_errors.log

When display_errors is on there is output.
But /var/log/apache2/ does not contain a php_errors.log file.

Have restarted apache (/etc/init.d/apache2 restart).

log_errors_max_len is 1024.

ls -ld /var/log/apache2
drwxr-x--- 2 root   adm    4096 Mar 30 18:47 apache2

ls -l /var/log/apache2
-rw-r----- 1 root adm        0 Mar 30 06:25 access.log
-rw-r----- 1 root adm     5967 Mar 30 01:47 access.log.1
-rw-r----- 1 root adm    11618 Mar 31 04:07 error.log
-rw-r----- 1 root adm    11742 Mar 30 06:25 error.log.1

What am I missing?

Body:
From above comments. When using Apache2, each VirtualHost can have it's own log files.

So the /etc/apache2/ directory would have a sites-available directory along these lines:

├── sites-available
│   ├── 000-default.conf
│   ├── default-ssl.conf
│   ├── default-tls.conf
│   ├── www.domain.com.conf
│   └── www.domain.com-le-ssl.conf

And the www. files might look like the following example.

To set up specific php log file, separate from Apache logs, follow this answer:

<VirtualHost *:80>
    ServerName example.com
    DocumentRoot /var/www/domains/example.com/html
    ErrorLog /var/www/domains/example.com/apache.error.log
    CustomLog /var/www/domains/example.com/apache.access.log common
    php_flag log_errors on
    php_flag display_errors on
    php_value error_reporting 2147483647
    php_value error_log /var/www/domains/example.com/php.error.log
</VirtualHost>


问:
C++ method pointer call yields undefined symbol error?
I would like to have a class that has a method pointer that points to one of two possible methods of the same class. I use Embarcadero XE2 bcc32 for this.

When I try the following, I get the Error E2451 Undefined symbol findPosition:

```<code>class A{
    public:
        double (A::*findPosition)(std::vector<int> arr, int tresh); //method pointer
        double mean(std::vector<int> arr, int tresh){return 0;};               //case 1
        double median(std::vector<int> arr, int tresh){return 0;};             //case 2
        A(){findPosition=&(A::mean);}                               //constructor set pointer to case 1
};
int _tmain(int argc, _TCHAR* argv[])
{
    std::vector<int> vals(5,1);   // 1 1 1 1 1, example input

    A obj;
    obj.findPosition=&(A::median);   //set method pointer to case 2
    (obj.*findPosition)(vals,0);     //ERROR: E2451 Undefined symbol 'findPosition'

    system("pause");
}
</code>```

Is (obj.*findPosition)(vals,0) not the correct version of a method-pointer call? Should I use boost:bind perhaps? Or is this generally a bad idea and I should stick to something like

```<code>class A{
    public:
        int flag;
        double findPosition(std::vector<int> arr, int tresh){
            if(flag==0)return mean(arr,tresh);
            else if(flag==1)return median(arr,tresh);
        };
        double mean(std::vector<int> arr, int tresh){return 0;};               //case 1
        double median(std::vector<int> arr, int tresh){return 0;};             //case 2
        A(){flag=0;}                               //constructor set use to case 1
};
</code>```

答:
The .* and ->* operators are defined as follows:

```<code>expression .* expression
expression ->* expression
</code>```

Where the right-hand expression must evaluate to a pointer that is pointing to a member within the object specified by the left-hand expression.

The code fails to compile because you are trying to pass in a non-existent local variable for the right-hand expression.  That missing variable is what the compiler is complaining about.

You need something more like this instead:

```<code>(obj.*obj.findPosition)(vals,0);
</code>```

Or, more clearer:

```<code>(obj.*(obj.findPosition))(vals,0);
</code>```

Or, more verbose:

```<code>double (A::*fp)(std::vector<int>, int) = obj.findPosition;
(obj.*fp)(vals,0);
</code>```

That being said, if you are not worried about portability to other compilers, you can use BCC's __closure extension instead:

```<code>class A{
    public:
        double (__closure *findPosition)(std::vector<int> arr, int tresh); //method pointer
        double mean(std::vector<int> arr, int tresh){return 0;};               //case 1
        double median(std::vector<int> arr, int tresh){return 0;};             //case 2
        A(){findPosition=&mean;}                               //constructor set pointer to case 1
};

int _tmain(int argc, _TCHAR* argv[])
{
    std::vector<int> vals(5,1);   // 1 1 1 1 1, example input

    A obj;
    obj.findPosition=&(obj.median);   //set method pointer to case 2
    obj.findPosition(vals,0);

    system("pause");
}
</code>```

Body:
I would like to have a class that has a method pointer that points to one of two possible methods of the same class. I use Embarcadero XE2 bcc32 for this.

When I try the following, I get the Error E2451 Undefined symbol findPosition:

class A{
    public:
        double (A::*findPosition)(std::vector<int> arr, int tresh); //method pointer
        double mean(std::vector<int> arr, int tresh){return 0;};               //case 1
        double median(std::vector<int> arr, int tresh){return 0;};             //case 2
        A(){findPosition=&(A::mean);}                               //constructor set pointer to case 1
};
int _tmain(int argc, _TCHAR* argv[])
{
    std::vector<int> vals(5,1);   // 1 1 1 1 1, example input

    A obj;
    obj.findPosition=&(A::median);   //set method pointer to case 2
    (obj.*findPosition)(vals,0);     //ERROR: E2451 Undefined symbol 'findPosition'

    system("pause");
}

Is (obj.*findPosition)(vals,0) not the correct version of a method-pointer call? Should I use boost:bind perhaps? Or is this generally a bad idea and I should stick to something like

class A{
    public:
        int flag;
        double findPosition(std::vector<int> arr, int tresh){
            if(flag==0)return mean(arr,tresh);
            else if(flag==1)return median(arr,tresh);
        };
        double mean(std::vector<int> arr, int tresh){return 0;};               //case 1
        double median(std::vector<int> arr, int tresh){return 0;};             //case 2
        A(){flag=0;}                               //constructor set use to case 1
};

Body:
The .* and ->* operators are defined as follows:

expression .* expression
expression ->* expression

Where the right-hand expression must evaluate to a pointer that is pointing to a member within the object specified by the left-hand expression.

The code fails to compile because you are trying to pass in a non-existent local variable for the right-hand expression.  That missing variable is what the compiler is complaining about.

You need something more like this instead:

(obj.*obj.findPosition)(vals,0);

Or, more clearer:

(obj.*(obj.findPosition))(vals,0);

Or, more verbose:

double (A::*fp)(std::vector<int>, int) = obj.findPosition;
(obj.*fp)(vals,0);

That being said, if you are not worried about portability to other compilers, you can use BCC's __closure extension instead:

class A{
    public:
        double (__closure *findPosition)(std::vector<int> arr, int tresh); //method pointer
        double mean(std::vector<int> arr, int tresh){return 0;};               //case 1
        double median(std::vector<int> arr, int tresh){return 0;};             //case 2
        A(){findPosition=&mean;}                               //constructor set pointer to case 1
};

int _tmain(int argc, _TCHAR* argv[])
{
    std::vector<int> vals(5,1);   // 1 1 1 1 1, example input

    A obj;
    obj.findPosition=&(obj.median);   //set method pointer to case 2
    obj.findPosition(vals,0);

    system("pause");
}


问:
Remove everything after some characters
I have two situations:

In the first, I may have a string like:

```<code>  Posted 03-20-2017 More info Go to Last Post
</code>```

And I may have a string like:

```<code>  Posted today More info Go to Last Post
</code>```

In both of the situations, I don't want anything from More Info...

I tried using gsub,but it doesn't work for both of the situations.  Does anyone have possible solution?

答:
Use the Ruby sub, which will give you a copy the first occurrence of pattern substituted for the second argument.

So it'll take your whole string "Posted 03-20-2017 More info Go to Last Post", will find your pattern and all what comes after More info..., and will replace it with the second argument More info, that in this case is the same as first (you can use a variable there).

```<code>"Posted 03-20-2017 More info Go to Last Post".sub /More info.*/, 'More info'
=> "Posted 03-20-2017 More info"
</code>```

Also gsub works in a similar way.

Title: Remove everything after some characters

Body:
I have two situations:

In the first, I may have a string like:

  Posted 03-20-2017 More info Go to Last Post

And I may have a string like:

  Posted today More info Go to Last Post

In both of the situations, I don't want anything from More Info...

I tried using gsub,but it doesn't work for both of the situations.  Does anyone have possible solution?

Body:
Use the Ruby sub, which will give you a copy the first occurrence of pattern substituted for the second argument.

So it'll take your whole string "Posted 03-20-2017 More info Go to Last Post", will find your pattern and all what comes after More info..., and will replace it with the second argument More info, that in this case is the same as first (you can use a variable there).

"Posted 03-20-2017 More info Go to Last Post".sub /More info.*/, 'More info'
=> "Posted 03-20-2017 More info"

Also gsub works in a similar way.


问:
NDB - querying repeated structured property for attribute
I have two models:

```<code>class Author(ndb.Model):
    email = ndb.StringProperty(indexed=true)

class Course(ndb.Model):
    student = ndb.StructuredProperty(Author, repeated=True)
</code>```

I am trying to query Course to find where a student's email matches that of user.email_address. Is it possible to structure this as a single query?

答:
You have to query by using Author object as a filter

```<code>query = Course.query(Course.student.email == 'my@email.com')
</code>```

But this query is correct only if you are querying for a single property. Official documentation suggests to use following filter

```<code>query = Course.query(Course.student == Student(email='my@email.com'))
</code>```

See https://cloud.google.com/appengine/docs/standard/python/ndb/queries#filtering_structured_properties for more information

Body:
I have two models:

class Author(ndb.Model):
    email = ndb.StringProperty(indexed=true)

class Course(ndb.Model):
    student = ndb.StructuredProperty(Author, repeated=True)

I am trying to query Course to find where a student's email matches that of user.email_address. Is it possible to structure this as a single query?

Body:
You have to query by using Author object as a filter

query = Course.query(Course.student.email == 'my@email.com')

But this query is correct only if you are querying for a single property. Official documentation suggests to use following filter

query = Course.query(Course.student == Student(email='my@email.com'))

See https://cloud.google.com/appengine/docs/standard/python/ndb/queries#filtering_structured_properties for more information


问:
How to extract all the emojis from text?
Consider the following list:

```<code>a_list = ['  me así, bla es se  ds ']
</code>```

How can I extract in a new list all the emojis inside a_list?:

```<code>new_lis = ['     ']
</code>```

I tried to use regex, but I do not have all the possible emojis encodings.

答:
If you don't want to use an external library, as a pythonic way you can simply use regular expressions and re.findall() with a proper regex to find the emojies:

```<code>In [74]: import re
In [75]: re.findall(r'[^\w\s,]', a_list[0])
Out[75]: ['', '', '', '', '', '']
</code>```

The regular expression r'[^\w\s,]' is a negated character class that matches any character that is not a word character, whitespace or comma.

As I mentioned in comment, a text is generally contain word characters and punctuation which will be easily dealt with by this approach, for other cases you can just add them to the character class manually. Note that since you can specify a range of characters in character class you can even make it shorter and more flexible.

Another solution is instead of a negated character class that excludes the non-emoji characters use a character class that accepts emojies ([] without ^). Since there are a lot of emojis with different unicode values, you just need to add the ranges to the character class. If you want to match more emojies here is a good reference contain all the standard emojies with the respective range for different emojies http://apps.timwhitlock.info/emoji/tables/unicode:

Body:
Consider the following list:

a_list = ['  me así, bla es se  ds ']

How can I extract in a new list all the emojis inside a_list?:

new_lis = ['     ']

I tried to use regex, but I do not have all the possible emojis encodings.

Body:
If you don't want to use an external library, as a pythonic way you can simply use regular expressions and re.findall() with a proper regex to find the emojies:

In [74]: import re
In [75]: re.findall(r'[^\w\s,]', a_list[0])
Out[75]: ['', '', '', '', '', '']

The regular expression r'[^\w\s,]' is a negated character class that matches any character that is not a word character, whitespace or comma.

As I mentioned in comment, a text is generally contain word characters and punctuation which will be easily dealt with by this approach, for other cases you can just add them to the character class manually. Note that since you can specify a range of characters in character class you can even make it shorter and more flexible.

Another solution is instead of a negated character class that excludes the non-emoji characters use a character class that accepts emojies ([] without ^). Since there are a lot of emojis with different unicode values, you just need to add the ranges to the character class. If you want to match more emojies here is a good reference contain all the standard emojies with the respective range for different emojies http://apps.timwhitlock.info/emoji/tables/unicode:


问:
How can I make both columns same height in Bootstrap?
I have 2 columns in bootstrap side-by-side, col-md-4 and col-md-8 but one is taller than the other.

How can I shrink the taller one to match the height of the smaller column?

The css class listing-top is using flex box.

DEMO https://jsfiddle.net/halnex/3dw85L1r/1/

HTML

```<code><section class="listing listing-top with-feature">
    <div class="col-md-4">
        <article class="tease top-latest tease-" data-post-id="1069327">

            <a class="overlay" href="#"></a>
            <div class="tag"></div>
            <figure style="background-image:url('http://i.imgur.com/WDCTb5S.jpg');">
                <div></div>
            </figure>
            <header>
                <h2><a href="#">Galaxy S8 face recognition already defeated with a simple picture</a></h2>
                <p class="excerpt">Face unlock feature once again defeated with anything resembling owner's face. </p>

                <p class="byline" itemprop="author creator" itemscope="" itemtype="#">
                    <a itemprop="url" href="#"><span itemprop="name">Author</span></a>
                    –  <time class="date" data-time="1490974219" datetime="2017-03-31T15:30:19+00:00">3/31/2017, 6:30 PM</time>
                </p>

            </header>
            <footer>
                <aside class="comments-hotness ">
                    <a title="25 posters participating" class="comment-count icon-comment-bubble-up" href="#">
                        <span class="comment-count-number">31</span>
                    </a>    </aside>

            </footer>
        </article>
    </div>

    <div class="col-md-8">
        <article class="tease top-latest tease-" data-post-id="1069327">

            <a class="overlay" href="#"></a>
            <div class="tag"></div>
            <figure style="background-image:url('http://i.imgur.com/WDCTb5S.jpg');">
                <div></div>
            </figure>
            <header>
                <h2><a href="#">Galaxy S8 face recognition already defeated with a simple picture</a></h2>
                <p class="excerpt">Face unlock feature once again defeated with anything resembling owner's face. </p>

                <p class="byline" itemprop="author creator" itemscope="" itemtype="#">
                    <a itemprop="url" href="#"><span itemprop="name">Author</span></a>
                    –  <time class="date" data-time="1490974219" datetime="2017-03-31T15:30:19+00:00">3/31/2017, 6:30 PM</time>
                </p>

            </header>
            <footer>
                <aside class="comments-hotness ">
                    <a title="25 posters participating" class="comment-count icon-comment-bubble-up" href="#">
                        <span class="comment-count-number">31</span>
                    </a>    </aside>

            </footer>
        </article>
    </div>
</section>
</code>```

CSS

```<code>.listing-top {
    -js-display: flex;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
    -ms-flex-flow: row wrap;
    flex-flow: row wrap;
    -webkit-box-pack: justify;
    -ms-flex-pack: justify;
    justify-content: space-between;
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
}
.listing-top.with-feature article.top-latest {
    margin-bottom: 20px;
    position: relative;
    cursor: pointer;
    cursor: hand;
    display: block;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -ms-flex-flow: none;
    flex-flow: none;
}
.listing-top.with-feature article.top-latest .overlay {
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 14;
}
.listing-top.with-feature article.top-latest .tag {
    -js-display: flex;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
    -ms-flex-flow: row nowrap;
    flex-flow: row nowrap;
}
.listing-top.with-feature article.top-latest .tag {
    pointer-events: none;
    position: absolute;
    height: 36px;
    z-index: 15;
    background-color: #fff;
    color: #000;
    text-transform: uppercase;
    font-size: 20px;
    font-family: economica;
    top: 15px;
    left: 0;
    display: none;
}
.listing-top.with-feature article .tag {
    pointer-events: none;
    position: absolute;
    height: 36px;
    z-index: 15;
    background-color: #fff;
    color: #000;
    text-transform: uppercase;
    font-size: 20px;
    font-family: economica;
    top: 15px;
    left: 0;
    display: none;
}
.listing-top.with-feature article.top-latest figure {
    width: 100%;
    height: 0;
    padding-bottom: 55.55556%;
}
.listing-top.with-feature article.top-latest figure {
    -webkit-transition: all .17s;
    transition: all .17s;
    background-repeat: no-repeat;
    background-size: cover;
    background-position: top;
    background-color: #f0f1f2;
    background-blend-mode: multiply;
    margin: 0;
}
.listing-top.with-feature article figure {
    width: 100%;
    height: 0;
    padding-bottom: 55.55556%;
}
.listing-top.with-feature article figure {
    -webkit-transition: all .17s;
    transition: all .17s;
    background-repeat: no-repeat;
    background-size: cover;
    background-position: top;
    background-color: #f0f1f2;
    background-blend-mode: multiply;
    margin: 0;
}
figure {
    margin: 1em 40px;
}
article, aside, details, figcaption, figure, footer, header, main, menu, nav, section, summary {
    display: block;
}
.listing-top.with-feature article.top-latest header {
    background: -webkit-linear-gradient(top,#fff 15px,hsla(210,7%,95%,0));
    background: linear-gradient(180deg,#fff 15px,hsla(210,7%,95%,0));
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr="#ffffff",endColorstr="#00f0f1f2",GradientType=0);
    margin: 15px;
    margin-top: -15px;
    padding: 15px;
    border-bottom: none;
    position: relative;
}
.listing-top.with-feature article header {
    background: -webkit-linear-gradient(top,#fff 15px,hsla(210,7%,95%,0));
    background: linear-gradient(180deg,#fff 15px,hsla(210,7%,95%,0));
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr="#ffffff",endColorstr="#00f0f1f2",GradientType=0);
    margin: 15px;
    margin-top: -15px;
    padding: 15px;
    border-bottom: none;
    position: relative;
}
.listing-top.with-feature article.top-latest footer {
    width: 100%;
    margin-top: -25px;
    bottom: -10px;
}
.listing-top.with-feature article.top-latest footer {
    position: absolute;
    z-index: 15;
}
.listing-top.with-feature article.top-latest:after {
    content: "";
    position: absolute;
    bottom: 0;
    height: 30px;
    width: 100%;
    border: 15px solid #ccc;
    border-top: none;
}
.listing-top.with-feature article:after {
    content: "";
    position: absolute;
    bottom: 0;
    height: 30px;
    width: 100%;
    border: 15px solid #ccc;
    border-top: none;
}
.listing-top.with-feature article.top-latest footer .comments-hotness .comment-count {
    background-size: cover;
    width: 34px;
    height: 34px;
    display: block;
    margin: 0 auto;
    text-align: center;
    background-position: 50%;
}
.listing-top.with-feature article.top-latest footer .comments-hotness .comment-count .comment-count-number {
    padding: 0;
    margin: 0;
    line-height: 34px;
    font-size: 18px;
    color: #fff;
}
.listing-top.with-feature article.top-latest footer .comments-hotness .comment-count {
    font-family: economica;
    color: #fff;
    background-repeat: no-repeat;
    display: block;
    background-image: url('../img/comments.svg');
}
@media (min-width: 1000px) {
    .listing-top.with-feature article.top-latest .tag:before {
        top: 11px;
        height: 14px;
        width: 18px;
        background-image: url('../img/arrow.svg');
    }
}
.listing-top.with-feature article.top-latest .tag:before {
    background-image: url('../img/arrows.svg');
    height: 9px;
    width: 18px;
    top: 13px;
    right: 10px;
}
.listing-top.with-feature article.top-latest .tag:before {
    content: "";
    position: absolute;
    background-repeat: no-repeat;
    background-size: cover;
}
.listing-top.with-feature article .tag:before {
    content: "";
    position: absolute;
    background-repeat: no-repeat;
    background-size: cover;
}
.listing-top.with-feature article.top-latest .tag:after {
    content: "Latest stories";
    margin-left: 10px;
    margin-right: 36px;
}
.listing-top.with-feature article.top-latest .tag:after {
    content: "";
    -ms-flex-item-align: center;
    -ms-grid-row-align: center;
    align-self: center;
}
.listing-top.with-feature article .tag:after {
    content: "";
    -ms-flex-item-align: center;
    -ms-grid-row-align: center;
    align-self: center;
}
</code>```

答:
You could make the inner content height:100%..

```<code>.listing-top.with-feature article.top-latest {
    margin-bottom: 20px;
    position: relative;
    cursor: pointer;
    cursor: hand;
    display: block;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -ms-flex-flow: none;
    flex-flow: none;
    height: 100%;
}
</code>```

https://jsfiddle.net/h5c703q3/

Body:
I have 2 columns in bootstrap side-by-side, col-md-4 and col-md-8 but one is taller than the other.

How can I shrink the taller one to match the height of the smaller column?

The css class listing-top is using flex box.

DEMO https://jsfiddle.net/halnex/3dw85L1r/1/

HTML

Galaxy S8 face recognition already defeated with a simple picture

Face unlock feature once again defeated with anything resembling owner's face.

                    Author
                    –  <time class="date" data-time="1490974219" datetime="2017-03-31T15:30:19+00:00">3/31/2017, 6:30 PM</time>

                        31

Galaxy S8 face recognition already defeated with a simple picture

Face unlock feature once again defeated with anything resembling owner's face.

                    Author
                    –  <time class="date" data-time="1490974219" datetime="2017-03-31T15:30:19+00:00">3/31/2017, 6:30 PM</time>

                        31

CSS

.listing-top {
    -js-display: flex;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
    -ms-flex-flow: row wrap;
    flex-flow: row wrap;
    -webkit-box-pack: justify;
    -ms-flex-pack: justify;
    justify-content: space-between;
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
}
.listing-top.with-feature article.top-latest {
    margin-bottom: 20px;
    position: relative;
    cursor: pointer;
    cursor: hand;
    display: block;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -ms-flex-flow: none;
    flex-flow: none;
}
.listing-top.with-feature article.top-latest .overlay {
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: 14;
}
.listing-top.with-feature article.top-latest .tag {
    -js-display: flex;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-orient: horizontal;
    -webkit-box-direction: normal;
    -ms-flex-flow: row nowrap;
    flex-flow: row nowrap;
}
.listing-top.with-feature article.top-latest .tag {
    pointer-events: none;
    position: absolute;
    height: 36px;
    z-index: 15;
    background-color: #fff;
    color: #000;
    text-transform: uppercase;
    font-size: 20px;
    font-family: economica;
    top: 15px;
    left: 0;
    display: none;
}
.listing-top.with-feature article .tag {
    pointer-events: none;
    position: absolute;
    height: 36px;
    z-index: 15;
    background-color: #fff;
    color: #000;
    text-transform: uppercase;
    font-size: 20px;
    font-family: economica;
    top: 15px;
    left: 0;
    display: none;
}
.listing-top.with-feature article.top-latest figure {
    width: 100%;
    height: 0;
    padding-bottom: 55.55556%;
}
.listing-top.with-feature article.top-latest figure {
    -webkit-transition: all .17s;
    transition: all .17s;
    background-repeat: no-repeat;
    background-size: cover;
    background-position: top;
    background-color: #f0f1f2;
    background-blend-mode: multiply;
    margin: 0;
}
.listing-top.with-feature article figure {
    width: 100%;
    height: 0;
    padding-bottom: 55.55556%;
}
.listing-top.with-feature article figure {
    -webkit-transition: all .17s;
    transition: all .17s;
    background-repeat: no-repeat;
    background-size: cover;
    background-position: top;
    background-color: #f0f1f2;
    background-blend-mode: multiply;
    margin: 0;
}
figure {
    margin: 1em 40px;
}
article, aside, details, figcaption, figure, footer, header, main, menu, nav, section, summary {
    display: block;
}
.listing-top.with-feature article.top-latest header {
    background: -webkit-linear-gradient(top,#fff 15px,hsla(210,7%,95%,0));
    background: linear-gradient(180deg,#fff 15px,hsla(210,7%,95%,0));
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr="#ffffff",endColorstr="#00f0f1f2",GradientType=0);
    margin: 15px;
    margin-top: -15px;
    padding: 15px;
    border-bottom: none;
    position: relative;
}
.listing-top.with-feature article header {
    background: -webkit-linear-gradient(top,#fff 15px,hsla(210,7%,95%,0));
    background: linear-gradient(180deg,#fff 15px,hsla(210,7%,95%,0));
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr="#ffffff",endColorstr="#00f0f1f2",GradientType=0);
    margin: 15px;
    margin-top: -15px;
    padding: 15px;
    border-bottom: none;
    position: relative;
}
.listing-top.with-feature article.top-latest footer {
    width: 100%;
    margin-top: -25px;
    bottom: -10px;
}
.listing-top.with-feature article.top-latest footer {
    position: absolute;
    z-index: 15;
}
.listing-top.with-feature article.top-latest:after {
    content: "";
    position: absolute;
    bottom: 0;
    height: 30px;
    width: 100%;
    border: 15px solid #ccc;
    border-top: none;
}
.listing-top.with-feature article:after {
    content: "";
    position: absolute;
    bottom: 0;
    height: 30px;
    width: 100%;
    border: 15px solid #ccc;
    border-top: none;
}
.listing-top.with-feature article.top-latest footer .comments-hotness .comment-count {
    background-size: cover;
    width: 34px;
    height: 34px;
    display: block;
    margin: 0 auto;
    text-align: center;
    background-position: 50%;
}
.listing-top.with-feature article.top-latest footer .comments-hotness .comment-count .comment-count-number {
    padding: 0;
    margin: 0;
    line-height: 34px;
    font-size: 18px;
    color: #fff;
}
.listing-top.with-feature article.top-latest footer .comments-hotness .comment-count {
    font-family: economica;
    color: #fff;
    background-repeat: no-repeat;
    display: block;
    background-image: url('../img/comments.svg');
}
@media (min-width: 1000px) {
    .listing-top.with-feature article.top-latest .tag:before {
        top: 11px;
        height: 14px;
        width: 18px;
        background-image: url('../img/arrow.svg');
    }
}
.listing-top.with-feature article.top-latest .tag:before {
    background-image: url('../img/arrows.svg');
    height: 9px;
    width: 18px;
    top: 13px;
    right: 10px;
}
.listing-top.with-feature article.top-latest .tag:before {
    content: "";
    position: absolute;
    background-repeat: no-repeat;
    background-size: cover;
}
.listing-top.with-feature article .tag:before {
    content: "";
    position: absolute;
    background-repeat: no-repeat;
    background-size: cover;
}
.listing-top.with-feature article.top-latest .tag:after {
    content: "Latest stories";
    margin-left: 10px;
    margin-right: 36px;
}
.listing-top.with-feature article.top-latest .tag:after {
    content: "";
    -ms-flex-item-align: center;
    -ms-grid-row-align: center;
    align-self: center;
}
.listing-top.with-feature article .tag:after {
    content: "";
    -ms-flex-item-align: center;
    -ms-grid-row-align: center;
    align-self: center;
}

Body:
You could make the inner content height:100%..

.listing-top.with-feature article.top-latest {
    margin-bottom: 20px;
    position: relative;
    cursor: pointer;
    cursor: hand;
    display: block;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -ms-flex-flow: none;
    flex-flow: none;
    height: 100%;
}

https://jsfiddle.net/h5c703q3/


问:
Flex Builder Tween Library
There are missing tween libraries in my Flex Builder how to add them?

Sultan

答:
In Flex there are Move events for moving objects, but I don't think there are any extras you can add.

If you're looking for a good Tween library check out TweenLite: http://www.greensock.com/tweenlite/

Title: Flex Builder Tween Library