问:
Make sql query simpler shorter ( Laravel )
is there any way to make these queries shorter or simpler? or maybe get the result in 1 query rather than 3.??
any advise appreciated</p>

```<code>        $room_single = \DB::table('book_room')
        ->leftJoin('book_tour', 'book_room.bookingID', '=', 'book_tour.bookingID')
        ->where('tourdateID', '=', $id)
        ->where('roomtype','=',1)
        ->where('book_room.status','=',1)
        ->count();

    $room_double = \DB::table('book_room')
        ->leftJoin('book_tour', 'book_room.bookingID', '=', 'book_tour.bookingID')
        ->where('tourdateID', '=', $id)
        ->where('roomtype','=',2)
        ->where('book_room.status','=',1)
        ->count();

    $room_triple = \DB::table('book_room')
        ->leftJoin('book_tour', 'book_room.bookingID', '=', 'book_tour.bookingID')
        ->where('tourdateID', '=', $id)
        ->where('roomtype','=',3)
        ->where('book_room.status','=',1)
        ->count();
    $total= $room_single+($room_double*2)+($room_triple*3) ;
</code>```

答:
In this case, since the roomtype column relates directly to how you would calculate the total you could just use sum instead of count:

```<code>$total = \DB::table('book_room')
    ->leftJoin('book_tour', 'book_room.bookingID', '=', 'book_tour.bookingID')
    ->where('tourdateID', '=', $id)
    ->where('book_room.status', '=', 1)
    ->sum('roomtype');
</code>```

UPDATE

If you still need the count for each roomtype then you could do something like:

```<code>$query = \DB::table('book_room')
    ->leftJoin('book_tour', 'book_room.bookingID', '=', 'book_tour.bookingID')
    ->where('tourdateID', '=', $id)
    ->where('book_room.status', '=', 1);

$room_single = $query->newQuery()->where('roomtype', 1)->count();
$room_double = $query->newQuery()->where('roomtype', 2)->count();
$room_triple = $query->newQuery()->where('roomtype', 3)->count();
$total = $room_single + ($room_double * 2) + ($room_triple * 3);
</code>```

Using newQuery means that you can reuse constraints without adding to the original.

Or if you don't want to make multiple queries and you want php to handle the counts

```<code>$rooms = \DB::table('book_room')
    ->select('roomtype')
    ->selectRaw('count(*) as room_count')
    ->leftJoin('book_tour', 'book_room.bookingID', '=', 'book_tour.bookingID')
    ->where('tourdateID', '=', $id)
    ->where('book_room.status', '=', 1)
    ->whereBetween('roomtype', [1, 3])//This is only needed if you have other room types
    ->groupBy('roomtype')
    ->orderBy('roomtype')
    ->get('roomtype');

list($room_single, $room_double, $room_triple) = $rooms->pluck('room_count')->toArray();
$total = $rooms->sum(function ($item) {
    return $item->room_count * $item->roomtype;
});
</code>```

Hope this helps!

Body:
is there any way to make these queries shorter or simpler? or maybe get the result in 1 query rather than 3.??
any advise appreciated

        $room_single = \DB::table('book_room')
        ->leftJoin('book_tour', 'book_room.bookingID', '=', 'book_tour.bookingID')
        ->where('tourdateID', '=', $id)
        ->where('roomtype','=',1)
        ->where('book_room.status','=',1)
        ->count();

    $room_double = \DB::table('book_room')
        ->leftJoin('book_tour', 'book_room.bookingID', '=', 'book_tour.bookingID')
        ->where('tourdateID', '=', $id)
        ->where('roomtype','=',2)
        ->where('book_room.status','=',1)
        ->count();

    $room_triple = \DB::table('book_room')
        ->leftJoin('book_tour', 'book_room.bookingID', '=', 'book_tour.bookingID')
        ->where('tourdateID', '=', $id)
        ->where('roomtype','=',3)
        ->where('book_room.status','=',1)
        ->count();
    $total= $room_single+($room_double*2)+($room_triple*3) ;

Body:
In this case, since the roomtype column relates directly to how you would calculate the total you could just use sum instead of count:

$total = \DB::table('book_room')
    ->leftJoin('book_tour', 'book_room.bookingID', '=', 'book_tour.bookingID')
    ->where('tourdateID', '=', $id)
    ->where('book_room.status', '=', 1)
    ->sum('roomtype');

UPDATE

If you still need the count for each roomtype then you could do something like:

$query = \DB::table('book_room')
    ->leftJoin('book_tour', 'book_room.bookingID', '=', 'book_tour.bookingID')
    ->where('tourdateID', '=', $id)
    ->where('book_room.status', '=', 1);

$room_single = $query->newQuery()->where('roomtype', 1)->count();
$room_double = $query->newQuery()->where('roomtype', 2)->count();
$room_triple = $query->newQuery()->where('roomtype', 3)->count();
$total = $room_single + ($room_double * 2) + ($room_triple * 3);

Using newQuery means that you can reuse constraints without adding to the original.

Or if you don't want to make multiple queries and you want php to handle the counts

$rooms = \DB::table('book_room')
    ->select('roomtype')
    ->selectRaw('count(*) as room_count')
    ->leftJoin('book_tour', 'book_room.bookingID', '=', 'book_tour.bookingID')
    ->where('tourdateID', '=', $id)
    ->where('book_room.status', '=', 1)
    ->whereBetween('roomtype', [1, 3])//This is only needed if you have other room types
    ->groupBy('roomtype')
    ->orderBy('roomtype')
    ->get('roomtype');

list($room_single, $room_double, $room_triple) = $rooms->pluck('room_count')->toArray();
$total = $rooms->sum(function ($item) {
    return $item->room_count * $item->roomtype;
});

Hope this helps!


来源: stackexchange

问:
Parenting a .NET form to an HWND
I'm developing a plugin (C++/CLI DLL) that runs inside of an certain applications, about which I only know the HWND.  My plugin shows various .NET forms that I'd like to behave as children of the main application (e.g. centered to the main window, etc).  Here's what I've tried:

```<code>// MyDialog.h
public ref class MyDialog : public System::Windows::Forms::Form {
    public:
        MyDialog(const int parentHWND);

    private:
        IntPtr parent_;
};

// MyDialog.cpp
// Attempt1: Use SetParent and CenterParent
MyDialog::MyDialog(const int parentHWND) : parent_(parentHWND) {
    SetParent(reinterpret_cast<HWND>(this->Handle.ToPointer()), reinterpret_cast<HWND>(parent_.ToPointer()));

    this->StartPosition = FormStartPosition::CenterParent;
}
</code>```

This appears to make MyDialog act as a child (i.e. you can't move it outside the main app, etc), but the call to CenterParent does not have the desired results.

I found several ideas online (including SO) that suggest creating a NativeWindow from the HWND and passing it to Show():

```<code>// in MyDialog.h
void Show() new;

// MyDialog.cpp
// ...
void MyDialog::Show() {
    NativeWindow^ nw = gcnew NativeWindow();
    nw->AssignHandle(parent_);
    this->Show(nw);
}
</code>```

However, this appears to, in all cases I can test, crash the main application (after showing my dialog, interestingly).  I will update the post with crash info if I can obtain it.

I am looking for suggestions on how to achieve the desired behavior consistently.  All I need is to be able to center a modeless dialog in the main window, and have it act as a child.

Any help would be appreciated.

答: I had a similar issue... If you overide the Form.OnLoad and do not call MyBase.OnLoad then StartPosition.CenterParent has no effect</p>

ContentLicense: CC BY-SA 2.5

Title: Parenting a .NET form to an HWND

Body:
I'm developing a plugin (C++/CLI DLL) that runs inside of an certain applications, about which I only know the HWND.  My plugin shows various .NET forms that I'd like to behave as children of the main application (e.g. centered to the main window, etc).  Here's what I've tried:

// MyDialog.h
public ref class MyDialog : public System::Windows::Forms::Form {
    public:
        MyDialog(const int parentHWND);

    private:
        IntPtr parent_;
};

// MyDialog.cpp
// Attempt1: Use SetParent and CenterParent
MyDialog::MyDialog(const int parentHWND) : parent_(parentHWND) {
    SetParent(reinterpret_cast<HWND>(this->Handle.ToPointer()), reinterpret_cast<HWND>(parent_.ToPointer()));

    this->StartPosition = FormStartPosition::CenterParent;
}

This appears to make MyDialog act as a child (i.e. you can't move it outside the main app, etc), but the call to CenterParent does not have the desired results.

I found several ideas online (including SO) that suggest creating a NativeWindow from the HWND and passing it to Show():

// in MyDialog.h
void Show() new;

// MyDialog.cpp
// ...
void MyDialog::Show() {
    NativeWindow^ nw = gcnew NativeWindow();
    nw->AssignHandle(parent_);
    this->Show(nw);
}

However, this appears to, in all cases I can test, crash the main application (after showing my dialog, interestingly).  I will update the post with crash info if I can obtain it.

I am looking for suggestions on how to achieve the desired behavior consistently.  All I need is to be able to center a modeless dialog in the main window, and have it act as a child.

Any help would be appreciated.


问:
List item inside model always null on post - Asp.net MVC
I am trying to post model which contains List<> item looks like below:

```<code>public class AddSubscriptionPlanModel
{
    public AddSubscriptionPlanModel()
    {
        AllFeatures = new List<Feature>();
    }
    public int Id { get; set; }
    public int SubscriptionPlanId { get; set; }
    public int SubscriptionId { get; set; }
    public string Name { get; set; }
    public bool IsActive { get; set; }
    [Display(Name = "No Of Users")]
    public int? NoOfUsers { get; set; }
    [Display(Name = "Duration Type")]
    public DurationType DurationType { get; set; }
    public int Duration { get; set; }
    public decimal Amount { get; set; }
    public int SubscriptionPlanTrailId { get; set; }
    public int FeatureId { get; set; }
    public DateTime CreatedDateUtc { get; set; }
    public DateTime LastUpdatedUtc { get; set; }
    public int CreatedBy { get; set; }
    public int LastUpdatedBy { get; set; }
    public List<Feature> AllFeatures { get; set; }
}
</code>```

I am populating all required fields on get method and feeding List from database

```<code>public ActionResult Mapping(int id)
{
    var features = FeatureManager.GetAllFeatures();
    var model = new Ejyle.DevAccelerate.Web.App.Models.SubscriptionPlan.AddSubscriptionPlanModel();

    model.AllFeatures = features;
    model.Id = id;
    model.SubscriptionId = id;
    model.NoOfUsers = 20;
    model.SubscriptionPlanId = 1;
    model.SubscriptionPlanTrailId = 1;
    model.Amount = 1000;
    model.CreatedBy = 1;
    model.LastUpdatedBy = 1;
    model.FeatureId = 1;
    model.Duration = 20;

    return View(model);
}
</code>```

And my view code looks like below :

```<code>@using (Html.BeginForm("Mapping", "SubscriptionPlans", FormMethod.Post))
{
    @Html.HiddenFor(model => model.Id)
    @Html.HiddenFor(model => model.Amount)
    @Html.HiddenFor(model => model.Duration)
    @Html.HiddenFor(model => model.FeatureId)
    @Html.HiddenFor(model => model.CreatedBy)
    @Html.HiddenFor(model => model.LastUpdatedBy)
    @Html.HiddenFor(model => model.NoOfUsers)
    @Html.HiddenFor(model => model.SubscriptionId)
    @Html.HiddenFor(model => model.SubscriptionPlanId)
    @Html.HiddenFor(model => model.SubscriptionPlanTrailId)
    @Html.HiddenFor(model => model.AllFeatures)
    <table class="table table-striped">
        <thead>
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.Name)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.IsActive)
                </th>
            </tr>
        </thead>
        <tbody>
            @for (int i=0; i < Model.AllFeatures.Count; i++)
            {
                <tr>
                    @Html.HiddenFor(model => model.AllFeatures[i].Id)
                    @Html.HiddenFor(model => model.AllFeatures[i].Name)
                    @Html.HiddenFor(model => model.AllFeatures[i].IsActive)
                    <td>
                        @Html.TextBoxFor(model => model.AllFeatures[i].Id)
                    </td>
                    <td>
                        @Html.TextBoxFor(model => model.AllFeatures[i].Name)
                    </td>
                    <td>
                        @Html.EditorFor(model => model.AllFeatures[i].IsActive)
                    </td>
                </tr>
            }
        </tbody>
    </table>
    <input type="submit" class="btn btn-success" value="Submit" name="Submit"/>
}
</code>```

On View, the list items rendered properly and even I am able to edit those fields.

But On post, all properties have the value except AllFeatures list item property which always shows count = 0.

Edit 1: This is how my view looks like while rendering features

Edit 2:

Signature of the method posting to:

```<code>[HttpPost]
public ActionResult Mapping(AddSubscriptionPlanModel model)
{
}
</code>```

答:
But On post, all properties have the value except AllFeatures list item property which always shows count = 0.

AllFeatures is a generic list of Feature. When you do this:

```<code>@Html.HiddenFor(model => model.AllFeatures)
</code>```

The Razor view engine will render this:

```<code><input id="AllFeatures"
       name="AllFeatures"
       type="hidden"
       value="System.Collections.Generic.List`1[Namespace.Feature]">
       <!--Where Namespace is the Namespace where Feature is defined. -->
</code>```

In other words, HiddenFor calls the ToString() on the item and simply puts that into the input tag's value attribute.

What happens upon POST

When you post the form, the DefaultModelBinder is looking for a property named AllFeatures but of type string so it can assign this to it:

```<code>System.Collections.Generic.List`1[Namespace.Feature]
</code>```

It does not find one since your model does not have AllFeatures of type string, so it simply ignores it and binds all the other properties.

AllFeatures list item property which always shows count = 0.

Yes, it will and this is not the AllFeatures list which you posted but the one from the constructor which clearly is an empty list with a count 0:

```<code>public AddSubscriptionPlanModel()
{
    AllFeatures = new List<Feature>();
}
</code>```

I am not sure why you are sending all the features to the client (browser) and then you need to post it back to the server.

Solution

To fix the issue, simply remove this line:

```<code>@Html.HiddenFor(model => model.AllFeatures)
</code>```

Now it will not cause any confusion during binding and MVC will bind the items in the loop to the AllFeatures property.

In fact, the only code you really need, as far as I can tell from your question is this(I could be wrong if you need the hidden fields for some other reason. But if you just want the user to edit the AllFeatures, you do not need any of the hidden fields):

```<code>@for (int i = 0; i < Model.AllFeatures.Count; i++)
{
    <tr>
        <td>
            @Html.TextBoxFor(model => model.AllFeatures[i].Id)
        </td>
        <td>
            @Html.TextBoxFor(model => model.AllFeatures[i].Name)
        </td>
        <td>
            @Html.EditorFor(model => model.AllFeatures[i].IsActive)
        </td>
    </tr>
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to post model which contains List<> item looks like below:

public class AddSubscriptionPlanModel
{
    public AddSubscriptionPlanModel()
    {
        AllFeatures = new List<Feature>();
    }
    public int Id { get; set; }
    public int SubscriptionPlanId { get; set; }
    public int SubscriptionId { get; set; }
    public string Name { get; set; }
    public bool IsActive { get; set; }
    [Display(Name = "No Of Users")]
    public int? NoOfUsers { get; set; }
    [Display(Name = "Duration Type")]
    public DurationType DurationType { get; set; }
    public int Duration { get; set; }
    public decimal Amount { get; set; }
    public int SubscriptionPlanTrailId { get; set; }
    public int FeatureId { get; set; }
    public DateTime CreatedDateUtc { get; set; }
    public DateTime LastUpdatedUtc { get; set; }
    public int CreatedBy { get; set; }
    public int LastUpdatedBy { get; set; }
    public List<Feature> AllFeatures { get; set; }
}

I am populating all required fields on get method and feeding List from database

public ActionResult Mapping(int id)
{
    var features = FeatureManager.GetAllFeatures();
    var model = new Ejyle.DevAccelerate.Web.App.Models.SubscriptionPlan.AddSubscriptionPlanModel();

    model.AllFeatures = features;
    model.Id = id;
    model.SubscriptionId = id;
    model.NoOfUsers = 20;
    model.SubscriptionPlanId = 1;
    model.SubscriptionPlanTrailId = 1;
    model.Amount = 1000;
    model.CreatedBy = 1;
    model.LastUpdatedBy = 1;
    model.FeatureId = 1;
    model.Duration = 20;

    return View(model);
}

And my view code looks like below :

@using (Html.BeginForm("Mapping", "SubscriptionPlans", FormMethod.Post))
{
    @Html.HiddenFor(model => model.Id)
    @Html.HiddenFor(model => model.Amount)
    @Html.HiddenFor(model => model.Duration)
    @Html.HiddenFor(model => model.FeatureId)
    @Html.HiddenFor(model => model.CreatedBy)
    @Html.HiddenFor(model => model.LastUpdatedBy)
    @Html.HiddenFor(model => model.NoOfUsers)
    @Html.HiddenFor(model => model.SubscriptionId)
    @Html.HiddenFor(model => model.SubscriptionPlanId)
    @Html.HiddenFor(model => model.SubscriptionPlanTrailId)
    @Html.HiddenFor(model => model.AllFeatures)

                    @Html.DisplayNameFor(model => model.Name)

                    @Html.DisplayNameFor(model => model.IsActive)

            @for (int i=0; i < Model.AllFeatures.Count; i++)
            {

                    @Html.HiddenFor(model => model.AllFeatures[i].Id)
                    @Html.HiddenFor(model => model.AllFeatures[i].Name)
                    @Html.HiddenFor(model => model.AllFeatures[i].IsActive)

                        @Html.TextBoxFor(model => model.AllFeatures[i].Id)

                        @Html.TextBoxFor(model => model.AllFeatures[i].Name)

                        @Html.EditorFor(model => model.AllFeatures[i].IsActive)

            }

    <input type="submit" class="btn btn-success" value="Submit" name="Submit"/>
}

On View, the list items rendered properly and even I am able to edit those fields.

But On post, all properties have the value except AllFeatures list item property which always shows count = 0.

Edit 1: This is how my view looks like while rendering features

Edit 2:

Signature of the method posting to:

[HttpPost]
public ActionResult Mapping(AddSubscriptionPlanModel model)
{
}

Body:
But On post, all properties have the value except AllFeatures list item property which always shows count = 0.

AllFeatures is a generic list of Feature. When you do this:

@Html.HiddenFor(model => model.AllFeatures)

The Razor view engine will render this:

<input id="AllFeatures"
       name="AllFeatures"
       type="hidden"
       value="System.Collections.Generic.List`1[Namespace.Feature]">
       <!--Where Namespace is the Namespace where Feature is defined. -->

In other words, HiddenFor calls the ToString() on the item and simply puts that into the input tag's value attribute.

What happens upon POST

When you post the form, the DefaultModelBinder is looking for a property named AllFeatures but of type string so it can assign this to it:

System.Collections.Generic.List`1[Namespace.Feature]

It does not find one since your model does not have AllFeatures of type string, so it simply ignores it and binds all the other properties.

AllFeatures list item property which always shows count = 0.

Yes, it will and this is not the AllFeatures list which you posted but the one from the constructor which clearly is an empty list with a count 0:

public AddSubscriptionPlanModel()
{
    AllFeatures = new List<Feature>();
}

I am not sure why you are sending all the features to the client (browser) and then you need to post it back to the server.

Solution

To fix the issue, simply remove this line:

@Html.HiddenFor(model => model.AllFeatures)

Now it will not cause any confusion during binding and MVC will bind the items in the loop to the AllFeatures property.

In fact, the only code you really need, as far as I can tell from your question is this(I could be wrong if you need the hidden fields for some other reason. But if you just want the user to edit the AllFeatures, you do not need any of the hidden fields):

@for (int i = 0; i < Model.AllFeatures.Count; i++)
{
    <tr>
        <td>
            @Html.TextBoxFor(model => model.AllFeatures[i].Id)
        </td>
        <td>
            @Html.TextBoxFor(model => model.AllFeatures[i].Name)
        </td>
        <td>
            @Html.EditorFor(model => model.AllFeatures[i].IsActive)
        </td>
    </tr>
}


问:
A (Possible) Counterexample to a Common Minimum Vertex Cover on a Tree Algo and My Approach
There have been many posts in the past regarding this topic from a quick search on the site, many of which use this dynamic programming recurrence:

C(x) = min(1 + sum (C(i) for i in x's children), len(x's children) + sum(C(i) for i in x's grandchildren))

Assuming the tree is rooted at node 1, I tried this algorithm against the chain of nodes 1-2-3-4-5-6, to get the following C(i):

| C(1) | C(2) | C(3) | C(4) | C(5) | C(6) |

|  3  |   2  |   2  |   1  |   1  |   1  |

However, the correct answer for C(1) should be 2, which is achieved by marking nodes 2 and 5.

I decided to try my own approach which is detailed below:

```<code>int solve(int curr, int height){
    if(dp[curr][height] > -1) return dp[curr][height];
    if(int(children[curr].size()) == 0) return dp[curr][height] = height > 1 ? 1 : 0;
    if(height == 3){
        int ret = 1;
        for(int i = 0; i < int(children[curr].size()); i++){
            int next = children[curr][i];
            ret += solve(next, 1);
        }
        return dp[curr][height] = ret;
    }
    int ret1 = 0; int ret2 = 1;
    if(height == 2){
        for(int i = 0; i < int(children[curr].size()); i++){
            int next = children[curr][i];
            ret1 += solve(next, 3); ret2 += solve(next, 1);
        }
        return dp[curr][height] = min(ret1, ret2);
    }
    for(int i = 0; i < int(children[curr].size()); i++){
        int next = children[curr][i];
        ret1 += solve(next, 2); ret2 += solve(next, 1);
    }
    return dp[curr][height] = min(ret1, ret2);
}
</code>```

curr is the current node that we are at, and height is the distance away from the closest marked node above it. The idea is that once a node has height = 3, it must be marked in that particular path. Otherwise, we can skip marking it for now. The exception is a leaf node, which must be marked if an adjacent node is not marked.

Can someone please verify the validity of my approach, and also explain why the first algorithm fails the chain test?

Thanks in advance!

答:
The first algorithm actually works. In a minimum vertex cover each edge has to be incident to at least one vertex. In your "counterexample" neither vertex 3 nor 4 are marked, therefore the edge (3,4) doesn't have an incident vertex in the set. So {2, 5} is not a vertex cover.

Your approach doesn't work at all. First of all, I think you still work with a wrong definition of a minimum vertex cover. I'm guessing, that you think, that each vertex has to be touched by an edge incident to a marked vertex.

And even if you use a wrong definition, your approach will not work. A vertex that has distance 3 to a marked parent vertex doesn't have to be marked. Look at this example:

```<code>  0
  |
  1
  |
  2
 / \
3   4
    |
    5
</code>```

In this example if vertex 0 is marked, then the vertices 3 and 4 get also marked, because they are distance 3 from the top. But it is not necessary to mark vertex 4, instead we could also mark vertex 5. Obviously this would give the same number of vertices in this example, but I'm sure you could extend this to a bigger example, where your approach fails.

Solution idea for the different definition:

I believe that a greedy solution works. (There is also a greedy algorithm for the minimum vertex cover). Start by the leaves go upwards to the center. Only mark nodes that are necessary to mark.

You can do this again with depth first search and DP. Let dp[v] be the shortest distance between v and a marked node in the subtree of v. To compute v, first compute all dp values of the children nodes and then decide, if it is necessary to mark it or not. If any child has dp[child] = 2, then you need to mark v and put dp[v] = 0. Otherwise you don't have to mark it and dp[v] = min(dp[children] + 1). At the end you might also need to mark the root node.

Note: I have not tested this.

Body:
There have been many posts in the past regarding this topic from a quick search on the site, many of which use this dynamic programming recurrence:

C(x) = min(1 + sum (C(i) for i in x's children), len(x's children) + sum(C(i) for i in x's grandchildren))

Assuming the tree is rooted at node 1, I tried this algorithm against the chain of nodes 1-2-3-4-5-6, to get the following C(i):

| C(1) | C(2) | C(3) | C(4) | C(5) | C(6) |

|  3  |   2  |   2  |   1  |   1  |   1  |

However, the correct answer for C(1) should be 2, which is achieved by marking nodes 2 and 5.

I decided to try my own approach which is detailed below:

int solve(int curr, int height){
    if(dp[curr][height] > -1) return dp[curr][height];
    if(int(children[curr].size()) == 0) return dp[curr][height] = height > 1 ? 1 : 0;
    if(height == 3){
        int ret = 1;
        for(int i = 0; i < int(children[curr].size()); i++){
            int next = children[curr][i];
            ret += solve(next, 1);
        }
        return dp[curr][height] = ret;
    }
    int ret1 = 0; int ret2 = 1;
    if(height == 2){
        for(int i = 0; i < int(children[curr].size()); i++){
            int next = children[curr][i];
            ret1 += solve(next, 3); ret2 += solve(next, 1);
        }
        return dp[curr][height] = min(ret1, ret2);
    }
    for(int i = 0; i < int(children[curr].size()); i++){
        int next = children[curr][i];
        ret1 += solve(next, 2); ret2 += solve(next, 1);
    }
    return dp[curr][height] = min(ret1, ret2);
}

curr is the current node that we are at, and height is the distance away from the closest marked node above it. The idea is that once a node has height = 3, it must be marked in that particular path. Otherwise, we can skip marking it for now. The exception is a leaf node, which must be marked if an adjacent node is not marked.

Can someone please verify the validity of my approach, and also explain why the first algorithm fails the chain test?

Thanks in advance!

Body:
The first algorithm actually works. In a minimum vertex cover each edge has to be incident to at least one vertex. In your "counterexample" neither vertex 3 nor 4 are marked, therefore the edge (3,4) doesn't have an incident vertex in the set. So {2, 5} is not a vertex cover.

Your approach doesn't work at all. First of all, I think you still work with a wrong definition of a minimum vertex cover. I'm guessing, that you think, that each vertex has to be touched by an edge incident to a marked vertex.

And even if you use a wrong definition, your approach will not work. A vertex that has distance 3 to a marked parent vertex doesn't have to be marked. Look at this example:

  0
  |
  1
  |
  2
 / \
3   4
    |
    5

In this example if vertex 0 is marked, then the vertices 3 and 4 get also marked, because they are distance 3 from the top. But it is not necessary to mark vertex 4, instead we could also mark vertex 5. Obviously this would give the same number of vertices in this example, but I'm sure you could extend this to a bigger example, where your approach fails.

Solution idea for the different definition:

I believe that a greedy solution works. (There is also a greedy algorithm for the minimum vertex cover). Start by the leaves go upwards to the center. Only mark nodes that are necessary to mark.

You can do this again with depth first search and DP. Let dp[v] be the shortest distance between v and a marked node in the subtree of v. To compute v, first compute all dp values of the children nodes and then decide, if it is necessary to mark it or not. If any child has dp[child] = 2, then you need to mark v and put dp[v] = 0. Otherwise you don't have to mark it and dp[v] = min(dp[children] + 1). At the end you might also need to mark the root node.

Note: I have not tested this.


问:
How do I enlarge an EER Diagram in MySQL Workbench?
I am working on a moderately complex schema in MySQL Workbench, and the single page of the EER diagram is now full up. Does anyone know how to enlarge it to two or more pages?</p>

答:
If the "Diagram Properties and Size..." option is grayed out, do the following:

Save your work, as this may crash Workbench;

Go to Model > Model Options;

Choose the "Diagram" tab;

Uncheck "Use defaults from global settings..." at the bottom;

Confirm "Ok".  This may crash Workbench, depending on the version and/or operating system.

Either way, "Model > Diagram Properties and Size..." should now be enabled, even if you had to reopen Workbench.


问:
Printing without newline (print 'a',) prints a space, how to remove?
I have this code:

```<code>>>> for i in xrange(20):
...     print 'a',
...
a a a a a a a a a a a a a a a a a a a a
</code>```

I want to output 'a', without ' ' like this:

```<code>aaaaaaaaaaaaaaaaaaaa
</code>```

Is it possible?

答:
Either what Ant says, or accumulate into a string, then print once:</p>

```<code>s = '';
for i in xrange(20):
    s += 'a'
print s
</code>```

Body:
I have this code:

>>> for i in xrange(20):
...     print 'a',
...
a a a a a a a a a a a a a a a a a a a a

I want to output 'a', without ' ' like this:

aaaaaaaaaaaaaaaaaaaa

Is it possible?

Body:
Either what Ant says, or accumulate into a string, then print once:

s = '';
for i in xrange(20):
    s += 'a'
print s


问:
Swift Generics: Cannot convert value of type to expected argument type
Here is my code:

```<code>protocol SomeProtocol {
}

class A: SomeProtocol {
}

func f1<T: SomeProtocol>(ofType: T.Type, listener: (T?) -> Void) {
}

func f2<T: SomeProtocol>(ofType: T.Type, listener: ([T]?) -> Void) {
}

func g() {
    let l1: (SomeProtocol?) -> Void = ...
    let l2: ([SomeProtocol]?) -> Void = ...
    f1(ofType: A.self, listener: l1) // NO ERROR
    f2(ofType: A.self, listener: l2) // COMPILE ERROR: Cannot convert value of type '([SomeProtocol]?) -> Void' to expected argument type '([_]?) -> Void'
}
</code>```

What is the problem with the second closure having an argument of an array of generic type objects?

答:
Swift 4.1 Update

This is a bug that was fixed in this pull request, which will make it into the release of Swift 4.1. Your code now compiles as expected in a 4.1 snapshot.

Pre Swift 4.1

This just looks like you're just stretching the compiler too far.

It can deal with conversions from arrays of sub-typed elements to arrays of super-typed elements, e.g [A] to [SomeProtocol] – this is covariance. It's worth noting that arrays have always been an edge case here, as arbitrary generics are invariant. Certain collections, such as Array, just get special treatment from the compiler allowing for covariance.

It can deal with conversions of functions with super-typed parameters to functions with sub-typed parameters, e.g (SomeProtocol) -> Void to (A) -> Void – this is contravariance.

However it appears that it currently cannot do both in one go (but really it should be able to; feel free to file a bug).

For what it's worth, this has nothing to do with generics, the following reproduces the same behaviour:

```<code>protocol SomeProtocol {}
class A : SomeProtocol {}

func f1(listener: (A) -> Void) {}
func f2(listener: ([A]) -> Void) {}
func f3(listener: () -> [SomeProtocol]) {}

func g() {

    let l1: (SomeProtocol) -> Void = { _ in }
    f1(listener: l1) // NO ERROR

    let l2: ([SomeProtocol]) -> Void = { _ in }
    f2(listener: l2)
    // COMPILER ERROR: Cannot convert value of type '([SomeProtocol]) -> Void' to
    // expected argument type '([A]) -> Void'

    // it's the same story for function return types
    let l3: () -> [A] = { [] }
    f3(listener: l3)
    // COMPILER ERROR: Cannot convert value of type '() -> [A]' to
    // expected argument type '() -> [SomeProtocol]'
}
</code>```

Until fixed, one solution in this case is to simply use a closure expression to act as a trampoline between the two function types:

```<code>// converting a ([SomeProtocol]) -> Void to a ([A]) -> Void.
// compiler infers closure expression to be of type ([A]) -> Void, and in the
// implementation, $0 gets implicitly converted from [A] to [SomeProtocol].
f2(listener: { l2($0) })

// converting a () -> [A] to a () -> [SomeProtocol].
// compiler infers closure expression to be of type () -> [SomeProtocol], and in the
// implementation, the result of l3 gets implicitly converted from [A] to [SomeProtocol]
f3(listener: { l3() })
</code>```

And, applied to your code:

```<code>f2(ofType: A.self, listener: { l2($0) })
</code>```

This works because the compiler infers the closure expression to be of type ([T]?) -> Void, which can be passed to f2. In the implementation of the closure, the compiler then performs an implicit conversion of $0 from [T]? to [SomeProtocol]?.

And, as Dominik is hinting at, this trampoline could also be done as an additional overload of f2:

```<code>func f2<T : SomeProtocol>(ofType type: T.Type, listener: ([SomeProtocol]?) -> Void) {
    // pass a closure expression of type ([T]?) -> Void to the original f2, we then
    // deal with the conversion from [T]? to [SomeProtocol]? in the closure.
    // (and by "we", I mean the compiler, implicitly)
    f2(ofType: type, listener: { (arr: [T]?) in listener(arr) })
}
</code>```

Allowing you to once again call it as f2(ofType: A.self, listener: l2).

Body:
Here is my code:

protocol SomeProtocol {
}

class A: SomeProtocol {
}

func f1<T: SomeProtocol>(ofType: T.Type, listener: (T?) -> Void) {
}

func f2<T: SomeProtocol>(ofType: T.Type, listener: ([T]?) -> Void) {
}

func g() {
    let l1: (SomeProtocol?) -> Void = ...
    let l2: ([SomeProtocol]?) -> Void = ...
    f1(ofType: A.self, listener: l1) // NO ERROR
    f2(ofType: A.self, listener: l2) // COMPILE ERROR: Cannot convert value of type '([SomeProtocol]?) -> Void' to expected argument type '([_]?) -> Void'
}

What is the problem with the second closure having an argument of an array of generic type objects?

Body:
Swift 4.1 Update

This is a bug that was fixed in this pull request, which will make it into the release of Swift 4.1. Your code now compiles as expected in a 4.1 snapshot.

Pre Swift 4.1

This just looks like you're just stretching the compiler too far.

It can deal with conversions from arrays of sub-typed elements to arrays of super-typed elements, e.g [A] to [SomeProtocol] – this is covariance. It's worth noting that arrays have always been an edge case here, as arbitrary generics are invariant. Certain collections, such as Array, just get special treatment from the compiler allowing for covariance.

It can deal with conversions of functions with super-typed parameters to functions with sub-typed parameters, e.g (SomeProtocol) -> Void to (A) -> Void – this is contravariance.

However it appears that it currently cannot do both in one go (but really it should be able to; feel free to file a bug).

For what it's worth, this has nothing to do with generics, the following reproduces the same behaviour:

protocol SomeProtocol {}
class A : SomeProtocol {}

func f1(listener: (A) -> Void) {}
func f2(listener: ([A]) -> Void) {}
func f3(listener: () -> [SomeProtocol]) {}

func g() {

    let l1: (SomeProtocol) -> Void = { _ in }
    f1(listener: l1) // NO ERROR

    let l2: ([SomeProtocol]) -> Void = { _ in }
    f2(listener: l2)
    // COMPILER ERROR: Cannot convert value of type '([SomeProtocol]) -> Void' to
    // expected argument type '([A]) -> Void'

    // it's the same story for function return types
    let l3: () -> [A] = { [] }
    f3(listener: l3)
    // COMPILER ERROR: Cannot convert value of type '() -> [A]' to
    // expected argument type '() -> [SomeProtocol]'
}

Until fixed, one solution in this case is to simply use a closure expression to act as a trampoline between the two function types:

// converting a ([SomeProtocol]) -> Void to a ([A]) -> Void.
// compiler infers closure expression to be of type ([A]) -> Void, and in the
// implementation, $0 gets implicitly converted from [A] to [SomeProtocol].
f2(listener: { l2($0) })

// converting a () -> [A] to a () -> [SomeProtocol].
// compiler infers closure expression to be of type () -> [SomeProtocol], and in the
// implementation, the result of l3 gets implicitly converted from [A] to [SomeProtocol]
f3(listener: { l3() })

And, applied to your code:

f2(ofType: A.self, listener: { l2($0) })

This works because the compiler infers the closure expression to be of type ([T]?) -> Void, which can be passed to f2. In the implementation of the closure, the compiler then performs an implicit conversion of $0 from [T]? to [SomeProtocol]?.

And, as Dominik is hinting at, this trampoline could also be done as an additional overload of f2:

func f2<T : SomeProtocol>(ofType type: T.Type, listener: ([SomeProtocol]?) -> Void) {
    // pass a closure expression of type ([T]?) -> Void to the original f2, we then
    // deal with the conversion from [T]? to [SomeProtocol]? in the closure.
    // (and by "we", I mean the compiler, implicitly)
    f2(ofType: type, listener: { (arr: [T]?) in listener(arr) })
}

Allowing you to once again call it as f2(ofType: A.self, listener: l2).


问:
How to identify a character within a word and substitute that letter into another string - Python
For my hangman project, in the situation that the person does guess a letter correctly, I want to be able to substitute that letter in for a '_' space.

```<code>word = input('Please enter a word for your opponent:')

letter = input('Enter a letter to try and guess the word:')

print('_ '*len(word))

if 'a' in word and letter:
    print('_ '*len(word) with 'a' in word)
</code>```

For example if the word entered was 'matt,' the output would be '_a__'

答:
You can also do this in a much simpler way. </p>

```<code>>>> word_split = list(word)
>>> for a in range(len(word_split)):
...     if word_split[a] != letter:
...             word_split[a] = "_"
...
>>> print(" ".join(word_split))
_ _ _ _ _ _ _ a _
</code>```

<p>However @COLDSPEED 's solution is an elegant one. </p>

Body:
For my hangman project, in the situation that the person does guess a letter correctly, I want to be able to substitute that letter in for a '_' space.

word = input('Please enter a word for your opponent:')

letter = input('Enter a letter to try and guess the word:')

print('_ '*len(word))

if 'a' in word and letter:
    print('_ '*len(word) with 'a' in word)

For example if the word entered was 'matt,' the output would be '_a__'

Body:
You can also do this in a much simpler way.

>>> word_split = list(word)
>>> for a in range(len(word_split)):
...     if word_split[a] != letter:
...             word_split[a] = "_"
...
>>> print(" ".join(word_split))
_ _ _ _ _ _ _ a _

However @COLDSPEED 's solution is an elegant one.


问:
excel CountIf or
Both options work fine as you can see in my picture of my spreadsheet in column R & Q where the counts are.
Most of my columns are in military time formats like 24:00 one of the column I am working on is the X column that I am trying to get added to this time count if possible I a Number column where the numbers start from 10,11,13 and so on. Long story short.
I need Numbers in column X # 10 ,11 to be in the count for count for column O as you can see in column Q & R  I got it set up for my count and it works just fine but that’s without the special deal I need from column X where I only needs these numbers from 10,11, a few from # 13.
So, in a nut shell I just need it to say give me the column O times if there is a # 10,11,13 in column X
= COUNTIF($O$13:$O$1000,">=0:21")-COUNTIF($O$13:$O$1000,">0:30")

Connection time

Connection time

答: https://support.google.com/docs/answer/3093480 - similar functionality. You have 0:21 - 0:30.. What's that all about? Zeros? O21 or 0.21? etc. If it's meant to be time, you want to strip out that stuff, and add things up probably using decimals so 30 seconds is 0.5 min.. Or convert everything to seconds... Then you can convert back after.If it's minutes and you want the granularity split it into columns. LEFT(cell,FIND(":"),cell) , RIGHT(cell,len(cell)-find(":")). May be off by one either way so a +1,-1 may be needed... Then convert text to number VALUE(text). And countif does not allow strings for comparison. So quotes around last parameter are a "no no"! Only numbers..</p>

Title: excel CountIf or


问:
R fromJSON - $ operator is invalid for atomic vectors
Why do I get this error below:

```<code>Error: $ operator is invalid for atomic vectors
</code>```

My dummy code for a simple test:

```<code>l <- fromJSON('[{"winner":"68694999",  "votes":[
   {"ts":"Thu Mar 25 03:13:01 UTC 2010", "user":{"name":"Lamur","user_id":"68694999"}},
   {"ts":"Thu Mar 25 03:13:08 UTC 2010", "user":{"name":"Lamur","user_id":"68694999"}}],
  "lastVote":{"timestamp":1269486788526,"user":
   {"name":"Lamur","user_id":"68694999"}},"startPrice":0}]'
)

for(i in l) {
    print(i$votes)
}
</code>```

I just want to get the data off votes

Any ideas?

This is my more complex json that I need to pull the data from:

```<code>json <- '[{
    "data": {
        "dailysummary": [{
            "date": {
                "pretty": "12:20 AM BST on June 28, 2017",
                "year": "2017",
                "mon": "06",
                "mday": "28",
                "hour": "00",
                "min": "20",
                "tzname": "Europe/London"
            },
            "fog": "0",
            "rain": "1",
            "snow": "0",
            "snowfallm": "",
            "snowfalli": "",
            "monthtodatesnowfallm": "",
            "monthtodatesnowfalli": "",
            "since1julsnowfallm": "",
            "since1julsnowfalli": "",
            "snowdepthm": "",
            "snowdepthi": "",
            "hail": "0",
            "thunder": "0",
            "tornado": "0",
            "meantempm": "16",
            "meantempi": "60",
            "meandewptm": "13",
            "meandewpti": "56",
            "meanpressurem": "997.19",
            "meanpressurei": "29.45",
            "meanwindspdm": "9",
            "meanwindspdi": "6",
            "meanwdire": "NW",
            "meanwdird": "326",
            "meanvism": "8.9",
            "meanvisi": "5.5",
            "humidity": "86",
            "maxtempm": "17",
            "maxtempi": "62",
            "mintempm": "14",
            "mintempi": "57",
            "maxhumidity": "100",
            "minhumidity": "77",
            "maxdewptm": "15",
            "maxdewpti": "59",
            "mindewptm": "10",
            "mindewpti": "50",
            "maxpressurem": "1001",
            "maxpressurei": "29.56",
            "minpressurem": "996",
            "minpressurei": "29.42",
            "maxwspdm": "18",
            "maxwspdi": "12",
            "minwspdm": "6",
            "minwspdi": "4",
            "maxvism": "10.0",
            "maxvisi": "6.2",
            "minvism": "4.5",
            "minvisi": "2.8",
            "gdegreedays": "10",
            "heatingdegreedays": "6",
            "coolingdegreedays": "0",
            "precipm": "0.0",
            "precipi": "0.00",
            "precipsource": "3Or6HourObs",
            "heatingdegreedaysnormal": "",
            "monthtodateheatingdegreedays": "",
            "monthtodateheatingdegreedaysnormal": "",
            "since1sepheatingdegreedays": "",
            "since1sepheatingdegreedaysnormal": "",
            "since1julheatingdegreedays": "",
            "since1julheatingdegreedaysnormal": "",
            "coolingdegreedaysnormal": "",
            "monthtodatecoolingdegreedays": "",
            "monthtodatecoolingdegreedaysnormal": "",
            "since1sepcoolingdegreedays": "",
            "since1sepcoolingdegreedaysnormal": "",
            "since1jancoolingdegreedays": "",
            "since1jancoolingdegreedaysnormal": ""
        }],
        "airport": "LCY"
    },
    "date": "2017-06-28"
},{
    "data": {
        "dailysummary": [{
            "date": {
                "pretty": "12:20 AM BST on June 29, 2017",
                "year": "2017",
                "mon": "06",
                "mday": "29",
                "hour": "00",
                "min": "20",
                "tzname": "Europe/London"
            },
            "fog": "0",
            "rain": "0",
            "snow": "0",
            "snowfallm": "",
            "snowfalli": "",
            "monthtodatesnowfallm": "",
            "monthtodatesnowfalli": "",
            "since1julsnowfallm": "",
            "since1julsnowfalli": "",
            "snowdepthm": "",
            "snowdepthi": "",
            "hail": "0",
            "thunder": "0",
            "tornado": "0",
            "meantempm": "16",
            "meantempi": "60",
            "meandewptm": "11",
            "meandewpti": "51",
            "meanpressurem": "995.85",
            "meanpressurei": "29.41",
            "meanwindspdm": "14",
            "meanwindspdi": "9",
            "meanwdire": "WSW",
            "meanwdird": "256",
            "meanvism": "10.0",
            "meanvisi": "6.2",
            "humidity": "71",
            "maxtempm": "18",
            "maxtempi": "64",
            "mintempm": "13",
            "mintempi": "55",
            "maxhumidity": "82",
            "minhumidity": "63",
            "maxdewptm": "11",
            "maxdewpti": "52",
            "mindewptm": "10",
            "mindewpti": "50",
            "maxpressurem": "999",
            "maxpressurei": "29.50",
            "minpressurem": "994",
            "minpressurei": "29.36",
            "maxwspdm": "24",
            "maxwspdi": "15",
            "minwspdm": "9",
            "minwspdi": "6",
            "maxvism": "10.0",
            "maxvisi": "6.2",
            "minvism": "10.0",
            "minvisi": "6.2",
            "gdegreedays": "10",
            "heatingdegreedays": "6",
            "coolingdegreedays": "0",
            "precipm": "0.0",
            "precipi": "0.00",
            "precipsource": "3Or6HourObs",
            "heatingdegreedaysnormal": "",
            "monthtodateheatingdegreedays": "",
            "monthtodateheatingdegreedaysnormal": "",
            "since1sepheatingdegreedays": "",
            "since1sepheatingdegreedaysnormal": "",
            "since1julheatingdegreedays": "",
            "since1julheatingdegreedaysnormal": "",
            "coolingdegreedaysnormal": "",
            "monthtodatecoolingdegreedays": "",
            "monthtodatecoolingdegreedaysnormal": "",
            "since1sepcoolingdegreedays": "",
            "since1sepcoolingdegreedaysnormal": "",
            "since1jancoolingdegreedays": "",
            "since1jancoolingdegreedaysnormal": ""
        }],
        "airport": "LCY"
    },
    "date": "2017-06-29"
}]'

l <- fromJSON(json, ,flatten=TRUE)
</code>```

I need to make it into a new dataframe:

```<code>airport key_date        ws      wd      tempi humidity
LCY     2017-06-28      x       x       x       x
LCY     2017-06-29      x       x       x       x
</code>```

This is my old code but it does not work with this l dataframe from json anymore:

```<code># Initialize a data frame.
weatherDf <- data.frame()

# Set key conditions for checking later.
keyConditions <- c("meanwindspdi", "meanwdird", "meantempm", "humidity")

for(i in l) {
    # Get the airport code.
    airport <- i$airport

    # Get the date.
    date <- as.POSIXct(as.numeric(as.character(i$date))/1000, origin="1970-01-01", tz="UTC-1")

    # Get the data in dailysummary only.
    dailySummary <- i$dailysummary

    # print(all(keyConditions %in% names(dailySummary)))

    # Make sure key conditions exist in dailySummary,
    # then use rbind or will get 'numbers of columns of arguments do not match'
    if (all(keyConditions %in% names(dailySummary))) {
        weatherDf <- rbind(weatherDf, ldply(
            list(dailySummary),
            function(x) c(airport, format(as.Date(date), "%Y-%m-%d"), x[["meanwindspdi"]], x[["meanwdird"]], x[["meantempm"]], x[["humidity"]])
        ))
    }
}

# Rename column names.
colnames(weatherDf) <- c("airport", "key_date", "ws", "wd", "tempi", 'humidity')

# Convert certain columns weatherDf type to numberic.
columns <-c("ws", "wd", "tempi", "humidity")
weatherDf[, columns] <- lapply(columns, function(x) as.numeric(weatherDf[[x]]))
</code>```

EDIT:

```<code>weatherDf <- data.frame()
for(i in 1:nrow(l)) {
    row <- l[i,]
    # do stuff with row

    # Get the date.
    date <- row$date

    # Get the airport code.
    airport <- row$data.airport
    print(airport)

    # Get the data in dailysummary only.
    dailySummary <- row$data.dailysummary

    # print(all(keyConditions %in% names(dailySummary)))
    weatherDf <- rbind(weatherDf, ldply(
        list(dailySummary),
        function(x) c(airport, format(as.Date(date), "%Y-%m-%d"), x[["meanwindspdi"]], x[["meanwdird"]], x[["meantempm"]], x[["humidity"]])
    ))
}
</code>```

Edit 2:

```<code>dailySummary <- row$data.dailysummary
print(names(dailySummary))
</code>```

Result:

```<code>NULL
</code>```

What I try to get:

```<code>[1] "fog"                                "rain"                               "snow"
 [4] "snowfallm"                          "snowfalli"                          "monthtodatesnowfallm"
 [7] "monthtodatesnowfalli"               "since1julsnowfallm"                 "since1julsnowfalli"
[10] "snowdepthm"                         "snowdepthi"                         "hail"
[13] "thunder"                            "tornado"                            "meantempm"
[16] "meantempi"                          "meandewptm"                         "meandewpti"
[19] "meanpressurem"                      "meanpressurei"                      "meanwindspdm"
[22] "meanwindspdi"                       "meanwdire"                          "meanwdird"
[25] "meanvism"                           "meanvisi"                           "humidity"
[28] "maxtempm"                           "maxtempi"                           "mintempm"
[31] "mintempi"                           "maxhumidity"                        "minhumidity"
[34] "maxdewptm"                          "maxdewpti"                          "mindewptm"
[37] "mindewpti"                          "maxpressurem"                       "maxpressurei"
[40] "minpressurem"                       "minpressurei"                       "maxwspdm"
[43] "maxwspdi"                           "minwspdm"                           "minwspdi"
[46] "maxvism"                            "maxvisi"                            "minvism"
[49] "minvisi"                            "gdegreedays"                        "heatingdegreedays"
[52] "coolingdegreedays"                  "precipm"                            "precipi"
[55] "precipsource"                       "heatingdegreedaysnormal"            "monthtodateheatingdegreedays"
[58] "monthtodateheatingdegreedaysnormal" "since1sepheatingdegreedays"         "since1sepheatingdegreedaysnormal"
[61] "since1julheatingdegreedays"         "since1julheatingdegreedaysnormal"   "coolingdegreedaysnormal"
[64] "monthtodatecoolingdegreedays"       "monthtodatecoolingdegreedaysnormal" "since1sepcoolingdegreedays"
[67] "since1sepcoolingdegreedaysnormal"   "since1jancoolingdegreedays"         "since1jancoolingdegreedaysnormal"
[70] "date.pretty"                        "date.year"                          "date.mon"
[73] "date.mday"                          "date.hour"                          "date.min"
[76] "date.tzname"
 [1] "fog"                                "rain"                               "snow"
 [4] "snowfallm"                          "snowfalli"                          "monthtodatesnowfallm"
 [7] "monthtodatesnowfalli"               "since1julsnowfallm"                 "since1julsnowfalli"
[10] "snowdepthm"                         "snowdepthi"                         "hail"
[13] "thunder"                            "tornado"                            "meantempm"
[16] "meantempi"                          "meandewptm"                         "meandewpti"
[19] "meanpressurem"                      "meanpressurei"                      "meanwindspdm"
[22] "meanwindspdi"                       "meanwdire"                          "meanwdird"
[25] "meanvism"                           "meanvisi"                           "humidity"
[28] "maxtempm"                           "maxtempi"                           "mintempm"
[31] "mintempi"                           "maxhumidity"                        "minhumidity"
[34] "maxdewptm"                          "maxdewpti"                          "mindewptm"
[37] "mindewpti"                          "maxpressurem"                       "maxpressurei"
[40] "minpressurem"                       "minpressurei"                       "maxwspdm"
[43] "maxwspdi"                           "minwspdm"                           "minwspdi"
[46] "maxvism"                            "maxvisi"                            "minvism"
[49] "minvisi"                            "gdegreedays"                        "heatingdegreedays"
[52] "coolingdegreedays"                  "precipm"                            "precipi"
[55] "precipsource"                       "heatingdegreedaysnormal"            "monthtodateheatingdegreedays"
[58] "monthtodateheatingdegreedaysnormal" "since1sepheatingdegreedays"         "since1sepheatingdegreedaysnormal"
[61] "since1julheatingdegreedays"         "since1julheatingdegreedaysnormal"   "coolingdegreedaysnormal"
[64] "monthtodatecoolingdegreedays"       "monthtodatecoolingdegreedaysnormal" "since1sepcoolingdegreedays"
[67] "since1sepcoolingdegreedaysnormal"   "since1jancoolingdegreedays"         "since1jancoolingdegreedaysnormal"
[70] "date.pretty"                        "date.year"                          "date.mon"
[73] "date.mday"                          "date.hour"                          "date.min"
[76] "date.tzname"
</code>```

答:
l$votes is a list. If you need to loop through multiples of these in a list having this format, this might work using the relatively new purrr package:

```<code>purrr::walk(l, ~ print(.x[[1]] ))
</code>```

If you want to do a loop, printing out the whole data frame for each item in the json structured like you showed, something like this could work:

```<code>for(i in l){
  print(i[[1]])
}
</code>```

Body:
Why do I get this error below:

Error: $ operator is invalid for atomic vectors

My dummy code for a simple test:

l <- fromJSON('[{"winner":"68694999",  "votes":[
   {"ts":"Thu Mar 25 03:13:01 UTC 2010", "user":{"name":"Lamur","user_id":"68694999"}},
   {"ts":"Thu Mar 25 03:13:08 UTC 2010", "user":{"name":"Lamur","user_id":"68694999"}}],
  "lastVote":{"timestamp":1269486788526,"user":
   {"name":"Lamur","user_id":"68694999"}},"startPrice":0}]'
)

for(i in l) {
    print(i$votes)
}

I just want to get the data off votes

Any ideas?

This is my more complex json that I need to pull the data from:

json <- '[{
    "data": {
        "dailysummary": [{
            "date": {
                "pretty": "12:20 AM BST on June 28, 2017",
                "year": "2017",
                "mon": "06",
                "mday": "28",
                "hour": "00",
                "min": "20",
                "tzname": "Europe/London"
            },
            "fog": "0",
            "rain": "1",
            "snow": "0",
            "snowfallm": "",
            "snowfalli": "",
            "monthtodatesnowfallm": "",
            "monthtodatesnowfalli": "",
            "since1julsnowfallm": "",
            "since1julsnowfalli": "",
            "snowdepthm": "",
            "snowdepthi": "",
            "hail": "0",
            "thunder": "0",
            "tornado": "0",
            "meantempm": "16",
            "meantempi": "60",
            "meandewptm": "13",
            "meandewpti": "56",
            "meanpressurem": "997.19",
            "meanpressurei": "29.45",
            "meanwindspdm": "9",
            "meanwindspdi": "6",
            "meanwdire": "NW",
            "meanwdird": "326",
            "meanvism": "8.9",
            "meanvisi": "5.5",
            "humidity": "86",
            "maxtempm": "17",
            "maxtempi": "62",
            "mintempm": "14",
            "mintempi": "57",
            "maxhumidity": "100",
            "minhumidity": "77",
            "maxdewptm": "15",
            "maxdewpti": "59",
            "mindewptm": "10",
            "mindewpti": "50",
            "maxpressurem": "1001",
            "maxpressurei": "29.56",
            "minpressurem": "996",
            "minpressurei": "29.42",
            "maxwspdm": "18",
            "maxwspdi": "12",
            "minwspdm": "6",
            "minwspdi": "4",
            "maxvism": "10.0",
            "maxvisi": "6.2",
            "minvism": "4.5",
            "minvisi": "2.8",
            "gdegreedays": "10",
            "heatingdegreedays": "6",
            "coolingdegreedays": "0",
            "precipm": "0.0",
            "precipi": "0.00",
            "precipsource": "3Or6HourObs",
            "heatingdegreedaysnormal": "",
            "monthtodateheatingdegreedays": "",
            "monthtodateheatingdegreedaysnormal": "",
            "since1sepheatingdegreedays": "",
            "since1sepheatingdegreedaysnormal": "",
            "since1julheatingdegreedays": "",
            "since1julheatingdegreedaysnormal": "",
            "coolingdegreedaysnormal": "",
            "monthtodatecoolingdegreedays": "",
            "monthtodatecoolingdegreedaysnormal": "",
            "since1sepcoolingdegreedays": "",
            "since1sepcoolingdegreedaysnormal": "",
            "since1jancoolingdegreedays": "",
            "since1jancoolingdegreedaysnormal": ""
        }],
        "airport": "LCY"
    },
    "date": "2017-06-28"
},{
    "data": {
        "dailysummary": [{
            "date": {
                "pretty": "12:20 AM BST on June 29, 2017",
                "year": "2017",
                "mon": "06",
                "mday": "29",
                "hour": "00",
                "min": "20",
                "tzname": "Europe/London"
            },
            "fog": "0",
            "rain": "0",
            "snow": "0",
            "snowfallm": "",
            "snowfalli": "",
            "monthtodatesnowfallm": "",
            "monthtodatesnowfalli": "",
            "since1julsnowfallm": "",
            "since1julsnowfalli": "",
            "snowdepthm": "",
            "snowdepthi": "",
            "hail": "0",
            "thunder": "0",
            "tornado": "0",
            "meantempm": "16",
            "meantempi": "60",
            "meandewptm": "11",
            "meandewpti": "51",
            "meanpressurem": "995.85",
            "meanpressurei": "29.41",
            "meanwindspdm": "14",
            "meanwindspdi": "9",
            "meanwdire": "WSW",
            "meanwdird": "256",
            "meanvism": "10.0",
            "meanvisi": "6.2",
            "humidity": "71",
            "maxtempm": "18",
            "maxtempi": "64",
            "mintempm": "13",
            "mintempi": "55",
            "maxhumidity": "82",
            "minhumidity": "63",
            "maxdewptm": "11",
            "maxdewpti": "52",
            "mindewptm": "10",
            "mindewpti": "50",
            "maxpressurem": "999",
            "maxpressurei": "29.50",
            "minpressurem": "994",
            "minpressurei": "29.36",
            "maxwspdm": "24",
            "maxwspdi": "15",
            "minwspdm": "9",
            "minwspdi": "6",
            "maxvism": "10.0",
            "maxvisi": "6.2",
            "minvism": "10.0",
            "minvisi": "6.2",
            "gdegreedays": "10",
            "heatingdegreedays": "6",
            "coolingdegreedays": "0",
            "precipm": "0.0",
            "precipi": "0.00",
            "precipsource": "3Or6HourObs",
            "heatingdegreedaysnormal": "",
            "monthtodateheatingdegreedays": "",
            "monthtodateheatingdegreedaysnormal": "",
            "since1sepheatingdegreedays": "",
            "since1sepheatingdegreedaysnormal": "",
            "since1julheatingdegreedays": "",
            "since1julheatingdegreedaysnormal": "",
            "coolingdegreedaysnormal": "",
            "monthtodatecoolingdegreedays": "",
            "monthtodatecoolingdegreedaysnormal": "",
            "since1sepcoolingdegreedays": "",
            "since1sepcoolingdegreedaysnormal": "",
            "since1jancoolingdegreedays": "",
            "since1jancoolingdegreedaysnormal": ""
        }],
        "airport": "LCY"
    },
    "date": "2017-06-29"
}]'

l <- fromJSON(json, ,flatten=TRUE)

I need to make it into a new dataframe:

airport key_date        ws      wd      tempi humidity
LCY     2017-06-28      x       x       x       x
LCY     2017-06-29      x       x       x       x

This is my old code but it does not work with this l dataframe from json anymore:

# Initialize a data frame.
weatherDf <- data.frame()

# Set key conditions for checking later.
keyConditions <- c("meanwindspdi", "meanwdird", "meantempm", "humidity")

for(i in l) {
    # Get the airport code.
    airport <- i$airport

    # Get the date.
    date <- as.POSIXct(as.numeric(as.character(i$date))/1000, origin="1970-01-01", tz="UTC-1")

    # Get the data in dailysummary only.
    dailySummary <- i$dailysummary

    # print(all(keyConditions %in% names(dailySummary)))

    # Make sure key conditions exist in dailySummary,
    # then use rbind or will get 'numbers of columns of arguments do not match'
    if (all(keyConditions %in% names(dailySummary))) {
        weatherDf <- rbind(weatherDf, ldply(
            list(dailySummary),
            function(x) c(airport, format(as.Date(date), "%Y-%m-%d"), x[["meanwindspdi"]], x[["meanwdird"]], x[["meantempm"]], x[["humidity"]])
        ))
    }
}

# Rename column names.
colnames(weatherDf) <- c("airport", "key_date", "ws", "wd", "tempi", 'humidity')

# Convert certain columns weatherDf type to numberic.
columns <-c("ws", "wd", "tempi", "humidity")
weatherDf[, columns] <- lapply(columns, function(x) as.numeric(weatherDf[[x]]))

EDIT:

weatherDf <- data.frame()
for(i in 1:nrow(l)) {
    row <- l[i,]
    # do stuff with row

    # Get the date.
    date <- row$date

    # Get the airport code.
    airport <- row$data.airport
    print(airport)

    # Get the data in dailysummary only.
    dailySummary <- row$data.dailysummary

    # print(all(keyConditions %in% names(dailySummary)))
    weatherDf <- rbind(weatherDf, ldply(
        list(dailySummary),
        function(x) c(airport, format(as.Date(date), "%Y-%m-%d"), x[["meanwindspdi"]], x[["meanwdird"]], x[["meantempm"]], x[["humidity"]])
    ))
}

Edit 2:

dailySummary <- row$data.dailysummary
print(names(dailySummary))

Result:

NULL

What I try to get:

[1] "fog"                                "rain"                               "snow"
 [4] "snowfallm"                          "snowfalli"                          "monthtodatesnowfallm"
 [7] "monthtodatesnowfalli"               "since1julsnowfallm"                 "since1julsnowfalli"
[10] "snowdepthm"                         "snowdepthi"                         "hail"
[13] "thunder"                            "tornado"                            "meantempm"
[16] "meantempi"                          "meandewptm"                         "meandewpti"
[19] "meanpressurem"                      "meanpressurei"                      "meanwindspdm"
[22] "meanwindspdi"                       "meanwdire"                          "meanwdird"
[25] "meanvism"                           "meanvisi"                           "humidity"
[28] "maxtempm"                           "maxtempi"                           "mintempm"
[31] "mintempi"                           "maxhumidity"                        "minhumidity"
[34] "maxdewptm"                          "maxdewpti"                          "mindewptm"
[37] "mindewpti"                          "maxpressurem"                       "maxpressurei"
[40] "minpressurem"                       "minpressurei"                       "maxwspdm"
[43] "maxwspdi"                           "minwspdm"                           "minwspdi"
[46] "maxvism"                            "maxvisi"                            "minvism"
[49] "minvisi"                            "gdegreedays"                        "heatingdegreedays"
[52] "coolingdegreedays"                  "precipm"                            "precipi"
[55] "precipsource"                       "heatingdegreedaysnormal"            "monthtodateheatingdegreedays"
[58] "monthtodateheatingdegreedaysnormal" "since1sepheatingdegreedays"         "since1sepheatingdegreedaysnormal"
[61] "since1julheatingdegreedays"         "since1julheatingdegreedaysnormal"   "coolingdegreedaysnormal"
[64] "monthtodatecoolingdegreedays"       "monthtodatecoolingdegreedaysnormal" "since1sepcoolingdegreedays"
[67] "since1sepcoolingdegreedaysnormal"   "since1jancoolingdegreedays"         "since1jancoolingdegreedaysnormal"
[70] "date.pretty"                        "date.year"                          "date.mon"
[73] "date.mday"                          "date.hour"                          "date.min"
[76] "date.tzname"
 [1] "fog"                                "rain"                               "snow"
 [4] "snowfallm"                          "snowfalli"                          "monthtodatesnowfallm"
 [7] "monthtodatesnowfalli"               "since1julsnowfallm"                 "since1julsnowfalli"
[10] "snowdepthm"                         "snowdepthi"                         "hail"
[13] "thunder"                            "tornado"                            "meantempm"
[16] "meantempi"                          "meandewptm"                         "meandewpti"
[19] "meanpressurem"                      "meanpressurei"                      "meanwindspdm"
[22] "meanwindspdi"                       "meanwdire"                          "meanwdird"
[25] "meanvism"                           "meanvisi"                           "humidity"
[28] "maxtempm"                           "maxtempi"                           "mintempm"
[31] "mintempi"                           "maxhumidity"                        "minhumidity"
[34] "maxdewptm"                          "maxdewpti"                          "mindewptm"
[37] "mindewpti"                          "maxpressurem"                       "maxpressurei"
[40] "minpressurem"                       "minpressurei"                       "maxwspdm"
[43] "maxwspdi"                           "minwspdm"                           "minwspdi"
[46] "maxvism"                            "maxvisi"                            "minvism"
[49] "minvisi"                            "gdegreedays"                        "heatingdegreedays"
[52] "coolingdegreedays"                  "precipm"                            "precipi"
[55] "precipsource"                       "heatingdegreedaysnormal"            "monthtodateheatingdegreedays"
[58] "monthtodateheatingdegreedaysnormal" "since1sepheatingdegreedays"         "since1sepheatingdegreedaysnormal"
[61] "since1julheatingdegreedays"         "since1julheatingdegreedaysnormal"   "coolingdegreedaysnormal"
[64] "monthtodatecoolingdegreedays"       "monthtodatecoolingdegreedaysnormal" "since1sepcoolingdegreedays"
[67] "since1sepcoolingdegreedaysnormal"   "since1jancoolingdegreedays"         "since1jancoolingdegreedaysnormal"
[70] "date.pretty"                        "date.year"                          "date.mon"
[73] "date.mday"                          "date.hour"                          "date.min"
[76] "date.tzname"

Body:
l$votes is a list. If you need to loop through multiples of these in a list having this format, this might work using the relatively new purrr package:

purrr::walk(l, ~ print(.x[[1]] ))

If you want to do a loop, printing out the whole data frame for each item in the json structured like you showed, something like this could work:

for(i in l){
  print(i[[1]])
}


问:
can't find plaint text in android
While learning how to build a simple user interface on The instructs. From the Palette window on the left, click Text in the left panel, and then drag Plain Text into the design editor and drop it near the top of the layout.  Where exactly can I find "plain-text", or is it something I type then drag into the design editor?

The link's down below:

https://developer.android.com/training/basics/firstapp/building-ui.html#textbox

答: If you are using Android Studio 2.3.3, click on Text in the Palette, and Plain Text will be one of the options:

Title: can't find plaint text in android


问:
how to perform cmake::find_package at build stage only
I'm trying to include to make cmake-based project the library vlc-qt, as an external project from github repository.

The project uses recommended way :

```<code>FIND_PACKAGE(VLCQt REQUIRED COMPONENTS Widgets)
</code>```

cmake performs this command at configuration stage so you see that library is not build on that moment.

what is a right way to avoid this?

答:
Put your own project and the VLCQt project into external projects with ExternalProject_Add and create a top-level CMakeLists.txt file to build them one after another.

Your directory structure will look something like this:

```<code>ProjectRoot/
|-- CMakeLists.txt
|-- MyProject/
|   |-- sources/
|   `-- CMakeLists.txt
`-- modules/
    |-- MyProject.cmake
    `-- ExternalVLCQt.cmake
</code>```

The ProjectRoot/modules/ExternalVLCQt.cmake may look like:

```<code>set(VLCQT_ROOT ${EXT_INSTALL_PATH}/vlcqt CACHE INTERNAL "")

ExternalProject_Add(vlcqt
    URL "http://url.of.source/release.0.1.tar.gz"
    CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${VLCQT_ROOT}
    INSTALL_COMMAND make install
)

list(APPEND GLOBAL_THIRDPARTY_LIB_ARGS "-DVLCQT_ROOT:PATH=${VLCQT_ROOT}")
</code>```

The ProjectRoot/modules/MyProject.cmake may look like:

```<code>ExternalProject_Add(my_project
    DEPENDS vlcqt
    SOURCE_DIR ${CMAKE_SOURCE_DIR}/MyProject
    CMAKE_ARGS
        ${GLOBAL_THIRDPARTY_LIB_ARGS}
        -DCMAKE_INSTALL_PREFIX=${EXT_INSTALL_PATH}/my_project
    BUILD_COMMAND make
)
</code>```

Then finally the ProjectRoot/CMakeLists.txt should contain the following:

```<code>cmake_minimum_required(VERSION 3.1.0 FATAL_ERROR)
project(MyProject VERSION 0.1)

set(CMAKE_MODULE_PATH
    "${CMAKE_CURRENT_SOURCE_DIR}/modules"
    ${CMAKE_MODULE_PATH}
)

include(ExternalProject)

set_directory_properties(PROPERTIES EP_BASE ${CMAKE_BINARY_DIR}/ExtProjects)
get_directory_property(EXT_BASE_PATH EP_BASE)

set(EXT_INSTALL_PATH ${EXT_BASE_PATH}/Install)

include(ExternalVLCQt)
include(MyProject)

install(DIRECTORY ${EXT_INSTALL_PATH}/my_project DESTINATION .)
</code>```

You can read more about this pattern here. By this pattern the ProjectRoot/MyProject/CMakeLists.txt will be configured at the build time of the top-level CMakeLists.txt after the vlcqt is built. Therefore the find_package will find the VLCQt package.

Note: In my example the VLCQT_ROOT will be received by the CMakeLists.txt of MyProject where the find_package command is used. This variable is a hint for the find_package command and for different packages this may vary. Every CMake modules used by the find_package has its own varaible requirements.

Body:
I'm trying to include to make cmake-based project the library vlc-qt, as an external project from github repository.

The project uses recommended way :

FIND_PACKAGE(VLCQt REQUIRED COMPONENTS Widgets)

cmake performs this command at configuration stage so you see that library is not build on that moment.

what is a right way to avoid this?

Body:
Put your own project and the VLCQt project into external projects with ExternalProject_Add and create a top-level CMakeLists.txt file to build them one after another.

Your directory structure will look something like this:

ProjectRoot/
|-- CMakeLists.txt
|-- MyProject/
|   |-- sources/
|   `-- CMakeLists.txt
`-- modules/
    |-- MyProject.cmake
    `-- ExternalVLCQt.cmake

The ProjectRoot/modules/ExternalVLCQt.cmake may look like:

set(VLCQT_ROOT ${EXT_INSTALL_PATH}/vlcqt CACHE INTERNAL "")

ExternalProject_Add(vlcqt
    URL "http://url.of.source/release.0.1.tar.gz"
    CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${VLCQT_ROOT}
    INSTALL_COMMAND make install
)

list(APPEND GLOBAL_THIRDPARTY_LIB_ARGS "-DVLCQT_ROOT:PATH=${VLCQT_ROOT}")

The ProjectRoot/modules/MyProject.cmake may look like:

ExternalProject_Add(my_project
    DEPENDS vlcqt
    SOURCE_DIR ${CMAKE_SOURCE_DIR}/MyProject
    CMAKE_ARGS
        ${GLOBAL_THIRDPARTY_LIB_ARGS}
        -DCMAKE_INSTALL_PREFIX=${EXT_INSTALL_PATH}/my_project
    BUILD_COMMAND make
)

Then finally the ProjectRoot/CMakeLists.txt should contain the following:

cmake_minimum_required(VERSION 3.1.0 FATAL_ERROR)
project(MyProject VERSION 0.1)

set(CMAKE_MODULE_PATH
    "${CMAKE_CURRENT_SOURCE_DIR}/modules"
    ${CMAKE_MODULE_PATH}
)

include(ExternalProject)

set_directory_properties(PROPERTIES EP_BASE ${CMAKE_BINARY_DIR}/ExtProjects)
get_directory_property(EXT_BASE_PATH EP_BASE)

set(EXT_INSTALL_PATH ${EXT_BASE_PATH}/Install)

include(ExternalVLCQt)
include(MyProject)

install(DIRECTORY ${EXT_INSTALL_PATH}/my_project DESTINATION .)

You can read more about this pattern here. By this pattern the ProjectRoot/MyProject/CMakeLists.txt will be configured at the build time of the top-level CMakeLists.txt after the vlcqt is built. Therefore the find_package will find the VLCQt package.

Note: In my example the VLCQT_ROOT will be received by the CMakeLists.txt of MyProject where the find_package command is used. This variable is a hint for the find_package command and for different packages this may vary. Every CMake modules used by the find_package has its own varaible requirements.


问:
How filters work? How to make one?
Before you start to hate: I'm not native english speaker and i don't know the exact names of thsese values. Feel free to redirect me to intersting posts/websites.

Start:
Input type: string sent by post method

I'd like how the filters (exactly filver_var) works. Does it remove the 'forbidden' chars from text or can it return false if forbidden chars are used?

How to make my own string filter. I'd like to make filter that alows letters, big letters, numbers and dots.
EDIT: Can I make function that does the same thing?

答:
```<code>filter_var(var, filtername, options)
</code>```

Parameter

Description

var: (Required) The variable to filter

filtername: (Optional)

Specifies the ID or name of the filter to use. Default is
  FILTER_DEFAULT, which results in no filtering.

options: (Optional)

Specifies one or more flags/options to use. Check each filter for
  possible options and flags

Return Value: Returns the filtered data on success, or FALSE on
 failure

```<code>FILTER_VALIDATE_BOOLEAN 258 Validates a boolean
FILTER_VALIDATE_EMAIL 274 Validates an e-mail address
FILTER_VALIDATE_FLOAT 259 Validates a float
FILTER_VALIDATE_INT 257 Validates an integer
FILTER_VALIDATE_IP 275 Validates an IP address
FILTER_VALIDATE_REGEXP 272 Validates a regular expression
FILTER_VALIDATE_URL 273  Validates a URL
FILTER_SANITIZE_EMAIL 517 Removes all illegal characters from an e-mail address
FILTER_SANITIZE_ENCODED 514 Removes/Encodes special characters
FILTER_SANITIZE_MAGIC_QUOTES 521 Apply addslashes()
FILTER_SANITIZE_NUMBER_FLOAT 520 Remove all characters, except digits, +- and optionally .,eE
FILTER_SANITIZE_NUMBER_INT 519 Removes all characters except digits and + -
FILTER_SANITIZE_SPECIAL_CHARS 515 Removes special characters
FILTER_SANITIZE_FULL_SPECIAL_CHARS
FILTER_SANITIZE_STRING 513 Removes tags/special characters from a string
FILTER_SANITIZE_STRIPPED 513 Alias of FILTER_SANITIZE_STRING
FILTER_SANITIZE_URL 518 Removes all illegal character from s URL
FILTER_UNSAFE_RAW 516 Do nothing, optionally strip/encode special characters
FILTER_CALLBACK 1024 Call a user-defined function to filter data
</code>```

Title: How filters work? How to make one?

Body:
filter_var(var, filtername, options)

Parameter

Description

var: (Required) The variable to filter

filtername: (Optional)

Specifies the ID or name of the filter to use. Default is
  FILTER_DEFAULT, which results in no filtering.

options: (Optional)

Specifies one or more flags/options to use. Check each filter for
  possible options and flags

Return Value: Returns the filtered data on success, or FALSE on
 failure

FILTER_VALIDATE_BOOLEAN 258 Validates a boolean
FILTER_VALIDATE_EMAIL 274 Validates an e-mail address
FILTER_VALIDATE_FLOAT 259 Validates a float
FILTER_VALIDATE_INT 257 Validates an integer
FILTER_VALIDATE_IP 275 Validates an IP address
FILTER_VALIDATE_REGEXP 272 Validates a regular expression
FILTER_VALIDATE_URL 273  Validates a URL
FILTER_SANITIZE_EMAIL 517 Removes all illegal characters from an e-mail address
FILTER_SANITIZE_ENCODED 514 Removes/Encodes special characters
FILTER_SANITIZE_MAGIC_QUOTES 521 Apply addslashes()
FILTER_SANITIZE_NUMBER_FLOAT 520 Remove all characters, except digits, +- and optionally .,eE
FILTER_SANITIZE_NUMBER_INT 519 Removes all characters except digits and + -
FILTER_SANITIZE_SPECIAL_CHARS 515 Removes special characters
FILTER_SANITIZE_FULL_SPECIAL_CHARS
FILTER_SANITIZE_STRING 513 Removes tags/special characters from a string
FILTER_SANITIZE_STRIPPED 513 Alias of FILTER_SANITIZE_STRING
FILTER_SANITIZE_URL 518 Removes all illegal character from s URL
FILTER_UNSAFE_RAW 516 Do nothing, optionally strip/encode special characters
FILTER_CALLBACK 1024 Call a user-defined function to filter data


问:
android InstantRun - Norton Security finds Trojan
A week ago Norton Security started to find Trojan horse (Trojan.Gen.NPE.2) in file R.class located:

app\build\intermediates\transforms\instantrun\debug\folders\1\5\main\android\support\v4\ r.class

and

app\build\intermediates\transforms\instantrunslicer\debug\folders\1\5\slice_2\android\support\v4\ r.class

Link to virustotal.com scan: https://www.virustotal.com/pl/file/282f4e09c102cd93c2f849c9fe9ed570188f5a03395ab84d2457a7c64d7acb1c/analysis/1499458308/

And the code:

```<code>package android.support.v4;

import com.android.tools.fd.runtime.IncrementalChange;
import com.android.tools.fd.runtime.InstantReloadException;

public final class R {
    public static final long serialVersionUID = 830508538663712626L;

    public R() {
        IncrementalChange var1 = $change;
        if(var1 != null) {
            Object[] var10001 = (Object[])var1.access$dispatch("init$args.([Landroid/support/v4/R;[Ljava/lang/Object;)Ljava/lang/Object;", new Object[]{null, new Object[0]});
            Object[] var2 = (Object[])var10001[0];
            this(var10001, (InstantReloadException)null);
            var2[0] = this;
            var1.access$dispatch("init$body.(Landroid/support/v4/R;[Ljava/lang/Object;)V", var2);
        } else {
            super();
        }
    }

    R(Object[] var1, InstantReloadException var2) {
        String var3 = (String)var1[1];
        switch(var3.hashCode()) {
        case -1968665286:
            super();
            return;
        case -71951640:
            this();
            return;
        default:
            throw new InstantReloadException(String.format("String switch could not find \'%s\' with hashcode %s in %s", new Object[]{var3, Integer.valueOf(var3.hashCode()), "android/support/v4/R"}));
        }
    }
}
</code>```

Is it false alarm?

答:
I cant add exclusions in Symantec on my laptop as its company's laptop and excluding applications, files or folders feature is deactivated. So in order to get going i have disabled instant run to get going else i can't even install app on my emulator and get stuck with installation errors.

You can disable instant run by unchecking instant run in Settings in Android Studio.

NOTE: This is just workaround and not permanent solution.

Body:
A week ago Norton Security started to find Trojan horse (Trojan.Gen.NPE.2) in file R.class located:

app\build\intermediates\transforms\instantrun\debug\folders\1\5\main\android\support\v4\ r.class

and

app\build\intermediates\transforms\instantrunslicer\debug\folders\1\5\slice_2\android\support\v4\ r.class

Link to virustotal.com scan: https://www.virustotal.com/pl/file/282f4e09c102cd93c2f849c9fe9ed570188f5a03395ab84d2457a7c64d7acb1c/analysis/1499458308/

And the code:

package android.support.v4;

import com.android.tools.fd.runtime.IncrementalChange;
import com.android.tools.fd.runtime.InstantReloadException;

public final class R {
    public static final long serialVersionUID = 830508538663712626L;

    public R() {
        IncrementalChange var1 = $change;
        if(var1 != null) {
            Object[] var10001 = (Object[])var1.access$dispatch("init$args.([Landroid/support/v4/R;[Ljava/lang/Object;)Ljava/lang/Object;", new Object[]{null, new Object[0]});
            Object[] var2 = (Object[])var10001[0];
            this(var10001, (InstantReloadException)null);
            var2[0] = this;
            var1.access$dispatch("init$body.(Landroid/support/v4/R;[Ljava/lang/Object;)V", var2);
        } else {
            super();
        }
    }

    R(Object[] var1, InstantReloadException var2) {
        String var3 = (String)var1[1];
        switch(var3.hashCode()) {
        case -1968665286:
            super();
            return;
        case -71951640:
            this();
            return;
        default:
            throw new InstantReloadException(String.format("String switch could not find \'%s\' with hashcode %s in %s", new Object[]{var3, Integer.valueOf(var3.hashCode()), "android/support/v4/R"}));
        }
    }
}

Is it false alarm?


问:
Sum a list of numbers in Python
Given a list of numbers such as:

```<code>[1, 2, 3, 4, 5, ...]
</code>```

How do I calculate their total sum:

```<code>1 + 2 + 3 + 4 + 5 + ...
</code>```

How do I calculate their pairwise averages:

```<code>[(1+2)/2, (2+3)/2, (3+4)/2, (4+5)/2, ...]
</code>```

答:
Loop through elements in the list and update the total like this:</p>

```<code>def sum(a):
    total = 0
    index = 0
    while index < len(a):
        total = total + a[index]
        index = index + 1
    return total
</code>```

ContentLicense: CC BY-SA 4.0

Title: Sum a list of numbers in Python

Body:
Given a list of numbers such as:

[1, 2, 3, 4, 5, ...]

How do I calculate their total sum:

1 + 2 + 3 + 4 + 5 + ...

How do I calculate their pairwise averages:

[(1+2)/2, (2+3)/2, (3+4)/2, (4+5)/2, ...]

Body:
Loop through elements in the list and update the total like this:

def sum(a):
    total = 0
    index = 0
    while index < len(a):
        total = total + a[index]
        index = index + 1
    return total


问:
custom font will not display not matter what i do
i want to add a custom font to my html page, but it does not work, i tried everything possible, checked other questions, trying to solve it their way, but nothing.

the font is in the same folder as my html file(the css is in the html file)

In html css i wrote:

```<code>@font-face {
    font-family: regular;
    src: url("8bitoperator_jve.ttf");
    //src: local("8bitoperator_jve.ttf"); i tried this too
}
body {
    background-color: #000;
    color: #FFF;
    font-family: regular;
}
</code>```

答:
You should find a specific font in local, but a font file in url. I mean, the local font doesn't need any path or file extension whereas a font file need it. If you want to target a local files first you can try like that:

```<code>@font-face {
    font-family: regular;
    src: local("8bitoperator_jve"),url("8bitoperator_jve.ttf") format('truetype');
}
</code>```

Also you can try loading the font-face from an external CSS file.

Body:
i want to add a custom font to my html page, but it does not work, i tried everything possible, checked other questions, trying to solve it their way, but nothing.

the font is in the same folder as my html file(the css is in the html file)

In html css i wrote:

@font-face {
    font-family: regular;
    src: url("8bitoperator_jve.ttf");
    //src: local("8bitoperator_jve.ttf"); i tried this too
}
body {
    background-color: #000;
    color: #FFF;
    font-family: regular;
}

Body:
You should find a specific font in local, but a font file in url. I mean, the local font doesn't need any path or file extension whereas a font file need it. If you want to target a local files first you can try like that:

@font-face {
    font-family: regular;
    src: local("8bitoperator_jve"),url("8bitoperator_jve.ttf") format('truetype');
}

Also you can try loading the font-face from an external CSS file.


答:
You can suppress the space by printing an empty string to stdout between the print statements.

```<code>>>> import sys
>>> for i in range(20):
...   print 'a',
...   sys.stdout.write('')
...
aaaaaaaaaaaaaaaaaaaa
</code>```

However, a cleaner solution is to first build the entire string you'd like to print and then output it with a single print statement.

Title: Printing without newline (print 'a',) prints a space, how to remove?

Body:
You can suppress the space by printing an empty string to stdout between the print statements.

>>> import sys
>>> for i in range(20):
...   print 'a',
...   sys.stdout.write('')
...
aaaaaaaaaaaaaaaaaaaa

However, a cleaner solution is to first build the entire string you'd like to print and then output it with a single print statement.


问:
javascript array - separate values and values of values by single quotes
I have an array that looks like this:

```<code>var array = ["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"]
</code>```

I want to return the results like this:

```<code>'Rock Paper','Shoot','Dulce','Once','Apple Mic','Chairs'
</code>```

This is what I have done so far:

```<code>includes = tagsI.map(tag => `'${tag}'`).join(',')
</code>```

But this only separates by commas and single quotes the values.. not the values of the values as well.

How can I do this?

Thank you

答:
Join the items of the array to a single string with commas. Split the string by the comma separators, map the items to the required format, and join again with commas.

const array = ["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"]

const result = array
  .join(',')
  .split(',')
  .map(tag => `'${tag}'`)
  .join(',');

console.log(result);```

Body:
I have an array that looks like this:

var array = ["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"]

I want to return the results like this:

'Rock Paper','Shoot','Dulce','Once','Apple Mic','Chairs'

This is what I have done so far:

includes = tagsI.map(tag => `'${tag}'`).join(',')

But this only separates by commas and single quotes the values.. not the values of the values as well.

How can I do this?

Thank you


问:
Pythonic way to merge keys with common values for a single dictionary
How do I merge the keys of a dictionary with common values into a tuple. For example:

```<code>A = {'E2': {'5', '7'}, 'E3': {'4', '8'}, 'E5': {'5', '7'}, 'E8': {'4', '8'}}

output = {('E2', 'E5'): {'5', '7'}, ('E3', 'E8'): {'4', '8'}}
</code>```

My attempt:

```<code>A = {'E2': {'5', '7'}, 'E3': {'4', '8'}, 'E5': {'5', '7'}, 'E8': {'4', '8'}}

output = {}
seen = []
for k, v in A.items():
    if v not in [s[1] for s in seen]: # not seen this value yet
        print('NOT SEEN')
        print(k, v)
        seen.append([k,v])
        output[k] = v
    else: # already seen it
        print('SEEN')
        print(k, v)
        # determine where we've seen it
        where = [x for x in seen if x[1]==v]
        output.pop(where[0][0])
        output[(where[0][0], k)] = v

print('OUTPUT = ', output)
</code>```

This prints:

```<code>OUTPUT =  {('E2', 'E5'): {'7', '5'}, ('E3', 'E8'): {'4', '8'}}
</code>```

答:
import itertools

A = {'E2': {'5', '7'}, 'E3': {'4', '8'}, 'E5': {'5', '7'}, 'E8': {'4', '8'}}

def key(x):
    # List supports ordering
    return sorted(list(x[1]))

def gen():
    for (group_key, group) in itertools.groupby(sorted(A.items(), key=key), key=key):
        gl = list(group)
        yield (tuple(x[0] for x in gl),
               gl[0][1]  # group_key is a list, but we want original set
              )

print(dict(gen()))
```

<p>If you are ready to convince yourself that set->list->set conversion is safe then you can make one-liner instead of generator:</p>

```print(dict((tuple(g[0] for g in group), set(group_key)) for
           (group_key, group) in
           itertools.groupby(sorted(A.items(), key=key), key=key)))
```

<p><strong>UPD: So, what exactly is going on here?</strong></p>

<p>First of all we are converting dict to iterable of tuples by calling <code>.items()</code>.
We want to group together items of this iterable which has the same second element (with index 1, or the former dict value).
This is exactly what <code>itertools.groupby</code> does. The arguments is an iterable and key by which we will group. It would seem, <code>key=lambda kv: kv[1]</code> is way to go. Unfortunately not. We can compare sets for equality, but the docs say that iterable should be ordered. And <code>sorted</code> function requires key comparable for order. Sets cannot be compared for order by lists can. We can safely create a list that contain the same elements as set, but we should sort it (equal sets can produce lists with different order, <code>{5, 7} == {7, 5}</code>, but <code>[5, 7] != [7, 5]</code>).</p>

<p>Now, after sorting and grouping we have the following data structure:</p>

```[
   (key_dict_value as list, iterable of (dict_key, dict_value) that has dict_value == key_dict_value),
   ...
]
```

<p>Now we can iterate over this iterable and create another iterable of tuples. We take second element (iterable, with index 1) of each tuple and convert it to a tuple (this is the key of our future dictionary). The value of our future dictionary is a value from original dictionary. We can take it either from some element of the second element of the tuple (this iterable cannot be empty since <code>groupby</code> cannot produce empty groups, see the first snippet) or from <code>key_dict_value</code> by converting it back to list (it is safe because this list was produced from the set, so it does not have equal elements, see the second snippet).</p>

<p><strong>UPD2</strong></p>

<p>While I was writing explanation I figured out that key for equality is not fine for <code>sorted</code> but fine for <code>groupby</code>, so here is even simpler solution without defining <code>key</code> function and converting list back to set:</p>

```print(dict((tuple(g[0] for g in group), group_key) for
           (group_key, group) in itertools.groupby(sorted(A.items(),
                                                          key=lambda x: sorted(list(x[1]))),
                                                   key=lambda x: x[1])))
```

Body:
How do I merge the keys of a dictionary with common values into a tuple. For example:

A = {'E2': {'5', '7'}, 'E3': {'4', '8'}, 'E5': {'5', '7'}, 'E8': {'4', '8'}}

output = {('E2', 'E5'): {'5', '7'}, ('E3', 'E8'): {'4', '8'}}

My attempt:

A = {'E2': {'5', '7'}, 'E3': {'4', '8'}, 'E5': {'5', '7'}, 'E8': {'4', '8'}}

output = {}
seen = []
for k, v in A.items():
    if v not in [s[1] for s in seen]: # not seen this value yet
        print('NOT SEEN')
        print(k, v)
        seen.append([k,v])
        output[k] = v
    else: # already seen it
        print('SEEN')
        print(k, v)
        # determine where we've seen it
        where = [x for x in seen if x[1]==v]
        output.pop(where[0][0])
        output[(where[0][0], k)] = v

print('OUTPUT = ', output)

This prints:

OUTPUT =  {('E2', 'E5'): {'7', '5'}, ('E3', 'E8'): {'4', '8'}}

Body:
import itertools

A = {'E2': {'5', '7'}, 'E3': {'4', '8'}, 'E5': {'5', '7'}, 'E8': {'4', '8'}}

def key(x):
    # List supports ordering
    return sorted(list(x[1]))

def gen():
    for (group_key, group) in itertools.groupby(sorted(A.items(), key=key), key=key):
        gl = list(group)
        yield (tuple(x[0] for x in gl),
               gl[0][1]  # group_key is a list, but we want original set
              )

print(dict(gen()))

If you are ready to convince yourself that set->list->set conversion is safe then you can make one-liner instead of generator:

print(dict((tuple(g[0] for g in group), set(group_key)) for
           (group_key, group) in
           itertools.groupby(sorted(A.items(), key=key), key=key)))

UPD: So, what exactly is going on here?

First of all we are converting dict to iterable of tuples by calling .items().
We want to group together items of this iterable which has the same second element (with index 1, or the former dict value).
This is exactly what itertools.groupby does. The arguments is an iterable and key by which we will group. It would seem, key=lambda kv: kv[1] is way to go. Unfortunately not. We can compare sets for equality, but the docs say that iterable should be ordered. And sorted function requires key comparable for order. Sets cannot be compared for order by lists can. We can safely create a list that contain the same elements as set, but we should sort it (equal sets can produce lists with different order, {5, 7} == {7, 5}, but [5, 7] != [7, 5]).

Now, after sorting and grouping we have the following data structure:

[
   (key_dict_value as list, iterable of (dict_key, dict_value) that has dict_value == key_dict_value),
   ...
]

Now we can iterate over this iterable and create another iterable of tuples. We take second element (iterable, with index 1) of each tuple and convert it to a tuple (this is the key of our future dictionary). The value of our future dictionary is a value from original dictionary. We can take it either from some element of the second element of the tuple (this iterable cannot be empty since groupby cannot produce empty groups, see the first snippet) or from key_dict_value by converting it back to list (it is safe because this list was produced from the set, so it does not have equal elements, see the second snippet).

UPD2

While I was writing explanation I figured out that key for equality is not fine for sorted but fine for groupby, so here is even simpler solution without defining key function and converting list back to set:

print(dict((tuple(g[0] for g in group), group_key) for
           (group_key, group) in itertools.groupby(sorted(A.items(),
                                                          key=lambda x: sorted(list(x[1]))),
                                                   key=lambda x: x[1])))


答:
Have nothing on Hamish's answer, he is 100% right. But if you wanna super simple solution without any explanation or code just work, when working with array of generics protocol, use this:</p>

```<code>func f1<T: SomeProtocol>(ofType: T.Type, listener: (T?) -> Void) {
}

func f2<Z: SomeProtocol>(ofType: Z.Type, listener: ([SomeProtocol]?) -> Void) {
}
</code>```

Title: Swift Generics: Cannot convert value of type to expected argument type

Body:
Here is my code:

protocol SomeProtocol {
}

class A: SomeProtocol {
}

func f1<T: SomeProtocol>(ofType: T.Type, listener: (T?) -> Void) {
}

func f2<T: SomeProtocol>(ofType: T.Type, listener: ([T]?) -> Void) {
}

func g() {
    let l1: (SomeProtocol?) -> Void = ...
    let l2: ([SomeProtocol]?) -> Void = ...
    f1(ofType: A.self, listener: l1) // NO ERROR
    f2(ofType: A.self, listener: l2) // COMPILE ERROR: Cannot convert value of type '([SomeProtocol]?) -> Void' to expected argument type '([_]?) -> Void'
}

What is the problem with the second closure having an argument of an array of generic type objects?

Body:
Have nothing on Hamish's answer, he is 100% right. But if you wanna super simple solution without any explanation or code just work, when working with array of generics protocol, use this:

func f1<T: SomeProtocol>(ofType: T.Type, listener: (T?) -> Void) {
}

func f2<Z: SomeProtocol>(ofType: Z.Type, listener: ([SomeProtocol]?) -> Void) {
}


问:
what's the gradle alternative to a fat JAR?
If transitive libs aren't packaged with the JAR task:

```<code>By default, jar task in gradle builds an executable jar file from your project source files. It will not contain any transitive libs that are needed for your program.
</code>```

To the contrary, Netbeans does package JAR dependencies or transitive libs.  Rather than a fat JAR how does gradle include libs?

```<code>plugins {
    id 'com.gradle.build-scan' version '1.8'
    id 'java'
    id 'application'
}

mainClassName = 'net.bounceme.dur.mbaas.json.Main'

buildScan {
    licenseAgreementUrl = 'https://gradle.com/terms-of-service'
    licenseAgree = 'yes'
}

repositories {
    jcenter()
}

jar {
    manifest {
        attributes 'Main-Class': 'net.bounceme.dur.mbaas.json.Main'
    }
}

dependencies {
    //compile fileTree(dir: 'libs', include: ['*.jar'])
    runtime group: 'com.google.firebase', name: 'firebase-admin', version: '5.2.0'
    compile fileTree(dir: 'lib', include: '*.jar')
}
</code>```

in relation to another question:  what's the "way" to package libs with the JAR task which doesn't result in a "fat JAR"?

答:
When using the application plugin, all libraries used by the application (own jar or transitive libraries) are put in a libs folder when packaged as an app. then these libs are referenced in the shell or batch script as classpath when launching the app.

The easiest way to create a fatjar in gradle, is to use the shadow plugin available via the plugin portal. see https://plugins.gradle.org/plugin/com.github.johnrengelman.plugin-shadow for details

Body:
If transitive libs aren't packaged with the JAR task:

By default, jar task in gradle builds an executable jar file from your project source files. It will not contain any transitive libs that are needed for your program.

To the contrary, Netbeans does package JAR dependencies or transitive libs.  Rather than a fat JAR how does gradle include libs?

plugins {
    id 'com.gradle.build-scan' version '1.8'
    id 'java'
    id 'application'
}

mainClassName = 'net.bounceme.dur.mbaas.json.Main'

buildScan {
    licenseAgreementUrl = 'https://gradle.com/terms-of-service'
    licenseAgree = 'yes'
}

repositories {
    jcenter()
}

jar {
    manifest {
        attributes 'Main-Class': 'net.bounceme.dur.mbaas.json.Main'
    }
}

dependencies {
    //compile fileTree(dir: 'libs', include: ['*.jar'])
    runtime group: 'com.google.firebase', name: 'firebase-admin', version: '5.2.0'
    compile fileTree(dir: 'lib', include: '*.jar')
}

in relation to another question:  what's the "way" to package libs with the JAR task which doesn't result in a "fat JAR"?