问:
Nunit, NCrunch and NSubstitute - Always 2 tests failing with UnexpectedArgumentMatcherException, which change (quasi) randomly
I have a text fixture which uses NUnit 3.4.1, NSubstitute 1.10.0 and NCrunch 2.23.0.2

There are at any point in time 2 faling tests in this fixture. Which test fail seems to vary every time I change something. Not all tests end up failing some time or another, but most do, and the problem is always an NSubstitute exception on a line like:

```<code>// _clock is initialized as _clock = Substitute.For<IClock>();
// the dates in the Returns statement change on every test
_clock.Now.Returns(new DateTime(2015, 1, 1));
</code>```

I add NCrunch to this mix because all tests seem to pass with the Resharper 2016 test runner. Mostly.

The exception I invariably get is:

```<code>NSubstitute.Exceptions.UnexpectedArgumentMatcherException : Argument matchers
    (Arg.Is, Arg.Any) should only be used in place of member arguments.
Do not use in a Returns() statement or anywhere else outside of a member call.
</code>```

Which is clear enough, except that on mosts of the tests I don't use any Arg.Is or Arg.Any.

IClock interface

Here's the IClock inerface in all it's glory. Now is a getter-only property, but that shouldn't be a problem for NSubstitute, should it?

```<code>public interface IClock
{
    DateTime Now { get; }
}
</code>```

Full Fixture, coming up

Sorry for the enormous amount of code coming up, but I don't want to assume it's due to one test or the other, so here goes:

```<code>[TestFixture]
public class AuctionTests : TestBase
{
    #region Fields

    AuctionService _auctionService;
    IClock _clock;
    Ride _ride;
    IMailService _mailer;

    #endregion

    [SetUp]
    public void Init()
    {
        _clock = Substitute.For<IClock>();
        _mailer = Substitute.For<IMailService>();

        _ride = new Ride
        {
            StartAuction = new DateTime(2016, 2, 12, 19, 0, 23),
            PriceForCustomer = 20m,
            InitialAuctionPrice = 15m,
            HighestAuctionPrice = 19m
        };

        SetupData(_ride);

        _auctionService = new AuctionService(RavenSession, _clock, _mailer);
    }

    [Test]
    public void Auction_rejects_price_when_price_is_higher_then_HighestAuctionPrice()
    {
        const decimal price = 90m;
        _clock.Now.Returns(new DateTime(2015, 1, 1));

        var result = _auctionService.Accept(_ride.Id, price);

        result.Should().BeFalse();
    }

    [Test]
    public void Auction_rejects_price_when_inactive()
    {
        _clock.Now.Returns(new DateTime(2016, 2, 12, 20, 1, 23));

        var result = _auctionService.Accept(_ride.Id, Arg.Any<decimal>());

        result.Should().BeFalse();
    }

    [Test]
    public void Auction_is_inactive_when_current_time_is_before_auction_startDate()
    {
        _clock.Now.Returns(new DateTime(2016, 2, 12, 18, 0, 23));

        var result = _auctionService.Accept(_ride.Id, Arg.Any<decimal>());

        Assert.IsFalse(result);
    }

    [Test]
    public void Auction_is_active_when_current_time_is_exactly_auction_startDate()
    {
        _clock.Now.Returns(_ride.StartAuction);

        var result = _auctionService.Accept(_ride.Id, _ride.InitialAuctionPrice);

        result.Should().BeTrue();
    }

    [Test]
    public void Action_price_is_valid_at_auction_start_time_if_equal_to_initial_price()
    {
        var price = _ride.InitialAuctionPrice;

        _clock.Now.Returns(_ride.StartAuction);

        var result = _auctionService.Accept(_ride.Id, price);

        result.Should().BeTrue();
    }

    [Test]
    public void Action_price_is_valid_at_auction_end_time_if_equal_to_highest_possible_price()
    {
        var price = _ride.HighestAuctionPrice;

        _clock.Now.Returns(_ride.StartAuction.AddMinutes(60));

        var result = _auctionService.Accept(_ride.Id, price);

        result.Should().BeTrue();
    }

    [Test]
    public void Action_price_is_invalid_if_not_within_time_parameters()
    {
        var price = 12m;

        _clock.Now.Returns(_ride.StartAuction.AddMinutes(30));

        var result = _auctionService.Accept(_ride.Id, price);

        result.Should().BeFalse();
    }

    [Test]
    [Ignore("Uitzoeken hoeveel seconde vertraging wenselijk is")]
    public void Accept_takes_delay_in_requests_into_account()
    {
        var price = 17m;

        _clock.Now.Returns(_ride.StartAuction.AddMinutes(30).AddSeconds(30));

        var result = _auctionService.Accept(_ride.Id, price);

        result.Should().BeTrue();
    }

    [Test]
    public void Ride_is_saved_with_accepted_price()
    {
        var price = 17m;

        var date = _ride.StartAuction.AddMinutes(30);
        _clock.Now.Returns(date);

        var result = _auctionService.Accept(_ride.Id, price);

        Assert.IsTrue(result);

        var dbRide = RavenSession.Load<Ride>(_ride.Id);

        price.IsSameOrEqualTo(dbRide.AcceptedAuctionPrice);
    }

    [Test]
    public void On_Start_Auction_InitialAuctionPrice_should_be_fifteen_percent_of_PriceForCustomer()
    {
        _ride.PriceForCustomer = 100;

        _auctionService.StartAuction(_ride.Id);

        Assert.AreEqual(85m, _ride.InitialAuctionPrice);
    }

    [Test]
    public void On_Start_Auction_send_email_to_priorityPartners()
    {
        var priorityPartner = new Partner { Priority = true, Email = "some@email.com" };

        SetupData(priorityPartner, new Partner { Priority = false });

        _auctionService.StartAuction(_ride.Id);

        _mailer.Received(1).SendAuctionEmail(Arg.Any<string>(), _ride);
    }
}
</code>```

Is there anything (obvious) that I'm missing? The quasi randomness of it all seems to point at code not being properly re-initialised for every test, but I completely fail to see how.

Any help is much appreciated.

答:
NSubstitute caches Arg.Any<...> calls from previous tests. An incorrect call in a prior test can result in this mysterious error appearing.

An awesome colleague showed me this trick to find out which test made this incorrect call.

Putting the following section in the Teardown method will cause invalid Arg.Any calls to fail.

```<code>    [TearDown]
    public void TearDown()
    {

        var argSpecs = SubstitutionContext.Current.DequeueAllArgumentSpecifications();
        if (argSpecs.Any())
        {
            throw new UnexpectedArgumentMatcherException();
        }
    }
</code>```

Body:
I have a text fixture which uses NUnit 3.4.1, NSubstitute 1.10.0 and NCrunch 2.23.0.2

There are at any point in time 2 faling tests in this fixture. Which test fail seems to vary every time I change something. Not all tests end up failing some time or another, but most do, and the problem is always an NSubstitute exception on a line like:

// _clock is initialized as _clock = Substitute.For<IClock>();
// the dates in the Returns statement change on every test
_clock.Now.Returns(new DateTime(2015, 1, 1));

I add NCrunch to this mix because all tests seem to pass with the Resharper 2016 test runner. Mostly.

The exception I invariably get is:

NSubstitute.Exceptions.UnexpectedArgumentMatcherException : Argument matchers
    (Arg.Is, Arg.Any) should only be used in place of member arguments.
Do not use in a Returns() statement or anywhere else outside of a member call.

Which is clear enough, except that on mosts of the tests I don't use any Arg.Is or Arg.Any.

IClock interface

Here's the IClock inerface in all it's glory. Now is a getter-only property, but that shouldn't be a problem for NSubstitute, should it?

public interface IClock
{
    DateTime Now { get; }
}

Full Fixture, coming up

Sorry for the enormous amount of code coming up, but I don't want to assume it's due to one test or the other, so here goes:

[TestFixture]
public class AuctionTests : TestBase
{
    #region Fields

    AuctionService _auctionService;
    IClock _clock;
    Ride _ride;
    IMailService _mailer;

    #endregion

    [SetUp]
    public void Init()
    {
        _clock = Substitute.For<IClock>();
        _mailer = Substitute.For<IMailService>();

        _ride = new Ride
        {
            StartAuction = new DateTime(2016, 2, 12, 19, 0, 23),
            PriceForCustomer = 20m,
            InitialAuctionPrice = 15m,
            HighestAuctionPrice = 19m
        };

        SetupData(_ride);

        _auctionService = new AuctionService(RavenSession, _clock, _mailer);
    }

    [Test]
    public void Auction_rejects_price_when_price_is_higher_then_HighestAuctionPrice()
    {
        const decimal price = 90m;
        _clock.Now.Returns(new DateTime(2015, 1, 1));

        var result = _auctionService.Accept(_ride.Id, price);

        result.Should().BeFalse();
    }

    [Test]
    public void Auction_rejects_price_when_inactive()
    {
        _clock.Now.Returns(new DateTime(2016, 2, 12, 20, 1, 23));

        var result = _auctionService.Accept(_ride.Id, Arg.Any<decimal>());

        result.Should().BeFalse();
    }

    [Test]
    public void Auction_is_inactive_when_current_time_is_before_auction_startDate()
    {
        _clock.Now.Returns(new DateTime(2016, 2, 12, 18, 0, 23));

        var result = _auctionService.Accept(_ride.Id, Arg.Any<decimal>());

        Assert.IsFalse(result);
    }

    [Test]
    public void Auction_is_active_when_current_time_is_exactly_auction_startDate()
    {
        _clock.Now.Returns(_ride.StartAuction);

        var result = _auctionService.Accept(_ride.Id, _ride.InitialAuctionPrice);

        result.Should().BeTrue();
    }

    [Test]
    public void Action_price_is_valid_at_auction_start_time_if_equal_to_initial_price()
    {
        var price = _ride.InitialAuctionPrice;

        _clock.Now.Returns(_ride.StartAuction);

        var result = _auctionService.Accept(_ride.Id, price);

        result.Should().BeTrue();
    }

    [Test]
    public void Action_price_is_valid_at_auction_end_time_if_equal_to_highest_possible_price()
    {
        var price = _ride.HighestAuctionPrice;

        _clock.Now.Returns(_ride.StartAuction.AddMinutes(60));

        var result = _auctionService.Accept(_ride.Id, price);

        result.Should().BeTrue();
    }

    [Test]
    public void Action_price_is_invalid_if_not_within_time_parameters()
    {
        var price = 12m;

        _clock.Now.Returns(_ride.StartAuction.AddMinutes(30));

        var result = _auctionService.Accept(_ride.Id, price);

        result.Should().BeFalse();
    }

    [Test]
    [Ignore("Uitzoeken hoeveel seconde vertraging wenselijk is")]
    public void Accept_takes_delay_in_requests_into_account()
    {
        var price = 17m;

        _clock.Now.Returns(_ride.StartAuction.AddMinutes(30).AddSeconds(30));

        var result = _auctionService.Accept(_ride.Id, price);

        result.Should().BeTrue();
    }

    [Test]
    public void Ride_is_saved_with_accepted_price()
    {
        var price = 17m;

        var date = _ride.StartAuction.AddMinutes(30);
        _clock.Now.Returns(date);

        var result = _auctionService.Accept(_ride.Id, price);

        Assert.IsTrue(result);

        var dbRide = RavenSession.Load<Ride>(_ride.Id);

        price.IsSameOrEqualTo(dbRide.AcceptedAuctionPrice);
    }

    [Test]
    public void On_Start_Auction_InitialAuctionPrice_should_be_fifteen_percent_of_PriceForCustomer()
    {
        _ride.PriceForCustomer = 100;

        _auctionService.StartAuction(_ride.Id);

        Assert.AreEqual(85m, _ride.InitialAuctionPrice);
    }

    [Test]
    public void On_Start_Auction_send_email_to_priorityPartners()
    {
        var priorityPartner = new Partner { Priority = true, Email = "some@email.com" };

        SetupData(priorityPartner, new Partner { Priority = false });

        _auctionService.StartAuction(_ride.Id);

        _mailer.Received(1).SendAuctionEmail(Arg.Any<string>(), _ride);
    }
}

Is there anything (obvious) that I'm missing? The quasi randomness of it all seems to point at code not being properly re-initialised for every test, but I completely fail to see how.

Any help is much appreciated.

Body:
NSubstitute caches Arg.Any<...> calls from previous tests. An incorrect call in a prior test can result in this mysterious error appearing.

An awesome colleague showed me this trick to find out which test made this incorrect call.

Putting the following section in the Teardown method will cause invalid Arg.Any calls to fail.

    [TearDown]
    public void TearDown()
    {

        var argSpecs = SubstitutionContext.Current.DequeueAllArgumentSpecifications();
        if (argSpecs.Any())
        {
            throw new UnexpectedArgumentMatcherException();
        }
    }


来源: stackexchange

问:
How can I horizontally and vertically center an  in a
?
I don't want to center a div, I want the contents of a div to be centered.  I would like horizontal and vertical alignment.

Sorry, if this is too easy or whatever, but this is kind of a hassle to get it right.

Grae

I am using IE7

答:
For horizontal alignment, use text-align:center;

For vertical alignment, see for example the W3 style guide

ContentLicense: CC BY-SA 2.5

Title: How can I horizontally and vertically center an <img> in a <div>?


问:
Validation in IOS app
I know that its a simple question but i have tried many times for my code check validation but its not working. When i click register button it takes me to next page instead of validating my form.My code is</p>

```<code>- (IBAction)Register:(id)sender {
    if ([self.name.text isEqualToString:@""]){
        NSString *message = @"Name";

        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Enter Your Name"
                                                                       message:message
                                                                preferredStyle:UIAlertControllerStyleAlert];

        [self presentViewController:alert animated:YES completion:nil];

        int duration = 1; // duration in seconds

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
            [alert dismissViewControllerAnimated:YES completion:nil];
        });

    } else if ([self.email.text isEqualToString:@""]){
        NSString *message = @"Email";

        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Enter Your Email Address"
                                                                       message:message
                                                                preferredStyle:UIAlertControllerStyleAlert];

        [self presentViewController:alert animated:YES completion:nil];

        int duration = 1; // duration in seconds

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
            [alert dismissViewControllerAnimated:YES completion:nil];
        });

    }else{

        NSString *emailRegEx = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
        NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegEx];
        //Valid email address

        if ([emailTest evaluateWithObject:_email.text] == YES)
        {
            // NSLog(@"Correct Email");
        }
        else
        {
            NSString *message = @"Invalid Email";

            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Email Format Incorrect"
                                                                           message:message
                                                                    preferredStyle:UIAlertControllerStyleAlert];

            [self presentViewController:alert animated:YES completion:nil];

            int duration = 1; // duration in seconds

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                [alert dismissViewControllerAnimated:YES completion:nil];
            });

        }

        if ([_code.titleLabel.text isEqualToString:@"Code"]) {
            NSString *message = @"Select Country Code";

            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:message
                                                                    preferredStyle:UIAlertControllerStyleAlert];

            [self presentViewController:alert animated:YES completion:nil];

            int duration = 1; // duration in seconds

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                [alert dismissViewControllerAnimated:YES completion:nil];
            });

        }

        if ([self.mobileCode.text isEqualToString:@""]) {
            NSString *message = @"Enter Mobile Code";

            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:message
                                                                    preferredStyle:UIAlertControllerStyleAlert];

            [self presentViewController:alert animated:YES completion:nil];

            int duration = 1; // duration in seconds

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                [alert dismissViewControllerAnimated:YES completion:nil];
            });

        }

        if ([self.number1.text isEqualToString:@""]) {
            NSString *message = @"Enter Your Number";

            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:message
                                                                    preferredStyle:UIAlertControllerStyleAlert];

            [self presentViewController:alert animated:YES completion:nil];

            int duration = 1; // duration in seconds

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                [alert dismissViewControllerAnimated:YES completion:nil];
            });

        }

    }
    [self Account];

}
</code>```

答:
Best way to validate Your TextFiled is

Create  a method for validation

```<code>-(BOOL)validation
{

  if (self.name.text.length==0){
// Show alert enter Name
return NO;

}

if ([self.email.text.length==0){
// Show alert enter Email
return NO;

}

if ([_code.titleLabel.text.length==0){
// Show alert Select Country
return NO;

}

// Similarly Create method to validate your email
if (![self validateEmailString:self.email.text]){
// Show alert invalid email
return NO;

}

// and so on check your validation

//Finally retrun YES , validation Over
return YES;
}
</code>```

Uses

```<code>if ([self validation])
{
  // validation over than call your API
[self Account];
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Validation in IOS app

Body:
I know that its a simple question but i have tried many times for my code check validation but its not working. When i click register button it takes me to next page instead of validating my form.My code is

- (IBAction)Register:(id)sender {
    if ([self.name.text isEqualToString:@""]){
        NSString *message = @"Name";

        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Enter Your Name"
                                                                       message:message
                                                                preferredStyle:UIAlertControllerStyleAlert];

        [self presentViewController:alert animated:YES completion:nil];

        int duration = 1; // duration in seconds

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
            [alert dismissViewControllerAnimated:YES completion:nil];
        });

    } else if ([self.email.text isEqualToString:@""]){
        NSString *message = @"Email";

        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Enter Your Email Address"
                                                                       message:message
                                                                preferredStyle:UIAlertControllerStyleAlert];

        [self presentViewController:alert animated:YES completion:nil];

        int duration = 1; // duration in seconds

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
            [alert dismissViewControllerAnimated:YES completion:nil];
        });

    }else{

        NSString *emailRegEx = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
        NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegEx];
        //Valid email address

        if ([emailTest evaluateWithObject:_email.text] == YES)
        {
            // NSLog(@"Correct Email");
        }
        else
        {
            NSString *message = @"Invalid Email";

            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Email Format Incorrect"
                                                                           message:message
                                                                    preferredStyle:UIAlertControllerStyleAlert];

            [self presentViewController:alert animated:YES completion:nil];

            int duration = 1; // duration in seconds

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                [alert dismissViewControllerAnimated:YES completion:nil];
            });

        }

        if ([_code.titleLabel.text isEqualToString:@"Code"]) {
            NSString *message = @"Select Country Code";

            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:message
                                                                    preferredStyle:UIAlertControllerStyleAlert];

            [self presentViewController:alert animated:YES completion:nil];

            int duration = 1; // duration in seconds

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                [alert dismissViewControllerAnimated:YES completion:nil];
            });

        }

        if ([self.mobileCode.text isEqualToString:@""]) {
            NSString *message = @"Enter Mobile Code";

            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:message
                                                                    preferredStyle:UIAlertControllerStyleAlert];

            [self presentViewController:alert animated:YES completion:nil];

            int duration = 1; // duration in seconds

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                [alert dismissViewControllerAnimated:YES completion:nil];
            });

        }

        if ([self.number1.text isEqualToString:@""]) {
            NSString *message = @"Enter Your Number";

            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:message
                                                                    preferredStyle:UIAlertControllerStyleAlert];

            [self presentViewController:alert animated:YES completion:nil];

            int duration = 1; // duration in seconds

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, duration * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
                [alert dismissViewControllerAnimated:YES completion:nil];
            });

        }

    }
    [self Account];

}

Body:
Best way to validate Your TextFiled is

Create  a method for validation

-(BOOL)validation
{

  if (self.name.text.length==0){
// Show alert enter Name
return NO;

}

if ([self.email.text.length==0){
// Show alert enter Email
return NO;

}

if ([_code.titleLabel.text.length==0){
// Show alert Select Country
return NO;

}

// Similarly Create method to validate your email
if (![self validateEmailString:self.email.text]){
// Show alert invalid email
return NO;

}

// and so on check your validation

//Finally retrun YES , validation Over
return YES;
}

Uses

if ([self validation])
{
  // validation over than call your API
[self Account];
}


问:
What is a Java ClassLoader?
In a few simple sentences, what is a Java ClassLoader, when is it used and why?

OK, I read a wiki article. ClassLoader loads classes. OK. So if I include jar files and import, a ClassLoader does the job.

Why should I bother with this ClassLoader? I've never used it and didn't know it existed.

The question is, why does the ClassLoader class exist? And also, how do you use it in practice? (Cases exist, I know.)

答:
ClassLoader in Java is a class which is used to load class files in Java. Java code is compiled into class file by javac compiler and JVM executes Java program, by executing byte codes written in class file.

ClassLoader is responsible for loading class files from file system, network or any other source. There are three default class loader used in Java, Bootstrap , Extension and System or Application class loader.

##  ClassLoader interaction with JVM

More @ : how-classloader-works-in-java.html

Title: What is a Java ClassLoader?


问:
Inputs inside Bootstrap grid doesnt work
I've been playing with the Bootstrap grid and my goal is to make this screen:

enter image description here

I used 4-8 scale, so the table is the 8 and search options is the 4.
I don't know why but the search rows doesnt respond to the mouse (as there something on them) - but does respond if I navigate to them using the tab button.

The code of this part is:

      Search by Date: <input type="date" ng-model="b.AllsearchDate">
      <button ng-click="b.AllsearchByDate()">

      </button>

      Search by Price: <input ng-model="b.AllsearchPrice"
      placeholder="Input max price...." type="number"/>
      <button ng-click="b.AllsearchByPrice()">

      </button>

      Search by Type: &nbsp <select ng-model="b.AllsearchType">
       <option value="" disabled selected>Select a Type</option>
       <option value="FOOD">Food</option>
       <option value="ELECTRICTY">Electricity</option>
       <option value="RESTAURANTS">Restaurants</option>
       <option value="HEALTH">Health</option>
       <option value="SPORTS">Sports</option>
       <option value="CAMPING">Camping</option>
       <option value="TRAVELLING">Traveling</option>
      </select>

      <button ng-click="b.AllsearchByType()">

      </button>

    ID
    Title
    Start Date
    End date
    Amount
    Type
    Message
    Price
    Image
    Actions

    {{c1.id}}
    {{c1.title}}
    {{c1.start_date}}
    {{c1.end_date}}
    {{c1.amount}}
    {{c1.type}}
    {{c1.message}}
    {{c1.price}}$

     <button ng-click="b.buy(c1)">

     </button>

  ```

Can't find any solutions on the web, can someone help me?

答:
Why are you using span instead of div? for rows & columns? The proper way is to use divs not spans for cols and rows.

This should help.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

        Search by Date:
        <input type="date" ng-model="b.AllsearchDate">
        <button ng-click="b.AllsearchByDate()">

                </button>

                Search by Price:
                <input ng-model="b.AllsearchPrice" placeholder="Input max price...." type="number" />
                <button ng-click="b.AllsearchByPrice()">

                </button>

        Search by Type: &nbsp
        <select ng-model="b.AllsearchType">
                    <option value="" disabled selected>Select a Type</option>
                    <option value="FOOD">Food</option>
                    <option value="ELECTRICTY">Electricity</option>
                    <option value="RESTAURANTS">Restaurants</option>
                    <option value="HEALTH">Health</option>
                    <option value="SPORTS">Sports</option>
                    <option value="CAMPING">Camping</option>
                    <option value="TRAVELLING">Traveling</option>
                </select>
        <button ng-click="b.AllsearchByType()">

                </button>

      ID
      Title
      Start Date
      End date
      Amount
      Type
      Message
      Price
      Image
      Actions

      {{c1.id}}
      {{c1.title}}
      {{c1.start_date}}
      {{c1.end_date}}
      {{c1.amount}}
      {{c1.type}}
      {{c1.message}}
      {{c1.price}}$

        <button ng-click="b.buy(c1)">

                </button>

```

Body:
I've been playing with the Bootstrap grid and my goal is to make this screen:

enter image description here

I used 4-8 scale, so the table is the 8 and search options is the 4.
I don't know why but the search rows doesnt respond to the mouse (as there something on them) - but does respond if I navigate to them using the tab button.

The code of this part is:

      Search by Date: <input type="date" ng-model="b.AllsearchDate">
      <button ng-click="b.AllsearchByDate()">

      </button>

      Search by Price: <input ng-model="b.AllsearchPrice"
      placeholder="Input max price...." type="number"/>
      <button ng-click="b.AllsearchByPrice()">

      </button>

      Search by Type: &nbsp <select ng-model="b.AllsearchType">
       <option value="" disabled selected>Select a Type</option>
       <option value="FOOD">Food</option>
       <option value="ELECTRICTY">Electricity</option>
       <option value="RESTAURANTS">Restaurants</option>
       <option value="HEALTH">Health</option>
       <option value="SPORTS">Sports</option>
       <option value="CAMPING">Camping</option>
       <option value="TRAVELLING">Traveling</option>
      </select>

      <button ng-click="b.AllsearchByType()">

      </button>

    ID
    Title
    Start Date
    End date
    Amount
    Type
    Message
    Price
    Image
    Actions

    {{c1.id}}
    {{c1.title}}
    {{c1.start_date}}
    {{c1.end_date}}
    {{c1.amount}}
    {{c1.type}}
    {{c1.message}}
    {{c1.price}}$

     <button ng-click="b.buy(c1)">

     </button>

Can't find any solutions on the web, can someone help me?

Body:
Why are you using span instead of div? for rows & columns? The proper way is to use divs not spans for cols and rows.

This should help.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row">
  <div class="col-sm-4">
    <!-- The Search Options -->
    <!-- ============================================================================================== -->
    <!-- Search by Date -->
    <!-- ============================================================================================== -->
    <div class="row">
      <div class="col-sm-12">
        Search by Date:
        <input type="date" ng-model="b.AllsearchDate">
        <button ng-click="b.AllsearchByDate()">
                    <img alt="Search" src="../Ico/search.png" height="19px">
                </button>
        <br />
        <br />
      </div>
    </div>
    <!-- ============================================================================================== -->
    <!-- Search by Price -->
    <!-- ============================================================================================== -->
    <div class="row">
      <a class="col-sm-12">
                Search by Price:
                <input ng-model="b.AllsearchPrice" placeholder="Input max price...." type="number" />
                <button ng-click="b.AllsearchByPrice()">
                    <img alt="Search" src="../Ico/search.png" height="19px">
                </button>
                <br />
                <br />
            </a>
    </div>
    <!-- ============================================================================================== -->
    <!-- Search by Category -->
    <!-- ============================================================================================== -->
    <div class="row">
      <div class="col-sm-12">
        Search by Type: &nbsp
        <select ng-model="b.AllsearchType">
                    <option value="" disabled selected>Select a Type</option>
                    <option value="FOOD">Food</option>
                    <option value="ELECTRICTY">Electricity</option>
                    <option value="RESTAURANTS">Restaurants</option>
                    <option value="HEALTH">Health</option>
                    <option value="SPORTS">Sports</option>
                    <option value="CAMPING">Camping</option>
                    <option value="TRAVELLING">Traveling</option>
                </select>
        <button ng-click="b.AllsearchByType()">
                    <img alt="Search" src="../Ico/search.png" height="19px">
                </button>
        <br />
        <br />
      </div>
    </div>
    <!-- ============================================================================================== -->
  </div>
  <!-- col-sm-4 -->
  <!-- ================================================================================== -->
  <!-- All Coupons table -->
  <!-- ================================================================================== -->
  <table border="1" class="col-sm-8">
    <tr>
      <th ng-click="b.orderBy('id')">ID</th>
      <th ng-click="b.orderBy('title')">Title</th>
      <th ng-click="b.orderBy('start_date')">Start Date</th>
      <th ng-click="b.orderBy('end_date')">End date</th>
      <th ng-click="b.orderBy('amount')">Amount</th>
      <th ng-click="b.orderBy('type')">Type</th>
      <th ng-click="b.orderBy('message')">Message</th>
      <th ng-click="b.orderBy('price')">Price</th>
      <th ng-click="b.orderBy('image')">Image</th>
      <th>Actions</th>
    </tr>
    <tr ng-repeat="c1 in b.allCoupons | orderBy: b.order : b.goUp">
      <td>{{c1.id}}</td>
      <td>{{c1.title}}</td>
      <td>{{c1.start_date}}</td>
      <td>{{c1.end_date}}</td>
      <td>{{c1.amount}}</td>
      <td>{{c1.type}}</td>
      <td>{{c1.message}}</td>
      <td>{{c1.price}}$</td>
      <td><img alt="" src={{c1.image}} width="100px" height="100px"></td>
      <td>
        <button ng-click="b.buy(c1)">
                    <img alt="Buy" src="../Ico/buy.png" width="60px" height="60px">
                </button>
      </td>
    </tr>
  </table>
  <br/>
  <br/>
</div>
<!-- row -->


问:
Open activity after clicking inside webview
How do we open an activity after clicking some specific link or button of a website which is from some website and open using webview?</p>

答:
Use shouldOverrideUrlLoading to give the host application a chance to take over the control when a new url is about to be loaded in the current WebView.
For more information shouldOverrideUrlLoading

Try this it will help you:

```<code>public class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    if (url.equals("url")) {
        Intent intent = new Intent(contxt, YourActivity.class);
        startActivity(intent);
        return true; // Handle By application itself
    } else {
        view.loadUrl(url);
        return true;
    }
}
}
</code>```

Body:
Use shouldOverrideUrlLoading to give the host application a chance to take over the control when a new url is about to be loaded in the current WebView.
For more information shouldOverrideUrlLoading

Try this it will help you:

public class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    if (url.equals("url")) {
        Intent intent = new Intent(contxt, YourActivity.class);
        startActivity(intent);
        return true; // Handle By application itself
    } else {
        view.loadUrl(url);
        return true;
    }
}
}


问:
Why does "const extern" give an error?
The following piece of code working fine:

```<code>#include <stdio.h>

extern int foo; // Without constant
int foo = 42;

int main()
{
    printf("%d\n",foo);
    return 0;
}
</code>```

But, the following piece of code give an error:

```<code>#include <stdio.h>

const extern int foo; // With constant
int foo = 42;

int main()
{
    printf("%d\n",foo);
    return 0;
}
</code>```

So, why does const extern give an error?

答:
Standard says:

C11-§6.7/4

All declarations in the same scope that refer to the same object or function shall specify compatible types

const int and int are not compatible for the same object foo in the same scope.

Title: Why does "const extern" give an error?

Body:
The following piece of code working fine:

#include <stdio.h>

extern int foo; // Without constant
int foo = 42;

int main()
{
    printf("%d\n",foo);
    return 0;
}

But, the following piece of code give an error:

#include <stdio.h>

const extern int foo; // With constant
int foo = 42;

int main()
{
    printf("%d\n",foo);
    return 0;
}

So, why does const extern give an error?


问:
Uses of static variables inside functions
I have been writing C code for many years, but I recently came accross a feature that I have never used: a static variable inside a function. Therefore, I was wondering what are some ways that you have used this feature and it was the right design decision.

E.g.

```<code>int count(){
    static int n;
    n = n + 1;
    return n;
}
</code>```

is a BAD design decision. why? because later you might want to decrement the count which would involve changing the function parameters, changing all calling code, ...

Hopefully this is clear enough,
thanks!

答:
There is one prominent example that you very much need to be static for protecting critical sections, namely a mutex. As an example for POSIX threads:

```<code>static pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&mut);
/* critical code comes here */
pthread_mutex_unlock(&mut);
</code>```

This wouldn't work with an auto variable.

POSIX has such static initialzers for mutexes, conditions and once variables.

Body:
I have been writing C code for many years, but I recently came accross a feature that I have never used: a static variable inside a function. Therefore, I was wondering what are some ways that you have used this feature and it was the right design decision.

E.g.

int count(){
    static int n;
    n = n + 1;
    return n;
}

is a BAD design decision. why? because later you might want to decrement the count which would involve changing the function parameters, changing all calling code, ...

Hopefully this is clear enough,
thanks!

Body:
There is one prominent example that you very much need to be static for protecting critical sections, namely a mutex. As an example for POSIX threads:

static pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&mut);
/* critical code comes here */
pthread_mutex_unlock(&mut);

This wouldn't work with an auto variable.

POSIX has such static initialzers for mutexes, conditions and once variables.


问:
How to save [x, y] in yaml file
In .yaml file. I know how to save x, y in

```<code>world:

   radius: 20
        x: -70
        y: -30
</code>```

My question is can I save it in the below format

```<code>world:

        radius: 20
        [-30, -70]
</code>```

Basically, I want to store two float number (x, y) in one line.

I program in c++

答:
No you can not, not in the way that you describe. You can easily test that by pasting your required output in an online YAML parser (e.g. this one) or, if you have Python installed, by installing a virtualenv and do¹:

```<code>pip install ruamel.yaml.cmd
yaml round-trip input.yaml
</code>```

Your required output has, at the top-level, a mapping with key world, for which the value starts out with being a mapping (with key radius and value 20) then switches to a flow style sequence: [-30, -70]. That is incorrect, you cannot mix mapping key-value pairs with sequences.

There are several ways to correct this. You can do:

```<code>world:
  radius: 20
  [-30, -70]:
</code>```

which is perfectly fine YAML, the pair -30, -70 being a key for a value null which doesn't need to be made explicit. Please note that some YAML parsers do not support this form, the one I linked to does.

The, IMO, most logical one-line solution:

```<code>world:
  radius: 20
  [x, y]: [-30, -70]
</code>```

which you can get by compiling and running:

```<code>#include <iostream>
#include "yaml-cpp/yaml.h"

int main()
{
   YAML::Emitter out;
   out << YAML::BeginMap;
   out << YAML::Key << "world";
   out << YAML::Value << YAML::BeginMap;
   out << YAML::Key << "radius";
   out << YAML::Value << 20;
   out << YAML::Key << YAML::Flow << YAML::BeginSeq << "x" << "y" << YAML::EndSeq;
   out << YAML::Key << YAML::Flow << YAML::BeginSeq << "-30" << "-70" << YAML::EndSeq;

   std::cout << out.c_str() << "\n";
   return 0;
}
</code>```

Your first YAML example is invalid YAML as well: you should align the keys and not the colons in a mapping:

```<code>world:

   radius: 20
   x: -70
   y: -30
</code>```

¹ Disclaimer: I am the author of the ruamel.yaml.cmd package. Using a local test can be important if your YAML file contains sensitive data.

Title: How to save [x, y] in yaml file

Body:
In .yaml file. I know how to save x, y in

world:

   radius: 20
        x: -70
        y: -30

My question is can I save it in the below format

world:

        radius: 20
        [-30, -70]

Basically, I want to store two float number (x, y) in one line.

I program in c++

Body:
No you can not, not in the way that you describe. You can easily test that by pasting your required output in an online YAML parser (e.g. this one) or, if you have Python installed, by installing a virtualenv and do¹:

pip install ruamel.yaml.cmd
yaml round-trip input.yaml

Your required output has, at the top-level, a mapping with key world, for which the value starts out with being a mapping (with key radius and value 20) then switches to a flow style sequence: [-30, -70]. That is incorrect, you cannot mix mapping key-value pairs with sequences.

There are several ways to correct this. You can do:

world:
  radius: 20
  [-30, -70]:

which is perfectly fine YAML, the pair -30, -70 being a key for a value null which doesn't need to be made explicit. Please note that some YAML parsers do not support this form, the one I linked to does.

The, IMO, most logical one-line solution:

world:
  radius: 20
  [x, y]: [-30, -70]

which you can get by compiling and running:

#include <iostream>
#include "yaml-cpp/yaml.h"

int main()
{
   YAML::Emitter out;
   out << YAML::BeginMap;
   out << YAML::Key << "world";
   out << YAML::Value << YAML::BeginMap;
   out << YAML::Key << "radius";
   out << YAML::Value << 20;
   out << YAML::Key << YAML::Flow << YAML::BeginSeq << "x" << "y" << YAML::EndSeq;
   out << YAML::Key << YAML::Flow << YAML::BeginSeq << "-30" << "-70" << YAML::EndSeq;

   std::cout << out.c_str() << "\n";
   return 0;
}

Your first YAML example is invalid YAML as well: you should align the keys and not the colons in a mapping:

world:

   radius: 20
   x: -70
   y: -30

¹ Disclaimer: I am the author of the ruamel.yaml.cmd package. Using a local test can be important if your YAML file contains sensitive data.


问:
run one where clause condition on the base of parameter
i have ha query like this </p>

```<code>Select * from table1
where col1 = true or col2 = false or
case when @param <> 2 then col3 = col4 end
</code>```

<p>last condition in where is throwing an error </p>

```<code> Incorrect syntax near '<'
</code>```

答:
You cannot use a CASE expression to control execution flow in SQL. CASE is an expression that simply returns a scalar value.

You can use the following predicates instead:

```<code>((@param <> 2 AND col3 = col4) OR (@param = 2))
</code>```

So, the WHERE clause of your query will look like:

```<code>WHERE (col1 = true) OR (col2 = false) OR ((@param <> 2 AND col3 = col4) OR (@param = 2))
</code>```

Body:
i have ha query like this

Select * from table1
where col1 = true or col2 = false or
case when @param <> 2 then col3 = col4 end

last condition in where is throwing an error

 Incorrect syntax near '<'

Body:
You cannot use a CASE expression to control execution flow in SQL. CASE is an expression that simply returns a scalar value.

You can use the following predicates instead:

((@param <> 2 AND col3 = col4) OR (@param = 2))

So, the WHERE clause of your query will look like:

WHERE (col1 = true) OR (col2 = false) OR ((@param <> 2 AND col3 = col4) OR (@param = 2))


答:
Try like below</p>

```<code>SELECT *
FROM TABLE1
WHERE ( COL1='TRUE' OR COL2='FALSE'
OR (@PARAM<>2 AND COL3=COL4) )
</code>```

Title: run one where clause condition on the base of parameter

Body:
Try like below

SELECT *
FROM TABLE1
WHERE ( COL1='TRUE' OR COL2='FALSE'
OR (@PARAM<>2 AND COL3=COL4) )


问:
Icons appear too small on Bootstrap navbar
How can I make the icons bigger and centered on the navbar?

There are no CSS rules that are associated to the navbar so why don't the icons show up the same as the other elements? I've tried several things but nothing seem to work.

in the following picture notice the icons on the right, they're not aligned with the other elements

Code:

```<code><header>
  <nav class = "navbar navbar-default navbar-fixed-top">
    <div class = "container">
      <div class = "navbar-header">
        <a class = "navbar-brand" href = "#">
          BRAND
        </a>
      </div>
      <ul class = "nav navbar-nav navbar-right">
        <li class = "text"><a href="#">ABCD</a></li>
        <li class = "text"><a href="#">EFGH</a></li>
        <li class = "text"><a href="#">IJKL</a></li>
        <li class = "text"><a href="#">MNOP</a></li>
        <li><i class = "fa fa-facebook"></i><li/>
        <li><i class = "fa fa-twitter"> </i><li/>
        <li><i class = "fa fa-instagram"> </i><li/>
      </ul>
    </div>
  </nav>
</header>
</code>```

答:
```<code>.fa {
  padding-top:15px;
  padding-bottom:15px;
  line-height:20px;
}
</code>```

You need to apply the same padding/line height as the anchor tags.

https://jsfiddle.net/ashzzx2j/

NB: Will need to extend the window with the preview in it.

Body:
How can I make the icons bigger and centered on the navbar?

There are no CSS rules that are associated to the navbar so why don't the icons show up the same as the other elements? I've tried several things but nothing seem to work.

in the following picture notice the icons on the right, they're not aligned with the other elements

Code:

          BRAND

ABCD

EFGH

IJKL

MNOP

Body:
.fa {
  padding-top:15px;
  padding-bottom:15px;
  line-height:20px;
}

You need to apply the same padding/line height as the anchor tags.

https://jsfiddle.net/ashzzx2j/

NB: Will need to extend the window with the preview in it.


问:
How is this strict aliasing undefined behaviour?
I know, I saw it already but I couldn't find any good explanation why is this undefined behaviour:

```<code>#include <stdio.h>
#include <stdint.h>

//Common union for both types
union float_int {
    float f;
    uint32_t i;
};

int main(void) {
    union float_int fi;
    //This should be problematic
    uint32_t* i_ptr = (uint32_t *)&fi.f;

    fi.f = 10.0f;
    printf("%f : %u\r\n", fi.f, fi.i); //Prints: 10.000000 : 1092616192 which is OK
    printf("%u\r\n", *i_ptr); //Prints: 1092616192 which is also OK

    return 0;
}
</code>```

If we check memory representation, both are 4-bytes long so there is no memory overflow in pointing or similar.

How is this undefined behaviour?

```<code>int main() {
    union float_int fi;
    void* v_ptr = &fi.f;
    uint32_t* i_ptr = (uint32_t *)v_ptr;
}
</code>```

Is this code still undefined behaviour? I want to read float number as unsigned integer 32-bits.

Why is using memcpy the only available way of doing it?

答:
Float and integer representations are different from one another.
This is why by defining such a union, is not a good use case.

In your example, you perform casting from void* to uint32_t*.
The casting is done in pointer-level.
It means that i_ptr points to a location in memory, viewed as an interger, without changing the bits themselves.

To summarize, if you want this casting to work, you'll need to modify the internal representation of the variable. For example:

```<code>printf("%u\r\n", (uint32_t)*i_ptr);
</code>```

Body:
I know, I saw it already but I couldn't find any good explanation why is this undefined behaviour:

#include <stdio.h>
#include <stdint.h>

//Common union for both types
union float_int {
    float f;
    uint32_t i;
};

int main(void) {
    union float_int fi;
    //This should be problematic
    uint32_t* i_ptr = (uint32_t *)&fi.f;

    fi.f = 10.0f;
    printf("%f : %u\r\n", fi.f, fi.i); //Prints: 10.000000 : 1092616192 which is OK
    printf("%u\r\n", *i_ptr); //Prints: 1092616192 which is also OK

    return 0;
}

If we check memory representation, both are 4-bytes long so there is no memory overflow in pointing or similar.

How is this undefined behaviour?

int main() {
    union float_int fi;
    void* v_ptr = &fi.f;
    uint32_t* i_ptr = (uint32_t *)v_ptr;
}

Is this code still undefined behaviour? I want to read float number as unsigned integer 32-bits.

Why is using memcpy the only available way of doing it?

Body:
Float and integer representations are different from one another.
This is why by defining such a union, is not a good use case.

In your example, you perform casting from void* to uint32_t*.
The casting is done in pointer-level.
It means that i_ptr points to a location in memory, viewed as an interger, without changing the bits themselves.

To summarize, if you want this casting to work, you'll need to modify the internal representation of the variable. For example:

printf("%u\r\n", (uint32_t)*i_ptr);


问:
Laravel - Delete data record from Database
I want to delete record Photo and Photo_list from Database but give me error

This is my Code in Controller

```<code>public function deletephoto($id)
{

    $product = $this->productRepository->findWithoutFail($id);
    Product::select('photo','photo_list')->delete($product->id);

    return redirect(route('stores.index'));

}
</code>```

答:
I don't think you can delete specific data with delete.
Delete is used to remove a row.

You will need to update your table with a request like that :

```<code>public function deletephoto($id)
{

    $product = $this->productRepository->findWithoutFail($id);
    Product::where('id', 100)->update(['photo' => NULL, 'photo_list' => NULL]);

    return redirect(route('stores.index'));

}
</code>```

You can see more here :

https://laravel.com/docs/5.3/eloquent#updates

https://laravel.com/docs/5.3/eloquent#deleting-models

Body:
I want to delete record Photo and Photo_list from Database but give me error

This is my Code in Controller

public function deletephoto($id)
{

    $product = $this->productRepository->findWithoutFail($id);
    Product::select('photo','photo_list')->delete($product->id);

    return redirect(route('stores.index'));

}

Body:
I don't think you can delete specific data with delete.
Delete is used to remove a row.

You will need to update your table with a request like that :

public function deletephoto($id)
{

    $product = $this->productRepository->findWithoutFail($id);
    Product::where('id', 100)->update(['photo' => NULL, 'photo_list' => NULL]);

    return redirect(route('stores.index'));

}

You can see more here :

https://laravel.com/docs/5.3/eloquent#updates

https://laravel.com/docs/5.3/eloquent#deleting-models


问:
C# MVC IIS long running requests
I have an C# MVC app. And one of the calls I know will take like 12 hours, I'm generating some reports.

I want to know if the IIS will keep the process running this long.
If I'll do it async will it run and somehow put it away and let him run for this long?

答:
In general, this is a very poor practice. Your app pool may be recycled for many reasons outside of your control.
You would greatly benefit from processing this in an external process and then providing the user the results via IIS.

However, starting .net 4.5.2 (https://blogs.msdn.microsoft.com/dotnet/2014/05/05/announcing-the-net-framework-4-5-2/) you can use the HostingEnvironment.QueueBackgroundWorkItem API.
The idea behind this is that the IIS will try to finish this work in case of a graceful shutdown of the app pool.

Title: C# MVC IIS long running requests


问:
XMLHttpRequest CORS to Google Cloud Storage only working in preflight request
I implemented browser based resumable uploads into Google's Cloud Storage using an XMLHttpRequest send to a server-side created resumable upload url. This works completely fine when disabling web security, which I did during development.

But now in the real world, CORS keeps making trouble. I tried this with other browsers (without success), too, but sticked to chrome for further testing.

Note: A fake.host entry in /etc/HOSTS is used to trick chrome into avoiding localhost-restrictions. Nevertheless, same happens with the "real" domain of our online test server.

The request is started using a normal XMLHttpRequest call:

```<code>var xhr = this.newXMLHttpRequest();
xhr.open('PUT', url, true);

xhr.setRequestHeader('Content-Type', this.currentInputFile.type);
xhr.setRequestHeader('Content-Range', 'bytes ' + startByte + '-' + (this.currentInputFile.size - 1) + '/' + this.currentInputFile.size);

xhr.onload = function(e) {
   ...
};

...

if (startByte > 0) {
    xhr.send(this.currentInputFile.slice(startByte));
} else {
    xhr.send(this.currentInputFile);
}
</code>```

The browser then successfully initiates a preflight request:

```<code>Remote Address:173.194.71.95:443
Request URL:https://www.googleapis.com/upload/storage/v1/b/my-bucket-name/o?uploadType=resumable&name=aa%20spacetestSMALL_512kb.mp4&upload_id=XXXXXXXXX
Request Method:OPTIONS
Status Code:200 OK
</code>```

Request Headers:

```<code>:host:www.googleapis.com
:method:OPTIONS
:path:/upload/storage/v1/b/my-bucket-name/o?uploadType=resumable&name=aa%20spacetestSMALL_512kb.mp4&upload_id=XXXXXXXXX
:scheme:https
:version:HTTP/1.1
accept:*/*
accept-encoding:gzip,deflate
accept-language:en-US,en;q=0.8,de;q=0.6
access-control-request-headers:content-range, content-type
access-control-request-method:PUT
origin:https://fake.host
referer:https://fake.host/upload.xhtml
user-agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.94 Safari/537.36
x-client-data:YYYYYY
</code>```

Query String Parameters

```<code>uploadType:resumable
name:aa spacetestSMALL_512kb.mp4
upload_id:XXXXXXXXX
</code>```

Response Headers

```<code>access-control-allow-credentials:true
access-control-allow-headers:content-range, content-type
access-control-allow-methods:PUT
access-control-allow-origin:https://fake.host
alternate-protocol:443:quic
content-length:0
content-type:text/html; charset=UTF-8
date:Fri, 05 Sep 2014 14:11:21 GMT
server:UploadServer ("Built on Aug 18 2014 11:58:36 (1408388316)")
status:200 OK
version:HTTP/1.1
</code>```

... and starts the PUT-request until all data is transferred. But afterwards chrome silently logs an error without completing/ending the request:

XMLHttpRequest cannot load https://www.googleapis.com/upload/storage/v1/b/my-bucket-name…XXXXXXXX. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://fake.host' is therefore not allowed access.

This is what chrome logs about the PUT request:

```<code>Request URL:https://www.googleapis.com/upload/storage/v1/b/my-bucket-name/o?uploadType=resumable&name=aa%20spacetestSMALL_512kb.mp4&upload_id=XXXXXXXXX
</code>```

Request Headers

```<code>Provisional headers are shown
Content-Range:bytes 0-3355302/3355303
Content-Type:video/mp4
Origin:https://fake.host
Referer:https://fake.host/upload.xhtml
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.94 Safari/537.36
X-DevTools-Emulate-Network-Conditions-Client-Id:YYYYYYY
</code>```

Query String

```<code>uploadType:resumable
name:aa spacetestSMALL_512kb.mp4
upload_id:XXXXXXXXX
</code>```

Notably, when adding the same url in http://client.cors-api.appspot.com/client and issuing any request, all but the OPTIONS request types fail, too. It seems like the cloud storage api only issues the correct response headers for OPTION requests, but not PUT/POST/GET/... requests.

So am I doing something impossible? Is there something broken? Is this a bug in the cloud storage api? I've spend hours googling and reading SO answers, without any luck so far.

For now, I could periodically check if the download transferred 100% of the data and just ignore the http request outcome, as the file is in fact completely uploaded to the storage bucket. But this is a rather ugly workaround which I really don't want to use if the real issue can be solved.

答:
When requesting a resumable upload url, you MUST include the origin the browser will send when trying to use that upload url, or else the subsequent uploading will fail, just as is happening in the question (the OPTIONS call will look good, but the PUT will not).

It must exactly match the browser's origin (which you can get as location.origin in javascript).

This is the step "Initiating a resumable upload session" in this documentation:
https://cloud.google.com/storage/docs/json_api/v1/how-tos/resumable-upload

If you're requesting the resumable upload url on the server side, you'll probably need the client side (the browser) to pass you its origin (eg: location.origin).

fwiw I was using Google's Cloud Storage library for python for this step, and needed to add the origin like this:

```<code>myblob.create_resumable_upload_session(mycontenttype, origin=browserorigin)
</code>```

Note that you definitely do not need to set up CORS for your bucket.

Body:
I implemented browser based resumable uploads into Google's Cloud Storage using an XMLHttpRequest send to a server-side created resumable upload url. This works completely fine when disabling web security, which I did during development.

But now in the real world, CORS keeps making trouble. I tried this with other browsers (without success), too, but sticked to chrome for further testing.

Note: A fake.host entry in /etc/HOSTS is used to trick chrome into avoiding localhost-restrictions. Nevertheless, same happens with the "real" domain of our online test server.

The request is started using a normal XMLHttpRequest call:

var xhr = this.newXMLHttpRequest();
xhr.open('PUT', url, true);

xhr.setRequestHeader('Content-Type', this.currentInputFile.type);
xhr.setRequestHeader('Content-Range', 'bytes ' + startByte + '-' + (this.currentInputFile.size - 1) + '/' + this.currentInputFile.size);

xhr.onload = function(e) {
   ...
};

...

if (startByte > 0) {
    xhr.send(this.currentInputFile.slice(startByte));
} else {
    xhr.send(this.currentInputFile);
}

The browser then successfully initiates a preflight request:

Remote Address:173.194.71.95:443
Request URL:https://www.googleapis.com/upload/storage/v1/b/my-bucket-name/o?uploadType=resumable&name=aa%20spacetestSMALL_512kb.mp4&upload_id=XXXXXXXXX
Request Method:OPTIONS
Status Code:200 OK

Request Headers:

:host:www.googleapis.com
:method:OPTIONS
:path:/upload/storage/v1/b/my-bucket-name/o?uploadType=resumable&name=aa%20spacetestSMALL_512kb.mp4&upload_id=XXXXXXXXX
:scheme:https
:version:HTTP/1.1
accept:*/*
accept-encoding:gzip,deflate
accept-language:en-US,en;q=0.8,de;q=0.6
access-control-request-headers:content-range, content-type
access-control-request-method:PUT
origin:https://fake.host
referer:https://fake.host/upload.xhtml
user-agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.94 Safari/537.36
x-client-data:YYYYYY

Query String Parameters

uploadType:resumable
name:aa spacetestSMALL_512kb.mp4
upload_id:XXXXXXXXX

Response Headers

access-control-allow-credentials:true
access-control-allow-headers:content-range, content-type
access-control-allow-methods:PUT
access-control-allow-origin:https://fake.host
alternate-protocol:443:quic
content-length:0
content-type:text/html; charset=UTF-8
date:Fri, 05 Sep 2014 14:11:21 GMT
server:UploadServer ("Built on Aug 18 2014 11:58:36 (1408388316)")
status:200 OK
version:HTTP/1.1

... and starts the PUT-request until all data is transferred. But afterwards chrome silently logs an error without completing/ending the request:

XMLHttpRequest cannot load https://www.googleapis.com/upload/storage/v1/b/my-bucket-name…XXXXXXXX. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://fake.host' is therefore not allowed access.

This is what chrome logs about the PUT request:

Request URL:https://www.googleapis.com/upload/storage/v1/b/my-bucket-name/o?uploadType=resumable&name=aa%20spacetestSMALL_512kb.mp4&upload_id=XXXXXXXXX

Request Headers

Provisional headers are shown
Content-Range:bytes 0-3355302/3355303
Content-Type:video/mp4
Origin:https://fake.host
Referer:https://fake.host/upload.xhtml
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.94 Safari/537.36
X-DevTools-Emulate-Network-Conditions-Client-Id:YYYYYYY

Query String

uploadType:resumable
name:aa spacetestSMALL_512kb.mp4
upload_id:XXXXXXXXX

Notably, when adding the same url in http://client.cors-api.appspot.com/client and issuing any request, all but the OPTIONS request types fail, too. It seems like the cloud storage api only issues the correct response headers for OPTION requests, but not PUT/POST/GET/... requests.

So am I doing something impossible? Is there something broken? Is this a bug in the cloud storage api? I've spend hours googling and reading SO answers, without any luck so far.

For now, I could periodically check if the download transferred 100% of the data and just ignore the http request outcome, as the file is in fact completely uploaded to the storage bucket. But this is a rather ugly workaround which I really don't want to use if the real issue can be solved.

Body:
When requesting a resumable upload url, you MUST include the origin the browser will send when trying to use that upload url, or else the subsequent uploading will fail, just as is happening in the question (the OPTIONS call will look good, but the PUT will not).

It must exactly match the browser's origin (which you can get as location.origin in javascript).

This is the step "Initiating a resumable upload session" in this documentation:
https://cloud.google.com/storage/docs/json_api/v1/how-tos/resumable-upload

If you're requesting the resumable upload url on the server side, you'll probably need the client side (the browser) to pass you its origin (eg: location.origin).

fwiw I was using Google's Cloud Storage library for python for this step, and needed to add the origin like this:

myblob.create_resumable_upload_session(mycontenttype, origin=browserorigin)

Note that you definitely do not need to set up CORS for your bucket.


问:
Inserting information in the sql lite database not working
The texts that were already stored in the database are displaying without any problem. But new inserted data not showing. I think "Nothing will be displayed by adding new text, as if the insertion action was not performed.". I don't know why it's not working.Please help...

My DatabaseHandler class

```<code> public class databaseHandler extends SQLiteOpenHelper
{

    private Context main_context;
    private static String DB_PATH;
    private static String DB_NAME = "word.sqlite";
    private static String DB_TBL_BOOKS = "word";
    private static String DB_TBL_SETTING = "setting";
    private static final  int DB_version = 1;
    public static final String COLUMN_ID = "ID";
    public static final String COLUMN_FIRST_NAME = "title";
    public static final String COLUMN_LAST_NAME = "content";
    private SQLiteDatabase db;

    public databaseHandler(Context con)
    {

        super(con, DB_NAME, null, DB_version);

        main_context = con;
        DB_PATH = con.getCacheDir().getPath() + "/" +DB_NAME;

    }
    public void createDataBase() throws IOException {
        boolean dbExist = checkDataBase();
        if (dbExist) {
            // do nothing - database already exist
        } else {

            // By calling this method and empty database will be created into
            // the default system path
            // of your application so we are gonna be able to overwrite that
            // database with our database.
            this.getReadableDatabase();
            copyDB();
        }
    }

    /**
     * Check if the database already exist to avoid re-copying the file each
     * time you open the application.
     *
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase() {
        SQLiteDatabase checkDB = null;
        try {
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null,
                    SQLiteDatabase.OPEN_READONLY);
        } catch (SQLiteException e) {
            // database does't exist yet.
        }
        if (checkDB != null) {
            checkDB.close();
        }
        return checkDB != null ? true : false;
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        String query;
        query = "CREATE TABLE word (id INTEGER PRIMARY KEY  NOT NULL , title VARCHAR, content VARCHAR DEFAULT null)";
        db.execSQL(query);
        Log.d("log","table Created");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        Log.w("tag", "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS word");
        onCreate(db);
    }

    private boolean db_exist() {

        File f = new File(DB_PATH);
        if (f.exists())
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    private boolean copyDB() {
        try {
            FileOutputStream out = new FileOutputStream(DB_PATH);
            InputStream in =main_context.getAssets().open(DB_NAME);
            byte[] buffer = new byte[1024];
            int ch;
            while ((ch = in.read(buffer)) > 0)
            {
                out.write(buffer , 0, ch);
            }
            out.flush();
            out.close();
            in.close();
            return true;
        } catch (Exception e) {
            Log.i("amirmessage", "error in 84 -> " + e.toString());
            return false;
        }
    }

    public void open()
    {
        if (db_exist())
        {
            try {
                File temp = new File(DB_PATH);
                db =SQLiteDatabase.openDatabase(temp.getAbsolutePath() , null ,  SQLiteDatabase.OPEN_READWRITE);
            }catch (Exception e) {
                Log.i("amirmessage", "error in 100 -> " + e.toString());

            }

        }
        else {
            if (copyDB())
            {
                open();
            }

        }
    }
    @Override
    public synchronized void close() {

        db.close();
    }
    //---------

    public List<HashMap<String , Object>> getresultOfSerach()
    {
        Cursor result = db.rawQuery("SELECT * FROM "+ DB_TBL_BOOKS  ,null);
        List<HashMap<String , Object>> all_data = new ArrayList<>();

       try {
           while ( result.moveToNext())
           {
               HashMap<String , Object> temp = new HashMap<>();
               temp.put("id" , result.getString(0));
               temp.put("content" , result.getString(2));

               temp.put("title" , result.getString(1));

               all_data.add(temp);
               Log.d("update","Query: ");

           }
       } finally
        {
            result.close();
        }

        return all_data;
    }

    public void addcontent(String state, String title)
    {

        ContentValues cv  = new ContentValues();
        cv.put("content", state);
        cv.put("title", title);
        db = this.getWritableDatabase();

            db.insert(DB_TBL_BOOKS,null,cv);

        Toast.makeText(main_context,state+title , Toast.LENGTH_SHORT).show();

    }
 }
</code>```

My Activity insert code is here

```<code>public class addcontent extends AppCompatActivity

  {

    private databaseHandler db;
    public String title1;
    public String content;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addcontent);
        db = new databaseHandler(getBaseContext());
        sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

        EditText etcontent = (EditText)findViewById(R.id.editText);
        EditText ettitle1 = (EditText)findViewById(R.id.editText2);

        title1=ettitle1.getText().toString();
        content=etcontent.getText().toString();

    }

      public void onbtnadd(View v)
    {

        db.open();
        db.addcontent( content,title1);

        db.close();

    }
}
</code>```

My MainActivity  code to Show information is here

```<code> public class Main2Activity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

private databaseHandler db;
private ListView resultListView;
private List<HashMap<String , Object>> resultsbooks;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent i = new Intent(getBaseContext(),addcontent.class);
            startActivity(i);
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    resultListView = (ListView) findViewById(R.id.catListview);
    db = new databaseHandler(getBaseContext());
    showresultOfSerarch();
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main2, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_camera) {
        // Handle the camera action
    } else if (id == R.id.nav_gallery) {

    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

public void onbtnfind()
{
    resultListView.setAdapter(null);

    String serachBy;

    serachBy = "author";

    String query =" ";

    showresultOfSerarch();

}
  public void showresultOfSerarch()
{
    db.open();

    resultsbooks = db.getresultOfSerach();
    db.close();

    String[] from = {"title","content"};
    int[] to = {R.id.txttitle,  R.id.txtcontent};

    SimpleAdapter adp = new SimpleAdapter(
            getBaseContext(), resultsbooks, R.layout.tbl_contest_row, from, to
    );
    resultListView.setAdapter(adp);
 }
</code>```

}

答:
U have done correct but a mistake.

Can u change ur class file

Change according  for ur field ids

```<code>public class AddContent extends AppCompatActivity

{
        private DatabaseHandler db;
    public String title1;
    public String content;
    EditText etcontent;
    EditText ettitle1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_content);
        db = new DatabaseHandler(getBaseContext());
//        sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

        Button btn_add = (Button) findViewById(R.id.btn_add);
        etcontent = (EditText) findViewById(R.id.edt_text1);
        ettitle1 = (EditText) findViewById(R.id.edt_text2);

        btn_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                title1 = ettitle1.getText().toString();
                content = etcontent.getText().toString();
                onbtnadd(v);

            }
        });

    }

    public void onbtnadd(View v) {
        db.open();
        db.addcontent(content, title1);
        db.close();

    }
</code>```

Body:
The texts that were already stored in the database are displaying without any problem. But new inserted data not showing. I think "Nothing will be displayed by adding new text, as if the insertion action was not performed.". I don't know why it's not working.Please help...

My DatabaseHandler class

 public class databaseHandler extends SQLiteOpenHelper
{

    private Context main_context;
    private static String DB_PATH;
    private static String DB_NAME = "word.sqlite";
    private static String DB_TBL_BOOKS = "word";
    private static String DB_TBL_SETTING = "setting";
    private static final  int DB_version = 1;
    public static final String COLUMN_ID = "ID";
    public static final String COLUMN_FIRST_NAME = "title";
    public static final String COLUMN_LAST_NAME = "content";
    private SQLiteDatabase db;

    public databaseHandler(Context con)
    {

        super(con, DB_NAME, null, DB_version);

        main_context = con;
        DB_PATH = con.getCacheDir().getPath() + "/" +DB_NAME;

    }
    public void createDataBase() throws IOException {
        boolean dbExist = checkDataBase();
        if (dbExist) {
            // do nothing - database already exist
        } else {

            // By calling this method and empty database will be created into
            // the default system path
            // of your application so we are gonna be able to overwrite that
            // database with our database.
            this.getReadableDatabase();
            copyDB();
        }
    }

    /**
     * Check if the database already exist to avoid re-copying the file each
     * time you open the application.
     *
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase() {
        SQLiteDatabase checkDB = null;
        try {
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null,
                    SQLiteDatabase.OPEN_READONLY);
        } catch (SQLiteException e) {
            // database does't exist yet.
        }
        if (checkDB != null) {
            checkDB.close();
        }
        return checkDB != null ? true : false;
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        String query;
        query = "CREATE TABLE word (id INTEGER PRIMARY KEY  NOT NULL , title VARCHAR, content VARCHAR DEFAULT null)";
        db.execSQL(query);
        Log.d("log","table Created");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        Log.w("tag", "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS word");
        onCreate(db);
    }

    private boolean db_exist() {

        File f = new File(DB_PATH);
        if (f.exists())
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    private boolean copyDB() {
        try {
            FileOutputStream out = new FileOutputStream(DB_PATH);
            InputStream in =main_context.getAssets().open(DB_NAME);
            byte[] buffer = new byte[1024];
            int ch;
            while ((ch = in.read(buffer)) > 0)
            {
                out.write(buffer , 0, ch);
            }
            out.flush();
            out.close();
            in.close();
            return true;
        } catch (Exception e) {
            Log.i("amirmessage", "error in 84 -> " + e.toString());
            return false;
        }
    }

    public void open()
    {
        if (db_exist())
        {
            try {
                File temp = new File(DB_PATH);
                db =SQLiteDatabase.openDatabase(temp.getAbsolutePath() , null ,  SQLiteDatabase.OPEN_READWRITE);
            }catch (Exception e) {
                Log.i("amirmessage", "error in 100 -> " + e.toString());

            }

        }
        else {
            if (copyDB())
            {
                open();
            }

        }
    }
    @Override
    public synchronized void close() {

        db.close();
    }
    //---------

    public List<HashMap<String , Object>> getresultOfSerach()
    {
        Cursor result = db.rawQuery("SELECT * FROM "+ DB_TBL_BOOKS  ,null);
        List<HashMap<String , Object>> all_data = new ArrayList<>();

       try {
           while ( result.moveToNext())
           {
               HashMap<String , Object> temp = new HashMap<>();
               temp.put("id" , result.getString(0));
               temp.put("content" , result.getString(2));

               temp.put("title" , result.getString(1));

               all_data.add(temp);
               Log.d("update","Query: ");

           }
       } finally
        {
            result.close();
        }

        return all_data;
    }

    public void addcontent(String state, String title)
    {

        ContentValues cv  = new ContentValues();
        cv.put("content", state);
        cv.put("title", title);
        db = this.getWritableDatabase();

            db.insert(DB_TBL_BOOKS,null,cv);

        Toast.makeText(main_context,state+title , Toast.LENGTH_SHORT).show();

    }
 }

My Activity insert code is here

public class addcontent extends AppCompatActivity

  {

    private databaseHandler db;
    public String title1;
    public String content;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addcontent);
        db = new databaseHandler(getBaseContext());
        sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

        EditText etcontent = (EditText)findViewById(R.id.editText);
        EditText ettitle1 = (EditText)findViewById(R.id.editText2);

        title1=ettitle1.getText().toString();
        content=etcontent.getText().toString();

    }

      public void onbtnadd(View v)
    {

        db.open();
        db.addcontent( content,title1);

        db.close();

    }
}

My MainActivity  code to Show information is here

 public class Main2Activity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

private databaseHandler db;
private ListView resultListView;
private List<HashMap<String , Object>> resultsbooks;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent i = new Intent(getBaseContext(),addcontent.class);
            startActivity(i);
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    resultListView = (ListView) findViewById(R.id.catListview);
    db = new databaseHandler(getBaseContext());
    showresultOfSerarch();
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main2, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_camera) {
        // Handle the camera action
    } else if (id == R.id.nav_gallery) {

    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

public void onbtnfind()
{
    resultListView.setAdapter(null);

    String serachBy;

    serachBy = "author";

    String query =" ";

    showresultOfSerarch();

}
  public void showresultOfSerarch()
{
    db.open();

    resultsbooks = db.getresultOfSerach();
    db.close();

    String[] from = {"title","content"};
    int[] to = {R.id.txttitle,  R.id.txtcontent};

    SimpleAdapter adp = new SimpleAdapter(
            getBaseContext(), resultsbooks, R.layout.tbl_contest_row, from, to
    );
    resultListView.setAdapter(adp);
 }

}

Body:
U have done correct but a mistake.

Can u change ur class file

Change according  for ur field ids

public class AddContent extends AppCompatActivity

{
        private DatabaseHandler db;
    public String title1;
    public String content;
    EditText etcontent;
    EditText ettitle1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_content);
        db = new DatabaseHandler(getBaseContext());
//        sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

        Button btn_add = (Button) findViewById(R.id.btn_add);
        etcontent = (EditText) findViewById(R.id.edt_text1);
        ettitle1 = (EditText) findViewById(R.id.edt_text2);

        btn_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                title1 = ettitle1.getText().toString();
                content = etcontent.getText().toString();
                onbtnadd(v);

            }
        });

    }

    public void onbtnadd(View v) {
        db.open();
        db.addcontent(content, title1);
        db.close();

    }


问:
How can I read the verbose output from a Cmdlet in C# using Exchange Powershell
Environment: Exchange 2007 sp3 (2003 sp2 mixed mode)

Visual Studio 2008, .Net 3.5

I'm working with an Exchange powershell move-mailbox cmdlet and have noted when I do so from the Exchange Management shell (using the Verbose switch) there is a ton of real-time information provided.

To provide a little context, I'm attempting to create a UI application that moves mailboxes similarly to the Exchange Management Console but desire to support an input file and specific server/database destinations for each entry (and threading).

Here's roughly what I have at present but I'm not sure if there is an event I need to register for or what...  And to be clear, I desire to get this information in real-time so I may update my UI to reflect what's occurring in the move sequence for the appropriate user (pretty much like the native functionality offered in the Management Console).  And in case you are wondering, the reason why I'm not content with the Management Console functionality is, I have an algorithm which I'm using to balance users depending on storage limit, Blackberry use, journaling, exception mailbox size etc which demands user be mapped to specific locations... and I do not desire to create many/several move groups for each common destination or to hunt for lists of users individually through the management console UI.

I can not seem to find any good documentation or examples of how to tie into reading the verbose messages that are provided within the console using C# (I see value in being able to read this kind of information in many different scenarios).

I've explored the Invoke and InvokeAsync methods and the StateChanged & DataReady events but none of these seem to provide the information (verbose comments) that I'm after.

Any direction or examples that can be provided will be very appreciated!

A code sample which is little more than how I would ordinarily call any other powershell command follows:

```<code>// config to use ExMgmt shell, create runspace and open it
RunspaceConfiguration rsConfig = RunspaceConfiguration.Create();

PSSnapInException snapInException = null;
PSSnapInInfo info = rsConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out snapInException);

if (snapInException != null) throw snapInException;

Runspace runspace = RunspaceFactory.CreateRunspace(rsConfig);

try
{
  runspace.Open();

  // create a pipeline and feed script text
  Pipeline pipeline = runspace.CreatePipeline();

  string targetDatabase = @"myServer\myStorageGroup\myDB";
  string mbxOwner = "user@company.com";

  Command myMoveMailbox = new Command("Move-Mailbox", false, false);
  myMoveMailbox.Parameters.Add("Identity", mbxOwner);
  myMoveMailbox.Parameters.Add("TargetDatabase", targetDatabase);
  myMoveMailbox.Parameters.Add("Verbose");
  myMoveMailbox.Parameters.Add("ValidateOnly");
  myMoveMailbox.Parameters.Add("Confirm", false);
  pipeline.Commands.Add(myMoveMailbox);

  System.Collections.ObjectModel.Collection<PSObject> output = null;

  // these next few lines that are commented out are where I've tried
  // registering for events and calling asynchronously but this doesn't
  // seem to get me anywhere closer
  //
  //pipeline.StateChanged += new EventHandler<PipelineStateEventArgs>(pipeline_StateChanged);
  //pipeline.Output.DataReady += new EventHandler(Output_DataReady);
  //pipeline.InvokeAsync();
  //pipeline.Input.Close();
  //return; tried these variations that are commented out but none seem to be useful

  output = pipeline.Invoke();

  // Check for errors in the pipeline and throw an exception if necessary
  if (pipeline.Error != null && pipeline.Error.Count > 0)
  {
     StringBuilder pipelineError = new StringBuilder();
     pipelineError.AppendFormat("Error calling Test() Cmdlet.  ");
     foreach (object item in pipeline.Error.ReadToEnd())
       pipelineError.AppendFormat("{0}\n", item.ToString());

     throw new Exception(pipelineError.ToString());
   }

   foreach (PSObject psObject in output)
   {
     // blah, blah, blah
     // this is normally where I would read details about a particular PS command
     // but really pertains to a command once it finishes and has nothing to do with
     // the verbose messages that I'm after... since this part of the methods pertains
     // to the after-effects of a command having run, I'm suspecting I need to look to
     // the asynch invoke method but am not certain or knowing how.
   }
}
finally
{
  runspace.Close();
}
</code>```

答:
Take a look at the PowerShell class.  It has a Streams property that allows you to access the Verbose stream's contents.  Note that the PowerShell class was introduced in PowerShell 2.0 but is probably what you want to use when embedded PowerShell within a hosting app.  In fact, the docs say:

Provides methods that are used to
  create a pipeline of commands and
  invoke those commands either
  synchronously or asynchronously within
  a runspace. This class also provides
  access to the output streams that
  contain data that is generated when
  the commands are invoked. This class
  is primarily intended for host
  applications that programmatically use
  Windows PowerShell to perform tasks.
  This class is introduced in Windows
  PowerShell 2.0.

Body:
Environment: Exchange 2007 sp3 (2003 sp2 mixed mode)

Visual Studio 2008, .Net 3.5

I'm working with an Exchange powershell move-mailbox cmdlet and have noted when I do so from the Exchange Management shell (using the Verbose switch) there is a ton of real-time information provided.

To provide a little context, I'm attempting to create a UI application that moves mailboxes similarly to the Exchange Management Console but desire to support an input file and specific server/database destinations for each entry (and threading).

Here's roughly what I have at present but I'm not sure if there is an event I need to register for or what...  And to be clear, I desire to get this information in real-time so I may update my UI to reflect what's occurring in the move sequence for the appropriate user (pretty much like the native functionality offered in the Management Console).  And in case you are wondering, the reason why I'm not content with the Management Console functionality is, I have an algorithm which I'm using to balance users depending on storage limit, Blackberry use, journaling, exception mailbox size etc which demands user be mapped to specific locations... and I do not desire to create many/several move groups for each common destination or to hunt for lists of users individually through the management console UI.

I can not seem to find any good documentation or examples of how to tie into reading the verbose messages that are provided within the console using C# (I see value in being able to read this kind of information in many different scenarios).

I've explored the Invoke and InvokeAsync methods and the StateChanged & DataReady events but none of these seem to provide the information (verbose comments) that I'm after.

Any direction or examples that can be provided will be very appreciated!

A code sample which is little more than how I would ordinarily call any other powershell command follows:

// config to use ExMgmt shell, create runspace and open it
RunspaceConfiguration rsConfig = RunspaceConfiguration.Create();

PSSnapInException snapInException = null;
PSSnapInInfo info = rsConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out snapInException);

if (snapInException != null) throw snapInException;

Runspace runspace = RunspaceFactory.CreateRunspace(rsConfig);

try
{
  runspace.Open();

  // create a pipeline and feed script text
  Pipeline pipeline = runspace.CreatePipeline();

  string targetDatabase = @"myServer\myStorageGroup\myDB";
  string mbxOwner = "user@company.com";

  Command myMoveMailbox = new Command("Move-Mailbox", false, false);
  myMoveMailbox.Parameters.Add("Identity", mbxOwner);
  myMoveMailbox.Parameters.Add("TargetDatabase", targetDatabase);
  myMoveMailbox.Parameters.Add("Verbose");
  myMoveMailbox.Parameters.Add("ValidateOnly");
  myMoveMailbox.Parameters.Add("Confirm", false);
  pipeline.Commands.Add(myMoveMailbox);

  System.Collections.ObjectModel.Collection<PSObject> output = null;

  // these next few lines that are commented out are where I've tried
  // registering for events and calling asynchronously but this doesn't
  // seem to get me anywhere closer
  //
  //pipeline.StateChanged += new EventHandler<PipelineStateEventArgs>(pipeline_StateChanged);
  //pipeline.Output.DataReady += new EventHandler(Output_DataReady);
  //pipeline.InvokeAsync();
  //pipeline.Input.Close();
  //return; tried these variations that are commented out but none seem to be useful

  output = pipeline.Invoke();

  // Check for errors in the pipeline and throw an exception if necessary
  if (pipeline.Error != null && pipeline.Error.Count > 0)
  {
     StringBuilder pipelineError = new StringBuilder();
     pipelineError.AppendFormat("Error calling Test() Cmdlet.  ");
     foreach (object item in pipeline.Error.ReadToEnd())
       pipelineError.AppendFormat("{0}\n", item.ToString());

     throw new Exception(pipelineError.ToString());
   }

   foreach (PSObject psObject in output)
   {
     // blah, blah, blah
     // this is normally where I would read details about a particular PS command
     // but really pertains to a command once it finishes and has nothing to do with
     // the verbose messages that I'm after... since this part of the methods pertains
     // to the after-effects of a command having run, I'm suspecting I need to look to
     // the asynch invoke method but am not certain or knowing how.
   }
}
finally
{
  runspace.Close();
}


答:
You can try fa-2x in class tag, exactly like:

class = "fa fa-facebook fa-2x"

class = "fa fa-twitter fa-2x"

class = "fa fa-instagram fa-2x"

Size of icon varies, by changing "x" from "x" till "5x"

Title: Icons appear too small on Bootstrap navbar


答:
These two declarations are contradictory:

```<code>const extern int foo; // With constant
int foo = 42;
</code>```

The first one declares foo as const, and the second one declares it as non const.

Error messages:

```<code>prog.cpp:4:5: error: conflicting declaration
   ‘int foo’ int foo = 42;
         ^~~
 prog.cpp:3:18: note: previous declaration as ‘const int foo’
    const extern int foo; // With constant
                     ^~~
</code>```

Title: Why does "const extern" give an error?

Body:
The following piece of code working fine:

#include <stdio.h>

extern int foo; // Without constant
int foo = 42;

int main()
{
    printf("%d\n",foo);
    return 0;
}

But, the following piece of code give an error:

#include <stdio.h>

const extern int foo; // With constant
int foo = 42;

int main()
{
    printf("%d\n",foo);
    return 0;
}

So, why does const extern give an error?

Body:
These two declarations are contradictory:

const extern int foo; // With constant
int foo = 42;

The first one declares foo as const, and the second one declares it as non const.

Error messages:

prog.cpp:4:5: error: conflicting declaration
   ‘int foo’ int foo = 42;
         ^~~
 prog.cpp:3:18: note: previous declaration as ‘const int foo’
    const extern int foo; // With constant
                     ^~~