问:
Asp.net Core Identity unit test controller actions
I'm having a problem working out how and what to test.

I have a controller that injects UserManager and calls the CreateAsync method to create a new user.

I don't want to test the Identity user manager as this has clearly been thoroughly tested already. What I would like to do is test that the controller runs through the correct paths (in my case, there are 3 paths, sending responses back with either model state errors, identity response errors or a simple string)

Should I be trying to create a mock of the user manager in order to create my test (I'm not sure how to set up user manager as a mock dependency)
Second, how can I set conditions to verify that the controller has taken a given path.

I am using xUnit and Moq.

```<code>[Route("api/[controller]")]
public class MembershipController : BaseApiController
{
    private UserManager<ApplicationUser> _userManager;

    public MembershipController(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }

    [HttpGet("RegisterNewUser")]
    public HttpResponseMessage RegisterNewUser([FromBody] NewUserRegistration user)
    {
        if (ModelState.IsValid)
        {
            ApplicationUser newUser = new ApplicationUser();
            newUser.UserName = user.username;
            newUser.Email = user.password;
            IdentityResult result = _userManager.CreateAsync(newUser, user.password).Result;

            if (result.Errors.Count() > 0)
            {
                var errors = new IdentityResultErrorResponse().returnResponseErrors(result.Errors);
                return this.WebApiResponse(errors, HttpStatusCode.BadRequest);
            }
        }
        else
        {
            var errors = new ViewModelResultErrorResponse().returnResponseErrors(ModelState);
            return this.WebApiResponse(errors, HttpStatusCode.BadRequest);
        }

        return this.WebApiResponse(
                    "We have sent a valifation email to you, please click on the verify email account link.",
                    HttpStatusCode.OK);
    }
}
</code>```

In My unit test I have the following to test a happy path scenario

```<code>    [Fact]
    public void RegisterNewUser_ReturnsHttpStatusOK_WhenValidModelPosted()
    {
        var mockStore = new Mock<IUserStore<ApplicationUser>>();
        var mockUserManager = new Mock<UserManager<ApplicationUser>>(mockStore.Object, null, null, null, null, null, null, null, null);

        ApplicationUser testUser = new ApplicationUser { UserName = "user@test.com" };

        mockStore.Setup(x => x.CreateAsync(testUser, It.IsAny<CancellationToken>()))
           .Returns(Task.FromResult(IdentityResult.Success));

        mockStore.Setup(x => x.FindByNameAsync(testUser.UserName, It.IsAny<CancellationToken>()))
                    .Returns(Task.FromResult(testUser));

        mockUserManager.Setup(x => x.CreateAsync(testUser).Result).Returns(new IdentityResult());

        MembershipController sut = new MembershipController(mockUserManager.Object);
        var input = new NewUserInputBuilder().Build();
        sut.RegisterNewUser(input);

    }
</code>```

Where "input" in sut.RegisterNewUser(input); refers to a helper class which constructs the viewmodel which the controller action requires:

```<code>public class NewUserInputBuilder
{
    private string username { get; set; }
    private string password { get; set; }
    private string passwordConfirmation { get; set; }
    private string firstname { get; set; }
    private string lastname { get; set; }

    internal NewUserInputBuilder()
    {
        this.username = "user@test.com";
        this.password = "password";
        this.passwordConfirmation = "password";
        this.firstname = "user";
        this.lastname = "name";
    }

    internal NewUserInputBuilder WithNoUsername()
    {
        this.username = "";
        return this;
    }

    internal NewUserInputBuilder WithMisMatchedPasswordConfirmation()
    {
        this.passwordConfirmation = "MismatchedPassword";
        return this;
    }

    internal NewUserRegistration Build()
    {
        return new NewUserRegistration
        { username = this.username, password = this.password,
            passwordConfirmation = this.passwordConfirmation,
            firstname = this.firstname, lastname = this.lastname
        };
    }
}
</code>```

My aim here is to force 3 conditions via tests:

Create a valid viewmodel and return a success message

Create a valid viewmodel but returns a IdentityResponse error (eg. user exists) which gets converted to

Create an invalid viewmodel and returns Modelstate errors

The errors are handled using a abstract class which returns a json object
The base class for the controller simply constructs a HttpResponseMessage for return.

Basically I want to check that the correct error response class is called by forcing the test down the modelstate error path, the identityresult.errors path and that the happy path can be achieved.

Then my plan is to test the error response classes in isolation.

Hopefully that is enough detail.

答:
Mehod under test should be made async and not use blocking calls ie .Result

```<code>[HttpGet("RegisterNewUser")]
public async Task<HttpResponseMessage> RegisterNewUser([FromBody] NewUserRegistration user) {
    if (ModelState.IsValid) {
        var newUser = new ApplicationUser() {
            UserName = user.username,
            Email = user.password
        };
        var result = await _userManager.CreateAsync(newUser, user.password);
        if (result.Errors.Count() > 0) {
            var errors = new IdentityResultErrorResponse().returnResponseErrors(result.Errors);
            return this.WebApiResponse(errors, HttpStatusCode.BadRequest);
        }
    } else {
        var errors = new ViewModelResultErrorResponse().returnResponseErrors(ModelState);
        return this.WebApiResponse(errors, HttpStatusCode.BadRequest);
    }

    return this.WebApiResponse(
                "We have sent a valifation email to you, please click on the verify email account link.",
                HttpStatusCode.OK);
}
</code>```

Review of Happy path scenario and method under test shows that there is no need to setup the UserStore as test will be overriding the user manager virtual members directly.

Note the test has also been made async as well.

Create a valid viewmodel and return a success message

```<code>[Fact]
public async Task RegisterNewUser_ReturnsHttpStatusOK_WhenValidModelPosted() {
    //Arrange
    var mockStore = Mock.Of<IUserStore<ApplicationUser>>();
    var mockUserManager = new Mock<UserManager<ApplicationUser>>(mockStore, null, null, null, null, null, null, null, null);

    mockUserManager
        .Setup(x => x.CreateAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>()))
        .ReturnsAsync(IdentityResult.Success);

    var sut = new MembershipController(mockUserManager.Object);
    var input = new NewUserInputBuilder().Build();

    //Act
    var actual = await sut.RegisterNewUser(input);

    //Assert
    actual
        .Should().NotBeNull()
        .And.Match<HttpResponseMessage>(_ => _.IsSuccessStatusCode == true);
}
</code>```

Create a valid viewmodel but returns a IdentityResponse error (eg. user exists) which gets converted

For this you just need to setup the mock to return a result with errors.

```<code>[Fact]
public async Task RegisterNewUser_ReturnsHttpStatusBadRequest_WhenViewModelPosted() {
    //Arrange

    //...code removed for brevity

    mockUserManager
        .Setup(x => x.CreateAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>()))
        .ReturnsAsync(IdentityResult.Failed(new IdentityError { Description = "test"}));

    //...code removed for brevity

    //Assert
    actual
        .Should().NotBeNull()
        .And.Match<HttpResponseMessage>(_ => _.StatusCode == HttpStatusCode.BadRequest);
}
</code>```

And for

Create an invalid viewmodel and returns Modelstate errors

You just need to set the model state of the controller so that it is invalid.

```<code>[Fact]
public async Task RegisterNewUser_ReturnsHttpStatusBadRequest_WhenInvalidModelState() {
    //Arrange
    var mockStore = Mock.Of<IUserStore<ApplicationUser>>();
    var mockUserManager = new Mock<UserManager<ApplicationUser>>(mockStore, null, null, null, null, null, null, null, null);

    var sut = new MembershipController(mockUserManager.Object);
    sut.ModelState.AddModelError("", "invalid data");
    var input = new NewUserInputBuilder().Build();

    //Act
    var actual = await sut.RegisterNewUser(input);

    //Assert
    actual
        .Should().NotBeNull()
        .And.Match<HttpResponseMessage>(_ => _.StatusCode == HttpStatusCode.BadRequest);
}
</code>```

FluentAssertions were used to do all the assertions. You could just as easily used Assert.* API.

This should be enough to get you on your way with the above question.

Body:
I'm having a problem working out how and what to test.

I have a controller that injects UserManager and calls the CreateAsync method to create a new user.

I don't want to test the Identity user manager as this has clearly been thoroughly tested already. What I would like to do is test that the controller runs through the correct paths (in my case, there are 3 paths, sending responses back with either model state errors, identity response errors or a simple string)

Should I be trying to create a mock of the user manager in order to create my test (I'm not sure how to set up user manager as a mock dependency)
Second, how can I set conditions to verify that the controller has taken a given path.

I am using xUnit and Moq.

[Route("api/[controller]")]
public class MembershipController : BaseApiController
{
    private UserManager<ApplicationUser> _userManager;

    public MembershipController(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }

    [HttpGet("RegisterNewUser")]
    public HttpResponseMessage RegisterNewUser([FromBody] NewUserRegistration user)
    {
        if (ModelState.IsValid)
        {
            ApplicationUser newUser = new ApplicationUser();
            newUser.UserName = user.username;
            newUser.Email = user.password;
            IdentityResult result = _userManager.CreateAsync(newUser, user.password).Result;

            if (result.Errors.Count() > 0)
            {
                var errors = new IdentityResultErrorResponse().returnResponseErrors(result.Errors);
                return this.WebApiResponse(errors, HttpStatusCode.BadRequest);
            }
        }
        else
        {
            var errors = new ViewModelResultErrorResponse().returnResponseErrors(ModelState);
            return this.WebApiResponse(errors, HttpStatusCode.BadRequest);
        }

        return this.WebApiResponse(
                    "We have sent a valifation email to you, please click on the verify email account link.",
                    HttpStatusCode.OK);
    }
}

In My unit test I have the following to test a happy path scenario

    [Fact]
    public void RegisterNewUser_ReturnsHttpStatusOK_WhenValidModelPosted()
    {
        var mockStore = new Mock<IUserStore<ApplicationUser>>();
        var mockUserManager = new Mock<UserManager<ApplicationUser>>(mockStore.Object, null, null, null, null, null, null, null, null);

        ApplicationUser testUser = new ApplicationUser { UserName = "user@test.com" };

        mockStore.Setup(x => x.CreateAsync(testUser, It.IsAny<CancellationToken>()))
           .Returns(Task.FromResult(IdentityResult.Success));

        mockStore.Setup(x => x.FindByNameAsync(testUser.UserName, It.IsAny<CancellationToken>()))
                    .Returns(Task.FromResult(testUser));

        mockUserManager.Setup(x => x.CreateAsync(testUser).Result).Returns(new IdentityResult());

        MembershipController sut = new MembershipController(mockUserManager.Object);
        var input = new NewUserInputBuilder().Build();
        sut.RegisterNewUser(input);

    }

Where "input" in sut.RegisterNewUser(input); refers to a helper class which constructs the viewmodel which the controller action requires:

public class NewUserInputBuilder
{
    private string username { get; set; }
    private string password { get; set; }
    private string passwordConfirmation { get; set; }
    private string firstname { get; set; }
    private string lastname { get; set; }

    internal NewUserInputBuilder()
    {
        this.username = "user@test.com";
        this.password = "password";
        this.passwordConfirmation = "password";
        this.firstname = "user";
        this.lastname = "name";
    }

    internal NewUserInputBuilder WithNoUsername()
    {
        this.username = "";
        return this;
    }

    internal NewUserInputBuilder WithMisMatchedPasswordConfirmation()
    {
        this.passwordConfirmation = "MismatchedPassword";
        return this;
    }

    internal NewUserRegistration Build()
    {
        return new NewUserRegistration
        { username = this.username, password = this.password,
            passwordConfirmation = this.passwordConfirmation,
            firstname = this.firstname, lastname = this.lastname
        };
    }
}

My aim here is to force 3 conditions via tests:

Create a valid viewmodel and return a success message

Create a valid viewmodel but returns a IdentityResponse error (eg. user exists) which gets converted to

Create an invalid viewmodel and returns Modelstate errors

The errors are handled using a abstract class which returns a json object
The base class for the controller simply constructs a HttpResponseMessage for return.

Basically I want to check that the correct error response class is called by forcing the test down the modelstate error path, the identityresult.errors path and that the happy path can be achieved.

Then my plan is to test the error response classes in isolation.

Hopefully that is enough detail.

Body:
Mehod under test should be made async and not use blocking calls ie .Result

[HttpGet("RegisterNewUser")]
public async Task<HttpResponseMessage> RegisterNewUser([FromBody] NewUserRegistration user) {
    if (ModelState.IsValid) {
        var newUser = new ApplicationUser() {
            UserName = user.username,
            Email = user.password
        };
        var result = await _userManager.CreateAsync(newUser, user.password);
        if (result.Errors.Count() > 0) {
            var errors = new IdentityResultErrorResponse().returnResponseErrors(result.Errors);
            return this.WebApiResponse(errors, HttpStatusCode.BadRequest);
        }
    } else {
        var errors = new ViewModelResultErrorResponse().returnResponseErrors(ModelState);
        return this.WebApiResponse(errors, HttpStatusCode.BadRequest);
    }

    return this.WebApiResponse(
                "We have sent a valifation email to you, please click on the verify email account link.",
                HttpStatusCode.OK);
}

Review of Happy path scenario and method under test shows that there is no need to setup the UserStore as test will be overriding the user manager virtual members directly.

Note the test has also been made async as well.

Create a valid viewmodel and return a success message

[Fact]
public async Task RegisterNewUser_ReturnsHttpStatusOK_WhenValidModelPosted() {
    //Arrange
    var mockStore = Mock.Of<IUserStore<ApplicationUser>>();
    var mockUserManager = new Mock<UserManager<ApplicationUser>>(mockStore, null, null, null, null, null, null, null, null);

    mockUserManager
        .Setup(x => x.CreateAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>()))
        .ReturnsAsync(IdentityResult.Success);

    var sut = new MembershipController(mockUserManager.Object);
    var input = new NewUserInputBuilder().Build();

    //Act
    var actual = await sut.RegisterNewUser(input);

    //Assert
    actual
        .Should().NotBeNull()
        .And.Match<HttpResponseMessage>(_ => _.IsSuccessStatusCode == true);
}

Create a valid viewmodel but returns a IdentityResponse error (eg. user exists) which gets converted

For this you just need to setup the mock to return a result with errors.

[Fact]
public async Task RegisterNewUser_ReturnsHttpStatusBadRequest_WhenViewModelPosted() {
    //Arrange

    //...code removed for brevity

    mockUserManager
        .Setup(x => x.CreateAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>()))
        .ReturnsAsync(IdentityResult.Failed(new IdentityError { Description = "test"}));

    //...code removed for brevity

    //Assert
    actual
        .Should().NotBeNull()
        .And.Match<HttpResponseMessage>(_ => _.StatusCode == HttpStatusCode.BadRequest);
}

And for

Create an invalid viewmodel and returns Modelstate errors

You just need to set the model state of the controller so that it is invalid.

[Fact]
public async Task RegisterNewUser_ReturnsHttpStatusBadRequest_WhenInvalidModelState() {
    //Arrange
    var mockStore = Mock.Of<IUserStore<ApplicationUser>>();
    var mockUserManager = new Mock<UserManager<ApplicationUser>>(mockStore, null, null, null, null, null, null, null, null);

    var sut = new MembershipController(mockUserManager.Object);
    sut.ModelState.AddModelError("", "invalid data");
    var input = new NewUserInputBuilder().Build();

    //Act
    var actual = await sut.RegisterNewUser(input);

    //Assert
    actual
        .Should().NotBeNull()
        .And.Match<HttpResponseMessage>(_ => _.StatusCode == HttpStatusCode.BadRequest);
}

FluentAssertions were used to do all the assertions. You could just as easily used Assert.* API.

This should be enough to get you on your way with the above question.


来源: stackexchange

问:
jQuery: how to get the id of a div (with a class named "hidden")
can you help me please ?

I'm searching for a solution to get an id from a hidden div and interact the id in an AJAX query when a click is happened

PHP code :

```<code>while ( $contents_print = mysqli_fetch_array( $req_print ) ) {
echo '
        <div class="post print" id="staggered-test">
            <img src="../00_sources/images/upload/pic_min/' . $contents_print[ 'pic_min' ] . '" alt="' . $contents_print[ 'pic_min' ] . '"/>
                <div class="post-content">
                    <a href="#modal" class="modal-action modal-trigger">Détail</a>
                    <div class="row"><blockquote>' . $contents_print[ 'detail_projet' ] . '</blockquote></div>
                </div>
            <div class="post-content valign-wrapper"><h4 class="header center">' . $contents_print[ 'nom_projet' ] . '</h4></div>
        </div>
    ';

echo '<div class="hidden" id="'.$contents_print[ 'id_projet' ].'"></div>';
}
</code>```

jQuery

```<code>$( document ).ready( function () {
  $(".post").siblings('div:hidden').attr("id").click(function() {
    var url_id = $(this).attr('id');
    //alert(url_id);
  });

  $.ajax({
    url: 'core/libs/contents-services.php?action=getFilterContent&id='+url_id,
    type: "get",
    dataType: "html",
    success: function ( reponse ) {
      $( '#modal' ).html( reponse );
      url_id = reponse.url_id;
    }
  });

  // the "href" attribute of the modal trigger must specify the modal ID that wants to be triggered
  $( '.modal' ).modal();
});
</code>```

May be I'm missing something, my code doesn't work

Please help me. Thanks a lot !

答:
You could do something like this:

```<code>$(".post").find(':hidden').each(function(a, el){
    console.log(a, $(el).attr("id"));
})
</code>```

Code

ContentLicense: CC BY-SA 3.0

Body:
can you help me please ?

I'm searching for a solution to get an id from a hidden div and interact the id in an AJAX query when a click is happened

PHP code :

while ( $contents_print = mysqli_fetch_array( $req_print ) ) {
echo '

                    Détail

' . $contents_print[ 'detail_projet' ] . '

' . $contents_print[ 'nom_projet' ] . '

    ';

echo '

';
}

jQuery

$( document ).ready( function () {
  $(".post").siblings('div:hidden').attr("id").click(function() {
    var url_id = $(this).attr('id');
    //alert(url_id);
  });

  $.ajax({
    url: 'core/libs/contents-services.php?action=getFilterContent&id='+url_id,
    type: "get",
    dataType: "html",
    success: function ( reponse ) {
      $( '#modal' ).html( reponse );
      url_id = reponse.url_id;
    }
  });

  // the "href" attribute of the modal trigger must specify the modal ID that wants to be triggered
  $( '.modal' ).modal();
});

May be I'm missing something, my code doesn't work

Please help me. Thanks a lot !

Body:
You could do something like this:

$(".post").find(':hidden').each(function(a, el){
    console.log(a, $(el).attr("id"));
})

Code


问:
Can I share a service between Angular and Node?
I have a standard utility service in my Angular5 Typescript app.
I want to share that with my node application, which is serving the app.

I can't find any info around it but I see issues as:

Using require() to import a TS file, and if the generated js file
lives in the same place

Ignoring the @Injectable which is a decorator
used on the angular service.

I assume it's possible as that's a major benefit of using full stack Javascript, but how can it be done?

I've  tried the following in NodeJs, which throws an error:

```<code>const utilService = require('../../src/app/services/util/util.service');
</code>```

答:
The only way I can think of how you can achieve this, is to provide a compiled (ES2015 and below) representation of your util.service. doing this could be an automated part of your build script/pipeline.

Or, if the util.service does not change that often, compile it by hand with

```<code>tsc ./src/app/services/util/util.service.ts --out ./src/app/services/util/util.service.js
</code>```

Body:
I have a standard utility service in my Angular5 Typescript app.
I want to share that with my node application, which is serving the app.

I can't find any info around it but I see issues as:

Using require() to import a TS file, and if the generated js file
lives in the same place

Ignoring the @Injectable which is a decorator
used on the angular service.

I assume it's possible as that's a major benefit of using full stack Javascript, but how can it be done?

I've  tried the following in NodeJs, which throws an error:

const utilService = require('../../src/app/services/util/util.service');

Body:
The only way I can think of how you can achieve this, is to provide a compiled (ES2015 and below) representation of your util.service. doing this could be an automated part of your build script/pipeline.

Or, if the util.service does not change that often, compile it by hand with

tsc ./src/app/services/util/util.service.ts --out ./src/app/services/util/util.service.js


问:
Trouble compiling for iOS 11.1 with Xamarin (Visual Studio)
There is not much of a point in posting actual code here, because we're talking about 7 different apps.

All of these apps have been up on the Apple Store and running fine.  Until the new iOS 11.1 came out.  Now I am being forced to update all of those apps, and rearrange the screen to allow for the new layout of the iPhone X.

Now all of this seems mostly reasonable, if not ridiculous for them changing their own design standard.  But the real problem is that I went through all of that.  Upgraded Xamarin (Visual Studio), and packages, and Xcode, and the Simulators, AND my Mac system.  Everything is up to speed.  The apps compile and test fine on any simulator I install them on.

The only change to the code is moving stuff around on the screen.  Well, that, and I now need to drop support for anything i386.  It all has to be x86_64 now.

From what I can tell, that is a difference from 32-bit to 64-bit.  And that change is a dropdown menu choice in the Project Options.  In any case, there is no indication at all that there is anything wrong with these apps at all.

So with all of this, I submit my apps for approval, and every single one of them gets rejected because "The app crashes on startup."  And they kindly attach a log file showing what went wrong.

Now, I know I can simply scour those logs, for all 7 apps... The log files need to be fed into some other program that can decipher them, because they are not human-readable.  Which is just annoying...

What I'm hoping is that someone can save me some trouble and explain what they changed in their systems that is not being caught by the compilers or the simulators.

Any help would be hot.

答:
1) Some of the frameworks that your app use may use libraries, that does not work correctly on iPhone. The reason for that is that when you compile your project on the simulator, is still compile it for a PC architecture, not a mobile one. And if there are any differences, only a real device could tell you about them.

2) I would suggest you to use this method to symbolicate crash reports from Apple. That at least should give you some clue. In summary, what you need to do is after you compile your app, you need to save a few files (.dSYM and .ipa) Then when apple send you back a report, you would be able to symbolicate it into human readable. You can find more info on how to do it here: https://developer.xamarin.com/guides/ios/troubleshooting/questions/symbolicate-ios-crash/


问:
Understanding using a method in map in Scala
Why does the line of asdf1 work in

```<code>  def trytoDouble(s: String): Option[Double] = {
    try {
      Some(s.toDouble)
    } catch {
      case e: Exception => None
    }
  }

val asdf1 = Source.fromFile("data/my.csv").getLines().map(_.split(",").map(_.trim).map(trytoDouble(_)))

val asdf2 = Source.fromFile("data/my.csv").getLines().map(_.split(",").map(trytoDouble(_.trim)))
</code>```

while the line of asdf2 gives me the error message

Type mismatch, expected String => NotInferedB, actual: Option[Double]

for trytoDouble?

答:
You can simplified your problem to see the point :

```<code>val oneLine = "line1, 13, 14, 15"               //> oneLine  : String = line1, 13, 14, 15
oneLine.split(",").map(_.trim)                  //> res2: Array[String] = Array(line1, 13, 14, 15)
</code>```

This line works

```<code> oneLine.split(",").map(s => trytoDouble(s.trim))//> res3: Array[Option[Double]] = Array(None, Some(13.0), Some(14.0), Some(15.0
</code>```

But this line does not :

```<code>oneLine.split(",").map(trytoDouble(_.trim))
</code>```

This is it because the compiler doesn't know how to infer the type of _ here, regarding the trim extension on String and the trytoDouble type.
The compiler message is :

```<code> missing parameter type for expanded function
</code>```

If you omit the trim, it's works :

```<code>  oneLine.split(",").map(trytoDouble(_))          //> res3: Array[Option[Double]] = Array(None, Some(13.0), Some(14.0), Some(15.0
</code>```

The inference type system, in scala, is limited. You come rapidely to this kind of situation where you have to help it.

Edit:

The placeholder is always replaced in the smallest containning expression.

In fact,

```<code> oneLine.split(",").map(trytoDouble(_.trim))
</code>```

is replaced by :

```<code>oneLine.split(",").map(trytoDouble(x => x.trim))
</code>```

but what you want is :

```<code>oneLine.split(",").map( x => trytoDouble(x.trim))
</code>```

Body:
Why does the line of asdf1 work in

  def trytoDouble(s: String): Option[Double] = {
    try {
      Some(s.toDouble)
    } catch {
      case e: Exception => None
    }
  }

val asdf1 = Source.fromFile("data/my.csv").getLines().map(_.split(",").map(_.trim).map(trytoDouble(_)))

val asdf2 = Source.fromFile("data/my.csv").getLines().map(_.split(",").map(trytoDouble(_.trim)))

while the line of asdf2 gives me the error message

Type mismatch, expected String => NotInferedB, actual: Option[Double]

for trytoDouble?

Body:
You can simplified your problem to see the point :

val oneLine = "line1, 13, 14, 15"               //> oneLine  : String = line1, 13, 14, 15
oneLine.split(",").map(_.trim)                  //> res2: Array[String] = Array(line1, 13, 14, 15)

This line works

 oneLine.split(",").map(s => trytoDouble(s.trim))//> res3: Array[Option[Double]] = Array(None, Some(13.0), Some(14.0), Some(15.0

But this line does not :

oneLine.split(",").map(trytoDouble(_.trim))

This is it because the compiler doesn't know how to infer the type of _ here, regarding the trim extension on String and the trytoDouble type.
The compiler message is :

 missing parameter type for expanded function

If you omit the trim, it's works :

  oneLine.split(",").map(trytoDouble(_))          //> res3: Array[Option[Double]] = Array(None, Some(13.0), Some(14.0), Some(15.0

The inference type system, in scala, is limited. You come rapidely to this kind of situation where you have to help it.

Edit:

The placeholder is always replaced in the smallest containning expression.

In fact,

 oneLine.split(",").map(trytoDouble(_.trim))

is replaced by :

oneLine.split(",").map(trytoDouble(x => x.trim))

but what you want is :

oneLine.split(",").map( x => trytoDouble(x.trim))


问:
Jersey 2 MVC - form data binding
I am building an MVC application using Jersey 2.26 and Java 8.

I would like to know if there is a way to bind form data to a POJO, much like you do in Spring, so that I could have something like this:

```<code>@POST
@Path("/edit")
@Consumes({ MediaType.APPLICATION_FORM_URLENCODED })
@Produces(MediaType.TEXT_HTML)
public Viewable editInventory(Inventory inventory) {
    ....
}
</code>```

I know you can bind individual primitives by using @FormParam("paramName"), but this is tedious as my post payload contains over a dozen attributes.
I have tried searching for docs and examples but can only find solutions for JSON and XML payloads.

答: Yes you can, you should consume MediaType.APPLICATION_JSON instead of MediaType.APPLICATION_FORM_URLENCODED, and if want also to response with that object you should add an annotation of javax.xml.bind.annotation.@XmlRootElement on Inventory class.

Title: Jersey 2 MVC - form data binding

Body:
I am building an MVC application using Jersey 2.26 and Java 8.

I would like to know if there is a way to bind form data to a POJO, much like you do in Spring, so that I could have something like this:

@POST
@Path("/edit")
@Consumes({ MediaType.APPLICATION_FORM_URLENCODED })
@Produces(MediaType.TEXT_HTML)
public Viewable editInventory(Inventory inventory) {
    ....
}

I know you can bind individual primitives by using @FormParam("paramName"), but this is tedious as my post payload contains over a dozen attributes.
I have tried searching for docs and examples but can only find solutions for JSON and XML payloads.


问:
How to get results according to distribution?
Is there a way in solr to get results according to some distribution of one of the indexed fields?

For example, imagine I have a catalog of books with fields synopsis, publication_year and genre.

I would like to build a query that returns the most relevant results according to synopsis favoring the most recently published books. However, in the final results (let's say 1000) I would like the genre to be distributed as closely as possible according to some given distribution. For example: 50% Science-Fiction, 25% Non-Fiction, 10% Politics and so on..

I know I could get a large result set and do some sort of weighted reservoir sampling to get the final 1000 books outside solr, but I am looking for a solution that would be solr only.

Is this possible and if  yes, how?

答:
While you won't be able to plugin your distribution, but you can use Collapse and Expand or Result Grouping to get n number of results for each genre. You then ignore any result returned above your threshold for that group.

You'll have to set the number of documents for each group to the maximum bucket size in your distribution of the total number of hits, i.e. 500 in your example above. This can give you a very large set of documents to work with, so I'd try to keep the total number returned pr. genre rather small at the start at least.

There might be some way to make the group sizes more dynamic by extending either of the two features above and adding your own code for limiting the number of documents collected per genre.

ContentLicense: CC BY-SA 4.0


问:
LetsEncrypt SSL Certificates with multi domains and multi subdomains
We've been using a PositiveSSL Multi-Domain Cert for some years, and that's been working fine. Under that Cert, we have, for instance:

domain1:

mail.domain1.com

www.domain1.com

domain1.com

domain2:

mail.domain2.fr

www.domain2.fr

domain2.fr

etc., with a total of 5 different domains.

Now, since we're going to expand our domain base and that the current Cert is expiring, we're looking closely at Lets-Encrypt.

Before I get into this, however, I'd like to know a couple of things:

(1)- does every subdomain (mail. www., etc.) as well as their main respective domain have to be listed in the main certificate? I'm mainly asking that because (a) that was my original understanding, and (b) the verification stage with Lets-Encrypt will differ (preferred-challenges=dns instead of by default apache-based), which will lead me to add DNS records for each domain/subdomain.

(2)- if it is indeed needed (and if I have no choice but use preferred-challenges=dns, at the time of the next Cert renewal (i.e. < 90 days), should the DNS records still have to be present? I'm asking this because last time I left the DNS records after creation, the mail server couldn't be reached anymore after the DNS propagation time. I'm pretty sure that it was because of my bad setup, but it's a risk I prefer to avoid taking.

(3)- if I'm missing here of you have a better advice to give me, let me know.

答:
In case someone has a similar issue or plan, this is what I've learned during this process:

Every domain name that the certificate will be used for has to be included. Let’s Encrypt will validate each of the domain names in the certificate.

If using DNS-01 validation, all of them will require DNS records to be added. With that, records will be required to re-validate the domains every 90 days (or whatever time frame you choose). This will require adding a new TXT record each time. Leaving the old TXT records from a previous validation will not work, the value changes each time.

There are also HTTP-01 and TLS-SNI-01 challenge types. If you already have an Apache instance running I recommend using HTTP-01.

If you don’t have a webserver on the machine that runs mail.domain1.com you can still use HTTP-01. Certbot has a feature called “standalone” mode where it can start up a small purpose built webserver to answer HTTP-01 challenges to provision a certificate.

To use HTTP or TLS-SNI validation on a non-web server, you would run something like: certbot certonly --standalone -d mail.example.com. You still need to have port 80 or 443 open in your firewall to use this method, but you need no server running on those ports. If you only want to open one port you can specify the challenge type explicitly, e.g. --preferred-challenges http to use port 80 or --preferred-challenges tls-sni to use port 443.


问:
Rewrite inpage javascript to js file
I use a piece of Javascript to display current weather on a dashboard. The function is writting in an "inpage" format, so in need the place it in my index.php. I want to move the function to my scripts.js, but how do I transform this code to work correctly? I am very new to Javascript functions... Any ideas?</p>

```<code>           reallySimpleWeather.weather({
               wunderkey: '', // leave blank for Yahoo
               location: 'Holten, NL', //your location
               woeid: '', // "Where on Earth ID"
               unit: 'c', // 'c' also works

               success: function(weather) {
                 html = '<div id="weergraden">'+weather.temp+'°'+' graden</div>';
                 html += '<div id="weerstatus">'+weather.currently.replace("Mostly ", "Veelal ").replace("Showers" , "Regenbuien").replace("Sunny", "Zonnig").replace("Partly ", "Lichte ").replace("Cloudy", "Bewolking").replace("Rain", "Regen").replace("Scattered " , "Verspreide ").replace("Clear", "Helder")+'</div>';
              html += '<img src="'+weather.image+'"></img>';
              //html += "<img src='"+serverurl+"weer/"+weather.currently.replace(" ", "_")+".png'></img>";
              document.getElementById('weer').innerHTML = html;
              setInterval(weather, 6000);
               },
               error: function(error) {
              document.getElementById('weer').innerHTML = '<p>'+error+'</p>';
               }
           });
</code>```

答:
You can just copypaste this code to separate file for example app.js,
and than connect it to your php page.

```<code><?php echo"<script language='javascript' src='reallySimpleWeatherCDN'></script>";?>
<?php echo"<script language='javascript' src=/javascript/app.js></script>";?>
</code>```

Consider that you are connecting app.js after reallySimpleWeather library

Title: Rewrite inpage javascript to js file

Body:
I use a piece of Javascript to display current weather on a dashboard. The function is writting in an "inpage" format, so in need the place it in my index.php. I want to move the function to my scripts.js, but how do I transform this code to work correctly? I am very new to Javascript functions... Any ideas?

           reallySimpleWeather.weather({
               wunderkey: '', // leave blank for Yahoo
               location: 'Holten, NL', //your location
               woeid: '', // "Where on Earth ID"
               unit: 'c', // 'c' also works

               success: function(weather) {
                 html = '
'+weather.temp+'°'+' graden
';
                 html += '
'+weather.currently.replace("Mostly ", "Veelal ").replace("Showers" , "Regenbuien").replace("Sunny", "Zonnig").replace("Partly ", "Lichte ").replace("Cloudy", "Bewolking").replace("Rain", "Regen").replace("Scattered " , "Verspreide ").replace("Clear", "Helder")+'
';
              html += '';
              //html += "";
              document.getElementById('weer').innerHTML = html;
              setInterval(weather, 6000);
               },
               error: function(error) {
              document.getElementById('weer').innerHTML = '
'+error+'
';
               }
           });

Body:
You can just copypaste this code to separate file for example app.js,
and than connect it to your php page.

<?php echo"<script language='javascript' src='reallySimpleWeatherCDN'></script>";?>
<?php echo"<script language='javascript' src=/javascript/app.js></script>";?>

Consider that you are connecting app.js after reallySimpleWeather library


问:
Angular 4 get local JSON File
I have searched 3 Hours and cant solved the problem. So i hope one of you know how i can fix it. I develope

First the code:

import { Injectable } from '@angular/core';
import { OnInit } from '@angular/core/src/metadata/lifecycle_hooks';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class UserService {
  isLoggedIn: boolean;
  user: string[];
  constructor(private http: HttpClient) {
  }

  getData(): void {
    this.http.get('./src/assets/dummy-response/authentication/login.dummy.json').subscribe(data => {
      // Read the user infos  from the JSON response
      this.user = data['user'];
      console.log(data);
    });
    this.http.get('').subscribe(data => {
      // Read the login_success from the JSON response
      this.isLoggedIn = data['login_success'];
      console.log(data);
    },
  err => {
    console.log('ALARM');
  });
  }
}
console.log('HALLOOOO');```

The error code:

enter image description here

directories structure:

enter image description here

So my question is, how can i access this file in assets/dummy-response/authentication/login.dummy.json?
I use the router from Angular and i think, thats the problem, that they dont let me pass.

答:
try this:</p>

```<code>var fs = require('fs');
var myData;

/* Read the file, and pass it to your callback*/
fs.readFile('./myjsondataFile.json', handleJSONFile);
var handleJSONFile = function (err, data) {
  if (err) {
     throw err;
 }
 myData= JSON.parse(data);
}
</code>```

Title: Angular 4 get local JSON File

Body:
I have searched 3 Hours and cant solved the problem. So i hope one of you know how i can fix it. I develope

First the code:

import { Injectable } from '@angular/core';
import { OnInit } from '@angular/core/src/metadata/lifecycle_hooks';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class UserService {
  isLoggedIn: boolean;
  user: string[];
  constructor(private http: HttpClient) {
  }

  getData(): void {
    this.http.get('./src/assets/dummy-response/authentication/login.dummy.json').subscribe(data => {
      // Read the user infos  from the JSON response
      this.user = data['user'];
      console.log(data);
    });
    this.http.get('').subscribe(data => {
      // Read the login_success from the JSON response
      this.isLoggedIn = data['login_success'];
      console.log(data);
    },
  err => {
    console.log('ALARM');
  });
  }
}
console.log('HALLOOOO');

The error code:

enter image description here

directories structure:

enter image description here

So my question is, how can i access this file in assets/dummy-response/authentication/login.dummy.json?
I use the router from Angular and i think, thats the problem, that they dont let me pass.

Body:
try this:

var fs = require('fs');
var myData;

/* Read the file, and pass it to your callback*/
fs.readFile('./myjsondataFile.json', handleJSONFile);
var handleJSONFile = function (err, data) {
  if (err) {
     throw err;
 }
 myData= JSON.parse(data);
}


问:
How do you query a database using a Date and Time from PHP Function
How do I fix my query code so that it searches the database using a Date and Time but the Date is a variable from the function? I am new to PHP and SQL and don't know how the Dots ( . ) and Quotations fully work ( "" '' ). How do i fix this piece of code?

```<code>WHERE Fixture.date => '$FixtureDate 00:00:00' AND Fixture.date =< '$FixtureDate 23:59:59'
</code>```

Please See code below

```<code>function FSearchDate($FixtureDate) {
    try {
        $conn = new PDO("mysql:host=" . $GLOBALS['servername'] . ";dbname=DATABASE_NAME", $GLOBALS['username'], $GLOBALS['password']);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $statement = $conn->query("
        SELECT Fixtures.fixtureid AS FixtureID,
        Fixtures.date AS Date,
        Fixtures.week AS Week,
        Fixtures.home_team AS HomeTeam,
        Fixtures.away_team AS AwayTeam,
        FixtureScores.home_team AS HomeScore,
        FixtureScores.away_team AS AwayScore
        FROM Fixtures
        INNER JOIN FixtureScores ON Fixtures.fixtureid=FixtureScores.fixtureid
        WHERE Fixture.date => '$FixtureDate 00:00:00' AND Fixture.date =< '$FixtureDate 23:59:59'"
        );
        $result = $statement->fetch();

        if ($result == null) { // Fixture ID Doesn't Exist
            echo '<script type="text/javascript">alert("The Fixture ID entered is not valid. Please enter a valid Fixture ID");</script>';
        } else {
            $GLOBALS['FixtureID'] = $result[0];
            $GLOBALS['FixtureDate'] = $result[1];
            $GLOBALS['FixtureWeek'] = $result[2];
            $GLOBALS['FixtureHomeTeamName'] = $result[3];
            $GLOBALS['FixtureAwayTeamName'] = $result[4];
            $GLOBALS['FixtureHomeTeamScore'] = $result[5];
            $GLOBALS['FixtureAwayTeamScore'] = $result[6];
        }
    }
    catch(PDOException $e) {
        echo "An problem occured: " . $e->getMessage();
    }

    $conn = null;
}
</code>```

答:
Your query is wrong:

```<code>WHERE Fixture.date => '$FixtureDate 00:00:00' AND Fixture.date =< '$FixtureDate 23:59:59'"
</code>```

You're trying to use the => and =< which don't do what you expected.

The => is the separator for associative arrays.

http://www.php.net/manual/en/language.types.array.php

Those should read as >= and <= respectively, as in "more than or equal to" and "less than or equal to".

Note: =< doesn't exist and isn't a valid operator/separator.

Say it out loud: "less than or equal to". We never say "equal to or less than".

Plus, you may have a variable scoping here for the FSearchDate() method, where you would might have to pass the database connection to. Yet, this might not be the case.

Body:
How do I fix my query code so that it searches the database using a Date and Time but the Date is a variable from the function? I am new to PHP and SQL and don't know how the Dots ( . ) and Quotations fully work ( "" '' ). How do i fix this piece of code?

WHERE Fixture.date => '$FixtureDate 00:00:00' AND Fixture.date =< '$FixtureDate 23:59:59'

Please See code below

function FSearchDate($FixtureDate) {
    try {
        $conn = new PDO("mysql:host=" . $GLOBALS['servername'] . ";dbname=DATABASE_NAME", $GLOBALS['username'], $GLOBALS['password']);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $statement = $conn->query("
        SELECT Fixtures.fixtureid AS FixtureID,
        Fixtures.date AS Date,
        Fixtures.week AS Week,
        Fixtures.home_team AS HomeTeam,
        Fixtures.away_team AS AwayTeam,
        FixtureScores.home_team AS HomeScore,
        FixtureScores.away_team AS AwayScore
        FROM Fixtures
        INNER JOIN FixtureScores ON Fixtures.fixtureid=FixtureScores.fixtureid
        WHERE Fixture.date => '$FixtureDate 00:00:00' AND Fixture.date =< '$FixtureDate 23:59:59'"
        );
        $result = $statement->fetch();

        if ($result == null) { // Fixture ID Doesn't Exist
            echo '';
        } else {
            $GLOBALS['FixtureID'] = $result[0];
            $GLOBALS['FixtureDate'] = $result[1];
            $GLOBALS['FixtureWeek'] = $result[2];
            $GLOBALS['FixtureHomeTeamName'] = $result[3];
            $GLOBALS['FixtureAwayTeamName'] = $result[4];
            $GLOBALS['FixtureHomeTeamScore'] = $result[5];
            $GLOBALS['FixtureAwayTeamScore'] = $result[6];
        }
    }
    catch(PDOException $e) {
        echo "An problem occured: " . $e->getMessage();
    }

    $conn = null;
}

Body:
Your query is wrong:

WHERE Fixture.date => '$FixtureDate 00:00:00' AND Fixture.date =< '$FixtureDate 23:59:59'"

You're trying to use the => and =< which don't do what you expected.

The => is the separator for associative arrays.

http://www.php.net/manual/en/language.types.array.php

Those should read as >= and <= respectively, as in "more than or equal to" and "less than or equal to".

Note: =< doesn't exist and isn't a valid operator/separator.

Say it out loud: "less than or equal to". We never say "equal to or less than".

Plus, you may have a variable scoping here for the FSearchDate() method, where you would might have to pass the database connection to. Yet, this might not be the case.


问:
Using string as array indices in NumPy
I'm handling large numerical arrays in python through a GUI.
I'd like to expose the slicing capabilities to a textbox in a GUI, so I can easily choose part of the array that should be used for the calculation at hand.

Simple example of what I'd like to do:

```<code>arr = array([0, 10, 20, 30, 40, 50, 60, 70, 80, 90])

a = "2:4" # example string from GUI Textbox
b = "[3, 4, 5]" # example string from GUI Textbox

print arr[a] # not valid code -> what should be written here to make it work?
print arr[b] # not valid code -> what should be written here to make it work?
</code>```

should output:

```<code>[20, 30]
[30, 40, 50]
</code>```

I found out about the slice function, but I'd need to parse my string manually and create a slice. Is there a simpler way?

答:
Try this i think it works, assuming that you will get min and max in your string.</p>

```<code>import re
a = "2:4"
min = int(min(re.findall(r'(\d)',a)))
max = int(max(re.findall(r'(\d)',a)))
print arr[min:max]
</code>```

Title: Using string as array indices in NumPy

Body:
I'm handling large numerical arrays in python through a GUI.
I'd like to expose the slicing capabilities to a textbox in a GUI, so I can easily choose part of the array that should be used for the calculation at hand.

Simple example of what I'd like to do:

arr = array([0, 10, 20, 30, 40, 50, 60, 70, 80, 90])

a = "2:4" # example string from GUI Textbox
b = "[3, 4, 5]" # example string from GUI Textbox

print arr[a] # not valid code -> what should be written here to make it work?
print arr[b] # not valid code -> what should be written here to make it work?

should output:

[20, 30]
[30, 40, 50]

I found out about the slice function, but I'd need to parse my string manually and create a slice. Is there a simpler way?

Body:
Try this i think it works, assuming that you will get min and max in your string.

import re
a = "2:4"
min = int(min(re.findall(r'(\d)',a)))
max = int(max(re.findall(r'(\d)',a)))
print arr[min:max]


问:
Cucumber: How to write snippets/step definitions in PHP?
I am trying to get Cucumber working to test a PHP application. So far I am able to get the feature to run by simplying running cucumber in my features directory. At the bottom of the results, it says:

If you want snippets in a different programming language, just make sure a file
with the appropriate file extension exists where cucumber looks for step definitions.

What does this mean exactly? I'm fine with writing most of my step definitions in Ruby, but at some point, I'm going to need to create some setup data (ideally creating it in PHP). How can I write step definitions in PHP as this statement suggests?

FYI: I am new to Ruby and Cucumber as well.

Solution: Cuke4PHP

Cuke4PHP implements the Cucumber wire protocol, making it possible to write step definitions in PHP.

答:
If you didn't find a solution, this is what I found today! This guy spared me the work I had to do to use PHP lol

https://github.com/olbrich/cuke4php

He has implemented the wire protocol for PHP. This in a nutshell is another server that runs PHP steps when Cucumber finds any. Also passes back the results.

Ah no need to configure env.rb any more.

ContentLicense: CC BY-SA 2.5


问:
Facebook graph v2.11: Only owners of the URL have the ability to specify the picture, name, thumbnail or description params
Today i'm using Facebook graph v2.11 to auto post to facebook but see error

Only owners of the URL have the ability to specify the picture, name, thumbnail or description params

My code

```<code>try {
    $response = $fb->post('/me/feed', $linkData, $token);
} catch (Facebook\Exceptions\FacebookResponseException $e) {
    trigger_error($e->getMessage());
    return false;
} catch (Facebook\Exceptions\FacebookSDKException $e) {
    trigger_error($e->getMessage());
    return false;
}
</code>```

Please help me, thank!

答:
Setting the picture, name, caption, thumbnail and description manually is deprecated.

However, there is a recent change in this. From the docs:

"As of November 7, 2017, link customization is available however the
  link must be owned by the posting page and a page access token is
  required. To verify ownership, check the
  ownership_permissions{can_customize_link_posts} field on the URL node.
  See our Link Ownership Guide for more information. For versions 2.10
  and lower, picture, name, thumbnail, and description are deprecated.
  caption is deprecated for all versions."

However, this is only available to pages via Domain Verification.

Body:
Today i'm using Facebook graph v2.11 to auto post to facebook but see error

Only owners of the URL have the ability to specify the picture, name, thumbnail or description params

My code

try {
    $response = $fb->post('/me/feed', $linkData, $token);
} catch (Facebook\Exceptions\FacebookResponseException $e) {
    trigger_error($e->getMessage());
    return false;
} catch (Facebook\Exceptions\FacebookSDKException $e) {
    trigger_error($e->getMessage());
    return false;
}

Please help me, thank!


问:
Preserve function context in Python
I'm having a function in Python that when being called first, reads the content of a file to a list and checks whether or not an element is within that list.

```<code>def is_in_file(element, path):
    with open(path, 'r') as f:
        lines = [line.strip() for line in f.readlines()]
    return element in lines
</code>```

When the function is being called again, however, the content of the file should not be read again; the function should instead remember the value of lines from the first call.

Is there a way to preserve the context of a function when calling the function again? I don't want to make lines global to not litter the above namespace. I guess it's quite similar to the use of a generator and the yield statement...

答:
You could save the lines in a keyword argument declared with a mutable default value:

```<code>def is_in_file(element, path, lines=[]):
    if lines:
        return element in lines
    with open(path, 'r') as f:
        lines += [line.strip() for line in f.readlines()]
    return element in lines
</code>```

Caveat:
you must be sure that this function is only called with one file; if you call it with a second file, it will not open it and continue to return values based on the first file opened.

A more flexible solution:

A more flexible solution is maybe to use a dictionary of lines, where each new file can be opened once and stored, using the path as key; you can then call the function with different files, and get the correct results while memoizing the contents.

```<code>def is_in_file(element, path, all_lines={}):
    try:
        return element in all_lines[path]
    except KeyError:
        with open(path, 'r') as f:
            all_lines[path] = [line.strip() for line in f.readlines()]
        return element in lines
</code>```

OO solution:

Create a class to encapsulate the content of a file, like what @SergeBallesta proposed; although it does not address exactly what you requested, it is likely the better solution in the long run.

Title: Preserve function context in Python

Body:
I'm having a function in Python that when being called first, reads the content of a file to a list and checks whether or not an element is within that list.

def is_in_file(element, path):
    with open(path, 'r') as f:
        lines = [line.strip() for line in f.readlines()]
    return element in lines

When the function is being called again, however, the content of the file should not be read again; the function should instead remember the value of lines from the first call.

Is there a way to preserve the context of a function when calling the function again? I don't want to make lines global to not litter the above namespace. I guess it's quite similar to the use of a generator and the yield statement...

Body:
You could save the lines in a keyword argument declared with a mutable default value:

def is_in_file(element, path, lines=[]):
    if lines:
        return element in lines
    with open(path, 'r') as f:
        lines += [line.strip() for line in f.readlines()]
    return element in lines

Caveat:
you must be sure that this function is only called with one file; if you call it with a second file, it will not open it and continue to return values based on the first file opened.

A more flexible solution:

A more flexible solution is maybe to use a dictionary of lines, where each new file can be opened once and stored, using the path as key; you can then call the function with different files, and get the correct results while memoizing the contents.

def is_in_file(element, path, all_lines={}):
    try:
        return element in all_lines[path]
    except KeyError:
        with open(path, 'r') as f:
            all_lines[path] = [line.strip() for line in f.readlines()]
        return element in lines

OO solution:

Create a class to encapsulate the content of a file, like what @SergeBallesta proposed; although it does not address exactly what you requested, it is likely the better solution in the long run.


问:
alert after php-formular has send
I have a E-Mail formular on my Webside. After the Mail is send i will give the user a feedback. How can i give the alert on my side with the formular?
Now I will be forwarded to sendMail.php with the alerttext writen on the page.

html-code (in index.html):

```<code><form ... action="sendMail.php">
   ...
</form>
</code>```

php-code (in sendMail.php):

```<code>$mail_senden = mail($empfaenger,$betreff,$msg,$header);

if($mail_senden){
  echo "nachricht1";
  exit();
} else{
  echo "nachricht2";
  exit();
}
</code>```

答:
A simple method would be to use Javascript + JQuery and do something like this:

Add this to index.html

```<code><script>
   $("#YourFormID").submit(function(){
        event.preventDefault();
        var mailData = $("#YourFormID").serialize();
        $.ajax({
             type: "GET",
             url: "sendMail.php?"+mailData,
             success: function(html){
                  if(html=='true'){
                      alert("E-Mail sent");
                  }
                  else{
                      alert("E-Mail was not sent";
                  }
        });
        $( "#YourFormID" ).submit();
    }
</script>
</code>```

And in your sendMail.php (YOU need it, but the User doesnt see it)

```<code>$empfaenger = $_GET['NameOfInputFieldWithThisValue'];
$betreff = $_GET['NameOfInputFieldWithThisValue'];
$msg = $_GET['NameOfInputFieldWithThisValue'];
$header = $_GET['NameOfInputFieldWithThisValue'];

$mail_senden = mail($empfaenger,$betreff,$msg,$header);

if($mail_senden){
  echo "true";
  exit();
} else{
  echo "false";
  exit();
}
</code>```

Haven't tested it, but I think it should work

PS: You need to include JQuery before your script-Tag opens

Title: alert after php-formular has send

Body:
I have a E-Mail formular on my Webside. After the Mail is send i will give the user a feedback. How can i give the alert on my side with the formular?
Now I will be forwarded to sendMail.php with the alerttext writen on the page.

html-code (in index.html):

<form ... action="sendMail.php">
   ...
</form>

php-code (in sendMail.php):

$mail_senden = mail($empfaenger,$betreff,$msg,$header);

if($mail_senden){
  echo "nachricht1";
  exit();
} else{
  echo "nachricht2";
  exit();
}

Body:
A simple method would be to use Javascript + JQuery and do something like this:

Add this to index.html

<script>
   $("#YourFormID").submit(function(){
        event.preventDefault();
        var mailData = $("#YourFormID").serialize();
        $.ajax({
             type: "GET",
             url: "sendMail.php?"+mailData,
             success: function(html){
                  if(html=='true'){
                      alert("E-Mail sent");
                  }
                  else{
                      alert("E-Mail was not sent";
                  }
        });
        $( "#YourFormID" ).submit();
    }
</script>

And in your sendMail.php (YOU need it, but the User doesnt see it)

$empfaenger = $_GET['NameOfInputFieldWithThisValue'];
$betreff = $_GET['NameOfInputFieldWithThisValue'];
$msg = $_GET['NameOfInputFieldWithThisValue'];
$header = $_GET['NameOfInputFieldWithThisValue'];

$mail_senden = mail($empfaenger,$betreff,$msg,$header);

if($mail_senden){
  echo "true";
  exit();
} else{
  echo "false";
  exit();
}

Haven't tested it, but I think it should work

PS: You need to include JQuery before your script-Tag opens


问:
Google People API - Is it possible to get custom fields?
I need to import google contacts to my application. For that I try to use the Google People API but I didn't find an option to get the contacts custom fields.

Is it possible to get contact custom fields with the new Google People API?
Should I use the old Google Contacts API for that?

Thanks!

答:
Request the userDefined projection with your personFields.

String url = "https://people.googleapis.com/v1/people/me/connections" +
              "?personFields=names,emailAddresses,userDefined";

The response looks like this:

```<code>"userDefined": [
        {
          "metadata": {
            "primary": true,
            "source": {
              "type": "CONTACT",
              "id": "5629e24b082d1a66"
            }
          },
          "key": "label1",
          "value": "foo"
        },
        {
          "metadata": {
            "source": {
              "type": "CONTACT",
              "id": "5629e24b082d1a66"
            }
          },
          "key": "label2",
          "value": "bar"
        }
      ]
</code>```

For more details, see  https://developers.google.com/people/api/rest/v1/people#Person.UserDefined

You can also update custom fields even though the documentation does not currently list userDefined as a valid field for updatePersonFields as the field mask.

https://developers.google.com/people/api/rest/v1/people/updateContact

Body:
Request the userDefined projection with your personFields.

String url = "https://people.googleapis.com/v1/people/me/connections" +
              "?personFields=names,emailAddresses,userDefined";

The response looks like this:

"userDefined": [
        {
          "metadata": {
            "primary": true,
            "source": {
              "type": "CONTACT",
              "id": "5629e24b082d1a66"
            }
          },
          "key": "label1",
          "value": "foo"
        },
        {
          "metadata": {
            "source": {
              "type": "CONTACT",
              "id": "5629e24b082d1a66"
            }
          },
          "key": "label2",
          "value": "bar"
        }
      ]

For more details, see  https://developers.google.com/people/api/rest/v1/people#Person.UserDefined

You can also update custom fields even though the documentation does not currently list userDefined as a valid field for updatePersonFields as the field mask.

https://developers.google.com/people/api/rest/v1/people/updateContact


问:
Using same column multiple times in WHERE clause
I have a following table structure.

USERS

PROPERTY_VALUE

PROPERTY_NAME

USER_PROPERTY_MAP

I am trying to retrieve user/s from the users table who have matching properties in property_value table.

A single user can have multiple properties. The example data here has 2 properties for user '1', but there can be more than 2. I want to use all those user properties in the WHERE clause.

This query works if user has a single property but it fails for more than 1 properties:

```<code>SELECT * FROM users u
INNER JOIN user_property_map upm ON u.id = upm.user_id
INNER JOIN property_value pv ON upm.property_value_id = pv.id
INNER JOIN property_name pn ON pv.property_name_id = pn.id
WHERE (pn.id = 1 AND pv.id IN (SELECT id FROM property_value WHERE value like '101')
AND pn.id = 2 AND pv.id IN (SELECT id FROM property_value WHERE value like '102')) and u.user_name = 'user1' and u.city = 'city1'
</code>```

I understand since the query has pn.id = 1 AND pn.id = 2 it will always fail because pn.id can be either 1 or 2 but not both at the same time. So how can I re-write it to make it work for n number of properties?

In above example data there is only one user with id = 1 that has both matching properties used in the WHERE clause. The query should return a single record with all columns of the USERS table.

To clarify my requirements

I am working on an application that has a users list page on the UI listing all users in the system. This list has information like user id, user name, city etc. - all columns of the in USERS table. Users can have properties as detailed in the database model above.

The users list page also provides functionality to search users based on these properties. When searching for users with 2 properties, 'property1' and 'property2', the page should fetch and display only matching rows. Based on the test data above, only user '1' fits the bill.

A user with 4 properties including 'property1' and 'property2' qualifies. But a user with only one property 'property1' would be excluded due to the missing 'property2'.

答:
```<code>SELECT * FROM users u
INNER JOIN user_property_map upm ON u.id = upm.user_id
INNER JOIN property_value pv ON upm.property_value_id = pv.id
INNER JOIN property_name pn ON pv.property_name_id = pn.id
WHERE (pn.id = 1 AND pv.id IN (SELECT id FROM property_value WHERE value
like '101') )
OR ( pn.id = 2 AND pv.id IN (SELECT id FROM property_value WHERE value like
'102'))

OR (...)
OR (...)
</code>```

You can't do AND because there is no such a case where id is 1 and 2 for the SAME ROW, you specify the where condition for each row!

If you run a simple test, like

```<code>SELECT * FROM users where id=1 and id=2
</code>```

you will get 0 results. To achieve that use

```<code> id in (1,2)
</code>```

or

```<code> id=1 or id=2
</code>```

That query can be optimised more but this is a good start I hope.

Body:
I have a following table structure.

USERS

PROPERTY_VALUE

PROPERTY_NAME

USER_PROPERTY_MAP

I am trying to retrieve user/s from the users table who have matching properties in property_value table.

A single user can have multiple properties. The example data here has 2 properties for user '1', but there can be more than 2. I want to use all those user properties in the WHERE clause.

This query works if user has a single property but it fails for more than 1 properties:

SELECT * FROM users u
INNER JOIN user_property_map upm ON u.id = upm.user_id
INNER JOIN property_value pv ON upm.property_value_id = pv.id
INNER JOIN property_name pn ON pv.property_name_id = pn.id
WHERE (pn.id = 1 AND pv.id IN (SELECT id FROM property_value WHERE value like '101')
AND pn.id = 2 AND pv.id IN (SELECT id FROM property_value WHERE value like '102')) and u.user_name = 'user1' and u.city = 'city1'

I understand since the query has pn.id = 1 AND pn.id = 2 it will always fail because pn.id can be either 1 or 2 but not both at the same time. So how can I re-write it to make it work for n number of properties?

In above example data there is only one user with id = 1 that has both matching properties used in the WHERE clause. The query should return a single record with all columns of the USERS table.

To clarify my requirements

I am working on an application that has a users list page on the UI listing all users in the system. This list has information like user id, user name, city etc. - all columns of the in USERS table. Users can have properties as detailed in the database model above.

The users list page also provides functionality to search users based on these properties. When searching for users with 2 properties, 'property1' and 'property2', the page should fetch and display only matching rows. Based on the test data above, only user '1' fits the bill.

A user with 4 properties including 'property1' and 'property2' qualifies. But a user with only one property 'property1' would be excluded due to the missing 'property2'.

Body:
SELECT * FROM users u
INNER JOIN user_property_map upm ON u.id = upm.user_id
INNER JOIN property_value pv ON upm.property_value_id = pv.id
INNER JOIN property_name pn ON pv.property_name_id = pn.id
WHERE (pn.id = 1 AND pv.id IN (SELECT id FROM property_value WHERE value
like '101') )
OR ( pn.id = 2 AND pv.id IN (SELECT id FROM property_value WHERE value like
'102'))

OR (...)
OR (...)

You can't do AND because there is no such a case where id is 1 and 2 for the SAME ROW, you specify the where condition for each row!

If you run a simple test, like

SELECT * FROM users where id=1 and id=2

you will get 0 results. To achieve that use

 id in (1,2)

or

 id=1 or id=2

That query can be optimised more but this is a good start I hope.


问:
jQuery not works on first click
I am using Rails and I am trying to create a bookmark icon in ajax.
The code works, the problem is on the first click the request is sent but the image doesn't change, for the next clicks the behavior is OK (request sent and image change).

My view:

```<code><%= link_to favorite_company_job_path(@job, matching_id: candidate.id), method: :post, remote: true do %>
  <span class="favorite">
    <% if candidate.favorite %>
      <img src="<%= asset_url "favorite-activated.png" %>" alt="favorito" class="img-40" id="favorite_activated_<%= candidate.id %>">
    <% else %>
      <img src="<%= asset_url "favorite.png"%>" alt="favorito" class="img-40" id="favorite_<%= candidate.id %>">
    <% end %>
  </span>
<% end %>
</code>```

My file favorite.js.erb

```<code>$('#favorite_<%= @matching.id %>').on({
  'click': function(){
    $('#favorite_<%= @matching.id %>').attr('src','<%= asset_url "favorite-activated.png" %>');
    $('#favorite_<%= @matching.id %>').attr('id','favorite_activated_<%= @matching.id %>');
  }
});

$('#favorite_activated_<%= @matching.id %>').on({
  'click': function(){
    $('#favorite_activated_<%= @matching.id %>').attr('src','<%= asset_url "favorite.png" %>');
    $('#favorite_activated_<%= @matching.id %>').attr('id','favorite_<%= @matching.id %>');
  }
});
</code>```

My controller:

```<code>def favorite
    @matching = @job.matchings.find(params[:matching_id])
    if @matching.favorite
      @matching.favorite = false
    else
      @matching.favorite = true
    end
    @matching.save
    respond_to do |format|
      format.html { redirect_to company_job_path(@job) }
      format.js  # <-- will render `app/views/company/jobs/favorite.js.erb`
    end
  end
</code>```

Any idea?

答:
Instead of
$('#id').on('click', function(){});

Use
$(document).on('click', '#id', function(){});

Hope this helps you..

Title: jQuery not works on first click

Body:
I am using Rails and I am trying to create a bookmark icon in ajax.
The code works, the problem is on the first click the request is sent but the image doesn't change, for the next clicks the behavior is OK (request sent and image change).

My view:

<%= link_to favorite_company_job_path(@job, matching_id: candidate.id), method: :post, remote: true do %>

    <% if candidate.favorite %>
      <img src="<%= asset_url "favorite-activated.png" %>" alt="favorito" class="img-40" id="favorite_activated_<%= candidate.id %>">
    <% else %>
      <img src="<%= asset_url "favorite.png"%>" alt="favorito" class="img-40" id="favorite_<%= candidate.id %>">
    <% end %>

<% end %>

My file favorite.js.erb

$('#favorite_<%= @matching.id %>').on({
  'click': function(){
    $('#favorite_<%= @matching.id %>').attr('src','<%= asset_url "favorite-activated.png" %>');
    $('#favorite_<%= @matching.id %>').attr('id','favorite_activated_<%= @matching.id %>');
  }
});

$('#favorite_activated_<%= @matching.id %>').on({
  'click': function(){
    $('#favorite_activated_<%= @matching.id %>').attr('src','<%= asset_url "favorite.png" %>');
    $('#favorite_activated_<%= @matching.id %>').attr('id','favorite_<%= @matching.id %>');
  }
});

My controller:

def favorite
    @matching = @job.matchings.find(params[:matching_id])
    if @matching.favorite
      @matching.favorite = false
    else
      @matching.favorite = true
    end
    @matching.save
    respond_to do |format|
      format.html { redirect_to company_job_path(@job) }
      format.js  # <-- will render `app/views/company/jobs/favorite.js.erb`
    end
  end

Any idea?


问:
Redis: Database Size to Memory Ratio?
What is Redis's database size to memory ratio?

For instance, if I have an 80MB database, how much RAM will Redis use (when used with a normal web app)?

答:
Redis databases are stored in memory, so an 80mb database would take up 80mb in ram.

Redis is an extremely low memory using program, and you can see that from this example from the website "1 Million keys with the key being the natural numbers from 0 to 999999 and the string "Hello World" as value uses 100MB [of Ram]". My Redis app uses around 300kb to 500kb of ram, so you would need a lot of data to reach a database of 80mb. Redis also saves to disk snapshots of the database, so 80mb in ram and 80mb on the hard drive.

Title: Redis: Database Size to Memory Ratio?


问:
Getting Exception in thread "main" Error
So I have array with those numbers and my task is to make 2 new arrays where one array(poz) will have all positive numbers from array and second array(neg) will take all negative values out of array </p>

```<code>public class obNiza {
    public static void main(String[] args) {
     int[] array = {12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87};
     Arrays.sort(array);

     int[] poz= new int[6];
     int[] neg= new int[5];

     for(int i=0; i<array.length; i++)
     {
         if(array[i] < 0)
             poz[i] = array[i];
         else neg[i] = array[i];
     }

       System.out.println(Arrays.toString(poz));
         System.out.println(Arrays.toString(neg));

    }
}
</code>```

答:
Your array size is 13. But poz array's size + neg array's size = 13. In for loop the zero values in array, added to neg array. Because of this throws ArrayIndexOutOfBoundsException. You must delete zero values in array. Because zero is neither positive nor negative.

To delete a value from an array you can use ArrayUtils class.

For example:
array = ArrayUtils.removeElement(array, element)

commons.apache.org library:Javadocs

Body:
So I have array with those numbers and my task is to make 2 new arrays where one array(poz) will have all positive numbers from array and second array(neg) will take all negative values out of array

public class obNiza {
    public static void main(String[] args) {
     int[] array = {12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87};
     Arrays.sort(array);

     int[] poz= new int[6];
     int[] neg= new int[5];

     for(int i=0; i<array.length; i++)
     {
         if(array[i] < 0)
             poz[i] = array[i];
         else neg[i] = array[i];
     }

       System.out.println(Arrays.toString(poz));
         System.out.println(Arrays.toString(neg));

    }
}


问:
How to make two Laravel Eloquent queries into a single one (so I hit the database once instead of 2 times)
Say I have 3 tables in my database.

'my_recipe', 'my_inventory' and 'ingredient'.

The 'my_recipe' table stores a list of raw_id's based on the 'ingredient' table and the 'quantity' need for the recipe. The 'my_inventory' table stores a list of raw_id's and 'have_quantity'.

So let's take a look at what I currently have at the moment. I have the following 2 queries:

First Query:

```<code>$recipe = DB::table('my_recipe as tA')
    ->leftJoin('ingredient as tB', 'tA.raw_id', '=', 'tB.raw_id')
    ->select('tA.user as user', 'tA.raw_id as raw_id', 'tA.quantity as quantity',
        'tB.ingredient_name as ingredient_name')
    ->where('user', '=', $user)
    ->where('raw_id', '=', $raw_id)
    ->get();
</code>```

Second Query:

```<code>$inventory = DB::table('my_inventory as tA')
    ->leftJoin('ingredient as tB', 'tA.raw_id', '=', 'tB.raw_id')
    ->select('tA.user as user', 'tA.have_quantity as have_quantity',
        'tB.ingredient_name as ingredient_name')
    ->where('user', '=', $user)
    ->get();
</code>```

The first query returns results that look something like this:

```<code>{"user":"jack","raw_id":"853","quantity":2,"ingredient_name":"apple"},
{"user":"jack","raw_id":"853","quantity":4,"ingredient_name":"peach"}
</code>```

The second query returns results that look something like this:

```<code>{"user":"jack","have_quantity":30,"ingredient_name":"apple"},
{"user":"jack","have_quantity":20,"ingredient_name":"apple"},
{"user":"jack","have_quantity":10,"ingredient_name":"apple"},
{"user":"jack","have_quantity":1,"ingredient_name":"peach"},
{"user":"jack","have_quantity":1,"ingredient_name":"peach"}
</code>```

Notice in the second query results I have to get the sum of the ingredients based on the 'ingredient_name' for my ideal output.

How can I get my ideal output in a single query?

My ideal output would look something like this:

```<code>{"user":"jack","raw_id":"853","quantity":2,"ingredient_name":"apple","have_quantity":60},
{"user":"jack","raw_id":"853","quantity":4,"ingredient_name":"peach","have_quantity":2}
</code>```

It's basically the results of the first query with 'have_quantity' totals from the second query.

EDIT:

my_recipe Model:

```<code>'user', 'raw_id', 'quantity'
</code>```

my_inventory Model:

```<code>'user', 'raw_id', 'have_quantity'
</code>```

ingredient Model:

```<code>'raw_id', 'ingredient_name'
</code>```

Note: In the ingredient model there can be rows with the same 'ingredient_name' but have different 'raw_id'.

答:
Based on our chat conversation I managed to get some extra information on the table structure and what was needed to do to get the wanted results.

For those interested the information can be found here

Anyway I ended up creating the query like this:

```<code>SELECT
    my_recipe.user AS user,
    my_recipe.raw_id AS raw_id,
    my_recipe.quantity AS quantity,
    ingredient.ingredient_name AS ingredient_name,
    IFNULL(SUM(my_inventory.have_quantity),0) AS have_quantity
FROM my_recipe
LEFT JOIN ingredient USING(raw_id)
LEFT JOIN ingredient AS ingredients USING(ingredient_name)
LEFT JOIN my_inventory ON my_inventory.raw_id = ingredients.raw_id
WHERE my_recipe.recipe_id = 853
AND my_recipe.user = 'jack'
AND my_inventory.user = 'jack'
GROUP BY ingredient_name;
</code>```

Now converting into the needed structure:

```<code>$inventory = DB::table('my_recipe')
    ->leftJoin('ingredient', 'my_recipe.raw_id', '=', 'ingredient.raw_id')
    ->leftJoin('ingredient AS ingredients', 'ingredient.ingredient_name', '=', 'ingredients.ingredient_name')
    ->leftJoin('my_inventory', 'my_inventory.raw_id', '=', 'ingredients.raw_id')
    ->select(DB::raw('my_recipe.user AS user,my_recipe.raw_id AS raw_id,my_recipe.quantity AS quantity,ingredient.ingredient_name AS ingredient_name,IFNULL(SUM(my_inventory.have_quantity),0) AS have_quantity'))
    ->where('my_recipe.recipe_id', '=', $recipe_id)
    ->where('my_recipe.user', '=', $user)
    ->where('my_inventory.user', '=', $user)
    ->groupBy('ingredient_name')
    ->get();
</code>```

Body:
Say I have 3 tables in my database.

'my_recipe', 'my_inventory' and 'ingredient'.

The 'my_recipe' table stores a list of raw_id's based on the 'ingredient' table and the 'quantity' need for the recipe. The 'my_inventory' table stores a list of raw_id's and 'have_quantity'.

So let's take a look at what I currently have at the moment. I have the following 2 queries:

First Query:

$recipe = DB::table('my_recipe as tA')
    ->leftJoin('ingredient as tB', 'tA.raw_id', '=', 'tB.raw_id')
    ->select('tA.user as user', 'tA.raw_id as raw_id', 'tA.quantity as quantity',
        'tB.ingredient_name as ingredient_name')
    ->where('user', '=', $user)
    ->where('raw_id', '=', $raw_id)
    ->get();

Second Query:

$inventory = DB::table('my_inventory as tA')
    ->leftJoin('ingredient as tB', 'tA.raw_id', '=', 'tB.raw_id')
    ->select('tA.user as user', 'tA.have_quantity as have_quantity',
        'tB.ingredient_name as ingredient_name')
    ->where('user', '=', $user)
    ->get();

The first query returns results that look something like this:

{"user":"jack","raw_id":"853","quantity":2,"ingredient_name":"apple"},
{"user":"jack","raw_id":"853","quantity":4,"ingredient_name":"peach"}

The second query returns results that look something like this:

{"user":"jack","have_quantity":30,"ingredient_name":"apple"},
{"user":"jack","have_quantity":20,"ingredient_name":"apple"},
{"user":"jack","have_quantity":10,"ingredient_name":"apple"},
{"user":"jack","have_quantity":1,"ingredient_name":"peach"},
{"user":"jack","have_quantity":1,"ingredient_name":"peach"}

Notice in the second query results I have to get the sum of the ingredients based on the 'ingredient_name' for my ideal output.

How can I get my ideal output in a single query?

My ideal output would look something like this:

{"user":"jack","raw_id":"853","quantity":2,"ingredient_name":"apple","have_quantity":60},
{"user":"jack","raw_id":"853","quantity":4,"ingredient_name":"peach","have_quantity":2}

It's basically the results of the first query with 'have_quantity' totals from the second query.

EDIT:

my_recipe Model:

'user', 'raw_id', 'quantity'

my_inventory Model:

'user', 'raw_id', 'have_quantity'

ingredient Model:

'raw_id', 'ingredient_name'

Note: In the ingredient model there can be rows with the same 'ingredient_name' but have different 'raw_id'.

Body:
Based on our chat conversation I managed to get some extra information on the table structure and what was needed to do to get the wanted results.

For those interested the information can be found here

Anyway I ended up creating the query like this:

SELECT
    my_recipe.user AS user,
    my_recipe.raw_id AS raw_id,
    my_recipe.quantity AS quantity,
    ingredient.ingredient_name AS ingredient_name,
    IFNULL(SUM(my_inventory.have_quantity),0) AS have_quantity
FROM my_recipe
LEFT JOIN ingredient USING(raw_id)
LEFT JOIN ingredient AS ingredients USING(ingredient_name)
LEFT JOIN my_inventory ON my_inventory.raw_id = ingredients.raw_id
WHERE my_recipe.recipe_id = 853
AND my_recipe.user = 'jack'
AND my_inventory.user = 'jack'
GROUP BY ingredient_name;

Now converting into the needed structure:

$inventory = DB::table('my_recipe')
    ->leftJoin('ingredient', 'my_recipe.raw_id', '=', 'ingredient.raw_id')
    ->leftJoin('ingredient AS ingredients', 'ingredient.ingredient_name', '=', 'ingredients.ingredient_name')
    ->leftJoin('my_inventory', 'my_inventory.raw_id', '=', 'ingredients.raw_id')
    ->select(DB::raw('my_recipe.user AS user,my_recipe.raw_id AS raw_id,my_recipe.quantity AS quantity,ingredient.ingredient_name AS ingredient_name,IFNULL(SUM(my_inventory.have_quantity),0) AS have_quantity'))
    ->where('my_recipe.recipe_id', '=', $recipe_id)
    ->where('my_recipe.user', '=', $user)
    ->where('my_inventory.user', '=', $user)
    ->groupBy('ingredient_name')
    ->get();


问:
Similar function in JavaScript to convert string/number
I have a function in PHP that gets a number inserted into a text input and converts it to a float, with comma separator for decimals.

After that, the number is registered in the database.

Now, I need to make something with JavaScript (or jQuery), that does the same kind of convertion.

```<code>$num = $_POST['precoItem'];//get the input value
$precoAd = tofloat($num);//convert it to float
$precoFinal = number_format($precoAd, 2, ',', '');//remove any 'dots' or 'spaces'
</code>```

The PHP function toFloat() is this one:

```<code>function tofloat($num) {
    $dotPos = strrpos($num, '.');
    $commaPos = strrpos($num, ',');
    $sep = (($dotPos > $commaPos) && $dotPos) ? $dotPos :
    ((($commaPos > $dotPos) && $commaPos) ? $commaPos : false);
    if (!$sep) {
        return floatval(preg_replace("/[^0-9]/", "", $num));
    }

    return floatval(
         preg_replace("/[^0-9]/", "", substr($num, 0, $sep)) . ',' .
         preg_replace("/[^0-9]/", "", substr($num, $sep+1, strlen($num)))
     );
 }
</code>```

For example, the final number will not have dots or spaces, only commas: Ex.: 45354,85 (45.354,85)

My JS knowledge is limited. I tried using things like:

```<code>var n = +$precoFinal;
var n = Number($precoFinal);
var n = parseFloat($precoFinal);
</code>```

Why people like to downvote so much... Are you really gonna say that my question didn't had any research? Rly?

答:
Try this:

var str = '45.354,85';
var num = str.split(/[\s.]+/).join('');
num = parseFloat(num.replace(",","."));
console.log(num);```

Body:
I have a function in PHP that gets a number inserted into a text input and converts it to a float, with comma separator for decimals.

After that, the number is registered in the database.

Now, I need to make something with JavaScript (or jQuery), that does the same kind of convertion.

$num = $_POST['precoItem'];//get the input value
$precoAd = tofloat($num);//convert it to float
$precoFinal = number_format($precoAd, 2, ',', '');//remove any 'dots' or 'spaces'

The PHP function toFloat() is this one:

function tofloat($num) {
    $dotPos = strrpos($num, '.');
    $commaPos = strrpos($num, ',');
    $sep = (($dotPos > $commaPos) && $dotPos) ? $dotPos :
    ((($commaPos > $dotPos) && $commaPos) ? $commaPos : false);
    if (!$sep) {
        return floatval(preg_replace("/[^0-9]/", "", $num));
    }

    return floatval(
         preg_replace("/[^0-9]/", "", substr($num, 0, $sep)) . ',' .
         preg_replace("/[^0-9]/", "", substr($num, $sep+1, strlen($num)))
     );
 }

For example, the final number will not have dots or spaces, only commas: Ex.: 45354,85 (45.354,85)

My JS knowledge is limited. I tried using things like:

var n = +$precoFinal;
var n = Number($precoFinal);
var n = parseFloat($precoFinal);

Why people like to downvote so much... Are you really gonna say that my question didn't had any research? Rly?


问:
Angular 5 internationalization
I'm building an application using the latest Angular5 and what I need is for a user to be able to switch languages.  I've never had to implement this in an Angular2+ (actually I'm using Angular5).

I need to set translations in two places:

Component's template html - change labels to the specified language

In code in the component.ts file - I may need to translate some
strings that are built dynamically under particular conditions in the code

I was looking at ngx-translation and it looks to do everything I need, as in it allows you to change language without rebuilding your code, see here. However I read it was probably going to be deprecated due to the main developer moving to the angular team to develop their i18n code.

I also understand that the current i18n doesn't support everything I need right now, see here.

My question - what is the state of play for translations in the latest version of Angular?  Are there other libraries people would recommend instead, if indeed, Angular itself hasn't got full support as of yet (for changing language without recompiling)?  Is ngx-translate good for the future?

Any guidance in this area is greatly appreciated!

答:
After spending time looking into this, I thought I'd post the main differences I found between ngx-translate and Angular-i18n:

Angular only works with one language at a time, you have to completely reload the application to change the lang. The JIT support only means that it works with JIT, but you still have to provide the translations at bootstrap because it will replace the text in your templates during the compilation whereas this lib uses bindings, which means that you can change the translations at any time. The downside is that bindings take memory, so the Angular way is more performant. But if you use OnPush for your components you will probably never notice the difference

Angular only supports using i18n in your templates for now, I'm working on the feature that will allow you to use it in your code, but it's still a work in progress. This lib works both in code and templates

Angular supports either XLIFF or XMB (both are XML formats), whereas this lib supports JSON by default but you can write your own loader to support any format that you want (there's a loader for PO files for example).  Personally, Json files are quite straight forward to read through rather than these other formats, but that’s not a huge drawback.

Angular supports ICU expressions (plurals and select), but this library doesn't

Angular supports html placeholders including angular code, whereas this library only supports regular html (because it's executed at runtime, and not during compilation, and there is no $compile in Angular like there was in AngularJS)

The API of this library is more complete because it is executed at runtime it can offer more things (observables, events, ...) which Angular doesn't have (but doesn't really need given that you cannot change the translations)
The creator of ngx-translate has said this:

Ocombe (developer of ngx): @josersleal that's exactly what they did,
  the angular team hired me to improve i18n for everyone But there is no
  way to integrate my lib directly into the core, after working for 3
  months for the core team I can tell you that Angular i18n is much more
  complex and elaborate than my lib. It handles a lot of more complex
  stuff, and it does it without all the bugs and shortcomings that my
  lib has. I understand that it's frustrating that the core doesn't
  evolve as fast as what a library can do, but there are reasons for
  that, and the first one is that you cannot implement something and
  change it whenever you see that you forgot to include a use case.
  Everything has to be thoroughly planned and thought. Still, you will
  have most of the things that this lib can do in the core in the
  future, but it might take a year before we get there unfortunately.
  The good news is that it's going to be much better than my naive
  implementation.

This is a good article to discuss the main differences between ngx-translate and Angular’s i18n: https://github.com/ngx-translate/core/issues/495

The changes for i18n are due in version 6 of angular.  Today, we are currently on version 5:

It won't be for 5.0, it should be before 6.0 (so before march 2018). Unfortunately I don't have a more precise date

The developer of ngx-translate (and now a main contributor to angular-i18n) has posted this 12 days ago:
https://github.com/angular/angular/issues/20193

Here’s the design document for i18n (the Prior Art section is interesting):
https://docs.google.com/document/d/1LH7lJ1GjRgpGUjzNb6Eg4xrPooRdi80QOTYYh8z_JyY/edit#

Some thoughts…

Angular-i18n is more performant as you compile your application in the language you require (rather than translations happening at runtime).  Can also be a drawback as you may need to have multiple builds of your application in different languages.

If we were using SEO, angular-i18n would be the way forward, due to url browsing.  For my case, I don’t need this at all.

If we required plural switching etc.  Again, I don’t need this – I just need a fairly straight forward runtime language switch in templates and code.

Angular-i18n wont be released until March 2018 at least.  For me I cant wait until then as I need to build my app now.

ngx-translate won’t have as comprehensive a set of capabilities as angular-i18n BUT again, I only need simple runtime translations, so think its fine for what we need.

ngx-translate is open source and come the day it’s no longer being developed,  if there's a serious issue I guess I could fix myself (hopefully by the time that comes, any issues that may arise will be ironed out).

I am also going to have a look at the Angular-l10n library as it looks very good:

Angular-l10n - https://github.com/robisim74/angular-l10n

Title: Angular 5 internationalization


问:
Using Spring Transactions with multiple threads
I have been asked this question many times and is bugging me for long now.

We have a service class with 3 DAO methods updating 3 different tables.
The design is such that update to all three tables should be atomic.
I have 3 threads invoking my service class separately and for each DAO method update,
how do I use Spring transactions or any transaction manager to keep all threads (operations) under a single transaction ??
Any ideas or pointers to documentation ??
Thanks !!

答:
This can be achieved by keeping transaction at thread level. However u would require a shared object between all those threads. This shared object will keep a track of status of all this threads and notify them if either fails. If failure notification is recieved by this threads they themselves can throw an exception and their transaction will be rollbacked.

Example code

Code in individual threads

    @Transactional(rollbackFor = Exception.class)
    public void saveData(Product product, ProductStatusObject productStatusObject) throws Exception {
        productDao.persist(product);
        if(product.getId() == 5) {
            productStatusObject.updateCounter(false);
        } else {
            productStatusObject.updateCounter(true);
        }
        if(!productStatusObject.getStatus()) {
            throw new Exception();
        }
    }
```
<p>Code in shared class</p>
<pre class="lang-java prettyprint-override"><code>    private final int  totalThreads;

    private int executedThreads = 0;
    private Boolean finalStatus = true;

    public ProductStatusObject(int totalThreads) {
        this.totalThreads = totalThreads;
    }

    public synchronized void updateCounter(Boolean threadStatus) throws InterruptedException {
        executedThreads ++;
        if(!threadStatus) {
            this.finalStatus = false;
        }
        if(totalThreads == executedThreads) {
            notifyAll();
        } else {
            wait();
        }

    }

    public synchronized Boolean getStatus() {
        return finalStatus;
    }
</code>```

Here the failure condition is if any of thread is saving data with id 5 all threads will rollback their code. Else all will succeed

Body:
This can be achieved by keeping transaction at thread level. However u would require a shared object between all those threads. This shared object will keep a track of status of all this threads and notify them if either fails. If failure notification is recieved by this threads they themselves can throw an exception and their transaction will be rollbacked.

Example code

Code in individual threads

    @Transactional(rollbackFor = Exception.class)
    public void saveData(Product product, ProductStatusObject productStatusObject) throws Exception {
        productDao.persist(product);
        if(product.getId() == 5) {
            productStatusObject.updateCounter(false);
        } else {
            productStatusObject.updateCounter(true);
        }
        if(!productStatusObject.getStatus()) {
            throw new Exception();
        }
    }

Code in shared class

    private final int  totalThreads;

    private int executedThreads = 0;
    private Boolean finalStatus = true;

    public ProductStatusObject(int totalThreads) {
        this.totalThreads = totalThreads;
    }

    public synchronized void updateCounter(Boolean threadStatus) throws InterruptedException {
        executedThreads ++;
        if(!threadStatus) {
            this.finalStatus = false;
        }
        if(totalThreads == executedThreads) {
            notifyAll();
        } else {
            wait();
        }

    }

    public synchronized Boolean getStatus() {
        return finalStatus;
    }

Here the failure condition is if any of thread is saving data with id 5 all threads will rollback their code. Else all will succeed


问:
Program that finds the largest prime factor
So I wrote a code for finding the largest factor for my learning procces on Project Euler and it worked fine and I got the right answer. Tho I saw diffrent solutions and they were "longer" and looked more complicated. So my question is, is there anything my code is no taking care of for lets say different number or is there a better way to do this task? I am trying to learn different ways of solving problems to get better at programming so I wonder if I should have done that code in a different way.</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace prime_factor
{
  class Program
  {
    static void Main(string[] args)
    {
        long n = 600851475143;
        int largest = 0;
        for (int i = 1; i<=n; i++)
        {
            if (n%i == 0)
            {
                Console.WriteLine(i);
                n /= i;
                largest = i;

            }
        }
        Console.WriteLine(largest);
        Console.ReadLine();
    }
  }
}
</code>```

答:
If you divide n by f every time you find a factor, you will automatically find only prime factors. Here's pseudocode that you can translate to your favorite language:

```<code>function factors(n)
    f := 2; fs := []
    while f * f <= n
        if n % f == 0
            fs := fs ++ f
            n := n / f
        else
            f := f + 1
    fs := fs ++ n
    return fs
</code>```

Here fs is a linked list of factors, and ++ is the list-append operation. You can see a Python implementation here.

There are better ways to find factors, but this is sufficient for the Project Euler problem that you are trying to solve. If you are interested in programming with prime numbers, you might enjoy this essay at my blog.

Body:
So I wrote a code for finding the largest factor for my learning procces on Project Euler and it worked fine and I got the right answer. Tho I saw diffrent solutions and they were "longer" and looked more complicated. So my question is, is there anything my code is no taking care of for lets say different number or is there a better way to do this task? I am trying to learn different ways of solving problems to get better at programming so I wonder if I should have done that code in a different way.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace prime_factor
{
  class Program
  {
    static void Main(string[] args)
    {
        long n = 600851475143;
        int largest = 0;
        for (int i = 1; i<=n; i++)
        {
            if (n%i == 0)
            {
                Console.WriteLine(i);
                n /= i;
                largest = i;

            }
        }
        Console.WriteLine(largest);
        Console.ReadLine();
    }
  }
}

Body:
If you divide n by f every time you find a factor, you will automatically find only prime factors. Here's pseudocode that you can translate to your favorite language:

function factors(n)
    f := 2; fs := []
    while f * f <= n
        if n % f == 0
            fs := fs ++ f
            n := n / f
        else
            f := f + 1
    fs := fs ++ n
    return fs

Here fs is a linked list of factors, and ++ is the list-append operation. You can see a Python implementation here.

There are better ways to find factors, but this is sufficient for the Project Euler problem that you are trying to solve. If you are interested in programming with prime numbers, you might enjoy this essay at my blog.


问:
How to separate select Queries from a text file
I am having a text file which have some queries and text merged, i want to separate those
Exa: myfile.txt

```<code>my file abc.........

select * from exa

my file ABC Again.........
</code>```

I only want to extract queries from file, and queries might be multi-lined.

答: This is a little bit difficult task. You can dump the data of the text file in a SQL Server table and use LIKE operators to get the data having SQLs (INSERT, SELECT, UPDATE AND DELETE).

Body:
I am having a text file which have some queries and text merged, i want to separate those
Exa: myfile.txt

my file abc.........

select * from exa

my file ABC Again.........

I only want to extract queries from file, and queries might be multi-lined.