问:
Trying to create a data pipeline with Rx .Net
I've been trying to pipeline some data using Rx .Net but I'm really struggling.

I've got a sequence of unsaved Foos which have some data. The Foos create a collection of Bars. After the bars have been saved, if the Bar has a BarId, the data from the Foo and the BarId from the Bar are used to create a Baz. Once all the Bars and Bazs for the Foo have been created, the Foo's data is cleared and the Foo is saved. Here are the classes:

```<code>public class Base
{
    public Guid Id { get; set; } = Guid.Empty;

    public override string ToString()
    {
        return $"{GetType().Name}::Id:{Id}";
    }

    public Task<Unit> Save()
    {
        Id = Guid.NewGuid();

        Console.WriteLine($"{ToString()} (save)");

        return Task.FromResult(Unit.Default);
    }
}

public sealed class Foo : Base
{
    public long FooId { get; }

    public string Data { get; private set; }

    public override string ToString()
    {
        return $"{base.ToString()},FooId:{FooId},Data:{Data ?? "NULL"}";
    }

    public Task<Unit> ClearData()
    {
        Data = null;

        return Task.FromResult(Unit.Default);
    }

    public Foo(long index)
    {
        FooId = index;
        Data = $"Foo({index})";

        Console.WriteLine($"{ToString()} (ctor)");
    }
}

public class Map : Base
{
    public int Index { get; }

    public string Mapping { get; }

    public Guid BarId { get; protected set; } = Guid.Empty;

    public sealed override string ToString()
    {
        return $"{base.ToString()},Index:{Index},BarId:{BarId},Mapping:{Mapping}";
    }

    protected Map(int index, string data, Func<string, string> mapper)
    {
        Mapping = mapper(data);
        Index = index;
    }
}

public sealed class Bar : Map
{
    public Bar(int index, string data, Func<string, string> mapper) : base(index, data, mapper)
    {
        if (new Random().Next(3) > 0)
        {
            BarId = Guid.NewGuid();

            Console.WriteLine($"{ToString()} (ctor)");
        }
    }
}

public sealed class Baz : Map
{
    public Baz(int index, Guid barId, string data, Func<string, string> mapper) : base(index, data, mapper)
    {
        BarId = barId;

        Console.WriteLine($"{ToString()} (ctor)");
    }
}
</code>```

I tried a number of things, but this one is the closest I got to what I'm looking for:

```<code>var foos = Observable.Interval(TimeSpan.FromSeconds(1)).Take(2).Select(i => new Foo(i));

var units = from foo in foos
            let idxs = Observable.Range(1, 3)
            from idx in idxs
            let bar = new Bar(idx, foo.Data, s => $"{s}Bar")
            from barSaved in bar.Save()
            where bar.BarId != Guid.Empty
            let baz = new Baz(idx, bar.BarId, foo.Data, s => $"{s}Baz")
            from bazSaved in baz.Save()
            from fooChanged in foo.ClearData()
            from fooSaved in foo.Save()
            select Unit.Default;

units.Subscribe();
</code>```

It creates the right amount of Bars and Bazs but it saves the Foo every time a saved Baz is created or never if there are no Bazs.

I'm hoping someone can help me out and maybe I'll also learn something new about Reactive Programming that will help me get a better understanding of the paradigm.

Edit:

I tried moving the Random number provider to a static instance but it didn't work. Here's some output that shows what occurs:

```<code>Foo::Id:00000000-0000-0000-0000-000000000000,FooId:0,Data:Foo(0) (ctor)
Bar::Id:00000000-0000-0000-0000-000000000000,Index:1,BarId:00000000-0000-0000-0000-000000000000,Mapping:Foo(0)Bar (ctor)
Bar::Id:28789b8b-03d4-4160-97f2-b2cbafd80c73,Index:1,BarId:00000000-0000-0000-0000-000000000000,Mapping:Foo(0)Bar (save)
Bar::Id:00000000-0000-0000-0000-000000000000,Index:2,BarId:81e79b81-6692-406f-a025-448cd203cb73,Mapping:Foo(0)Bar (ctor)
Bar::Id:d43d2e43-b812-4657-9e4f-a5b875a595fb,Index:2,BarId:81e79b81-6692-406f-a025-448cd203cb73,Mapping:Foo(0)Bar (save)
Baz::Id:00000000-0000-0000-0000-000000000000,Index:2,BarId:81e79b81-6692-406f-a025-448cd203cb73,Mapping:Foo(0)Baz (ctor)
Baz::Id:fdf464d1-9240-49e4-89cd-dbab758159fc,Index:2,BarId:81e79b81-6692-406f-a025-448cd203cb73,Mapping:Foo(0)Baz (save)
Foo::Id:04d9d819-26bc-41dc-8f1b-a0e509acd2e5,FooId:0,Data:NULL (save)
Bar::Id:00000000-0000-0000-0000-000000000000,Index:3,BarId:6894c1f0-d776-496f-9da4-4f272a338f90,Mapping:Bar (ctor)
Bar::Id:6b82fc20-80ff-41bd-848d-a115f58392c4,Index:3,BarId:6894c1f0-d776-496f-9da4-4f272a338f90,Mapping:Bar (save)
Baz::Id:00000000-0000-0000-0000-000000000000,Index:3,BarId:6894c1f0-d776-496f-9da4-4f272a338f90,Mapping:Baz (ctor)
Baz::Id:fa361c43-ee07-44cc-8628-4835fce6da9d,Index:3,BarId:6894c1f0-d776-496f-9da4-4f272a338f90,Mapping:Baz (save)
Foo::Id:6f423cf5-8260-4d98-a0bc-4762893b5fe4,FooId:0,Data:NULL (save)
Foo::Id:00000000-0000-0000-0000-000000000000,FooId:1,Data:Foo(1) (ctor)
Bar::Id:00000000-0000-0000-0000-000000000000,Index:1,BarId:5a79b126-27d8-43a1-9bb6-4d28394d5710,Mapping:Foo(1)Bar (ctor)
Bar::Id:94f5842f-eb1c-4248-a70a-dac5eb843cc1,Index:1,BarId:5a79b126-27d8-43a1-9bb6-4d28394d5710,Mapping:Foo(1)Bar (save)
Baz::Id:00000000-0000-0000-0000-000000000000,Index:1,BarId:5a79b126-27d8-43a1-9bb6-4d28394d5710,Mapping:Foo(1)Baz (ctor)
Baz::Id:d46b1d7e-eda2-4c63-8810-830e3416e975,Index:1,BarId:5a79b126-27d8-43a1-9bb6-4d28394d5710,Mapping:Foo(1)Baz (save)
Foo::Id:e198e636-bfd7-49c5-a260-346524ec4019,FooId:1,Data:NULL (save)
Bar::Id:00000000-0000-0000-0000-000000000000,Index:2,BarId:00000000-0000-0000-0000-000000000000,Mapping:Bar (ctor)
Bar::Id:206a8796-32da-493f-9582-7c551781e2d5,Index:2,BarId:00000000-0000-0000-0000-000000000000,Mapping:Bar (save)
Bar::Id:00000000-0000-0000-0000-000000000000,Index:3,BarId:154481ad-33c3-49d7-af2b-3f7738f1f692,Mapping:Bar (ctor)
Bar::Id:ffda6907-93b0-411f-aa40-3fee790b52cb,Index:3,BarId:154481ad-33c3-49d7-af2b-3f7738f1f692,Mapping:Bar (save)
Baz::Id:00000000-0000-0000-0000-000000000000,Index:3,BarId:154481ad-33c3-49d7-af2b-3f7738f1f692,Mapping:Baz (ctor)
Baz::Id:2071927f-27d6-4df6-a74f-1c0bdfbba8d5,Index:3,BarId:154481ad-33c3-49d7-af2b-3f7738f1f692,Mapping:Baz (save)
Foo::Id:07460e6e-d3db-4ed8-a441-e16f06cd908a,FooId:1,Data:NULL (save)
</code>```

As you can see, when a Baz is saved, the Foo clears its data and saves, making all the subsequent Bars and Bazs lose their data - see their Mapping has no Foo(index).

Edit:

What I'm trying to achieve is that once all the Bars and Bazs for a Foo have been created and saved, only then is the Foo's data cleared and a save done.

Edited source code to include tracing.

答:
I think your problem is the if (new Random().Next(3) > 0). The Random object seeds from the system clock so if this code is called in rapid succession you get the same value. Try it this way:

```<code>public sealed class Bar : Map
{
    public static Random _rand = new Random();
    public Bar(int index, string data, Func<string, string> mapper) : base(index, data, mapper)
    {
        if (_rand.Next(3) > 0)
        {
            BarId = Guid.NewGuid();
        }
    }
}
</code>```

It appears to give the right kind of result then.

I would keep the Random instance outside the method and then try this:

```<code>var units =
    from foo in foos
    from inner in
    (
        from idx in Observable.Range(1, 3)
        let bar = new Bar(idx, foo.Data, s => $"{s}Bar")
        from barSaved in bar.Save()
        where bar.BarId != Guid.Empty
        let baz = new Baz(idx, bar.BarId, foo.Data, s => $"{s}Baz")
        from bazSaved in baz.Save()
        select Unit.Default
    ).ToArray()
    from fooChanged in foo.ClearData()
    from fooSaved in foo.Save()
    select Unit.Default;
</code>```

Body:
I've been trying to pipeline some data using Rx .Net but I'm really struggling.

I've got a sequence of unsaved Foos which have some data. The Foos create a collection of Bars. After the bars have been saved, if the Bar has a BarId, the data from the Foo and the BarId from the Bar are used to create a Baz. Once all the Bars and Bazs for the Foo have been created, the Foo's data is cleared and the Foo is saved. Here are the classes:

public class Base
{
    public Guid Id { get; set; } = Guid.Empty;

    public override string ToString()
    {
        return $"{GetType().Name}::Id:{Id}";
    }

    public Task<Unit> Save()
    {
        Id = Guid.NewGuid();

        Console.WriteLine($"{ToString()} (save)");

        return Task.FromResult(Unit.Default);
    }
}

public sealed class Foo : Base
{
    public long FooId { get; }

    public string Data { get; private set; }

    public override string ToString()
    {
        return $"{base.ToString()},FooId:{FooId},Data:{Data ?? "NULL"}";
    }

    public Task<Unit> ClearData()
    {
        Data = null;

        return Task.FromResult(Unit.Default);
    }

    public Foo(long index)
    {
        FooId = index;
        Data = $"Foo({index})";

        Console.WriteLine($"{ToString()} (ctor)");
    }
}

public class Map : Base
{
    public int Index { get; }

    public string Mapping { get; }

    public Guid BarId { get; protected set; } = Guid.Empty;

    public sealed override string ToString()
    {
        return $"{base.ToString()},Index:{Index},BarId:{BarId},Mapping:{Mapping}";
    }

    protected Map(int index, string data, Func<string, string> mapper)
    {
        Mapping = mapper(data);
        Index = index;
    }
}

public sealed class Bar : Map
{
    public Bar(int index, string data, Func<string, string> mapper) : base(index, data, mapper)
    {
        if (new Random().Next(3) > 0)
        {
            BarId = Guid.NewGuid();

            Console.WriteLine($"{ToString()} (ctor)");
        }
    }
}

public sealed class Baz : Map
{
    public Baz(int index, Guid barId, string data, Func<string, string> mapper) : base(index, data, mapper)
    {
        BarId = barId;

        Console.WriteLine($"{ToString()} (ctor)");
    }
}

I tried a number of things, but this one is the closest I got to what I'm looking for:

var foos = Observable.Interval(TimeSpan.FromSeconds(1)).Take(2).Select(i => new Foo(i));

var units = from foo in foos
            let idxs = Observable.Range(1, 3)
            from idx in idxs
            let bar = new Bar(idx, foo.Data, s => $"{s}Bar")
            from barSaved in bar.Save()
            where bar.BarId != Guid.Empty
            let baz = new Baz(idx, bar.BarId, foo.Data, s => $"{s}Baz")
            from bazSaved in baz.Save()
            from fooChanged in foo.ClearData()
            from fooSaved in foo.Save()
            select Unit.Default;

units.Subscribe();

It creates the right amount of Bars and Bazs but it saves the Foo every time a saved Baz is created or never if there are no Bazs.

I'm hoping someone can help me out and maybe I'll also learn something new about Reactive Programming that will help me get a better understanding of the paradigm.

Edit:

I tried moving the Random number provider to a static instance but it didn't work. Here's some output that shows what occurs:

Foo::Id:00000000-0000-0000-0000-000000000000,FooId:0,Data:Foo(0) (ctor)
Bar::Id:00000000-0000-0000-0000-000000000000,Index:1,BarId:00000000-0000-0000-0000-000000000000,Mapping:Foo(0)Bar (ctor)
Bar::Id:28789b8b-03d4-4160-97f2-b2cbafd80c73,Index:1,BarId:00000000-0000-0000-0000-000000000000,Mapping:Foo(0)Bar (save)
Bar::Id:00000000-0000-0000-0000-000000000000,Index:2,BarId:81e79b81-6692-406f-a025-448cd203cb73,Mapping:Foo(0)Bar (ctor)
Bar::Id:d43d2e43-b812-4657-9e4f-a5b875a595fb,Index:2,BarId:81e79b81-6692-406f-a025-448cd203cb73,Mapping:Foo(0)Bar (save)
Baz::Id:00000000-0000-0000-0000-000000000000,Index:2,BarId:81e79b81-6692-406f-a025-448cd203cb73,Mapping:Foo(0)Baz (ctor)
Baz::Id:fdf464d1-9240-49e4-89cd-dbab758159fc,Index:2,BarId:81e79b81-6692-406f-a025-448cd203cb73,Mapping:Foo(0)Baz (save)
Foo::Id:04d9d819-26bc-41dc-8f1b-a0e509acd2e5,FooId:0,Data:NULL (save)
Bar::Id:00000000-0000-0000-0000-000000000000,Index:3,BarId:6894c1f0-d776-496f-9da4-4f272a338f90,Mapping:Bar (ctor)
Bar::Id:6b82fc20-80ff-41bd-848d-a115f58392c4,Index:3,BarId:6894c1f0-d776-496f-9da4-4f272a338f90,Mapping:Bar (save)
Baz::Id:00000000-0000-0000-0000-000000000000,Index:3,BarId:6894c1f0-d776-496f-9da4-4f272a338f90,Mapping:Baz (ctor)
Baz::Id:fa361c43-ee07-44cc-8628-4835fce6da9d,Index:3,BarId:6894c1f0-d776-496f-9da4-4f272a338f90,Mapping:Baz (save)
Foo::Id:6f423cf5-8260-4d98-a0bc-4762893b5fe4,FooId:0,Data:NULL (save)
Foo::Id:00000000-0000-0000-0000-000000000000,FooId:1,Data:Foo(1) (ctor)
Bar::Id:00000000-0000-0000-0000-000000000000,Index:1,BarId:5a79b126-27d8-43a1-9bb6-4d28394d5710,Mapping:Foo(1)Bar (ctor)
Bar::Id:94f5842f-eb1c-4248-a70a-dac5eb843cc1,Index:1,BarId:5a79b126-27d8-43a1-9bb6-4d28394d5710,Mapping:Foo(1)Bar (save)
Baz::Id:00000000-0000-0000-0000-000000000000,Index:1,BarId:5a79b126-27d8-43a1-9bb6-4d28394d5710,Mapping:Foo(1)Baz (ctor)
Baz::Id:d46b1d7e-eda2-4c63-8810-830e3416e975,Index:1,BarId:5a79b126-27d8-43a1-9bb6-4d28394d5710,Mapping:Foo(1)Baz (save)
Foo::Id:e198e636-bfd7-49c5-a260-346524ec4019,FooId:1,Data:NULL (save)
Bar::Id:00000000-0000-0000-0000-000000000000,Index:2,BarId:00000000-0000-0000-0000-000000000000,Mapping:Bar (ctor)
Bar::Id:206a8796-32da-493f-9582-7c551781e2d5,Index:2,BarId:00000000-0000-0000-0000-000000000000,Mapping:Bar (save)
Bar::Id:00000000-0000-0000-0000-000000000000,Index:3,BarId:154481ad-33c3-49d7-af2b-3f7738f1f692,Mapping:Bar (ctor)
Bar::Id:ffda6907-93b0-411f-aa40-3fee790b52cb,Index:3,BarId:154481ad-33c3-49d7-af2b-3f7738f1f692,Mapping:Bar (save)
Baz::Id:00000000-0000-0000-0000-000000000000,Index:3,BarId:154481ad-33c3-49d7-af2b-3f7738f1f692,Mapping:Baz (ctor)
Baz::Id:2071927f-27d6-4df6-a74f-1c0bdfbba8d5,Index:3,BarId:154481ad-33c3-49d7-af2b-3f7738f1f692,Mapping:Baz (save)
Foo::Id:07460e6e-d3db-4ed8-a441-e16f06cd908a,FooId:1,Data:NULL (save)

As you can see, when a Baz is saved, the Foo clears its data and saves, making all the subsequent Bars and Bazs lose their data - see their Mapping has no Foo(index).

Edit:

What I'm trying to achieve is that once all the Bars and Bazs for a Foo have been created and saved, only then is the Foo's data cleared and a save done.

Edited source code to include tracing.

Body:
I think your problem is the if (new Random().Next(3) > 0). The Random object seeds from the system clock so if this code is called in rapid succession you get the same value. Try it this way:

public sealed class Bar : Map
{
    public static Random _rand = new Random();
    public Bar(int index, string data, Func<string, string> mapper) : base(index, data, mapper)
    {
        if (_rand.Next(3) > 0)
        {
            BarId = Guid.NewGuid();
        }
    }
}

It appears to give the right kind of result then.

I would keep the Random instance outside the method and then try this:

var units =
    from foo in foos
    from inner in
    (
        from idx in Observable.Range(1, 3)
        let bar = new Bar(idx, foo.Data, s => $"{s}Bar")
        from barSaved in bar.Save()
        where bar.BarId != Guid.Empty
        let baz = new Baz(idx, bar.BarId, foo.Data, s => $"{s}Baz")
        from bazSaved in baz.Save()
        select Unit.Default
    ).ToArray()
    from fooChanged in foo.ClearData()
    from fooSaved in foo.Save()
    select Unit.Default;


来源: stackexchange

问:
How to stack two images and center in the middle
I want the images to be centered  and I need two of the images to be stacked up on each other in the center. I have logo on the left and nav bar on the right

.projImg {
  margin: 0;
}

.projImg img {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div class="mainProj">
    <main>
        <figure class="projImg">
            <img src="https://i.imgur.com/UiAiZYm.jpg" alt="projectImage1">
        </figure>

        <figure class="projImg">
            <img src="https://i.imgur.com/4F4Agjz.jpg" alt="projectImage2">
        </figure>

        <figure class="projImg">
            <img src="https://i.imgur.com/GncQ8QI.jpg" alt="projectImage3">
        </figure>

        <figure class="projImg">
            <img src="https://i.imgur.com/MGkSJza.jpg" alt="projectImage4">
        </figure>
    </main>
  </div></code>```

答:
```<code>.projImg {
  margin: 0;
}

.projImg img {
  display: block;
  margin: auto;

}
</code>```

use this CSS code to centralize your images.

ContentLicense: CC BY-SA 3.0

Body:
.projImg {
  margin: 0;
}

.projImg img {
  display: block;
  margin: auto;

}

use this CSS code to centralize your images.


问:
Paypal credit card validation
I want to check that the credit card number provided by customer to my site is valid or not for further transaction. for that i wand to only verify taht the CC no is valid or not by Paypal.
A method for that can be with paypal api
step 1: DoDirectPayment with PAYMENTACTION=Authorization for amt of $1, then
step 2: DoVoid that request

Does any one can tell me
is any amount is charged by paypal for doing tis stuff?
or any other better way you know?

My site is in PHP..

答: I made it with the help of PAYPAL API's DoVoid Function. I'm making a payment of $1 in Authentication Mode, and if it return success i'm using DoVoid with returned transaction-id. </p>

ContentLicense: CC BY-SA 2.5

Title: Paypal credit card validation


问:
Merge the two different JSON using node JS
I have two requests that return their data as JSON using NodeJS Seriate.

The first response is:

```<code>{
    "status": true,
    "message": "Data Found",
    "data": [
        {
            "statusCode": 200,
            "body": {
                "expand": "renderedFields,names,schem,operations,editmeta,changelog,versionedRepresentations",
                "id": "64672",
                "self": "https://computenext.atlassian.net/rest/api/2/issue/64672",
                "key": "CKS-2016",
                "fields": {
                    "parent": {
                        "id": "64670",
                        "key": "CKS-2014"
                    }
                }
            }
        }
    ]
}
</code>```

The second response is:

```<code>{
    "statusCode": 200,
    "body": {
        "errors": [],
        "detail": [
            {
                "repositories": [
                    {
                        "name": "registry",
                        "avatar": "http://stash.computenext.com/projects/SERVICES/avatar.png?s=32",
                        "avatarDescription": "services"
                    }
                ]
            }
        ]
    }
}
</code>```

I want to merge the two responses, that would have the following structure:

```<code>{
    "status": true,
    "message": "Data Found",
    "data": [
        {
            "statusCode": 200,
            "body": {
                "expand": "renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations",
                "id": "64672",
                "self": "https://computenext.atlassian.net/rest/api/2/issue/64672",
                "key": "CKS-2016",
                "fields": {
                    "parent": {
                        "id": "64670",
                        "key": "CKS-2014",
                        "detail": [
                            {
                                "repositories": [
                                    {
                                        "name": "registry",
                                        "avatar": "http://stash.computenext.com/projects/SERVICES/avatar.png?s=32",
                                        "avatarDescription": "services"
                                    }
                                ]
                            }
                        ]
                    }
                }
            }
        }
    ]
}
</code>```

I searched and found several methods of joining or extending two JSON objects but nothing similar to that.

How can I achieve this?

My Actual Code is,

```<code>exports.getIssues = function(req, res) {
    console.log(filename + '>>get Issues>>');
    var response = {
        status : Boolean,
        message : String,
        data : String
    };
    var request = require('request');
    var username = const.username ;
    var password = const.password ;
    var options = {
        url : 'https://computenext.atlassian.net/rest/api/2/search?jql=status+%3D+Resolved+ORDER+BY+updated',
        auth : {
            username : username,
            password : password
        }
    };

    request( options, function(error, obj) {
                if (error) {
                    response.message = appmsg.DATA_NT_FOUND;
                    response.status = false;
                    response.data = obj;
                    res.send(response);
                } else {
                     response.message = appmsg.DATA_FOUND;
                     response.status = true;
                     response.data = JSON.parse(obj.body);
                     //res.send(response);
                    var issueKey = response.data.issues;

                    // var keyData = issueKey[0].key;
                    // console.log(response.data.issues);
                    // console.log(keyData);
                    var output = [];
                    for(var i = 0; i < issueKey.length; i++) {
                        var issue = issueKey[i].key;
                        //var key = [];
                        //key.push(issue);
                        console.log(issue);

                        var respon = {
                            status : Boolean,
                            message : String,
                            data : String
                        };
                            var request = require('request'),
                                username = const.username ,
                                password = const.username ,
                                url = "https://computenext.atlassian.net/rest/api/2/issue/" + issue,
                                auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

                            //console.log(url);
                            request({url : url,headers : {"Authorization" : auth}}, function(err, object){
                                if (object) {

                                        var info = object;
                                        output.push(info); // this is not working as ouput is undefined at this    point
                                        //var pout = JSON.parse(output);
                                        //console.log(info);
                                        console.log("==============================================================================");
                                        //console.log(output);
                                        console.log("******************************************************************************");
                                            if(issueKey.length === output.length){
                                                respon.message = appmsg.DATA_FOUND;
                                                respon.status = true;
                                                respon.data = output;
                                                //console.log(output);
                                                //res.send(respon);

                                                  var id = issueKey[0].id;
                                                  console.log(id);

                                                   var commitout = [];
                                                    for(var i = 0; i < issueKey.length; i++) {
                                                        var commits = issueKey[i].id;
                                                        console.log(commits);

                                                      var request = require('request'),
                                                      username = const.username ,
                                                      password = const.password ,
                                                      url = "https://computenext.atlassian.net/rest/dev-status/1.0/issue/detail?issueId=" + commits + "&applicationType=stash&dataType=repository",
                                                      auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

                                                    //console.log(url);
                                                    var test = [];
                                                    request({url : url,headers : {"Authorization" : auth}}, function(err, obj1){
                                                      if (obj1) {

                                                              var info1 = obj1.body;
                                                              commitout.push(info1);
                                                              if(issueKey.length === commitout.length){
                                                                respon.message = appmsg.DATA_FOUND;
                                                                respon.status = true;
                                                                respon.data = commitout;
                                                                // console.log(commitout);
                                                                  //var test = merge(output, commitout);

                                                                  var text = output.body;
                                                                  var resultdone = output;

                                                                  resultdone.data = resultdone + commitout.body;

                                                                  console.log(resultdone.data);

                                                                res.send(resultdone.data);
                                                              }
                                                            }
                                                   });
                                                  }

                                    }
                                }

                        });

                }
            }

        });
</code>```

};

How can i merge the two arrays? in one response. That is my question..

答:
Never mainpulate the string of JSON directly.  Parse it first.

```<code>const firstRes = JSON.parse(firstResJson);
const secondRes = JSON.prase(secondResJson);
</code>```

Now, it's a bit unclear what you want to do, and why you want to do it, but try this:

```<code>firstRes.data.body.fields.parent.detail = secondRes.body.detail;
</code>```

Then, you'll find your combined data in firstRes.  To get it back to JSON:

```<code>JSON.stringify(firstRes);
</code>```

Body:
I have two requests that return their data as JSON using NodeJS Seriate.

The first response is:

{
    "status": true,
    "message": "Data Found",
    "data": [
        {
            "statusCode": 200,
            "body": {
                "expand": "renderedFields,names,schem,operations,editmeta,changelog,versionedRepresentations",
                "id": "64672",
                "self": "https://computenext.atlassian.net/rest/api/2/issue/64672",
                "key": "CKS-2016",
                "fields": {
                    "parent": {
                        "id": "64670",
                        "key": "CKS-2014"
                    }
                }
            }
        }
    ]
}

The second response is:

{
    "statusCode": 200,
    "body": {
        "errors": [],
        "detail": [
            {
                "repositories": [
                    {
                        "name": "registry",
                        "avatar": "http://stash.computenext.com/projects/SERVICES/avatar.png?s=32",
                        "avatarDescription": "services"
                    }
                ]
            }
        ]
    }
}

I want to merge the two responses, that would have the following structure:

{
    "status": true,
    "message": "Data Found",
    "data": [
        {
            "statusCode": 200,
            "body": {
                "expand": "renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations",
                "id": "64672",
                "self": "https://computenext.atlassian.net/rest/api/2/issue/64672",
                "key": "CKS-2016",
                "fields": {
                    "parent": {
                        "id": "64670",
                        "key": "CKS-2014",
                        "detail": [
                            {
                                "repositories": [
                                    {
                                        "name": "registry",
                                        "avatar": "http://stash.computenext.com/projects/SERVICES/avatar.png?s=32",
                                        "avatarDescription": "services"
                                    }
                                ]
                            }
                        ]
                    }
                }
            }
        }
    ]
}

I searched and found several methods of joining or extending two JSON objects but nothing similar to that.

How can I achieve this?

My Actual Code is,

exports.getIssues = function(req, res) {
    console.log(filename + '>>get Issues>>');
    var response = {
        status : Boolean,
        message : String,
        data : String
    };
    var request = require('request');
    var username = const.username ;
    var password = const.password ;
    var options = {
        url : 'https://computenext.atlassian.net/rest/api/2/search?jql=status+%3D+Resolved+ORDER+BY+updated',
        auth : {
            username : username,
            password : password
        }
    };

    request( options, function(error, obj) {
                if (error) {
                    response.message = appmsg.DATA_NT_FOUND;
                    response.status = false;
                    response.data = obj;
                    res.send(response);
                } else {
                     response.message = appmsg.DATA_FOUND;
                     response.status = true;
                     response.data = JSON.parse(obj.body);
                     //res.send(response);
                    var issueKey = response.data.issues;

                    // var keyData = issueKey[0].key;
                    // console.log(response.data.issues);
                    // console.log(keyData);
                    var output = [];
                    for(var i = 0; i < issueKey.length; i++) {
                        var issue = issueKey[i].key;
                        //var key = [];
                        //key.push(issue);
                        console.log(issue);

                        var respon = {
                            status : Boolean,
                            message : String,
                            data : String
                        };
                            var request = require('request'),
                                username = const.username ,
                                password = const.username ,
                                url = "https://computenext.atlassian.net/rest/api/2/issue/" + issue,
                                auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

                            //console.log(url);
                            request({url : url,headers : {"Authorization" : auth}}, function(err, object){
                                if (object) {

                                        var info = object;
                                        output.push(info); // this is not working as ouput is undefined at this    point
                                        //var pout = JSON.parse(output);
                                        //console.log(info);
                                        console.log("==============================================================================");
                                        //console.log(output);
                                        console.log("******************************************************************************");
                                            if(issueKey.length === output.length){
                                                respon.message = appmsg.DATA_FOUND;
                                                respon.status = true;
                                                respon.data = output;
                                                //console.log(output);
                                                //res.send(respon);

                                                  var id = issueKey[0].id;
                                                  console.log(id);

                                                   var commitout = [];
                                                    for(var i = 0; i < issueKey.length; i++) {
                                                        var commits = issueKey[i].id;
                                                        console.log(commits);

                                                      var request = require('request'),
                                                      username = const.username ,
                                                      password = const.password ,
                                                      url = "https://computenext.atlassian.net/rest/dev-status/1.0/issue/detail?issueId=" + commits + "&applicationType=stash&dataType=repository",
                                                      auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

                                                    //console.log(url);
                                                    var test = [];
                                                    request({url : url,headers : {"Authorization" : auth}}, function(err, obj1){
                                                      if (obj1) {

                                                              var info1 = obj1.body;
                                                              commitout.push(info1);
                                                              if(issueKey.length === commitout.length){
                                                                respon.message = appmsg.DATA_FOUND;
                                                                respon.status = true;
                                                                respon.data = commitout;
                                                                // console.log(commitout);
                                                                  //var test = merge(output, commitout);

                                                                  var text = output.body;
                                                                  var resultdone = output;

                                                                  resultdone.data = resultdone + commitout.body;

                                                                  console.log(resultdone.data);

                                                                res.send(resultdone.data);
                                                              }
                                                            }
                                                   });
                                                  }

                                    }
                                }

                        });

                }
            }

        });

};

How can i merge the two arrays? in one response. That is my question..

Body:
Never mainpulate the string of JSON directly.  Parse it first.

const firstRes = JSON.parse(firstResJson);
const secondRes = JSON.prase(secondResJson);

Now, it's a bit unclear what you want to do, and why you want to do it, but try this:

firstRes.data.body.fields.parent.detail = secondRes.body.detail;

Then, you'll find your combined data in firstRes.  To get it back to JSON:

JSON.stringify(firstRes);


问:
Hangfire with multiple servers
I am working on an application where I have multiple servers on different machines doing long operations for me. There is a windows service running on those machines written with hangfire/topshelf. Only one operation can run at a time per machine. Additionally I want to do some status check and cleaning jobs periodically on each server, so I can't just queue them as jobs.

Is there a way to do that in hangfire? Also, is there a way to send a follow-up job to the same server as an earlier job?

ADD-ON: I know one possibility would be to add another hangfire layer: Make each of the services a hangfire client with own DB and serve themselves, and then schedule recurring jobs for them, but that seems awfully complicated - especially when scaling out and adding servers.

答: I know this is a bit late, but the way we handle this sort of thing is just to write a simple console application and schedule it with Windows Task Scheduler.</p>

Title: Hangfire with multiple servers


问:
Jenkins - Maven error - Could not find or load main class
I am trying to run maven project using Jenkins for the first time and I am getting the following the error in Jenkins - console O/P.

```<code>Error: Could not find or load main class MAVEN_HOME
ERROR: Failed to launch Maven. Exit code = 1
Finished: FAILURE
</code>```

My POM

I am able to run the maven project in eclipse successfully

```<code><i>
        <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.aig.cucumberwork</groupId>
  <artifactId>com.aig.cucumberwork</artifactId>
  <version>0.0.1-SNAPSHOT</version>
    <dependencies>
   <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.7.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/info.cukes/cucumber-java -->
<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-java</artifactId>
    <version>1.2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/info.cukes/cucumber-junit -->
<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-junit</artifactId>
    <version>1.2.2</version>
    <scope>test</scope>
</dependency>
  </dependencies>
</project>
</i>
</code>```

```<code>Maven build
Root POM : C:\Users\marajend\test\com.aig.cucumberwork\pom.xml
</code>```

I am able to run the maven project in eclipse successfully

答:
Seems the error you are seeing Error: Could not find or load main class MAVEN_HOME is clear and concise. You need to check the following steps :

Within the Environment Variables create a User Variable as, MAVEN_HOME with a valid value e.g. C:\apache-maven-3.3.3

Within Jenkins Configuration you have to mention MAVEN_HOME again with the same valid value e.g. C:\apache-maven-3.3.3

Body:
I am trying to run maven project using Jenkins for the first time and I am getting the following the error in Jenkins - console O/P.

Error: Could not find or load main class MAVEN_HOME
ERROR: Failed to launch Maven. Exit code = 1
Finished: FAILURE

My POM

I am able to run the maven project in eclipse successfully

        <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.aig.cucumberwork</groupId>
  <artifactId>com.aig.cucumberwork</artifactId>
  <version>0.0.1-SNAPSHOT</version>
    <dependencies>
   <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.7.1</version>
    </dependency>

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-java</artifactId>
    <version>1.2.2</version>
</dependency>

<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-junit</artifactId>
    <version>1.2.2</version>
    <scope>test</scope>
</dependency>
  </dependencies>
</project>

Maven build
Root POM : C:\Users\marajend\test\com.aig.cucumberwork\pom.xml

I am able to run the maven project in eclipse successfully


问:
How do we make keyboard appear below textView in swift?
I have done keyboard appearing below textfield using

on View did Load adding a observer()

```<code>    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(Gold_Loan_First_ViewController.keyboardDidShow(_:)), name: UIKeyboardDidShowNotification, object: nil)

    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(Gold_Loan_First_ViewController.keyboardWillBeHidden(_:)), name: UIKeyboardWillHideNotification, object: nil)
</code>```

And then updating the frame

```<code>weak var activeField: UITextField?

func textFieldDidEndEditing(textField: UITextField) {
    self.activeField = nil

}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if textField==txtOTP {
        txtOTP.errorMessage=""
    }
  return true
}
func textFieldDidBeginEditing(textField: UITextField) {
    self.activeField = textField

}

func keyboardDidShow(notification: NSNotification)
{
    if let activeField = self.activeField,
        let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
        let contentInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardSize.height, right: 0.0)
        self.scrollView.contentInset = contentInsets
        self.scrollView.scrollIndicatorInsets = contentInsets
        var aRect = self.view.frame
        aRect.size.height -= keyboardSize.size.height
        if (!CGRectContainsPoint(aRect, activeField.frame.origin)) {
            self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
        }
    }

}

func keyboardWillBeHidden(notification: NSNotification)
{
    let contentInsets = UIEdgeInsetsZero
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
}
</code>```

But how do I do it for a textView. I tried the same code with didBeginEditing  of textView with no positive effect

答:
Salman Ghumsani is Right.

Please change UIKeyboardFrameBeginUserInfoKey to UIKeyboardFrameEndUserInfoKey.

Apple Debeloper Document: Keyboard Notification User Info Keys

UIKeyboardFrameEndUserInfoKey

The key for an NSValue object containing a CGRect that identifies the ending frame rectangle of the keyboard in screen coordinates. The frame rectangle reflects the current orientation of the device.

UIKeyboardFrameBeginUserInfoKey

The key for an
NSValue
 object containing a
CGRect
 that identifies the starting frame rectangle of the keyboard in screen coordinates. The frame rectangle reflects the current orientation of the device.

Conclusion

So, if u use UIKeyboardFrameBeginUserInfoKey u might get the keyboard height to 0. Causing the system thought UITextView was not covered.

Body:
I have done keyboard appearing below textfield using

on View did Load adding a observer()

    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(Gold_Loan_First_ViewController.keyboardDidShow(_:)), name: UIKeyboardDidShowNotification, object: nil)

    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(Gold_Loan_First_ViewController.keyboardWillBeHidden(_:)), name: UIKeyboardWillHideNotification, object: nil)

And then updating the frame

weak var activeField: UITextField?

func textFieldDidEndEditing(textField: UITextField) {
    self.activeField = nil

}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if textField==txtOTP {
        txtOTP.errorMessage=""
    }
  return true
}
func textFieldDidBeginEditing(textField: UITextField) {
    self.activeField = textField

}

func keyboardDidShow(notification: NSNotification)
{
    if let activeField = self.activeField,
        let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
        let contentInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardSize.height, right: 0.0)
        self.scrollView.contentInset = contentInsets
        self.scrollView.scrollIndicatorInsets = contentInsets
        var aRect = self.view.frame
        aRect.size.height -= keyboardSize.size.height
        if (!CGRectContainsPoint(aRect, activeField.frame.origin)) {
            self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
        }
    }

}

func keyboardWillBeHidden(notification: NSNotification)
{
    let contentInsets = UIEdgeInsetsZero
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
}

But how do I do it for a textView. I tried the same code with didBeginEditing  of textView with no positive effect


问:
Using Snakefile variables in config file [snakemake]
Is it possible to use variable from Snakefile in config file? In below example, I would like Snakefile to recognize 'foo' as variable name and use its value.

Snakefile:

```<code>from pathlib import Path

foo = Path('path_to_dir')

rule all:
   input:
       config['OUT_FILE')
</code>```

Config file:

```<code>OUT_FILE: foo / "data/results/abc.png"
</code>```

If this is not possible, is there an alternate solution that could be used?

答: You can use a placeholder or relative path in the config and replace that programmatically once the config file has been parsed, at the beginning of the Snakefile. Remember, snakemake is python plus rule syntax, so you can use any python code directly in your workflow.</p>

Body:
Is it possible to use variable from Snakefile in config file? In below example, I would like Snakefile to recognize 'foo' as variable name and use its value.

Snakefile:

from pathlib import Path

foo = Path('path_to_dir')

rule all:
   input:
       config['OUT_FILE')

Config file:

OUT_FILE: foo / "data/results/abc.png"

If this is not possible, is there an alternate solution that could be used?


答:
Because when a reaches 10 in the inner loop, the outer loop also exits, so you only see

```<code>012345678910
</code>```

Because after the 1st time the outer loop is executed, b is already 11 and the inner loop is no longer executed.

For your desired output, you should reset b to zero every time the outer loop is executed

```<code>for (...) {
    for (b = 0; ... ; ...) {...}
    //   ^~~~~ This is what you should do
}
</code>```

Title: Loop program output

Body:
I got curious and experimented a little on looping and I kind of confused myself here.

Question 1:
Why does this code output 012345678910 instead of 00000000000111111111112222222222233333333333444444444445555555555566666666666777
7777777788888888888999999999991010101010101010101010 ?

for(a=0;a<=10;a++){
    for(a=0;a<=10;a++){
        printf("%d", a);
    }
}

Question 2: For the code shown below, does taking out the first statement mean that it would start on 0? If yes, then why does it output 12345678910 instead of 01234567891001234567891001234567891001234567891001234567891001234567891001234567
8910012345678910012345678910012345678910012345678910 ?

for(a=0;a<=10;a++){
    for(;b<=10;b++){
        printf("%d", b);
    }
}

Body:
Because when a reaches 10 in the inner loop, the outer loop also exits, so you only see

012345678910

Because after the 1st time the outer loop is executed, b is already 11 and the inner loop is no longer executed.

For your desired output, you should reset b to zero every time the outer loop is executed

for (...) {
    for (b = 0; ... ; ...) {...}
    //   ^~~~~ This is what you should do
}


问:
Getting audio to start after you click on the play button
What would I change in the code if I didn't want the audio to start after you clicked on it. If I wanted the play button to show, and not pause, with no audio playing until you clicked on the play button and not the picture?

How it looks now after you Click on the image. It goes straight to the audio. I want it to go to the play button first.

https://jsfiddle.net/7ux1s23j/42/

I want it to go to this image first after you click on the picture.

Screenshot

Links

  <svg class="pause" style="display: none;margin:5px 7px;" width="36" height="40" viewbox="0 0 60 100">
    <path d="M0 8c0-5 3-8 8-8s9 3 9 8v84c0 5-4 8-9 8s-8-3-8-8V8zm43 0c0-5 3-8 8-8s8 3 8 8v84c0 5-3 8-8 8s-8-3-8-8V8z"></path>
  </svg>

  <svg class="play hide " style="margin:5px 9px;" width="38" height="40" viewbox="0 0 85 100">
    <path d="M81 44.6c5 3 5 7.8 0 10.8L9 98.7c-5 3-9 .7-9-5V6.3c0-5.7 4-8 9-5l72 43.3z"></path>
  </svg>

<audio id="player" preload="none">
  <source src="http://hi5.1980s.fm/;" type="audio/mpeg">
  </source>
</audio>

```

答:
Try as follows

//music
var audio = new Audio('http://www.sousound.com/music/healing/healing_01.mp3')
checksound();

function checksound() {

var myElement = document.getElementById("soundMenu");
  myElement.innerHTML = "Turn Sound " + (audio.paused ? "OFF" : "ON");

  if (audio.paused) {
    audio.play();
  } else {
    audio.pause();
  }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="soundMenu" onclick="checksound()">Play</button></code>```

Body:
Try as follows

//music
var audio = new Audio('http://www.sousound.com/music/healing/healing_01.mp3')
checksound();

function checksound() {

var myElement = document.getElementById("soundMenu");
  myElement.innerHTML = "Turn Sound " + (audio.paused ? "OFF" : "ON");

  if (audio.paused) {
    audio.play();
  } else {
    audio.pause();
  }

}

<button id="soundMenu" onclick="checksound()">Play</button>


问:
Laravel action is not authorized
I'm trying to delete a post that belongs to the user who made it, however i get this error(this was in the network log by the way)

"/Applications/MAMP/htdocs/eli42/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php"
  line : 201 message : "This action is unauthorized." trace : [{,…},…]

I'm utilizing laravel 5.5 policy not sure if im doing this right, i registered it in my AuthServiceProvider within $protected policies

Post::class => PostPolicy::class,

Route

Route::delete('auth/post/{id}', 'PostController@destroy');

PostPolicy.php

```<code><?php

namespace App\Policies;

use App\User;
use App\Post;

use Illuminate\Auth\Access\HandlesAuthorization;

class PostPolicy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can view the post.
     *
     * @param  \App\User  $user
     * @param  \App\Post  $post
     * @return mixed
     */
    public function view(User $user, Post $post)
    {
        //
    }

    /**
     * Determine whether the user can create posts.
     *
     * @param  \App\User  $user
     * @return mixed
     */
    public function create(User $user)
    {
        //
    }

    /**
     * Determine whether the user can update the post.
     *
     * @param  \App\User  $user
     * @param  \App\Post  $post
     * @return mixed
     */
    public function update(User $user, Post $post)
    {
        //
    }

    /**
     * Determine whether the user can delete the post.
     *
     * @param  \App\User  $user
     * @param  \App\Post  $post
     * @return mixed
     */
    public function delete(User $user, Post $post)
    {
        //

        return $user->id === $post->user_id;

    }
</code>```

PostController.php (there is more code to this file but i wanted to highlight the delete function)

```<code><?php

namespace App\Http\Controllers;

use App\Post;
use App\User;
use App\Policies\TaskPolicy;

use Illuminate\Http\Request;
use Illuminate\Http\Response;

class PostController extends Controller
{

    public function destroy($id, Post $post)
    {
        $mypost = $this->authorize('delete',$post);

        if($mypost){
             Post::destroy($id);

        }

    }
}
</code>```

Main.js to delete post

```<code>$scope.deletePost = function(post){
    var index = $scope.myposts.indexOf(post);

    if(index != -1){
        $scope.myposts.splice(index, 1);
    }

    $http.delete('auth/post/' + post.id);

};
</code>```

html

```<code>   <button ng-click="deletePost(post)">x</button>
</code>```

before

after

答:
You don't need to retrieve the post, let Laravel does that for you.

Edit your route to be like this:

Route::delete('auth/post/{post}', 'PostController@destroy');

Note that the post between curly brackets will be the variable name assigned to the post if found by Laravel. If no post found, Laravel will return Not Found 404.

Then in your controller, you have to tell Laravel that you'r expecting a post coming through the route:

The method signuture will be like this: destroy(Post $post). $post is the as {post} in your route.

Finally, for authorization, you will not get the post returned from authorize method. You pass the $post found by Laravel to the authorize method.

Here is the full method:

```<code>public function destroy(Post $post)
{
    $this->authorize('delete', $post);

    if ($post->delete()) {
        return response()->json(['message' => 'deleted']);
    };

    return response()->json(['error' => 'something went wrong'], 400);
}
</code>```

Title: Laravel action is not authorized

Body:
I'm trying to delete a post that belongs to the user who made it, however i get this error(this was in the network log by the way)

"/Applications/MAMP/htdocs/eli42/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php"
  line : 201 message : "This action is unauthorized." trace : [{,…},…]

I'm utilizing laravel 5.5 policy not sure if im doing this right, i registered it in my AuthServiceProvider within $protected policies

Post::class => PostPolicy::class,

Route

Route::delete('auth/post/{id}', 'PostController@destroy');

PostPolicy.php

<?php

namespace App\Policies;

use App\User;
use App\Post;

use Illuminate\Auth\Access\HandlesAuthorization;

class PostPolicy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can view the post.
     *
     * @param  \App\User  $user
     * @param  \App\Post  $post
     * @return mixed
     */
    public function view(User $user, Post $post)
    {
        //
    }

    /**
     * Determine whether the user can create posts.
     *
     * @param  \App\User  $user
     * @return mixed
     */
    public function create(User $user)
    {
        //
    }

    /**
     * Determine whether the user can update the post.
     *
     * @param  \App\User  $user
     * @param  \App\Post  $post
     * @return mixed
     */
    public function update(User $user, Post $post)
    {
        //
    }

    /**
     * Determine whether the user can delete the post.
     *
     * @param  \App\User  $user
     * @param  \App\Post  $post
     * @return mixed
     */
    public function delete(User $user, Post $post)
    {
        //

        return $user->id === $post->user_id;

    }

PostController.php (there is more code to this file but i wanted to highlight the delete function)

<?php

namespace App\Http\Controllers;

use App\Post;
use App\User;
use App\Policies\TaskPolicy;

use Illuminate\Http\Request;
use Illuminate\Http\Response;

class PostController extends Controller
{

    public function destroy($id, Post $post)
    {
        $mypost = $this->authorize('delete',$post);

        if($mypost){
             Post::destroy($id);

        }

    }
}

Main.js to delete post

$scope.deletePost = function(post){
    var index = $scope.myposts.indexOf(post);

    if(index != -1){
        $scope.myposts.splice(index, 1);
    }

    $http.delete('auth/post/' + post.id);

};

html

   <button ng-click="deletePost(post)">x</button>

before

after

Body:
You don't need to retrieve the post, let Laravel does that for you.

Edit your route to be like this:

Route::delete('auth/post/{post}', 'PostController@destroy');

Note that the post between curly brackets will be the variable name assigned to the post if found by Laravel. If no post found, Laravel will return Not Found 404.

Then in your controller, you have to tell Laravel that you'r expecting a post coming through the route:

The method signuture will be like this: destroy(Post $post). $post is the as {post} in your route.

Finally, for authorization, you will not get the post returned from authorize method. You pass the $post found by Laravel to the authorize method.

Here is the full method:

public function destroy(Post $post)
{
    $this->authorize('delete', $post);

    if ($post->delete()) {
        return response()->json(['message' => 'deleted']);
    };

    return response()->json(['error' => 'something went wrong'], 400);
}


问:
Writing data into MongoDB with Spark
When I tried to write a spark dataframe into mongodb, I found that spark only create one task to do it. This cause bad performance because only one executor is actually running even if allocate many executors in the job.

my partial pyspark code:

```<code>df.write.format("com.mongodb.spark.sql.DefaultSource") \
    .mode("append") \
    .option("spark.mongodb.output.uri", connectionString) \
    .save()
</code>```

Could spark running multiple task in this case? Thanks

Spark submit:

```<code>spark-submit --master yarn --num-executors 3 --executor-memory 5g --jars $JARS_PATH/mongo-java-driver-3.5.0.jar,$JARS_PATH/mongodb-driver-core-3.5.0.jar,$JARS_PATH/mongo-spark-connector_2.11-2.2.1.jar spark-mongo.py
</code>```

I found log that contain this INFO

```<code>INFO TaskSetManager: Starting task 0.0 in stage 0.0 (TID 0, linxtd-itbigd04, executor 1, partition 0, PROCESS_LOCAL, 4660 bytes)
INFO BlockManagerMasterEndpoint: Registering block manager linxtd-itbigd04:36793 with 1458.6 MB RAM, BlockManagerId(1, linxtd-itbigd04, 36793, None)
INFO BlockManagerInfo: Added broadcast_0_piece0 in memory on linxtd-itbigd04:36793 (size: 19.7 KB, free: 1458.6 MB)
INFO TaskSetManager: Finished task 0.0 in stage 0.0 (TID 0) in 17364 ms on linxtd-itbigd04 (executor 1) (1/1)
</code>```

答:
Like I suspected, and mentioned in the comments, your data wasn’t partitioned thus Spark created one task to deal with it.

You have to be careful when using the jdbc source if you don’t provide a partition reading and writing data wont be parallelized and you end up with one task.

You can read more about this topic in one of my spark gotchas - Reading data using jdbc source.

Disclaimer: I’m on of the co-authors of that repo.

Title: Writing data into MongoDB with Spark

Body:
When I tried to write a spark dataframe into mongodb, I found that spark only create one task to do it. This cause bad performance because only one executor is actually running even if allocate many executors in the job.

my partial pyspark code:

df.write.format("com.mongodb.spark.sql.DefaultSource") \
    .mode("append") \
    .option("spark.mongodb.output.uri", connectionString) \
    .save()

Could spark running multiple task in this case? Thanks

Spark submit:

spark-submit --master yarn --num-executors 3 --executor-memory 5g --jars $JARS_PATH/mongo-java-driver-3.5.0.jar,$JARS_PATH/mongodb-driver-core-3.5.0.jar,$JARS_PATH/mongo-spark-connector_2.11-2.2.1.jar spark-mongo.py

I found log that contain this INFO

INFO TaskSetManager: Starting task 0.0 in stage 0.0 (TID 0, linxtd-itbigd04, executor 1, partition 0, PROCESS_LOCAL, 4660 bytes)
INFO BlockManagerMasterEndpoint: Registering block manager linxtd-itbigd04:36793 with 1458.6 MB RAM, BlockManagerId(1, linxtd-itbigd04, 36793, None)
INFO BlockManagerInfo: Added broadcast_0_piece0 in memory on linxtd-itbigd04:36793 (size: 19.7 KB, free: 1458.6 MB)
INFO TaskSetManager: Finished task 0.0 in stage 0.0 (TID 0) in 17364 ms on linxtd-itbigd04 (executor 1) (1/1)


问:
CocoaPods not working in macOS High Sierra
After upgrading to macOS High Sierra CocoaPods is not working. While it is tempting to move away from CocoaPods, it's unfortunately not in scope right now. The error message is below.

```<code>zsh: /Users/****/.gems/bin/pod: bad interpreter: /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin: no such file or directory
</code>```

I realize that the error stems from Ruby being upgraded but what is the easies fix? Trying to make CocoaPods use the new ruby version yields other errors.

Edit: For now i installed Ruby 2.0 with rvm install 2.0.0 and rvm use 2.0.0 and then reinstalled CocoaPods sudo gem install cocoapods. Seems to be working now.

答:
Go to Terminal...

step 1). sudo gem install cocoapods

after completion of install cocoa pods then

step 2).   pod repo update

Completed

Body:
After upgrading to macOS High Sierra CocoaPods is not working. While it is tempting to move away from CocoaPods, it's unfortunately not in scope right now. The error message is below.

zsh: /Users/****/.gems/bin/pod: bad interpreter: /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin: no such file or directory

I realize that the error stems from Ruby being upgraded but what is the easies fix? Trying to make CocoaPods use the new ruby version yields other errors.

Edit: For now i installed Ruby 2.0 with rvm install 2.0.0 and rvm use 2.0.0 and then reinstalled CocoaPods sudo gem install cocoapods. Seems to be working now.


问:
Hide registration and login form when user is logged in ASP.NET
I am new at ASP.NET and I am having some difficulties. What I have below is a Registration and Login, both in one page. However, when a user is logged in, I would like the registration and login form to be hided.
There is a LOGOUT option when the user is logged in.
Any guidance would be great, thank you!</p>

```<code><%@ Page Language="VB" MasterPageFile="~/MasterPage.master" Title="Untitled Page" %>

<script runat="server">
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

    End Sub

    Protected Sub Login1_Authenticate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.AuthenticateEventArgs)

    End Sub

    Protected Sub Login1_Authenticate1(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.AuthenticateEventArgs)

    End Sub

    Protected Sub Login1_Authenticate2(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.AuthenticateEventArgs)

    End Sub

Protected Sub CreateUserWizard1_CreatedUser(ByVal sender As Object, ByVal e As System.EventArgs)

End Sub
</script>

<%-- Add content controls here --%>
<asp:Content ID="Content1" runat="server"
    contentplaceholderid="ContentPlaceHolder1">
    <table width="640px"><tr>
    <td width="360px">
                    <p>
                        <asp:CreateUserWizard ID="CreateUserWizard1" runat="server">
                            <WizardSteps>
                                <asp:CreateUserWizardStep runat="server" />
                                <asp:CompleteWizardStep runat="server" />
                            </WizardSteps>
                        </asp:CreateUserWizard>
</p>
                    <br />
                    <br />
                    </td>
                    <td width="270px">
                        <p>
        <asp:Login ID="Login1" runat="server" DestinationPageUrl="~/Home.aspx">
        </asp:Login>
        <asp:LoginView ID="LoginView1" runat="server">
            <AnonymousTemplate>
                Please log In
            </AnonymousTemplate>
        </asp:LoginView>
</p>
    <p>
        <asp:LoginStatus ID="LoginStatus1" runat="server" />
</p>
</td>
</tr>
</table>

</asp:Content>
</code>```

答:
I'd suggest LoginView.</p>

```<code><asp:LoginView ID="LoginView1" runat="server">
        <LoggedInTemplate>
            <asp:LoginStatus ID="LoginStatus1" runat="server" />
            <asp:LoginName ID="LoginName1" runat="server" />
        </LoggedInTemplate>
        <AnonymousTemplate>
            <p>
                <asp:Login ID="Login1" runat="server">
                </asp:Login>
            </p>
            <p>
            <asp:CreateUserWizard ID="CreateUserWizard1" runat="server">
                <WizardSteps>
                    <asp:CreateUserWizardStep runat="server" />
                    <asp:CompleteWizardStep runat="server" />
                </WizardSteps>
            </asp:CreateUserWizard>
           </p>
        </AnonymousTemplate>
</asp:LoginView>
</code>```

Body:
I am new at ASP.NET and I am having some difficulties. What I have below is a Registration and Login, both in one page. However, when a user is logged in, I would like the registration and login form to be hided.
There is a LOGOUT option when the user is logged in.
Any guidance would be great, thank you!

<%@ Page Language="VB" MasterPageFile="~/MasterPage.master" Title="Untitled Page" %>

<%-- Add content controls here --%>
<asp:Content ID="Content1" runat="server"
    contentplaceholderid="ContentPlaceHolder1">

                        <asp:CreateUserWizard ID="CreateUserWizard1" runat="server">
                            <WizardSteps>
                                <asp:CreateUserWizardStep runat="server" />
                                <asp:CompleteWizardStep runat="server" />
                            </WizardSteps>
                        </asp:CreateUserWizard>

        <asp:Login ID="Login1" runat="server" DestinationPageUrl="~/Home.aspx">
        </asp:Login>
        <asp:LoginView ID="LoginView1" runat="server">
            <AnonymousTemplate>
                Please log In
            </AnonymousTemplate>
        </asp:LoginView>

        <asp:LoginStatus ID="LoginStatus1" runat="server" />

</asp:Content>

Body:
I'd suggest LoginView.

<asp:LoginView ID="LoginView1" runat="server">
        <LoggedInTemplate>
            <asp:LoginStatus ID="LoginStatus1" runat="server" />
            <asp:LoginName ID="LoginName1" runat="server" />
        </LoggedInTemplate>
        <AnonymousTemplate>
            <p>
                <asp:Login ID="Login1" runat="server">
                </asp:Login>
            </p>
            <p>
            <asp:CreateUserWizard ID="CreateUserWizard1" runat="server">
                <WizardSteps>
                    <asp:CreateUserWizardStep runat="server" />
                    <asp:CompleteWizardStep runat="server" />
                </WizardSteps>
            </asp:CreateUserWizard>
           </p>
        </AnonymousTemplate>
</asp:LoginView>


问:
vue.js 2 img tag lost after re-render ( fetch again ) data from server
I working with vuejs on my project go on fine until i meet this issue : i have my page to show data grid with image carousel "Owl carousel" and the code look like below :

```<code>fetchData: async function () {
    let self = this
    let query = self.$route.query

    if ($.inArray(self.rowPerPage, self.selectChoice) !== -1) {
      query['rowPerPage'] = self.rowPerPage
    } else {
      query['rowPerPage'] = 5
    }

    query['page'] = self.page

    /*Get Properties*/
    HTTP.get('property/search', {
      params: query,
      headers: {'pointer-access-token': window.$cookies.get('pointer-access-token')}
    }).then(function (data) {

      let date = new Date();
      let testTime = data.data.data[0].created_at

      self.properties = data.data.data
      self.pages = data.data.pages
      self.rowPerPage = data.data.rowPerPage

    });
  }
</code>```

code above to read data from server and code below is html that i re-render :

```<code><div class="listing-item share-list-container" v-if="properties"
             v-for="(property,propertyIndex) in properties">
  ...
  <div class="listing-carousel">
    <div v-for="photo in property.photo">
   <img v-lazy="domainName + photoPath + photo" :alt="property.projectName">
    </div>
  </div>
  ...
</div>
</code>```

"img" tag was disappear after DOM was loaded, it wasn't lost from all item, this tag lost 1 or 2 on most items and some items still have this image tag.i really have clue about this.

Thank for idea !

答: cast the image path to string from your server</p>

Body:
I working with vuejs on my project go on fine until i meet this issue : i have my page to show data grid with image carousel "Owl carousel" and the code look like below :

fetchData: async function () {
    let self = this
    let query = self.$route.query

    if ($.inArray(self.rowPerPage, self.selectChoice) !== -1) {
      query['rowPerPage'] = self.rowPerPage
    } else {
      query['rowPerPage'] = 5
    }

    query['page'] = self.page

    /*Get Properties*/
    HTTP.get('property/search', {
      params: query,
      headers: {'pointer-access-token': window.$cookies.get('pointer-access-token')}
    }).then(function (data) {

      let date = new Date();
      let testTime = data.data.data[0].created_at

      self.properties = data.data.data
      self.pages = data.data.pages
      self.rowPerPage = data.data.rowPerPage

    });
  }

code above to read data from server and code below is html that i re-render :

  ...

  ...

"img" tag was disappear after DOM was loaded, it wasn't lost from all item, this tag lost 1 or 2 on most items and some items still have this image tag.i really have clue about this.

Thank for idea !


问:
UWP KeyRoutedEventArgs.handled Does Not Cancel Backspace Key
Is there a way to cancel the backspace key with a KeyDownEvent in UWP?  This event uses KeyRoutedEventArgs, so there is no SuppressKeyPress function.

event.Handled = true does not help; it only stops the event from being called multiple times in quick succession from the same key press.

Does such a function exist?

答:
If you have a TextBox defined like this:

```<code><Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <TextBox KeyDown="TextBox_KeyDown"/>
</Grid>
</code>```

And in the KeyDown-event if you just set Handled = true every time, user can't enter anything:

```<code>    private void TextBox_KeyDown(object sender, KeyRoutedEventArgs e)
    {
        e.Handled = true;
    }
</code>```

But as you mentioned, if you check for Back-key and set the Handled = true, it doesn't work: User is still able to use backspace. So this doesn't work.

```<code>    private void TextBox_KeyDown(object sender, KeyRoutedEventArgs e)
    {
        if (e.Key == Windows.System.VirtualKey.Back)
        {
            e.Handled = true;
            return;
        }
    }
</code>```

If you debug the code you can see that the character is already gone when the eventhandler is executed. You have to work around this, using other events. Here's one option:

XAML:

```<code>    <TextBox KeyDown="TextBox_KeyDown" KeyUp="TextBox_KeyUp"/>
</code>```

Code behind:

```<code>    private string currentText;
    private void TextBox_KeyDown(object sender, KeyRoutedEventArgs e)
    {
        if (e.Key == Windows.System.VirtualKey.Back)
        {
            if (string.IsNullOrWhiteSpace(currentText))
                return;

            ((TextBox)sender).Text = currentText;
            ((TextBox)sender).SelectionStart = currentText.Length;
            ((TextBox)sender).SelectionLength = 0;
        }
    }

    private void TextBox_KeyUp(object sender, KeyRoutedEventArgs e)
    {
        currentText = ((TextBox)sender).Text;
    }
</code>```

Body:
If you have a TextBox defined like this:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <TextBox KeyDown="TextBox_KeyDown"/>
</Grid>

And in the KeyDown-event if you just set Handled = true every time, user can't enter anything:

    private void TextBox_KeyDown(object sender, KeyRoutedEventArgs e)
    {
        e.Handled = true;
    }

But as you mentioned, if you check for Back-key and set the Handled = true, it doesn't work: User is still able to use backspace. So this doesn't work.

    private void TextBox_KeyDown(object sender, KeyRoutedEventArgs e)
    {
        if (e.Key == Windows.System.VirtualKey.Back)
        {
            e.Handled = true;
            return;
        }
    }

If you debug the code you can see that the character is already gone when the eventhandler is executed. You have to work around this, using other events. Here's one option:

XAML:

    <TextBox KeyDown="TextBox_KeyDown" KeyUp="TextBox_KeyUp"/>

Code behind:

    private string currentText;
    private void TextBox_KeyDown(object sender, KeyRoutedEventArgs e)
    {
        if (e.Key == Windows.System.VirtualKey.Back)
        {
            if (string.IsNullOrWhiteSpace(currentText))
                return;

            ((TextBox)sender).Text = currentText;
            ((TextBox)sender).SelectionStart = currentText.Length;
            ((TextBox)sender).SelectionLength = 0;
        }
    }

    private void TextBox_KeyUp(object sender, KeyRoutedEventArgs e)
    {
        currentText = ((TextBox)sender).Text;
    }


问:
Docker level load balancing using ECS
I am using elastic beanstalk to deploy the web services as Docker containers on AWS using ECS. Default load balancer available in EBS provides me network-level autoscaling to handle the load on EC2 instance.

How to handle auto-scaling in application level and use dockerization features using ECS like Kubernetes handling the dockers? I want to scale my individual dockers when it receives more memory or CPU usage. Please help me to achieve this.

答:
You can have the ECS cluster managed by an auto scaling group . This would take care of the hardware underlying the docker images.
As far as the containers themselves are concerned, you can go the way of application auto scaling.

Since both these services can be configured to answer to CW alarms for both downscale and upscale, you can have a HIGH cpu/ram alarm policy to add 1 host and 2 container replicas for example and remove the same amount on a LOW alarm.

Hope this helps

Title: Docker level load balancing using ECS


问:
Convert varchar data to time format in postgresql
I currently have a range of transaction data, and I am trying to query the data for the sum of transactions within a certain time frame. One field, transaction_time is a varchar. An example of one of these times is "13:42", which corresponds to 1:42pm. I was experimenting around with to_timestamp, but I have been unable to figure it out. Would anyone have any idea as to how to alter this varchar to represent time data.

Kind regards

答:
cast it to time.</p>

```<code>select cast('13:42' as time)
</code>```

Body:
cast it to time.

select cast('13:42' as time)


问:
How to Load WebView in Fragment class? How to load Webview in android?
I am trying to create a WebView in a Fragment which should be loaded. I added it already to my xml File. However, the findViewById method only works if I extend an Activity class. Is there anyway of which I can use it in Fragment as well?

I already tested the Solution from another Question, but it doesn't work.

```<code>public class OneFragment extends Fragment{

public WebView PlanWebView;

public OneFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    PlanWebView WebView = (PlanWebView) getView().findViewById(R.id.PlanWebView);
    // Unknown class: "PlanWebView";
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_one, container, false);
}

}
</code>```

答:
in Fragment you can declare your variables in onCreateView method.</p>

```<code>public class OneFragment extends Fragment{

public WebView PlanWebView;

public OneFragment() {
// Required empty public constructor
}

@Override
 public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
    }

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {

 }

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_one, container, false);
PlanWebView  = (WebView)view.findViewById(R.id.PlanWebView);
return view;
   }

 }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to create a WebView in a Fragment which should be loaded. I added it already to my xml File. However, the findViewById method only works if I extend an Activity class. Is there anyway of which I can use it in Fragment as well?

I already tested the Solution from another Question, but it doesn't work.

public class OneFragment extends Fragment{

public WebView PlanWebView;

public OneFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    PlanWebView WebView = (PlanWebView) getView().findViewById(R.id.PlanWebView);
    // Unknown class: "PlanWebView";
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_one, container, false);
}

}

Body:
in Fragment you can declare your variables in onCreateView method.

public class OneFragment extends Fragment{

public WebView PlanWebView;

public OneFragment() {
// Required empty public constructor
}

@Override
 public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
    }

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {

 }

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_one, container, false);
PlanWebView  = (WebView)view.findViewById(R.id.PlanWebView);
return view;
   }

 }


答:
For the first one, you are not getting the answer because you use same counter variable in inner loop:

Modify it to use different variable:

```<code>for(int a=0;a<=10;a++){
    for(int b=0;b<=10;b++){
        printf("%d", a);
    }
}
</code>```

Title: Loop program output

Body:
For the first one, you are not getting the answer because you use same counter variable in inner loop:

Modify it to use different variable:

for(int a=0;a<=10;a++){
    for(int b=0;b<=10;b++){
        printf("%d", a);
    }
}