问:
Angular 2 / 4 / 5 reactive forms validation - how to make it more concise?
EDIT 2:

I have created an issue for the angular team to simplify the form validation. Give it thumbs up if you want a simpler form validation experience.

https://github.com/angular/angular/issues/20477

EDIT 1:

The answer from H.abidi goes in the desired direction, but it only works for material components. In other words, I think the material also recognized this problem and they solved it for their components.

ORIGINAL QUESTION:

This is an example of an input field without validation CSS styles or error messages (e.g. red border on input field when invalid):

```<code>    <input required type="date" id="Rechnungsdatum" name="Rechnungsdatum" formControlName="Rechnungsdatum">
    <label for="Rechnungsdatum">Rechnungsdatum*</label>
</code>```

A similar input field with validation, where I apply CSS classes such as "valid valid--inline" or "invalid invalid-inline" via [ngClass] and where I display error messages and error icons looks like:

```<code>    <input required type="text" id="Rechnungsnummer" name="Rechnungsnummer" formControlName="Rechnungsnummer" [ngClass]="{'invalid invalid--inline': !signupForm.get('Rechnungsnummer').valid && (signupForm.get('Rechnungsnummer').touched || formDir.submitted),
    'valid valid--inline': signupForm.get('Rechnungsnummer').valid && (signupForm.get('Rechnungsnummer').touched || formDir.submitted)}">
    <label for="Rechnungsnummer">Rechnungsnummer*</label>
    <div class="message" *ngIf="!signupForm.get('Rechnungsnummer').valid && !signupForm.get('Rechnungsnummer').errors['required'] && (signupForm.get('Rechnungsnummer').touched || formDir.submitted)">
      <i class="icon icon-026-exclamation-mark-circle" aria-hidden="true"></i>
      Rechnungsnummer muss zwischen 3 und 6 Zeichen lang sein
    </div>
    <div class="message" *ngIf="signupForm.get('Rechnungsnummer').errors['required'] && (signupForm.get('Rechnungsnummer').touched || formDir.submitted)">
      <i class="icon icon-026-exclamation-mark-circle" aria-hidden="true"></i>
      Rechnungsnummer erforderlich
    </div>
</code>```

The code:

```<code>!signupForm.get('Rechnungsnummer').valid && (signupForm.get('Rechnungsnummer').touched || formDir.submitted)
</code>```

is repetitive. Is there a best practice to make this more concise? Or even to define some rules based on which CSS classes are added and error messages are displayed. I have a feeling that this is too much logic inside the template.

Additionally is it possible to avoid specifying the name of the form control for every input? E.g. instead of

```<code>signupForm.get('Rechnungsnummer').valid
</code>```

have something like

```<code>signupForm.currentFormControl.valid
</code>```

or like

```<code><input id="1" #thisInput [ngClass]="{valid: thisInput.valid}>
<input id="2" #thisInput [ngClass]="{valid: thisInput.valid}>
</code>```

答:
Before using ErrorStateMatcher my code was like this :

```<code>    <p [class.errors]="form.controls.lastname.touched && form.controls.lastname.invalid">
      <mat-input-container>
        <input id="idLastname" matInput placeholder="Nom" formControlName="lastname">
        <span *ngIf="form.controls.lastname.touched && form.controls.lastname.errors?.required">
      <br>le nom est obligatoire</span>
      </mat-input-container>
    </p>
</code>```

And css class errors

```<code>.errors {
  color: red;
}
</code>```

Body:
EDIT 2:

I have created an issue for the angular team to simplify the form validation. Give it thumbs up if you want a simpler form validation experience.

https://github.com/angular/angular/issues/20477

EDIT 1:

The answer from H.abidi goes in the desired direction, but it only works for material components. In other words, I think the material also recognized this problem and they solved it for their components.

ORIGINAL QUESTION:

This is an example of an input field without validation CSS styles or error messages (e.g. red border on input field when invalid):

    <input required type="date" id="Rechnungsdatum" name="Rechnungsdatum" formControlName="Rechnungsdatum">
    Rechnungsdatum*

A similar input field with validation, where I apply CSS classes such as "valid valid--inline" or "invalid invalid-inline" via [ngClass] and where I display error messages and error icons looks like:

    <input required type="text" id="Rechnungsnummer" name="Rechnungsnummer" formControlName="Rechnungsnummer" [ngClass]="{'invalid invalid--inline': !signupForm.get('Rechnungsnummer').valid && (signupForm.get('Rechnungsnummer').touched || formDir.submitted),
    'valid valid--inline': signupForm.get('Rechnungsnummer').valid && (signupForm.get('Rechnungsnummer').touched || formDir.submitted)}">
    Rechnungsnummer*

      Rechnungsnummer muss zwischen 3 und 6 Zeichen lang sein

      Rechnungsnummer erforderlich

The code:

!signupForm.get('Rechnungsnummer').valid && (signupForm.get('Rechnungsnummer').touched || formDir.submitted)

is repetitive. Is there a best practice to make this more concise? Or even to define some rules based on which CSS classes are added and error messages are displayed. I have a feeling that this is too much logic inside the template.

Additionally is it possible to avoid specifying the name of the form control for every input? E.g. instead of

signupForm.get('Rechnungsnummer').valid

have something like

signupForm.currentFormControl.valid

or like

<input id="1" #thisInput [ngClass]="{valid: thisInput.valid}>
<input id="2" #thisInput [ngClass]="{valid: thisInput.valid}>

Body:
Before using ErrorStateMatcher my code was like this :

    <p [class.errors]="form.controls.lastname.touched && form.controls.lastname.invalid">
      <mat-input-container>
        <input id="idLastname" matInput placeholder="Nom" formControlName="lastname">
        <span *ngIf="form.controls.lastname.touched && form.controls.lastname.errors?.required">
      <br>le nom est obligatoire</span>
      </mat-input-container>
    </p>

And css class errors

.errors {
  color: red;
}


来源: stackexchange

问:
Full width of col-md-10 when using col-md-2 for sidebar bootstrap 4
I am trying to add background color for nav-header, and since it is within col-md-10, it won't take full width when sidebar (col-md-2) is closed.
I tried to wrap it inside another div, but it doesn't work, I can't override col-md-10 rules. Is there any way to do this?</p>

```<code><div class="container-fluid">
    <div class="row d-flex d-md-block flex-nowrap wrapper">
        <div class="col-md-2 float-left col-1 pl-0 pr-0 collapse width hidden" id="sidebar">
            <div class="list-group border-0 card text-center text-md-left">

                <a href="#" class="list-group-item d-inline-block collapsed" data-parent="#sidebar"><i class="fa fa-film"></i> <span class="d-none d-md-inline">Item 2</span></a>
                <a href="#menu3" class="list-group-item d-inline-block collapsed" data-toggle="collapse" data-parent="#sidebar" aria-expanded="false"><i class="fa fa-book"></i> <span class="d-none d-md-inline">Item 3 </span></a><a href="#" class="list-group-item d-inline-block collapsed" data-parent="#sidebar"><i class="fa fa-heart"></i> <span class="d-none d-md-inline">Item 4</span></a>
                <a href="#" class="list-group-item d-inline-block collapsed" data-parent="#sidebar"><i class="fa fa-list"></i> <span class="d-none d-md-inline">Item 5</span></a>

            </div>
        </div>
        <main class="col-md-10 float-left">
            <div class="nav-header">
                <a href="#" data-target="#sidebar" data-toggle="collapse"><i class="fa fa-navicon fa-2x py-2 p-1"></i></a>
                <a href="/" class="navbar-brand"><img src="img/logo.png" height="45" alt=""></a>
            </div>
            <div class="page-header">
                <h2>Bootstrap 4 Sidebar Menu</h2>
            </div>

            <hr>

        </main>
    </div>
</div>
</code>```

答:
That's tricky.  Unless you can use the sass functions to build your columns, you'll have to override the styles for that particular .col-md-10.  Maybe something like this?

```<code>#sidebar:not(.show) + [class*=col-] {
  -webkit-box-flex: 0;
  -webkit-flex: 0 0 100%;
  -ms-flex: 0 0 100%;
  flex: 0 0 100%;
  max-width: 100%;
}
</code>```

Demo (Note: I'm using jsfiddle because stack snippets is blocking a part of bootstrap's js and failing to execute the part for opening or closing the menu)

Edit

For those curious, the SCSS way to do it would be to use a mixin

Your SCSS might look like this:

```<code>#sidebar + main {
  @include make-col(12);
}
#sidebar.show + main {
  @include make-col(10);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to add background color for nav-header, and since it is within col-md-10, it won't take full width when sidebar (col-md-2) is closed.
I tried to wrap it inside another div, but it doesn't work, I can't override col-md-10 rules. Is there any way to do this?

                 Item 2
                 Item 3  Item 4
                 Item 5

Bootstrap 4 Sidebar Menu

Body:
That's tricky.  Unless you can use the sass functions to build your columns, you'll have to override the styles for that particular .col-md-10.  Maybe something like this?

#sidebar:not(.show) + [class*=col-] {
  -webkit-box-flex: 0;
  -webkit-flex: 0 0 100%;
  -ms-flex: 0 0 100%;
  flex: 0 0 100%;
  max-width: 100%;
}

Demo (Note: I'm using jsfiddle because stack snippets is blocking a part of bootstrap's js and failing to execute the part for opening or closing the menu)

Edit

For those curious, the SCSS way to do it would be to use a mixin

Your SCSS might look like this:

#sidebar + main {
  @include make-col(12);
}
#sidebar.show + main {
  @include make-col(10);
}


问:
React Native - i want to hide green message on header in the first screen
who help me hide green message on header in the first screen  :(
Thanks

答:
You can't hide it. You only can hide red and yellow boxes from warnings and errors.
https://facebook.github.io/react-native/docs/debugging.html#warnings
Anyway, that only appear in develop mode, don't be afraid to see it in production.
Greetings!</p>


问:
Simulate Push Notification in UITest
We would like to test the receiving of push notifications (while the app is active) in an UITest. The goto solution with sending real push notifications sounds a bit like an overkill (and only works on a real device): see http://www.pixeldock.com/blog/testing-push-notifications-with-xcode-uitests/

My question is: Is it possible to call (directly or indirectly) the UIAppicaltionDelegate's didReceiveRemoteNotification from an (UI) XCTestCase?

答:
You can trigger events in your app from within a UITest. I have done it before by putting buttons onto my views (a limitation is that I had to add the button(s) to every view I wanted the events happening on).

To make sure you only add the buttons when UITesting, in your setUp() function pass in launchArguments by appending elements to the launchArguments array.

launchArguments.append("push_notification_button")

To access from within the app:

```<code>if ProcessInfo.processInfo.arguments.contains("push_notification_button") {
    // Add button
}
</code>```

Title: Simulate Push Notification in UITest

Body:
You can trigger events in your app from within a UITest. I have done it before by putting buttons onto my views (a limitation is that I had to add the button(s) to every view I wanted the events happening on).

To make sure you only add the buttons when UITesting, in your setUp() function pass in launchArguments by appending elements to the launchArguments array.

launchArguments.append("push_notification_button")

To access from within the app:

if ProcessInfo.processInfo.arguments.contains("push_notification_button") {
    // Add button
}


问:
On Exception-Safety in a Function-Call
Is the call to f() exception-safe?

```<code>inline std::auto_ptr<C> auto_new() {
   return std::auto_ptr<C>(new C());
}

void f(std::auto_ptr<C> p1,
       std::auto_ptr<C> p2);

// ...
{
    f(auto_new(), auto_new());
}
</code>```

In other words, does it make any difference when it comes to the atomicity of the first and second auto_new() function calls if the two functions are inline?

答: Yes, it's exception safe; no, inline makes no difference to the sequence points guaranteed in the calling expression.

ContentLicense: CC BY-SA 2.5

Title: On Exception-Safety in a Function-Call

Body:
Is the call to f() exception-safe?

inline std::auto_ptr<C> auto_new() {
   return std::auto_ptr<C>(new C());
}

void f(std::auto_ptr<C> p1,
       std::auto_ptr<C> p2);

// ...
{
    f(auto_new(), auto_new());
}

In other words, does it make any difference when it comes to the atomicity of the first and second auto_new() function calls if the two functions are inline?


问:
Magnolia 5.5.7 Stories App Internalization
We want to use the Stories App instead of Pages.
How is internalization handled in the stories? Is it possible?</p>

答:
Currently, It is not supported. However, you could use the existing patterns to implement it yourself (if you are motivated to).

I can say that we are interested in the topic though and most likely there will be some activity about the topic at some point.


问:
UISearchBar's scope buttons are covering the first row of results
I'm working with UISearchBar for the first time and can't quite make it do what I want.

When you activate the scope buttons, they cover the first row of the table.  The only way to see all of your search results seem to be to hide the scope buttons when editing is finished;  in my Googling on this I have seen that suggested.

I want the functionality that Mail has, where the scope buttons stay up as long as there is text in the search box, and you can see the search results change as you change the active scope button.  But I can't figure out any way to make this happen without having the first row of the table covered by the scope buttons.  You can't just scroll the table view down;  the search bar is in the table view's header, so the whole thing scrolls together.

Suggestions appreciated!

Updated after trying Andrew's suggestion below.

One thing I forgot about is that in viewDidAppear I scroll the table view content up, so that the search box is off the top of the screen but can be scrolled down when needed.  This is obviously part of my problem.  So, in viewDidAppear I have

```<code>if (theSearchBar.showsScopeBar != YES) {
    [self.tableView setContentOffset:CGPointMake(0, 44) animated:YES];
}
</code>```

In searchBarShouldBeginEditing, I now have:

```<code>[self.navigationController setNavigationBarHidden:YES];
[self.tableView setContentOffset:CGPointMake(0, -44) animated:YES];
[UIView beginAnimations:@"searchBarUp" context:nil];
[UIView setAnimationDuration:1.0f];
searchBar.frame = CGRectOffset(searchBar.frame, 0, -44);
[UIView commitAnimations];
</code>```

This gives the correct result, but when the scope bars come up, there is a gap between the top of the view and the top of the search bar, and the first row is covered.  Then the scroll bar (with the scope buttons) slides up into place.  This obviously doesn't look very good.

What I would expect the above code to do is:

hide the nav bar, which would put the top row of the table right below the status bar

scroll the table content back down, which would put the top of the search bar right below the status bar

move the search bar up so that there is a 44 pixel gap between the bottom of the search bar, to be filled in by the scope buttons

This does appear to be what happens, except you can see the gap left by the nav bar until the scroll bar moves up to meet it.  You would think this could be fixed by hiding the nav bar last, but no... when I tried that I ended up with both the first row of the table covered and a nav bar sized hole between the status and search bars.

Another thing I find very odd is that if I use the above code snippet as is, except with animation:NO on the call to setContentOffset, I get a different result.  In this case the first row of the table is not covered, but the search box is above the top of the view and cannot be scrolled down (it won't stay).  Only the scope buttons are visible.  It doesn't make sense to me that just turning off animation would change the outcome.

Now, you might think that with everything in the right place, displaying the search results would just work. But no.  Even though the nav bar is now out of the picture, the search bar still comes up with a large gap above it, and the same adjustments to the table content and the search bar frame are required as above.

I should note that the code in viewWillAppear is only executed once, since we never leave the view, so it's not the case that the table is being readjusted upwards each time.

I would love to understand what's going on, as well as how to fix it, if anyone can help shed some light.

Updated again for clarity - when I say "fix it", what I mean is make it look good without visible gaps when the pieces are moving into place.  I don't even necessarily want it animated;  the sliding into position takes too long.  But as I mentioned above, turning animation off makes things end up in the wrong place again.

Updated one last time - I got it to look much better by removing the animation block around the line to move the search bar.  I guess that introduced a pause before the animation began.  It's good enough now, at least for the moment.  I'm still accepting Andrew's answer since he steered me in the right direction.

答:
This is what I did, I'm using SearchViewController:</p>

```<code>if #available(iOS 11.0, *) {
    navigationItem.searchController = searchController
    }
    else{
        tableView.tableHeaderView = searchController.searchBar
    }
</code>```

Body:
I'm working with UISearchBar for the first time and can't quite make it do what I want.

When you activate the scope buttons, they cover the first row of the table.  The only way to see all of your search results seem to be to hide the scope buttons when editing is finished;  in my Googling on this I have seen that suggested.

I want the functionality that Mail has, where the scope buttons stay up as long as there is text in the search box, and you can see the search results change as you change the active scope button.  But I can't figure out any way to make this happen without having the first row of the table covered by the scope buttons.  You can't just scroll the table view down;  the search bar is in the table view's header, so the whole thing scrolls together.

Suggestions appreciated!

Updated after trying Andrew's suggestion below.

One thing I forgot about is that in viewDidAppear I scroll the table view content up, so that the search box is off the top of the screen but can be scrolled down when needed.  This is obviously part of my problem.  So, in viewDidAppear I have

if (theSearchBar.showsScopeBar != YES) {
    [self.tableView setContentOffset:CGPointMake(0, 44) animated:YES];
}

In searchBarShouldBeginEditing, I now have:

[self.navigationController setNavigationBarHidden:YES];
[self.tableView setContentOffset:CGPointMake(0, -44) animated:YES];
[UIView beginAnimations:@"searchBarUp" context:nil];
[UIView setAnimationDuration:1.0f];
searchBar.frame = CGRectOffset(searchBar.frame, 0, -44);
[UIView commitAnimations];

This gives the correct result, but when the scope bars come up, there is a gap between the top of the view and the top of the search bar, and the first row is covered.  Then the scroll bar (with the scope buttons) slides up into place.  This obviously doesn't look very good.

What I would expect the above code to do is:

hide the nav bar, which would put the top row of the table right below the status bar

scroll the table content back down, which would put the top of the search bar right below the status bar

move the search bar up so that there is a 44 pixel gap between the bottom of the search bar, to be filled in by the scope buttons

This does appear to be what happens, except you can see the gap left by the nav bar until the scroll bar moves up to meet it.  You would think this could be fixed by hiding the nav bar last, but no... when I tried that I ended up with both the first row of the table covered and a nav bar sized hole between the status and search bars.

Another thing I find very odd is that if I use the above code snippet as is, except with animation:NO on the call to setContentOffset, I get a different result.  In this case the first row of the table is not covered, but the search box is above the top of the view and cannot be scrolled down (it won't stay).  Only the scope buttons are visible.  It doesn't make sense to me that just turning off animation would change the outcome.

Now, you might think that with everything in the right place, displaying the search results would just work. But no.  Even though the nav bar is now out of the picture, the search bar still comes up with a large gap above it, and the same adjustments to the table content and the search bar frame are required as above.

I should note that the code in viewWillAppear is only executed once, since we never leave the view, so it's not the case that the table is being readjusted upwards each time.

I would love to understand what's going on, as well as how to fix it, if anyone can help shed some light.

Updated again for clarity - when I say "fix it", what I mean is make it look good without visible gaps when the pieces are moving into place.  I don't even necessarily want it animated;  the sliding into position takes too long.  But as I mentioned above, turning animation off makes things end up in the wrong place again.

Updated one last time - I got it to look much better by removing the animation block around the line to move the search bar.  I guess that introduced a pause before the animation began.  It's good enough now, at least for the moment.  I'm still accepting Andrew's answer since he steered me in the right direction.

Body:
This is what I did, I'm using SearchViewController:

if #available(iOS 11.0, *) {
    navigationItem.searchController = searchController
    }
    else{
        tableView.tableHeaderView = searchController.searchBar
    }


问:
Overriding existing (untagged) table styles using CSS?
So. I'm a CSS amateur, and I'm dealing with an issue a bit above my experience.

Basically: we have a site with a third-party vendor. We cannot modify their stylesheet. I've been told we cannot forward the URL. We cannot unpublish the without deleting it, which is not an option. We cannot upload our own stylesheet. We cannot edit the page HTML beyond a small window. And we need to disable the the site-- specifically, login functions-- so users can't use it, and provide them a link to the new site.

tldr; If this sounds backwards and convoluted, please understand I'm just doing my best to work with a third-party that doesn't really have a lot of flexibility.

So far, I've done this by identifying the styles they have, and writing my own css to disable them (just setting everything to height:0px width:0px overflow:hidden has worked pretty okay) and inputting that into the text/html field they let me edit. Which, honestly, seems kind of like a design flaw that I can break any page as badly as I'm doing, but what do I know...

Problem: they have a login form in a table. No div or class associated with it. With no class/id, I can't style it through css. Styling "table" to height:0px, width:0px just, uh, blanks the whole page.

So, my question: how do I style a table with no class/id in CSS alone with no ability to add a tag to it?

And yes. I know what I'm doing is probably giving everyone reading it an aneurysm. I'm sorry for my CSS crimes.

答:
You can target the said form trough some parent which will work until they either reposition the table outside that parent or fuck with something you used to target the parent.

To be more specific I need a HTML structure of the said page.
But generally let's say you find a parent with a class Parent and this is the only form (otherwise you have to say nth child of type form) inside that parent you can use .Parent>form { your CSS code}

This should expand options for you. Ideally find a parent somewhere that has id and hope its unique for site.

NOTE: Be very afraid when you target things like this, if you can't bind that to either that specific page or specific unique-for-site id parent, you risk somewhere being the one or multiple other match for your CSS selector, and since in most cases (unless you use CSS loader or have separate indexes including separate CSS files) you share same CSS to entire web page it will change them as well.

NOTE: Be even more afraid if you use CSS outside of it's domain - STYLING especcialy for security things, like giving access. This is a serious security violation if you only hide login elements. Anyone with a bit of knowledge can read the code and hide it on client and login. At least don't load then into DOM using display:none; instead visibility: hidden;


问:
entity framework core with mysql unknown column in field list
I have a users table and a products table
and a many-to-many relationship between them in table UsersProducts.

Each user can request to get more products, And I decided I need to save the date when I gave the user the products

```<code>public class UserProduct
{
    public int UserId { get; set; }
    public User User { get; set; }
    public Product Product { get; set; }
    public int ProductId { get; set; }
    public DateTime DateAssigned { get; set; }
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
  modelBuilder.Entity<UserProduct>()
    .HasKey(bc => new { UserId = bc.UserId, ProductId = bc.ProductId });

  modelBuilder.Entity<UserProduct>()
    .HasOne(bc => bc.User)
    .WithMany(b => b.Products)
    .HasForeignKey(bc => bc.UserId);

  modelBuilder.Entity<UserProduct>()
    .HasOne(bc => bc.Product)
    .WithMany(c => c.Owners)
    .HasForeignKey(bc => bc.ProductId);

  base.OnModelCreating(modelBuilder);
}
</code>```

When I try to access (UsersProducts.Where(...)) it I get "unknown column in field list" in regards to DateAssigned column.

This is the code EF generated in the migration

```<code>    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.AddColumn<DateTime>(
            name: "DateAssigned",
            table: "UsersProducts",
            type: "datetime(6)",
            nullable: false,
            defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified));
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropColumn(
            name: "DateAssigned",
            table: "UsersProducts");
    }
</code>```

It seems the column exists in the table, So why is this happening?

答:
Try to add it in mapping

.Property(t => t.DateAssigned).HasColumnName("DateAssigned")

Body:
I have a users table and a products table
and a many-to-many relationship between them in table UsersProducts.

Each user can request to get more products, And I decided I need to save the date when I gave the user the products

public class UserProduct
{
    public int UserId { get; set; }
    public User User { get; set; }
    public Product Product { get; set; }
    public int ProductId { get; set; }
    public DateTime DateAssigned { get; set; }
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
  modelBuilder.Entity<UserProduct>()
    .HasKey(bc => new { UserId = bc.UserId, ProductId = bc.ProductId });

  modelBuilder.Entity<UserProduct>()
    .HasOne(bc => bc.User)
    .WithMany(b => b.Products)
    .HasForeignKey(bc => bc.UserId);

  modelBuilder.Entity<UserProduct>()
    .HasOne(bc => bc.Product)
    .WithMany(c => c.Owners)
    .HasForeignKey(bc => bc.ProductId);

  base.OnModelCreating(modelBuilder);
}

When I try to access (UsersProducts.Where(...)) it I get "unknown column in field list" in regards to DateAssigned column.

This is the code EF generated in the migration

    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.AddColumn<DateTime>(
            name: "DateAssigned",
            table: "UsersProducts",
            type: "datetime(6)",
            nullable: false,
            defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified));
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropColumn(
            name: "DateAssigned",
            table: "UsersProducts");
    }

It seems the column exists in the table, So why is this happening?


问:
Hyperledger Composer 0.15.0 sharing network with the local Playground
I was wondering if since the 0.15.0 release and switching to cards someone has figured out how to access the same network both locally via the CLI and in the Playground and with the same Fabric runtime.
So far, I have been able to install my network's runtime, start and ping it on the Playground's fabric after creating PeerAdmin card  using the script that came with Playground.
However, importing the newly deployed network's admin card fails in the Playground. If, however, I deploy the network via the Playground, export the admin card, download/import the admin card from the Playground and then try to composer ping it, it just sits there timing out after a while.    This is MacOS High Sierra. So what gives and what can be done?
Thanks much!</p>

答:
If I understood your issue correctly, this is how you can solve it:

Create your business network in Playground

Export business network card from Playground (download button on card) which produces {nameOfUser}.card file.

Now you transfer this card to wherever you have installed fabric/playground

Run command: composer card import -f {nameOfUser}.card

Now your business card should appear under location  {usersHome}/.composer/cards/user@network-name

Inside /cards folder, you should see 2 folders. One is "PeerAdmin" which was created if you followed setup and another one is your imported one

Copy connection.json from "PeerAdmin" to your new card and replace it. (this is most important step)

Run command: composer-rest-server and use as network card: user@network-name - folder that you copied

With all this steps I successfully created and ran server. Now you can access it on port IP:3000/explorer


问:
Search and replace rows of a data frame in R
```<code>  search <- function(x,max_hp){
  count <- 1
  result <- matrix(NA, nrow =nrow(x), ncol = ncol(x))
  for(i in 1:nrow(x)){
    temp_row <- x[i,]
    if(temp_row[4] < max_hp){
      result[count,] <- temp_row
      count <- count + 1
    }
  }
  return(result)
}
</code>```

I want to search the rows of mtcars data frame in R that have hp > 240
 using a for loop (iterating over each row of the data frame) and then, return only the ones that match. But, my code doesn't work. I want to store each matched row in an empty matrix.

答:
I have too few points to comment but I have a couple points to share.  First, I agree with @Otto Kässi or @seeellayewhy.  I would just add that if you don't whant any NAs in mtcars$hp to remain in your result, you need to use

```<code>result <- mtcars[which(mtcars$hp > 240),]
</code>```

Regarding substituting rows, I would just follow the above command with

```<code>result <- rbind(result,newrows)
</code>```

R will complain if any attributes of the columns in newrows are different than in result, especially if any of your columns are factor data types with any difference in the levels defined.

Body:
  search <- function(x,max_hp){
  count <- 1
  result <- matrix(NA, nrow =nrow(x), ncol = ncol(x))
  for(i in 1:nrow(x)){
    temp_row <- x[i,]
    if(temp_row[4] < max_hp){
      result[count,] <- temp_row
      count <- count + 1
    }
  }
  return(result)
}

I want to search the rows of mtcars data frame in R that have hp > 240
 using a for loop (iterating over each row of the data frame) and then, return only the ones that match. But, my code doesn't work. I want to store each matched row in an empty matrix.

Body:
I have too few points to comment but I have a couple points to share.  First, I agree with @Otto Kässi or @seeellayewhy.  I would just add that if you don't whant any NAs in mtcars$hp to remain in your result, you need to use

result <- mtcars[which(mtcars$hp > 240),]

Regarding substituting rows, I would just follow the above command with

result <- rbind(result,newrows)

R will complain if any attributes of the columns in newrows are different than in result, especially if any of your columns are factor data types with any difference in the levels defined.


问:
TreeView double-click behaviour in .NET / C#
I have a regular .NET Windows Forms treeview control. The nodes are setup like this:

Group
 --child
 --child
```

If I double-click a collapsed Group node, it expands (as you'd expect) and the NodeMouseDoubleClick event is fired off, where my code does something if the selected node is NOT a group node.

The problem arises when the Group is located near the bottom of the treeview, so that when I double-click the Group node it would require the treeview to expand vertically to fit the child nodes into view. In such cases, if I double-click the Group node, by the time it expands and adjusts the treeview, my mouse cursor is over a child node (it had to push everything up), and that causes the NodeMouseDoubleClick to think the child node is selected, which causes very odd behaviour.

How can I get around this?  Should I not be using NodeMouseDoubleClick or..?

I see it was also explained in the feedback report Problem with TreeView DoubleClick event after expanding/collapsing caused change of scroll.

答: The NodeDoubleClick is fine, but instead of using the e.Node, use this.treeView1.SelectedNode.

OwnerDisplayName: Ivan

ContentLicense: CC BY-SA 4.0

Body:
I have a regular .NET Windows Forms treeview control. The nodes are setup like this:

Group
 --child
 --child

If I double-click a collapsed Group node, it expands (as you'd expect) and the NodeMouseDoubleClick event is fired off, where my code does something if the selected node is NOT a group node.

The problem arises when the Group is located near the bottom of the treeview, so that when I double-click the Group node it would require the treeview to expand vertically to fit the child nodes into view. In such cases, if I double-click the Group node, by the time it expands and adjusts the treeview, my mouse cursor is over a child node (it had to push everything up), and that causes the NodeMouseDoubleClick to think the child node is selected, which causes very odd behaviour.

How can I get around this?  Should I not be using NodeMouseDoubleClick or..?

I see it was also explained in the feedback report Problem with TreeView DoubleClick event after expanding/collapsing caused change of scroll.

LastEditorDisplayName: Sergio

OwnerDisplayName: BFree


问:
Can I bind an onclick event and edit a point in chartjs
I am using chartjs for making a small project. I am getting some confusion and hard luck in editing the points.

Is there any function in this library I can bind an onclick event to which will show me a pop up and I can remove the point?

Here is the summary what I want:

Click on the point and a popup appear

After clicking on the remove button it removed the point and redraw the point.
Right now i am only using simple line chart this is my jsFiddle

I am using chartjs 2.6

答:
You can use the onclick event in the option to show the popup.
Then you can check whether a point was clicked with getElementsAtEvent and if so remove it from the options and update the chart.
I've updated your jsfiddle.</p>

```<code>var option = {
    showLines: true,
    onClick: function(evt) {
      var element = myLineChart.getElementAtEvent(evt);
      if(element.length > 0)
      {
        var ind = element[0]._index;
        if(confirm('Do you want to remove this point?')){
          data.datasets[0].data.splice(ind, 1);
          data.labels.splice(ind, 1);
          myLineChart.update(data);
        }
      }
    }
};
</code>```

Body:
You can use the onclick event in the option to show the popup.
Then you can check whether a point was clicked with getElementsAtEvent and if so remove it from the options and update the chart.
I've updated your jsfiddle.

var option = {
    showLines: true,
    onClick: function(evt) {
      var element = myLineChart.getElementAtEvent(evt);
      if(element.length > 0)
      {
        var ind = element[0]._index;
        if(confirm('Do you want to remove this point?')){
          data.datasets[0].data.splice(ind, 1);
          data.labels.splice(ind, 1);
          myLineChart.update(data);
        }
      }
    }
};


问:
BigQuery add number to row_number()
I'm new to BigQuery and I would like to ask if there is a possible way to set a starting number for row_number() function using the Legacy SQL. I have tried this code:

```<code>SELECT
ROW_NUMBER() OVER(order by col1) + 20 AS xxx
From tb1
</code>```

but it return this error:

Error: Encountered " "+" "+ "" at line 2, column 44. Was expecting:

Any answer will be greatly appreciated

Thanks!

答:
You could try wrapping with ():

```<code>SELECT (ROW_NUMBER() OVER(order by col1)) + 20 AS xxx
From tb1;
</code>```

If not use subquery:

```<code>SELECT s.xxx + 20 AS xxx
FROM ( SELECT ROW_NUMBER() OVER(order by col1) AS xxx
       From tb1) s
</code>```

Title: BigQuery add number to row_number()

Body:
I'm new to BigQuery and I would like to ask if there is a possible way to set a starting number for row_number() function using the Legacy SQL. I have tried this code:

SELECT
ROW_NUMBER() OVER(order by col1) + 20 AS xxx
From tb1

but it return this error:

Error: Encountered " "+" "+ "" at line 2, column 44. Was expecting:

Any answer will be greatly appreciated

Thanks!

Body:
You could try wrapping with ():

SELECT (ROW_NUMBER() OVER(order by col1)) + 20 AS xxx
From tb1;

If not use subquery:

SELECT s.xxx + 20 AS xxx
FROM ( SELECT ROW_NUMBER() OVER(order by col1) AS xxx
       From tb1) s


问:
Difference in methods for converting std string to char*
I know there are a ton questions on how to convert a std::string to a char* and through my research, I have adopted a few different options.  However, the only one that seems to work for me is const_cast from the c_str() method.

So I am using that for now, but would like to know more information as to why the other methods do not work.  What am I missing in my understanding as to why this isn't working as intended which seems to work for many others.

```<code>#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    char* test = "Hello World";
    string testStr(test);

    vector<char> testVec2(testStr.begin(), testStr.end());
    // testVec2[0] = 'F';
    char* test2 = reinterpret_cast<char*>(testVec2.data());

    vector<char> testVec3(testStr.begin(), testStr.end());
    // testVec3[0] = 'G';
    char* test3 = &testVec3[0];

    // The only one that works
    char* test4 = const_cast<char*>(testStr.c_str());

    cout << "char* test: " << test << " [" << strlen(test) << "]" << endl;
    cout << "str test: " << testStr << " [" << testStr.length() << "]" <<     endl;
    cout << "=== conv testing === " << endl;
    cout << "char* test2: " << test2 << " [" << strlen(test2) << "]" <<     endl;
    cout << "char* test3: " << test3 << " [" << strlen(test3) << "]" << endl;
    cout << "char* test4: " << test4 << " [" << strlen(test4) << "]" << endl;

    cin.get();
    return 0;
}
</code>```

I know the pitfalls of using const_cast but it works for my situation at the moment.  I simply take the string from the user, pass it to a C API and do nothing else with it (no worries of it being modified).

Here is a sample of the output
https://imgur.com/a/2S1HD

So what am I doing wrong and is there a better way to do this?

UPDATE
Thanks to everyone for the extremely fast answers.  It seems that my underlying confusion was the assumption of the null terminating character not being in the new buffer that I was assigning to the char* variable.  Hence why my output was showing random characters after the string (that should have been my clue but it has been so long since I've done C/C++)

I also should have tagged this C++17 originally (since fixed) as that is what I am aiming for.  I did not have that enabled in my console app in Visual Studio which made the solution by Passer By below work.  That is the method I will use going forward.

Bottom line, changing my target to C++17 this works as expected

```<code>char* test = "Hello World";
string testStr(test);
vector<char> testVec2(testStr.begin(), testStr.end());
char* test2 = testStr.data();
</code>```

答:
Since c++11 the best way to get a non-const char* from a std::string is to use this:

```<code>std::string s = "hello";

my_non_const_correct_c_function(&s[0]); // better than using const_cast
</code>```

With a const_cast you can run into undefined behavior if you use it on a std::string that was not declared const.

Body:
I know there are a ton questions on how to convert a std::string to a char* and through my research, I have adopted a few different options.  However, the only one that seems to work for me is const_cast from the c_str() method.

So I am using that for now, but would like to know more information as to why the other methods do not work.  What am I missing in my understanding as to why this isn't working as intended which seems to work for many others.

#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    char* test = "Hello World";
    string testStr(test);

    vector<char> testVec2(testStr.begin(), testStr.end());
    // testVec2[0] = 'F';
    char* test2 = reinterpret_cast<char*>(testVec2.data());

    vector<char> testVec3(testStr.begin(), testStr.end());
    // testVec3[0] = 'G';
    char* test3 = &testVec3[0];

    // The only one that works
    char* test4 = const_cast<char*>(testStr.c_str());

    cout << "char* test: " << test << " [" << strlen(test) << "]" << endl;
    cout << "str test: " << testStr << " [" << testStr.length() << "]" <<     endl;
    cout << "=== conv testing === " << endl;
    cout << "char* test2: " << test2 << " [" << strlen(test2) << "]" <<     endl;
    cout << "char* test3: " << test3 << " [" << strlen(test3) << "]" << endl;
    cout << "char* test4: " << test4 << " [" << strlen(test4) << "]" << endl;

    cin.get();
    return 0;
}

I know the pitfalls of using const_cast but it works for my situation at the moment.  I simply take the string from the user, pass it to a C API and do nothing else with it (no worries of it being modified).

Here is a sample of the output
https://imgur.com/a/2S1HD

So what am I doing wrong and is there a better way to do this?

UPDATE
Thanks to everyone for the extremely fast answers.  It seems that my underlying confusion was the assumption of the null terminating character not being in the new buffer that I was assigning to the char* variable.  Hence why my output was showing random characters after the string (that should have been my clue but it has been so long since I've done C/C++)

I also should have tagged this C++17 originally (since fixed) as that is what I am aiming for.  I did not have that enabled in my console app in Visual Studio which made the solution by Passer By below work.  That is the method I will use going forward.

Bottom line, changing my target to C++17 this works as expected

char* test = "Hello World";
string testStr(test);
vector<char> testVec2(testStr.begin(), testStr.end());
char* test2 = testStr.data();

Body:
Since c++11 the best way to get a non-const char* from a std::string is to use this:

std::string s = "hello";

my_non_const_correct_c_function(&s[0]); // better than using const_cast

With a const_cast you can run into undefined behavior if you use it on a std::string that was not declared const.


问:
substring in sh returns "Bad substitution"
In this code:

```<code>#!/bin/sh
a='sdsdsd'
c=${a:0:1}
</code>```

I use second line to read bytes of string one by one (in a loop), but it returns error in sh ("sh: 3: Bad substitution").
any way to do it in sh mode?
for some reasons i should use sh (not bash, and i know bash will be OK)

答:
The substring parameter expansion is not part of the POSIX shell specification. It's a ksh/bash feature. If you need it, you can't use #!/bin/sh

If you need to use sh, you need to call out to expr

```<code>$ dash -c '
    a="ABCDEF"
    i=1
    while [ "$i" -le "${#a}" ]; do
        c=$(expr substr "$a" "$i" 1)
        echo "$i:$c"
        i=$((i + 1))
    done
'
1:A
2:B
3:C
4:D
5:E
6:F
</code>```

Body:
In this code:

#!/bin/sh
a='sdsdsd'
c=${a:0:1}

I use second line to read bytes of string one by one (in a loop), but it returns error in sh ("sh: 3: Bad substitution").
any way to do it in sh mode?
for some reasons i should use sh (not bash, and i know bash will be OK)

Body:
The substring parameter expansion is not part of the POSIX shell specification. It's a ksh/bash feature. If you need it, you can't use #!/bin/sh

If you need to use sh, you need to call out to expr

$ dash -c '
    a="ABCDEF"
    i=1
    while [ "$i" -le "${#a}" ]; do
        c=$(expr substr "$a" "$i" 1)
        echo "$i:$c"
        i=$((i + 1))
    done
'
1:A
2:B
3:C
4:D
5:E
6:F


问:
Return term_id's recursively
I have this code:

```<code>public function get_taxonomy_hierarchy( $taxonomy, $parent = 0 )
{
    $taxonomy = is_array( $taxonomy ) ? array_shift( $taxonomy ) : $taxonomy;
    $terms = get_terms( $taxonomy, [ 'parent' => $parent ] );
    $children = [];
    foreach ( $terms as $term ) {
        $term->url = get_term_link( $term->term_id);
        $term->children = $this->get_taxonomy_hierarchy( $taxonomy, $term->term_id );
        $children[ ] = $term->id;
    }
    return $children;
}
</code>```

My problem is that this function only returns direct descendants id's and ignores others. What am I missing here?

答:
It looks to me like you need to push the term_ids to the children array, rather than just declaring $children[ ] = $term->id;

```<code>public function get_taxonomy_hierarchy( $taxonomy, $parent = 0 )
{
    $taxonomy = is_array( $taxonomy ) ? array_shift( $taxonomy ) : $taxonomy;
    $terms = get_terms( $taxonomy, [ 'parent' => $parent ] );
    $children = [];
    foreach ( $terms as $term ) {
        $term->url = get_term_link( $term->term_id);
        $term->children = $this->get_taxonomy_hierarchy( $taxonomy, $term->term_id );

    array_push($children, $term->term_id);
    }
    return $children;
}
</code>```

Also, shouldn't it be $term->term_id; in line 9 of your code?

Title: Return term_id's recursively

Body:
I have this code:

public function get_taxonomy_hierarchy( $taxonomy, $parent = 0 )
{
    $taxonomy = is_array( $taxonomy ) ? array_shift( $taxonomy ) : $taxonomy;
    $terms = get_terms( $taxonomy, [ 'parent' => $parent ] );
    $children = [];
    foreach ( $terms as $term ) {
        $term->url = get_term_link( $term->term_id);
        $term->children = $this->get_taxonomy_hierarchy( $taxonomy, $term->term_id );
        $children[ ] = $term->id;
    }
    return $children;
}

My problem is that this function only returns direct descendants id's and ignores others. What am I missing here?

Body:
It looks to me like you need to push the term_ids to the children array, rather than just declaring $children[ ] = $term->id;

public function get_taxonomy_hierarchy( $taxonomy, $parent = 0 )
{
    $taxonomy = is_array( $taxonomy ) ? array_shift( $taxonomy ) : $taxonomy;
    $terms = get_terms( $taxonomy, [ 'parent' => $parent ] );
    $children = [];
    foreach ( $terms as $term ) {
        $term->url = get_term_link( $term->term_id);
        $term->children = $this->get_taxonomy_hierarchy( $taxonomy, $term->term_id );

    array_push($children, $term->term_id);
    }
    return $children;
}

Also, shouldn't it be $term->term_id; in line 9 of your code?


问:
Bash: check if one decimal number is greater than another decimal number
I have a case like this:

```<code>string1="some_string"
string2="some_string"
int1="0.87"
int2="${var}"
</code>```

$var is the output of some other script, and it has the form 0.994343123 or 0.3454657 or whatever (starts with 0. and the biggest value is around 0.9972343)

Now, I don't know how bash works, but usually string 0.87 is never less than or equal to 0.9999999, they are just different.

I would need something like this (pseudocode):

```<code>if (string1 equals string2 and int1 is less than int2):
    do something;
else
    do something else.
</code>```

What i would expect is 0.87687 is greater than 0.87 (correct?? i was never good at math...)

Can anyone help me with the code for that if??

Thanks in advance!

答:
Since bash does not handle floating point arithmetic, you may use bc -l to compare 2 floating point numbers and join the condition with && as:

```<code>if [[ $string1 = $string2 && $(bc -l <<< "$int1 < $int2") -eq 1 ]]; then
   echo "yes"
else
   echo "no"
fi
</code>```

Body:
I have a case like this:

string1="some_string"
string2="some_string"
int1="0.87"
int2="${var}"

$var is the output of some other script, and it has the form 0.994343123 or 0.3454657 or whatever (starts with 0. and the biggest value is around 0.9972343)

Now, I don't know how bash works, but usually string 0.87 is never less than or equal to 0.9999999, they are just different.

I would need something like this (pseudocode):

if (string1 equals string2 and int1 is less than int2):
    do something;
else
    do something else.

What i would expect is 0.87687 is greater than 0.87 (correct?? i was never good at math...)

Can anyone help me with the code for that if??

Thanks in advance!

Body:
Since bash does not handle floating point arithmetic, you may use bc -l to compare 2 floating point numbers and join the condition with && as:

if [[ $string1 = $string2 && $(bc -l <<< "$int1 < $int2") -eq 1 ]]; then
   echo "yes"
else
   echo "no"
fi


问:
newbie question memory and code optimisation
this is what i write

```<code>domaine *detailsDomaine = [search_result objectAtIndex:indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:@"%@",[detailsDomaine valueForKey:@"nom"]];
</code>```

Is it possible to not assign a variable (detailsDomaine)to reach the same result ?
Do i have to release detailsDomaine variable after that ?

I'm not using it anywhere else in the rest of the code...

答:
It is possible not to create separate variable for this. Replace detailsDomaine in second row with your right side of assignment in first row:

```<code>cell.textLabel.text = [NSString stringWithFormat:@"%@",[[search_result objectAtIndex:indexPath.row] valueForKey:@"nom"]];
</code>```

And no, you don't have to release the detailsDomaine object afterwards since you did not retain it.

Body:
this is what i write

domaine *detailsDomaine = [search_result objectAtIndex:indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:@"%@",[detailsDomaine valueForKey:@"nom"]];

Is it possible to not assign a variable (detailsDomaine)to reach the same result ?
Do i have to release detailsDomaine variable after that ?

I'm not using it anywhere else in the rest of the code...

Body:
It is possible not to create separate variable for this. Replace detailsDomaine in second row with your right side of assignment in first row:

cell.textLabel.text = [NSString stringWithFormat:@"%@",[[search_result objectAtIndex:indexPath.row] valueForKey:@"nom"]];

And no, you don't have to release the detailsDomaine object afterwards since you did not retain it.


问:
checkout.fi payment gateway implement (convert php code to asp.net with C#)
I am implementing checkout.fi payment gateway. I got the source code in php and java.I don't have any idea about php. That's why I want to convert Php source code to Asp.net code. Any Help Please
Below link given the sample code of PHP
https://checkoutfinland.github.io/#testing
and other sample java code link on github
https://github.com/AgiSol/checkout-java/

i have made code in asp.net but it is not working. For reference i have taking a Test Data. Below my code. This code run on button click event.

Code here

```<code>```
 protected void Button2_Click(object sender, EventArgs e){
    string ver = "0001";
    string stamp = DateTime.Now.ToString("yyyyMMddHHmmssfff");
    string amount = "1000";
    string refer = "2432324";
    string message = "hi";
    string language = "FI";
    string returnurl = "domain.com/return.aspx";
    string cancelurl = "domain.com/cancel.aspx";
    string reject = "2";
    string delaye = "";
    string country = "FIN";
    string currency = "EUR";
    string device = "10"; // 10 = XML
    string content = "1";
    string type = "0";
    string algorithms = "3";
    string delivery_date = "20171207";
    string firstname = "Tarun";
    string family = "Parmar";
    string address = "Ääkköstie 5b3\nKulmaravintolan yläkerta";
    string postcode = "33100";
    string postoffice = "Tampere";
    string MERCHANT="375917";
    string  SECRET_KEY= "SAIPPUAKAUPPIAS";
    string macnew =  encryptionMD5(ver,  stamp, amount, refer, message, language,MERCHANT ,returnurl, cancelurl, reject,delaye, country,currency, device, content, type,algorithms, delivery_date, firstname,family, address, postcode,postoffice, SECRET_KEY).ToUpper();

   string email = "support@checkout.fi";
   string phone = "0800552010";
   string status = "1";
   string generatedMac = GetHashSha256(ver,stamp, refer, amount, status, algorithms, SECRET_KEY);

    NameValueCollection collections = new NameValueCollection();
    collections.Add("VERSION", ver);
    collections.Add("STAMP", DateTime.Now.ToString("yyyyMMddHHmmssfff"));
    collections.Add("AMOUNT",  amount);
    collections.Add("REFERENCE", refer);
    collections.Add("MESSAGE", message);
    collections.Add("LANGUAGE", language);
    collections.Add("RETURN", "domain.com/return.aspx");
    collections.Add("CANCEL", "domain.com/cancel.aspx");
    collections.Add("REJECT",  reject);
    collections.Add("DELAYED", delaye);
    collections.Add("COUNTRY",  country);
    collections.Add("CURRENCY", currency);
    collections.Add("DEVICE",  device);
    collections.Add("CONTENT", content);
    collections.Add("TYPE", type);
    collections.Add("ALGORITHM", algorithms);
    collections.Add("DELIVERY_DATE", delivery_date);
    collections.Add("FIRSTNAME", firstname);
    collections.Add("FAMILYNAME", family);
    collections.Add("ADDRESS",address);
    collections.Add("POSTCODE",  postcode);
    collections.Add("POSTOFFIC", postoffice);
    collections.Add("MAC", macnew);
    collections.Add("EMAIL", email);
    collections.Add("PHONE",  phone);
    collections.Add("MERCHANT",MERCHANT);
    collections.Add("SECRET_KEY", SECRET_KEY);

    string remoteUrl = "https://payment.checkout.fi";
    string html = "";
    html += "";
    html += string.Format("<form name='PostForm' method='POST' action='{0}'>", remoteUrl);
    foreach (string key in collections.Keys)
    {
        html += string.Format("<input name='{0}' type='text' value='{1}'>", key, collections[key]);
    }
    html += "</form>";
    Response.Clear();
    Response.ContentEncoding = Encoding.GetEncoding("ISO-8859-1");
    Response.HeaderEncoding = Encoding.GetEncoding("ISO-8859-1");
    Response.Charset = "ISO-8859-1";
    Response.Write(html);
    Response.End();
}
```

<p></p>

<p>Function For encryptionMD5
        ```
 public string encryptionMD5(String VERSION, String STAMP, String AMOUNT, String REFERENCEs, String MESSAGE, String LANGUAGE, String merchantId, String RETURN, String CANCEL, String REJECT, String DELAYED, String COUNTRY, String CURRENCY, String DEVICE, String CONTENT, String TYPE, String ALGORITHM, String DELIVERY_DATE, String FIRSTNAME, String FAMILYNAME, String ADDRESS, String POSTCODE, String POSTOFFICE, String PasswordID)
    {

        string  passwords = VERSION + STAMP + AMOUNT + REFERENCEs + MESSAGE + LANGUAGE + merchantId + RETURN + CANCEL + REJECT + DELAYED + COUNTRY + CURRENCY + DEVICE + CONTENT + TYPE + ALGORITHM + DELIVERY_DATE + FIRSTNAME + FAMILYNAME + ADDRESS + POSTCODE + POSTOFFICE + PasswordID;
        MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
        byte[] encrypt;
        UTF8Encoding encode = new UTF8Encoding();
        encrypt = md5.ComputeHash(encode.GetBytes(passwords));

```<code>       StringBuilder encryptdata = new StringBuilder();
        for (int i= 0; i<encrypt.Length; i++)   {
               encryptdata.Append(encrypt[i].ToString());
          }
         return encryptdata.ToString();
  }
</code>```

```</p>

<p>Function For GetHashSha256</p>

``````<code>

public string GetHashSha256(string  VERSION,string STAMP, string REFERENCE,string PAYMENT, string STATUS, string ALGORITHM, string password)

    {
        string text = VERSION + STAMP + REFERENCE + PAYMENT + STATUS + ALGORITHM + password;
        byte[] bytes = Encoding.ASCII.GetBytes(text);
        SHA256Managed hashstring = new SHA256Managed();
        byte[] hash = hashstring.ComputeHash(bytes);
        string hashString = string.Empty;
        foreach (byte x in hash)
        {
            hashString += String.Format("{0:x2}", x);
        }
        return hashString;
    }
</code>```

This above code give below error

Creating a Payment Transaction failed (-24).
Error in field: MAC

Thanks in Advance if anybody help in solving this problem.

答:
Well, the Finland checkout payment gateway means that your MAC is not hashed correctly. I downloaded the java version from their github and it works perfectly. You are not generating the correct MD5 hash.

Quite a few problems in your code. First of all you must append + sign with each of the strings because they do same in Java. Second, you are assigning algorithms = "3". You should use algorithms = "2" for MD5. Third your encryptionMD5 doesn't returns correct hash.

Below is the correct implementation that I have done for you:

```<code>    string ver = "0001";
    string stamp = "kpjkq1510841290161";
    string amount = "1490";
    string refer = "12345";
    string message = "My custom message";
    string language = "FI";
    string returnurl = "http://localhost/success";
    string cancelurl = "http://localhost/cancel";
    string reject = "http://localhost/rejected";
    string delaye = "http://localhost/delayed";
    string country = "FIN";
    string currency = "EUR";
    string device = "10"; // 10 = XML
    string content = "1";
    string type = "0";
    string algorithms = "2";
    string delivery_date = "20171123";
    string firstname = "Tero";
    string family = "Testaaja";
    string address = "Mystreet 1";
    string postcode = "12345";
    string postoffice = "Tampere";
    string MERCHANT = "375917";
    string SECRET_KEY = "SAIPPUAKAUPPIAS";

using (MD5 md5Hash = MD5.Create())
            {
                string fromValue = String.Join("+", new string[] { ver, stamp, amount, refer, message, language, MERCHANT, returnurl, cancelurl, reject, delaye, country, currency, device, content, type, algorithms, delivery_date, firstname, family, address, postcode, postoffice, SECRET_KEY });
                string macnew = GetMd5Hash(md5Hash, fromValue);
            }

public string GetMd5Hash(MD5 md5Hash, string input)
        {
            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();
            // Loop through each byte of the hashed data
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            // Return the hexadecimal string.
            return sBuilder.ToString();
        }
</code>```

Output is c84e068fcab5c4dad93a29dd4c567b7f

Verified from finland checkout java github project.

And one tip is that you should use StringBuilder for appending text instead of concatenating with + sign for improved performance.

Body:
I am implementing checkout.fi payment gateway. I got the source code in php and java.I don't have any idea about php. That's why I want to convert Php source code to Asp.net code. Any Help Please
Below link given the sample code of PHP
https://checkoutfinland.github.io/#testing
and other sample java code link on github
https://github.com/AgiSol/checkout-java/

i have made code in asp.net but it is not working. For reference i have taking a Test Data. Below my code. This code run on button click event.

Code here

 protected void Button2_Click(object sender, EventArgs e){
    string ver = "0001";
    string stamp = DateTime.Now.ToString("yyyyMMddHHmmssfff");
    string amount = "1000";
    string refer = "2432324";
    string message = "hi";
    string language = "FI";
    string returnurl = "domain.com/return.aspx";
    string cancelurl = "domain.com/cancel.aspx";
    string reject = "2";
    string delaye = "";
    string country = "FIN";
    string currency = "EUR";
    string device = "10"; // 10 = XML
    string content = "1";
    string type = "0";
    string algorithms = "3";
    string delivery_date = "20171207";
    string firstname = "Tarun";
    string family = "Parmar";
    string address = "Ääkköstie 5b3\nKulmaravintolan yläkerta";
    string postcode = "33100";
    string postoffice = "Tampere";
    string MERCHANT="375917";
    string  SECRET_KEY= "SAIPPUAKAUPPIAS";
    string macnew =  encryptionMD5(ver,  stamp, amount, refer, message, language,MERCHANT ,returnurl, cancelurl, reject,delaye, country,currency, device, content, type,algorithms, delivery_date, firstname,family, address, postcode,postoffice, SECRET_KEY).ToUpper();

   string email = "support@checkout.fi";
   string phone = "0800552010";
   string status = "1";
   string generatedMac = GetHashSha256(ver,stamp, refer, amount, status, algorithms, SECRET_KEY);

    NameValueCollection collections = new NameValueCollection();
    collections.Add("VERSION", ver);
    collections.Add("STAMP", DateTime.Now.ToString("yyyyMMddHHmmssfff"));
    collections.Add("AMOUNT",  amount);
    collections.Add("REFERENCE", refer);
    collections.Add("MESSAGE", message);
    collections.Add("LANGUAGE", language);
    collections.Add("RETURN", "domain.com/return.aspx");
    collections.Add("CANCEL", "domain.com/cancel.aspx");
    collections.Add("REJECT",  reject);
    collections.Add("DELAYED", delaye);
    collections.Add("COUNTRY",  country);
    collections.Add("CURRENCY", currency);
    collections.Add("DEVICE",  device);
    collections.Add("CONTENT", content);
    collections.Add("TYPE", type);
    collections.Add("ALGORITHM", algorithms);
    collections.Add("DELIVERY_DATE", delivery_date);
    collections.Add("FIRSTNAME", firstname);
    collections.Add("FAMILYNAME", family);
    collections.Add("ADDRESS",address);
    collections.Add("POSTCODE",  postcode);
    collections.Add("POSTOFFIC", postoffice);
    collections.Add("MAC", macnew);
    collections.Add("EMAIL", email);
    collections.Add("PHONE",  phone);
    collections.Add("MERCHANT",MERCHANT);
    collections.Add("SECRET_KEY", SECRET_KEY);

    string remoteUrl = "https://payment.checkout.fi";
    string html = "";
    html += "";
    html += string.Format("<form name='PostForm' method='POST' action='{0}'>", remoteUrl);
    foreach (string key in collections.Keys)
    {
        html += string.Format("<input name='{0}' type='text' value='{1}'>", key, collections[key]);
    }
    html += "</form>";
    Response.Clear();
    Response.ContentEncoding = Encoding.GetEncoding("ISO-8859-1");
    Response.HeaderEncoding = Encoding.GetEncoding("ISO-8859-1");
    Response.Charset = "ISO-8859-1";
    Response.Write(html);
    Response.End();
}

Function For encryptionMD5

 public string encryptionMD5(String VERSION, String STAMP, String AMOUNT, String REFERENCEs, String MESSAGE, String LANGUAGE, String merchantId, String RETURN, String CANCEL, String REJECT, String DELAYED, String COUNTRY, String CURRENCY, String DEVICE, String CONTENT, String TYPE, String ALGORITHM, String DELIVERY_DATE, String FIRSTNAME, String FAMILYNAME, String ADDRESS, String POSTCODE, String POSTOFFICE, String PasswordID)
    {

        string  passwords = VERSION + STAMP + AMOUNT + REFERENCEs + MESSAGE + LANGUAGE + merchantId + RETURN + CANCEL + REJECT + DELAYED + COUNTRY + CURRENCY + DEVICE + CONTENT + TYPE + ALGORITHM + DELIVERY_DATE + FIRSTNAME + FAMILYNAME + ADDRESS + POSTCODE + POSTOFFICE + PasswordID;
        MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
        byte[] encrypt;
        UTF8Encoding encode = new UTF8Encoding();
        encrypt = md5.ComputeHash(encode.GetBytes(passwords));

       StringBuilder encryptdata = new StringBuilder();
        for (int i= 0; i<encrypt.Length; i++)   {
               encryptdata.Append(encrypt[i].ToString());
          }
         return encryptdata.ToString();
  }

Function For GetHashSha256

public string GetHashSha256(string  VERSION,string STAMP, string REFERENCE,string PAYMENT, string STATUS, string ALGORITHM, string password)

    {
        string text = VERSION + STAMP + REFERENCE + PAYMENT + STATUS + ALGORITHM + password;
        byte[] bytes = Encoding.ASCII.GetBytes(text);
        SHA256Managed hashstring = new SHA256Managed();
        byte[] hash = hashstring.ComputeHash(bytes);
        string hashString = string.Empty;
        foreach (byte x in hash)
        {
            hashString += String.Format("{0:x2}", x);
        }
        return hashString;
    }

This above code give below error

Creating a Payment Transaction failed (-24).
Error in field: MAC

Thanks in Advance if anybody help in solving this problem.

Body:
Well, the Finland checkout payment gateway means that your MAC is not hashed correctly. I downloaded the java version from their github and it works perfectly. You are not generating the correct MD5 hash.

Quite a few problems in your code. First of all you must append + sign with each of the strings because they do same in Java. Second, you are assigning algorithms = "3". You should use algorithms = "2" for MD5. Third your encryptionMD5 doesn't returns correct hash.

Below is the correct implementation that I have done for you:

    string ver = "0001";
    string stamp = "kpjkq1510841290161";
    string amount = "1490";
    string refer = "12345";
    string message = "My custom message";
    string language = "FI";
    string returnurl = "http://localhost/success";
    string cancelurl = "http://localhost/cancel";
    string reject = "http://localhost/rejected";
    string delaye = "http://localhost/delayed";
    string country = "FIN";
    string currency = "EUR";
    string device = "10"; // 10 = XML
    string content = "1";
    string type = "0";
    string algorithms = "2";
    string delivery_date = "20171123";
    string firstname = "Tero";
    string family = "Testaaja";
    string address = "Mystreet 1";
    string postcode = "12345";
    string postoffice = "Tampere";
    string MERCHANT = "375917";
    string SECRET_KEY = "SAIPPUAKAUPPIAS";

using (MD5 md5Hash = MD5.Create())
            {
                string fromValue = String.Join("+", new string[] { ver, stamp, amount, refer, message, language, MERCHANT, returnurl, cancelurl, reject, delaye, country, currency, device, content, type, algorithms, delivery_date, firstname, family, address, postcode, postoffice, SECRET_KEY });
                string macnew = GetMd5Hash(md5Hash, fromValue);
            }

public string GetMd5Hash(MD5 md5Hash, string input)
        {
            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();
            // Loop through each byte of the hashed data
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            // Return the hexadecimal string.
            return sBuilder.ToString();
        }

Output is c84e068fcab5c4dad93a29dd4c567b7f

Verified from finland checkout java github project.

And one tip is that you should use StringBuilder for appending text instead of concatenating with + sign for improved performance.


问:
Google EMM - The caller is not registered as an MDM issue
I created MSA account and Oauth2 client ID and client secret. By using that client ID I am trying to use generateSignupUrl API
. But this API is giving me following error.

```<code>{
 "error": {
  "errors": [
   {
    "domain": "androidenterprise",
    "reason": "forbiddenNotAnMdm",
    "message": "The caller is not registered as an MDM."
   }
  ],
  "code": 403,
  "message": "The caller is not registered as an MDM."
 }
}
</code>```

Note: I created Oauth2 credentials for the same account that is registered as MSA and also using the same account to use mentioned API.

答:
To use the Google Play EMM API you need to register in the EMM Community, you currently see this error because you are not registered. Note that to use the Google Play EMM API you will also need to implement a custom DPC app.

It you want to manage Android devices without registering in the EMM Community and without implementing a custom DPC app, you can use the new Android Management API.

Body:
I created MSA account and Oauth2 client ID and client secret. By using that client ID I am trying to use generateSignupUrl API
. But this API is giving me following error.

{
 "error": {
  "errors": [
   {
    "domain": "androidenterprise",
    "reason": "forbiddenNotAnMdm",
    "message": "The caller is not registered as an MDM."
   }
  ],
  "code": 403,
  "message": "The caller is not registered as an MDM."
 }
}

Note: I created Oauth2 credentials for the same account that is registered as MSA and also using the same account to use mentioned API.


问:
Error from server (Forbidden): error when creating .. : clusterroles.rbac.authorization.k8s.io ...: attempt to grant extra privileges:
Failed to create clusterroles. <> already assigned as the roles of "container engine admin" & "container engine cluster admin"</p>

```<code>Error from server (Forbidden): error when creating "prometheus-
operator/prometheus-operator-cluster-role.yaml":
clusterroles.rbac.authorization.k8s.io "prometheus-operator"
is forbidden: attempt to grant extra privileges: [{[create]
[extensions] [thirdpartyresources] [] []} {[*]
[monitoring.coreos.com] [alertmanagers] [] []} {[*]
[monitoring.coreos.com] [prometheuses] [] []} {[*]
[monitoring.coreos.com] [servicemonitors] [] []} {[*]
[apps] [statefulsets] [] []} {[*] [] [configmaps] [] []}
{[*] [] [secrets] [] []} {[list] [] [pods] [] []} {[delete]
[] [pods] [] []} {[get] [] [services] [] []} {[create]
[] [services] [] []} {[update] [] [services] [] []} {[get]
[] [endpoints] [] []} {[create] [] [endpoints] [] []}
{[update] [] [endpoints] [] []} {[list] [] [nodes]
[] []} {[watch] [] [nodes] [] []}]
user=&{<<my_account>>@gmail.com
[system:authenticated] map[]} ownerrules=[{[create]
[authorization.k8s.io] [selfsubjectaccessreviews]
[] []} {[get] [] [] [] [/api /api/* /apis /apis/*
/healthz /swaggerapi /swaggerapi/* /version]}]
ruleResolutionErrors=[]
</code>```

答:
I've got the same problem on Google Kubernetes Engine.

According to the answer of enj and the comment of ccyang2005 please find the following snipet who solve my problem :)

Step 1 : Get your identity

```<code>gcloud info | grep Account
</code>```

Will output you something like Account: [myname@example.org]

Step 2 : grant cluster-admin to your current identity

```<code>kubectl create clusterrolebinding myname-cluster-admin-binding \
  --clusterrole=cluster-admin \
  --user=myname@example.org
</code>```

Will output somthing like Clusterrolebinding "myname-cluster-admin-binding" created

After that, you'll be able to create CusterRoles

Body:
Failed to create clusterroles. <> already assigned as the roles of "container engine admin" & "container engine cluster admin"

Error from server (Forbidden): error when creating "prometheus-
operator/prometheus-operator-cluster-role.yaml":
clusterroles.rbac.authorization.k8s.io "prometheus-operator"
is forbidden: attempt to grant extra privileges: [{[create]
[extensions] [thirdpartyresources] [] []} {[*]
[monitoring.coreos.com] [alertmanagers] [] []} {[*]
[monitoring.coreos.com] [prometheuses] [] []} {[*]
[monitoring.coreos.com] [servicemonitors] [] []} {[*]
[apps] [statefulsets] [] []} {[*] [] [configmaps] [] []}
{[*] [] [secrets] [] []} {[list] [] [pods] [] []} {[delete]
[] [pods] [] []} {[get] [] [services] [] []} {[create]
[] [services] [] []} {[update] [] [services] [] []} {[get]
[] [endpoints] [] []} {[create] [] [endpoints] [] []}
{[update] [] [endpoints] [] []} {[list] [] [nodes]
[] []} {[watch] [] [nodes] [] []}]
user=&{<<my_account>>@gmail.com
[system:authenticated] map[]} ownerrules=[{[create]
[authorization.k8s.io] [selfsubjectaccessreviews]
[] []} {[get] [] [] [] [/api /api/* /apis /apis/*
/healthz /swaggerapi /swaggerapi/* /version]}]
ruleResolutionErrors=[]

Body:
I've got the same problem on Google Kubernetes Engine.

According to the answer of enj and the comment of ccyang2005 please find the following snipet who solve my problem :)

Step 1 : Get your identity

gcloud info | grep Account

Will output you something like Account: [myname@example.org]

Step 2 : grant cluster-admin to your current identity

kubectl create clusterrolebinding myname-cluster-admin-binding \
  --clusterrole=cluster-admin \
  --user=myname@example.org

Will output somthing like Clusterrolebinding "myname-cluster-admin-binding" created

After that, you'll be able to create CusterRoles


问:
Java - moving first letter of string to the end, and determining if word is the same when spelled backwards
I'm trying to make a program that when a user inputs a string using scanner, the first letter gets moved to the end of the word, and then the word is spelled backwards. The program then determines if you get the original word.

e.g if user types in 'potato' the program will move 'p' to the end, and will display true, as we get the same word backwards - 'otatop'.

Example output:
You have entered "BANANA".
Is ANANAB same as BANANA? True.

Thank you in advance for any help.

Jack

This is what I've got so far, but I don't think it works properly.

```<code>public class WordPlay {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        String word;
        String palindrome = "";
        String quit = "quit";

        do {
            System.out.print("Enter a word: ");
            word = scanner.nextLine().toUpperCase();

            int length = word.length();

            for (int i = length - 1; i >= 0; i--) {
                palindrome = palindrome + word.charAt(i);
            }

            if (word.equals(palindrome)) {
                System.out.println("Is the word + palindrome + " same as " + word + "?", true);
            } else {
                System.out.println(false);
            }
        } while (!word.equals(quit));
        System.out.println("Good Bye");
        scanner.close();

    }

}
</code>```

答:
Here it is.</p>

```<code>public static void main(String[] args) {

    // To take input.
    Scanner scan = new Scanner(System.in);

    System.out.print("Enter Word: ");
    String word = scan.next(); // taking the word from user

    // moving first letter to the end.
    String newWord = word.substring(1) + word.charAt(0);

    // reversing the newWord.
    String reversed = new StringBuffer(newWord).reverse().toString();

    // printing output.
    System.out.println("You have entered '"+word+"'. "
            + "Is "+newWord+" same as "+word+"? "
            +reversed.equals(word)+".");

    // closing the input stream.
    scan.close();

}
</code>```

Body:
I'm trying to make a program that when a user inputs a string using scanner, the first letter gets moved to the end of the word, and then the word is spelled backwards. The program then determines if you get the original word.

e.g if user types in 'potato' the program will move 'p' to the end, and will display true, as we get the same word backwards - 'otatop'.

Example output:
You have entered "BANANA".
Is ANANAB same as BANANA? True.

Thank you in advance for any help.

Jack

This is what I've got so far, but I don't think it works properly.

public class WordPlay {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        String word;
        String palindrome = "";
        String quit = "quit";

        do {
            System.out.print("Enter a word: ");
            word = scanner.nextLine().toUpperCase();

            int length = word.length();

            for (int i = length - 1; i >= 0; i--) {
                palindrome = palindrome + word.charAt(i);
            }

            if (word.equals(palindrome)) {
                System.out.println("Is the word + palindrome + " same as " + word + "?", true);
            } else {
                System.out.println(false);
            }
        } while (!word.equals(quit));
        System.out.println("Good Bye");
        scanner.close();

    }

}

Body:
Here it is.

public static void main(String[] args) {

    // To take input.
    Scanner scan = new Scanner(System.in);

    System.out.print("Enter Word: ");
    String word = scan.next(); // taking the word from user

    // moving first letter to the end.
    String newWord = word.substring(1) + word.charAt(0);

    // reversing the newWord.
    String reversed = new StringBuffer(newWord).reverse().toString();

    // printing output.
    System.out.println("You have entered '"+word+"'. "
            + "Is "+newWord+" same as "+word+"? "
            +reversed.equals(word)+".");

    // closing the input stream.
    scan.close();

}


答:
No, you don't need to release detailsDomaine because you did not allocate any memory for it or retain it. You could do something like this:

```<code>cell.textLabel.text = [NSString stringWithFormat:@"%@", [[search_result objectAtIndex:indexPath.row] valueForKey:@"nom"]];
</code>```

but it's rather ugly.

Title: newbie question memory and code optimisation

Body:
No, you don't need to release detailsDomaine because you did not allocate any memory for it or retain it. You could do something like this:

cell.textLabel.text = [NSString stringWithFormat:@"%@", [[search_result objectAtIndex:indexPath.row] valueForKey:@"nom"]];

but it's rather ugly.


问:
Xcode 9 - Failed to create IXPlaceholder for app bundle ID
Upon updating to Xcode 9 and in the "launching" phase of compilation on the simulator I get the error:

Failed to create IXPlaceholder for app bundle ID

Emphasis placed on this issue only occurs trying to launch the simulator, as working with my actual iPhone 6s launches without any issues .

Attempts:

Ensured info.plist "Bundle Identifier" is correct. it is "$(PRODUCT_BUNDLE_IDENTIFIER)"

Checked to see if typing the bundle identifier manually would work, but it did not.

Project Cleaned

Deleted Derived Data

Xcode relaunched

Computer Restarted

Xcode betas uninstalled

Xcode Uninstalled and Reinstalled

Provisioning Profile Expires in 11 months

Automatically Manage Signing is unchecked then checked again

Paid Developer for 2 years now and have never had this issue before. Searched online for a solution with no luck and notice only a couple others have had this issue with no clear resolution.

What direction should I take to get this issue resolved. I don't see anything wrong with the provisioning files / certificates, but I could be wrong if someone could guide me in the right direction.

Thank you

答:
I had same problem, this solve it

In you Info.plist:

Bundle_display_name : Dictionary

set to String value not dictionary

Bundle_display_name : String

i hope this help you


问:
Dynamic center div bootstrap
I'm trying to create a responsive div list

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

```

As you can see, from above i have four divs and when i only have 3 divs, they will in left

Is it possible do it dynamically when there is only 3 div  and they will be centered ?

If yes, how can i do that. Thanks in advance and sorry for my bad english

答:
If you can upgrade to Boostrap 4 you can do it like this:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>

column 1

column 2

column 3

column 4

```

so how many .col that you add you will always get them centered.

Bootstrap 4 uses Flexbox.

Title: Dynamic center div bootstrap

Body:
I'm trying to create a responsive div list

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

As you can see, from above i have four divs and when i only have 3 divs, they will in left

Is it possible do it dynamically when there is only 3 div  and they will be centered ?

If yes, how can i do that. Thanks in advance and sorry for my bad english

Body:
If you can upgrade to Boostrap 4 you can do it like this:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>
<style type="text/css">.col {background: #555; border: 2px solid #fff; color: #fff;}</style>

<div class="container">
    <div class="row">
        <div class="col">column 1</div>
        <div class="col">column 2</div>
        <div class="col">column 3</div>
        <div class="col">column 4</div>
    </div>
</div>

so how many .col that you add you will always get them centered.

Bootstrap 4 uses Flexbox.


问:
Cassandra: customer data per keyspace
Problem: one of our new customers want the data to be stored in his own country (law regulations). However we use existing customer's data spread across few datacenters in different countries.

Question: how we can separate new customer's data to reside in its own country without much changing existing Cassandra architecture?

Potential Solution #1: to use separate keyspace for this customer. Schemas will be the same between keyspaces what adds the complexity for data migration and so on. DataStax support confirmed that it is possible to configure keyspace per region.
However Spring Data Cassandra we use, doesn't allow to choose keyspace dynamically.
The only way is to use CqlTemplate and to run use keyspace blabla everytime before the call or to add keyspace before the table select * from blabla.mytable but it sounds as a hack for me.

Potential Solution #2 to use separate environment for new client but management rejects to do it.

Any other ways to achieve this goal?

答:
After many back and forth, we have decided to not do the dynamic keyspace resolution within the same JVM.

It was taken the decision to have dedicated Jetty/Tomcat per keyspace and on nginx router level to define to what server the request should be redirected to (based on companyId from the request url).

For example, all our endpoints have /companyId/<value> so based on the value, we can redirect the request to proper server which uses correct keyspace.

Title: Cassandra: customer data per keyspace


问:
How to make a GET operation where you send an API key and code in header?
I would like to be able to get values from a server by using their API, to be able to do that I have to send an API-key and an API-Code in the header, I have tried with Retrofit to be able to use annotations but with no luck, so if anyone can look through the code and point me in the right direction, I would appreciate it!

Below I will add some code examples:

APIService

```<code>public interface APIService {

@GET("/temperature")
@Headers({"api-key: "my api key", "code: "my-api-code"})
Call<Post> getTemperature();
</code>```

ApiUtils

```<code>public class ApiUtils {

private ApiUtils() {}

public static final String BASE_URL = "my url";

public static APIService getAPIService() {

    return RetrofitClient.getClient(BASE_URL).create(APIService.class);
}
</code>```

Retrofit Client

```<code>public class RetrofitClient {

private static Retrofit retrofit = null;

public static Retrofit getClient(String baseUrl) {
    if (retrofit==null) {
        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
}
</code>```

Main Activity

```<code>public class MainActivity extends AppCompatActivity {

private static final String TAG = MainActivity.class.getSimpleName();
private TextView mResponseTv;

private APIService mAPIService;

@NonNull
private CompositeDisposable mDisposables;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final EditText titleEt = (EditText) findViewById(R.id.et_title);
    final EditText bodyEt = (EditText) findViewById(R.id.et_body);
    Button submitBtn = (Button) findViewById(R.id.btn_submit);
    mResponseTv = (TextView) findViewById(R.id.tv_response);

    mAPIService = ApiUtils.getAPIService();

    mDisposables = new CompositeDisposable();

    submitBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String title = titleEt.getText().toString().trim();
            String body = bodyEt.getText().toString().trim();
            if(!TextUtils.isEmpty(title) && !TextUtils.isEmpty(body)) {
                sendPost(title, body);
            }
        }
    });
}

public void showErrorMessage() {
    Toast.makeText(this, R.string.mssg_error_submitting_post, Toast.LENGTH_SHORT).show();
}

public void getTemperature() {
    mAPIService.getTemperature().enqueue(new Callback<Post>() {
        @Override
        public void onResponse(Call<Post> call, Response<Post> response) {
            if (response.isSuccessful()) {
                showResponse(response.body().toString());
            }
        }

        @Override
        public void onFailure(Call<Post> call, Throwable t) {
            showErrorMessage();
        }
    });
}
</code>```

答:
If you use Retrofit 2 you can try this

```<code>public interface APIService {

@GET("/temperature")
Call<Post> getTemperature(@Header("api-key") String my_api_key, @Header("code") String my-api-code);
</code>```

And pass codes in your call

Body:
I would like to be able to get values from a server by using their API, to be able to do that I have to send an API-key and an API-Code in the header, I have tried with Retrofit to be able to use annotations but with no luck, so if anyone can look through the code and point me in the right direction, I would appreciate it!

Below I will add some code examples:

APIService

public interface APIService {

@GET("/temperature")
@Headers({"api-key: "my api key", "code: "my-api-code"})
Call<Post> getTemperature();

ApiUtils

public class ApiUtils {

private ApiUtils() {}

public static final String BASE_URL = "my url";

public static APIService getAPIService() {

    return RetrofitClient.getClient(BASE_URL).create(APIService.class);
}

Retrofit Client

public class RetrofitClient {

private static Retrofit retrofit = null;

public static Retrofit getClient(String baseUrl) {
    if (retrofit==null) {
        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
}

Main Activity

public class MainActivity extends AppCompatActivity {

private static final String TAG = MainActivity.class.getSimpleName();
private TextView mResponseTv;

private APIService mAPIService;

@NonNull
private CompositeDisposable mDisposables;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final EditText titleEt = (EditText) findViewById(R.id.et_title);
    final EditText bodyEt = (EditText) findViewById(R.id.et_body);
    Button submitBtn = (Button) findViewById(R.id.btn_submit);
    mResponseTv = (TextView) findViewById(R.id.tv_response);

    mAPIService = ApiUtils.getAPIService();

    mDisposables = new CompositeDisposable();

    submitBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String title = titleEt.getText().toString().trim();
            String body = bodyEt.getText().toString().trim();
            if(!TextUtils.isEmpty(title) && !TextUtils.isEmpty(body)) {
                sendPost(title, body);
            }
        }
    });
}

public void showErrorMessage() {
    Toast.makeText(this, R.string.mssg_error_submitting_post, Toast.LENGTH_SHORT).show();
}

public void getTemperature() {
    mAPIService.getTemperature().enqueue(new Callback<Post>() {
        @Override
        public void onResponse(Call<Post> call, Response<Post> response) {
            if (response.isSuccessful()) {
                showResponse(response.body().toString());
            }
        }

        @Override
        public void onFailure(Call<Post> call, Throwable t) {
            showErrorMessage();
        }
    });
}

Body:
If you use Retrofit 2 you can try this

public interface APIService {

@GET("/temperature")
Call<Post> getTemperature(@Header("api-key") String my_api_key, @Header("code") String my-api-code);

And pass codes in your call


问:
Portability of binary serialization of double/float type in C++
The C++ standard does not discuss the underlying layout of float and double types, only the range of values they should represent.  (This is also true for signed types, is it two's compliment or something else)

My question is: What the are techniques used to serialize/deserialize POD types such as double and float in a portable manner? At the moment it seems the only way to do this is to have the value represented literally(as in "123.456"), The ieee754 layout for double is not standard on all architectures.

答:
What's wrong with a human readable format.

It has a couple of advantages over binary:

It's readable

It's portable

It makes support really easy

(as you can ask the user to look at it in their favorite editor even word)

It's easy to fix

(or adjust files manually in error situations)

Disadvantage:

It's not compact

If this a real problem you can always zip it.

It may be slightly slower to extract/generate

Note a binary format probably needs to be normalized as well (see htonl())

To output a double at full precision:

```<code>double v = 2.20;
std::cout << std::setprecision(std::numeric_limits<double>::digits) << v;
</code>```

OK. I am not convinced that is exactly precise. It may lose precision.

OwnerDisplayName: Matthieu N.

LastEditorDisplayName: Matthieu N.

Body:
What's wrong with a human readable format.

It has a couple of advantages over binary:

It's readable

It's portable

It makes support really easy

(as you can ask the user to look at it in their favorite editor even word)

It's easy to fix

(or adjust files manually in error situations)

Disadvantage:

It's not compact

If this a real problem you can always zip it.

It may be slightly slower to extract/generate

Note a binary format probably needs to be normalized as well (see htonl())

To output a double at full precision:

double v = 2.20;
std::cout << std::setprecision(std::numeric_limits<double>::digits) << v;

OK. I am not convinced that is exactly precise. It may lose precision.