问:
Setting threshold on max number of classes selected/activated on click on multiple divs/id's
I've been working on a skill tree 'persay' and I ran into an interesting problem.

I have my code setup to allow a user to click a talent to show that particular talent has been selected up to a max number of 4 talents total. Once you have selected 4 talents you have to deselect a talent to select a different one.

My problem comes when I duplicate the talent tree for a second talent tree on the same page(for a second hero/class essentially or a second party member out of your party). I can't figure out how to make the same 'threshold of a max of 4 talents' on other skill trees standalone. What happens is that they all share the same threshold across all trees. I have tried making separate id's each and even changing the variable names within each function.

var skillTotal = 0;
var skillSelected = 0;

$( "#selectable01>li.skill-slot" ).bind( "click", function ( e ) {
    var threshold = 4;
        var price = 1;
        if ($(this).hasClass('selected')) {
                skillTotal = skillTotal - 1;
                skillSelected--;
                $(this).toggleClass('selected');
        }
        else if (price + skillTotal <= threshold) {
                skillTotal = skillTotal + price;
                skillSelected++;
                $(this).toggleClass('selected');
        }
});

$( "#selectable02>li.skill-slot" ).bind( "click", function ( e ) {
    var threshold = 4;
        var price = 1;
        if ($(this).hasClass('selected')) {
                skillTotal = skillTotal - 1;
                skillSelected--;
                $(this).toggleClass('selected');
        }
        else if (price + skillTotal <= threshold) {
                skillTotal = skillTotal + price;
                skillSelected++;
                $(this).toggleClass('selected');
        }
});

/* NOT USING THIS CURRENTLY
$( "#campSelectable>li.camp-slot" ).bind( "click", function ( e ) {
    var campThreshold = 3;
        var campPrice = 1;
        if ($(this).hasClass('selected')) {
                campTotal = campTotal - campPrice;
                selectedCamp--;
                $(this).toggleClass('selected');
        }
        else if (campPrice + campTotal <= campThreshold) {
                campTotal = campTotal + campPrice;
                selectedCamp++;
                $(this).toggleClass('selected');
        }
}); */```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.skill-slot, .camp-slot{
  border:2px solid black;
  width:100px;
  margin: 5px;
  opacity: .4;
}

.skill-slot:hover, .camp-slot:hover {
  opacity: 1;
}

.raffle-slot.taken{
  background:red;
}
.selected{
  background: rgb(255, 128, 128);
  opacity: 1;
}</code>```

1

2

3

4

5

6

7

1

2

3

4

5

6

7

```

Here are the things I have tried:
Initially my identifier was : $( "#calc>ol>li.skill-slot" ).on so I began adding additional id's to drill down further and make sure that my functions were targeting specific div's, so I moved to this: $( "#calc>#selectable01>li.skill-slot" ).on and $( "#calc>#selectable02>li.skill-slot" ).on

The reason I didn't want to target a second ID is because I'll be using templates that are appended to the #calc div effectively replacing the current roster with a new one. I also did this for testing to see if I could resolve the issue by making them their own individual id's, which didn't work.

答:
As you are using global variables for the count and total, this obviously leads to a global limit. To make the limit local to each of the groups, you could use  data attributes of these ol elements, so they work independently from each other. With some other little improvements, your code could look like this:

$("#selectable01, #selectable02").data("skillTotal", 0).data("skillSelected", 0);

$("#selectable01>li.skill-slot,#selectable02>li.skill-slot").on("click", function () {
    var threshold = 4,
        price = 1,
        sign = $(this).hasClass('selected') ? -1: 1,
        $p = $(this).parent(),
        newPrice = $p.data("skillTotal") + sign*price;
    if (newPrice > threshold) return;
    $p.data("skillTotal", newPrice)
      .data("skillSelected", $p.data("skillSelected") + sign);
    $(this).toggleClass('selected');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.skill-slot, .camp-slot{
  border:2px solid black;
  width:100px;
  margin: 5px;
  opacity: .4;
}

.skill-slot:hover, .camp-slot:hover {
  opacity: 1;
}

.raffle-slot.taken{
  background:red;
}
.selected{
  background: rgb(255, 128, 128);
  opacity: 1;
}</code>```

1

2

3

4

5

6

7

1

2

3

4

5

6

7

```

Body:
I've been working on a skill tree 'persay' and I ran into an interesting problem.

I have my code setup to allow a user to click a talent to show that particular talent has been selected up to a max number of 4 talents total. Once you have selected 4 talents you have to deselect a talent to select a different one.

My problem comes when I duplicate the talent tree for a second talent tree on the same page(for a second hero/class essentially or a second party member out of your party). I can't figure out how to make the same 'threshold of a max of 4 talents' on other skill trees standalone. What happens is that they all share the same threshold across all trees. I have tried making separate id's each and even changing the variable names within each function.

var skillTotal = 0;
var skillSelected = 0;

$( "#selectable01>li.skill-slot" ).bind( "click", function ( e ) {
    var threshold = 4;
        var price = 1;
        if ($(this).hasClass('selected')) {
                skillTotal = skillTotal - 1;
                skillSelected--;
                $(this).toggleClass('selected');
        }
        else if (price + skillTotal <= threshold) {
                skillTotal = skillTotal + price;
                skillSelected++;
                $(this).toggleClass('selected');
        }
});

$( "#selectable02>li.skill-slot" ).bind( "click", function ( e ) {
    var threshold = 4;
        var price = 1;
        if ($(this).hasClass('selected')) {
                skillTotal = skillTotal - 1;
                skillSelected--;
                $(this).toggleClass('selected');
        }
        else if (price + skillTotal <= threshold) {
                skillTotal = skillTotal + price;
                skillSelected++;
                $(this).toggleClass('selected');
        }
});

/* NOT USING THIS CURRENTLY
$( "#campSelectable>li.camp-slot" ).bind( "click", function ( e ) {
    var campThreshold = 3;
        var campPrice = 1;
        if ($(this).hasClass('selected')) {
                campTotal = campTotal - campPrice;
                selectedCamp--;
                $(this).toggleClass('selected');
        }
        else if (campPrice + campTotal <= campThreshold) {
                campTotal = campTotal + campPrice;
                selectedCamp++;
                $(this).toggleClass('selected');
        }
}); */

.skill-slot, .camp-slot{
  border:2px solid black;
  width:100px;
  margin: 5px;
  opacity: .4;
}

.skill-slot:hover, .camp-slot:hover {
  opacity: 1;
}

.raffle-slot.taken{
  background:red;
}
.selected{
  background: rgb(255, 128, 128);
  opacity: 1;
}

1

2

3

4

5

6

7

1

2

3

4

5

6

7

Here are the things I have tried:
Initially my identifier was : $( "#calc>ol>li.skill-slot" ).on so I began adding additional id's to drill down further and make sure that my functions were targeting specific div's, so I moved to this: $( "#calc>#selectable01>li.skill-slot" ).on and $( "#calc>#selectable02>li.skill-slot" ).on

The reason I didn't want to target a second ID is because I'll be using templates that are appended to the #calc div effectively replacing the current roster with a new one. I also did this for testing to see if I could resolve the issue by making them their own individual id's, which didn't work.

Body:
As you are using global variables for the count and total, this obviously leads to a global limit. To make the limit local to each of the groups, you could use  data attributes of these ol elements, so they work independently from each other. With some other little improvements, your code could look like this:

$("#selectable01, #selectable02").data("skillTotal", 0).data("skillSelected", 0);

$("#selectable01>li.skill-slot,#selectable02>li.skill-slot").on("click", function () {
    var threshold = 4,
        price = 1,
        sign = $(this).hasClass('selected') ? -1: 1,
        $p = $(this).parent(),
        newPrice = $p.data("skillTotal") + sign*price;
    if (newPrice > threshold) return;
    $p.data("skillTotal", newPrice)
      .data("skillSelected", $p.data("skillSelected") + sign);
    $(this).toggleClass('selected');
});

.skill-slot, .camp-slot{
  border:2px solid black;
  width:100px;
  margin: 5px;
  opacity: .4;
}

.skill-slot:hover, .camp-slot:hover {
  opacity: 1;
}

.raffle-slot.taken{
  background:red;
}
.selected{
  background: rgb(255, 128, 128);
  opacity: 1;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="calc">
<ol class="roster" id="selectable01">
<li class="skill-slot">1</li>
<li class="skill-slot">2</li>
<li class="skill-slot">3</li>
<li class="skill-slot">4</li>
<li class="skill-slot">5</li>
<li class="skill-slot">6</li>
<li class="skill-slot">7</li>
</ol>

<ol class="roster" id="selectable02">
<li class="skill-slot">1</li>
<li class="skill-slot">2</li>
<li class="skill-slot">3</li>
<li class="skill-slot">4</li>
<li class="skill-slot">5</li>
<li class="skill-slot">6</li>
<li class="skill-slot">7</li>
</ol>

</div>


来源: stackexchange

问:
How to delete a row from UITableView
I'm trying to delete a row from my table view and so far have been unsuccessful. I keep getting this error:

"Terminating app due to uncaught exception
  'NSInternalInconsistencyException', reason: 'Invalid update: invalid
  number of rows in section 0.  The number of rows contained in an
  existing section after the update (5) must be equal to the number of
  rows contained in that section before the update (5), plus or minus
  the number of rows inserted or deleted from that section (0 inserted,
  1 deleted).'" The array which i use to populate the table view is
  declared in that class, also i get my objects for my array from an
  sqlite db.

The code that i used to try deleting rows is as follows.

```<code>- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

if (editingStyle == UITableViewCellEditingStyleDelete) {
    // Delete the row from the data source

    [categoryArray objectAtIndex:indexPath.row];
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];

}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
</code>```

Now for the questions i hope to get answered:

-How can i delete rows properly?

-Will i face deleting the row if its the only one left in the tableView?

-Can i change the tableView that is used in the method to be the UITableView i declared in
my .h file?

Many Thanks.

Edit

-Full .m code

```<code>#import "DeleteCategoryTableView.h"
#import "KeyCryptAppAppDelegate.h"

@implementation DeleteCategoryTableView
@synthesize categoryArray;

#pragma mark -
#pragma mark Initialization

-(void) initializeCategoryArray {

sqlite3 *db= [KeyCryptAppAppDelegate getNewDBConnection];
KeyCryptAppAppDelegate *appDelegate = (KeyCryptAppAppDelegate *)[[UIApplication sharedApplication] delegate];

const char *sql = [[NSString stringWithFormat:(@"Select Category from Categories;")]cString];

sqlite3_stmt *compiledStatement;

if (sqlite3_prepare_v2(db, sql, -1, &compiledStatement, NULL)==SQLITE_OK)
{
    while(sqlite3_step(compiledStatement) == SQLITE_ROW)
        [categoryArray addObject:[NSString stringWithUTF8String:(char*) sqlite3_column_text(compiledStatement, 0)]];

}
else {
    NSAssert1(0,@"Error preparing statement", sqlite3_errmsg(db));
}
sqlite3_finalize(compiledStatement);
}
/*
- (id)initWithStyle:(UITableViewStyle)style {
// Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
if ((self = [super initWithStyle:style])) {
}
return self;
}
*/
#pragma mark -
#pragma mark View lifecycle
- (void)viewDidLoad {
self.title = NSLocalizedString(@"Delete Categories",@"Delete your Categories");
categoryArray = [[NSMutableArray alloc]init];
[self initializeCategoryArray];
[super viewDidLoad];

// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
/*
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section    {
// Return the number of rows in the section.
return [self.categoryArray count];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}

// Configure the cell...
NSUInteger row = [indexPath row];
cell.text = [categoryArray objectAtIndex:row];
return cell;
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

if (editingStyle == UITableViewCellEditingStyleDelete) {
    // Delete the row from the data source

    [categoryArray removeObjectAtIndex:indexPath.row];
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    [deleteCategoryTable reloadData];

    NSString *selectedCategory = [categoryArray objectAtIndex:indexPath.row];

    sqlite3 *db= [KeyCryptAppAppDelegate getNewDBConnection];
    KeyCryptAppAppDelegate *appDelegate = (KeyCryptAppAppDelegate *)[[UIApplication sharedApplication] delegate];
    const char *sql = [[NSString stringWithFormat:@"Delete from Categories where Category = '%@';", selectedCategory]cString];

    sqlite3_stmt *compiledStatement;

    if (sqlite3_prepare_v2(db, sql, -1, &compiledStatement, NULL)==SQLITE_OK)
    {
        sqlite3_exec(db,sql,NULL,NULL,NULL);

    }
    else {
        NSAssert1(0,@"Error preparing statement", sqlite3_errmsg(db));
    }
    sqlite3_finalize(compiledStatement);
}

else if (editingStyle == UITableViewCellEditingStyleInsert) {
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic may go here. Create and push another view controller.
/*
 <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
 // ...
 // Pass the selected object to the new view controller.
 [self.navigationController pushViewController:detailViewController animated:YES];
 [detailViewController release];
 */
}
#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];

// Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
}

- (void)dealloc {
[super dealloc];
}

@end
</code>```

答:
for this purpose dont try to delete the row try to delete from array or data source(in case array is preparing from database) then try to reload array by simply call the database function.

then

```<code>[table reloadData].
</code>```

this is the correct practice.

ContentLicense: CC BY-SA 3.0

Title: How to delete a row from UITableView

Body:
I'm trying to delete a row from my table view and so far have been unsuccessful. I keep getting this error:

"Terminating app due to uncaught exception
  'NSInternalInconsistencyException', reason: 'Invalid update: invalid
  number of rows in section 0.  The number of rows contained in an
  existing section after the update (5) must be equal to the number of
  rows contained in that section before the update (5), plus or minus
  the number of rows inserted or deleted from that section (0 inserted,
  1 deleted).'" The array which i use to populate the table view is
  declared in that class, also i get my objects for my array from an
  sqlite db.

The code that i used to try deleting rows is as follows.

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

if (editingStyle == UITableViewCellEditingStyleDelete) {
    // Delete the row from the data source

    [categoryArray objectAtIndex:indexPath.row];
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];

}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}

Now for the questions i hope to get answered:

-How can i delete rows properly?

-Will i face deleting the row if its the only one left in the tableView?

-Can i change the tableView that is used in the method to be the UITableView i declared in
my .h file?

Many Thanks.

Edit

-Full .m code

#import "DeleteCategoryTableView.h"
#import "KeyCryptAppAppDelegate.h"

@implementation DeleteCategoryTableView
@synthesize categoryArray;

#pragma mark -
#pragma mark Initialization

-(void) initializeCategoryArray {

sqlite3 *db= [KeyCryptAppAppDelegate getNewDBConnection];
KeyCryptAppAppDelegate *appDelegate = (KeyCryptAppAppDelegate *)[[UIApplication sharedApplication] delegate];

const char *sql = [[NSString stringWithFormat:(@"Select Category from Categories;")]cString];

sqlite3_stmt *compiledStatement;

if (sqlite3_prepare_v2(db, sql, -1, &compiledStatement, NULL)==SQLITE_OK)
{
    while(sqlite3_step(compiledStatement) == SQLITE_ROW)
        [categoryArray addObject:[NSString stringWithUTF8String:(char*) sqlite3_column_text(compiledStatement, 0)]];

}
else {
    NSAssert1(0,@"Error preparing statement", sqlite3_errmsg(db));
}
sqlite3_finalize(compiledStatement);
}
/*
- (id)initWithStyle:(UITableViewStyle)style {
// Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
if ((self = [super initWithStyle:style])) {
}
return self;
}
*/
#pragma mark -
#pragma mark View lifecycle
- (void)viewDidLoad {
self.title = NSLocalizedString(@"Delete Categories",@"Delete your Categories");
categoryArray = [[NSMutableArray alloc]init];
[self initializeCategoryArray];
[super viewDidLoad];

// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
/*
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section    {
// Return the number of rows in the section.
return [self.categoryArray count];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}

// Configure the cell...
NSUInteger row = [indexPath row];
cell.text = [categoryArray objectAtIndex:row];
return cell;
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

if (editingStyle == UITableViewCellEditingStyleDelete) {
    // Delete the row from the data source

    [categoryArray removeObjectAtIndex:indexPath.row];
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    [deleteCategoryTable reloadData];

    NSString *selectedCategory = [categoryArray objectAtIndex:indexPath.row];

    sqlite3 *db= [KeyCryptAppAppDelegate getNewDBConnection];
    KeyCryptAppAppDelegate *appDelegate = (KeyCryptAppAppDelegate *)[[UIApplication sharedApplication] delegate];
    const char *sql = [[NSString stringWithFormat:@"Delete from Categories where Category = '%@';", selectedCategory]cString];

    sqlite3_stmt *compiledStatement;

    if (sqlite3_prepare_v2(db, sql, -1, &compiledStatement, NULL)==SQLITE_OK)
    {
        sqlite3_exec(db,sql,NULL,NULL,NULL);

    }
    else {
        NSAssert1(0,@"Error preparing statement", sqlite3_errmsg(db));
    }
    sqlite3_finalize(compiledStatement);
}

else if (editingStyle == UITableViewCellEditingStyleInsert) {
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic may go here. Create and push another view controller.
/*
 <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
 // ...
 // Pass the selected object to the new view controller.
 [self.navigationController pushViewController:detailViewController animated:YES];
 [detailViewController release];
 */
}
#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];

// Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
}

- (void)dealloc {
[super dealloc];
}

@end

Body:
for this purpose dont try to delete the row try to delete from array or data source(in case array is preparing from database) then try to reload array by simply call the database function.

then

[table reloadData].

this is the correct practice.

ContentLicense: CC BY-SA 2.5


问:
Redistributables for deploying C++ exe developed with Visual Studio 2015 on Windows 7
I have developed a 32-bit C++ application using Visual Studio 2015 (on Windows 10). I want to deploy it onto machines running Windows 7 and later.

I put together a WiX installer and included the VC++ redistributable merge module as described here. The merge module I included was C:\Program Files (x86)\Common Files\Merge Modules\Microsoft_VC140_CRT_x86.msm.

This installer appears to work fine but on Windows 7 the installed program will not run, complaining about missing api-ms-win-crt-runtime-l1-1-0.dll.

From searching I suspect that there may be extra files in the redistributable package vc_redist.x86.exe from here, but the WiX docs tell me to use an msm rather than an exe.

It's also possible that the merge module failed to install. I didn't see any errors but I haven't re-run it with logs enabled to check that possibility.

Another option may be to use burn but I am not familiar with this tool; I will go that route if it's the correct one but I'd prefer to stick with MSI if possible.

答:
It's worth noting that it is now possible to distribute the Universal C Runtime DLLs with your application. The MSDN blog post describes the steps:

Install the Windnows 10 SDK

Go to C:\Program Files (x86)\Windows Kits\10\Redist\ucrt and find the DLLs for the platform you are targeting

Copy them into your application's program directory

They are not big. About 2 megabytes in total.

I ended up using this technique because:

It does not require me to create a separate WiX package and then bootstrap them;

It does not require the user to run any extra installers

I cannot speak to whether it would work on all computers, but it works on the ones I have tested.


问:
WireMock. Ignore all request beside only one
I start WireMock as standalone process:

java -jar wiremock-standalone-2.6.0.jar --port 8080 -v

OK.

When http request content suffix /api/profile/Favorite/  the WireMock must return stub response. On all other requests must by ignore by WireMock and must be forward to production server.

How I must config WireMock for this?

答:
It sounds like you're looking for proxy behavior. For standalone WireMock you pass in --proxy-all="http://yourserver.com" as a parameter.

The section on Record and Playback in the docs has more examples.


问:
T-SQL Execute Recursion for Each Value in Multiple Columns
I have a dataset with two columns. A person in the first column may be in the span of control of a person in the second column (i.e. everyone is in Michael's span of control, Dwight & Stanley are in Jim's span of control):

```<code>source_id     source          target_id     target
1             Michael Scott   5             Kelly Kapoor
3             Dwight Schrute  2             Jim Halpert
4             Stanley Hudson  2             Jim Halpert
2             Jim Halpert     5             Kelly Kapoor
</code>```

I have a table that lists each person and their supervisor:

```<code>person_id       person           supervisor_id     supervisor
1               Michael Scott    0                 None
2               Jim Halpert      1                 Michael Scott
3               Dwight Schrute   2                 Jim Halpert
4               Stanley Hudson   2                 Jim Halpert
6               Ryan Howard      1                 Michael Scott
5               Kelly Kapoor     6                 Ryan Howard
</code>```

I have a block of code that uses recursion to find a single person's span of control from the preceding table:

```<code>with anchor as
(
    select person_id, supervisor_id from table where unique_id = @ID
    union all
    select a.person_id, a.supervisor_id
    from table a
    inner join Anchor b ON b.person_id = a.supervisor_id
)

select a.person_id
from anchor a
</code>```

This block of code can be turned into a stored procedure or a function. Running it for Jim (for example), returns:

```<code>person_id
3 (Dwight Schrute)
4 (Stanley Hudson)
</code>```

How do I compare each value in the initial dataset (from both the source and target columns) to the values in the column returned by the preceding block of code? In other words, for each row in source, I need to check if that name is within the span of control of target. In addition, for each row in target, I need to check if that name is within the span of control of source.

Desired End Result:

```<code>source_id     source          target_id     target         isEitherPersonInOther'sSOC
1             Michael Scott   5             Kelly Kapoor   Yes
3             Dwight Schrute  2             Jim Halpert    Yes
4             Stanley Hudson  2             Jim Halpert    Yes
2             Jim Halpert     5             Kelly Kapoor   No
</code>```

I know iterations are bad (i.e. running the stored procedure for each row with a cursor or while loop). I also know cross apply and a function together may work, but I have been unable to figure my way through that.

Thank you for any insight you all may have!

答:
What it looks like you need is to take your recursive CTE and output ID pairs into a temp table.  I'm picturing something like this:

```<code>DECLARE @id int
DECLARE cx CURSOR FOR
    SELECT person_id FROM PersonSupervisor

CREATE TABLE #tmpPS (Supervisor int, personInChain int)

OPEN cx
FETCH NEXT FROM cx
    INTO @id

WHILE @@FETCH_STATUS = 0
BEGIN
    with anchor as
    (
        select person_id, supervisor_id from table where unique_id = @ID
        union all
        select a.person_id, a.supervisor_id
        from table a
        inner join Anchor b ON b.person_id = a.supervisor_id
    )
    INSERT INTO #tmpPS
    select @id, a.person_id
    from anchor a

    FETCH NEXT FROM cx
        INTO @id
END
Close cx
Deallocate cx
</code>```

This creates a table of all relationships, recursively expanded. Then you can output whether any given person is either above or below a given other person with this subquery. Add it to whatever query outputs your base grid:

```<code>SELECT
    SourceId,
    Source,
    TargetId,
    Target,
    CASE
        WHEN EXISTS (SELECT 1 FROM #tmpPS WHERE Supervisor = SourceId and PersonInChain = TargetId)
            THEN 'Yes'
        WHEN EXISTS (SELECT 1 FROM #tmpPS WHERE Supervisor = TargetId and PersonInChain = SourceId)
            THEN 'Yes'
        ELSE 'No'
    END as [isEitherPersonInOther'sSOC]
FROM ....
</code>```

This also implies a version of this where you can separate the relationships out - If the first query, the TargetId is a subordinate of the SourceId. If the second query, then TargetId is a superior to SourceId.

Body:
I have a dataset with two columns. A person in the first column may be in the span of control of a person in the second column (i.e. everyone is in Michael's span of control, Dwight & Stanley are in Jim's span of control):

source_id     source          target_id     target
1             Michael Scott   5             Kelly Kapoor
3             Dwight Schrute  2             Jim Halpert
4             Stanley Hudson  2             Jim Halpert
2             Jim Halpert     5             Kelly Kapoor

I have a table that lists each person and their supervisor:

person_id       person           supervisor_id     supervisor
1               Michael Scott    0                 None
2               Jim Halpert      1                 Michael Scott
3               Dwight Schrute   2                 Jim Halpert
4               Stanley Hudson   2                 Jim Halpert
6               Ryan Howard      1                 Michael Scott
5               Kelly Kapoor     6                 Ryan Howard

I have a block of code that uses recursion to find a single person's span of control from the preceding table:

with anchor as
(
    select person_id, supervisor_id from table where unique_id = @ID
    union all
    select a.person_id, a.supervisor_id
    from table a
    inner join Anchor b ON b.person_id = a.supervisor_id
)

select a.person_id
from anchor a

This block of code can be turned into a stored procedure or a function. Running it for Jim (for example), returns:

person_id
3 (Dwight Schrute)
4 (Stanley Hudson)

How do I compare each value in the initial dataset (from both the source and target columns) to the values in the column returned by the preceding block of code? In other words, for each row in source, I need to check if that name is within the span of control of target. In addition, for each row in target, I need to check if that name is within the span of control of source.

Desired End Result:

source_id     source          target_id     target         isEitherPersonInOther'sSOC
1             Michael Scott   5             Kelly Kapoor   Yes
3             Dwight Schrute  2             Jim Halpert    Yes
4             Stanley Hudson  2             Jim Halpert    Yes
2             Jim Halpert     5             Kelly Kapoor   No

I know iterations are bad (i.e. running the stored procedure for each row with a cursor or while loop). I also know cross apply and a function together may work, but I have been unable to figure my way through that.

Thank you for any insight you all may have!

Body:
What it looks like you need is to take your recursive CTE and output ID pairs into a temp table.  I'm picturing something like this:

DECLARE @id int
DECLARE cx CURSOR FOR
    SELECT person_id FROM PersonSupervisor

CREATE TABLE #tmpPS (Supervisor int, personInChain int)

OPEN cx
FETCH NEXT FROM cx
    INTO @id

WHILE @@FETCH_STATUS = 0
BEGIN
    with anchor as
    (
        select person_id, supervisor_id from table where unique_id = @ID
        union all
        select a.person_id, a.supervisor_id
        from table a
        inner join Anchor b ON b.person_id = a.supervisor_id
    )
    INSERT INTO #tmpPS
    select @id, a.person_id
    from anchor a

    FETCH NEXT FROM cx
        INTO @id
END
Close cx
Deallocate cx

This creates a table of all relationships, recursively expanded. Then you can output whether any given person is either above or below a given other person with this subquery. Add it to whatever query outputs your base grid:

SELECT
    SourceId,
    Source,
    TargetId,
    Target,
    CASE
        WHEN EXISTS (SELECT 1 FROM #tmpPS WHERE Supervisor = SourceId and PersonInChain = TargetId)
            THEN 'Yes'
        WHEN EXISTS (SELECT 1 FROM #tmpPS WHERE Supervisor = TargetId and PersonInChain = SourceId)
            THEN 'Yes'
        ELSE 'No'
    END as [isEitherPersonInOther'sSOC]
FROM ....

This also implies a version of this where you can separate the relationships out - If the first query, the TargetId is a subordinate of the SourceId. If the second query, then TargetId is a superior to SourceId.


问:
Unable to write config file for Prometheus on Kubernetes
I am running prometheus on a kubernetes cluster and trying to scrape pods, nodes, services. I am getting the following error when i reload the config by sending POST request-

```<code>failed to reload config: couldn't load configuration (-config.file=/etc/prometheus/conf/prometheus.yml): unknown fields in kubernetes_sd_config: api_server
</code>```

While trying to follow official docs for writing config file, I am not able to understand the relabel_configs, source_labels, target_labels, action, keep, regex part. Can somebody explain these parts and also the use of labels in prometheus. Thanks in advance.

Following is the prometheus.yml file-

```<code>scrape_configs:

- job_name: 'kubernetes-nodes'

  # Default to scraping over https. If required, just disable this or change to
  # `http`.
  scheme: https

  # This TLS & bearer token file config is used to connect to the actual scrape
  # endpoints for cluster components. This is separate to discovery auth
  # configuration because discovery & scraping are two separate concerns in
  # Prometheus. The discovery auth config is automatic if Prometheus runs inside
  # the cluster. Otherwise, more config options have to be provided within the
  # <kubernetes_sd_config>.
  tls_config:
    ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
    # If your node certificates are self-signed or use a different CA to the
    # master CA, then disable certificate verification below. Note that
    # certificate verification is an integral part of a secure infrastructure
    # so this should only be disabled in a controlled environment. You can
    # disable certificate verification by uncommenting the line below.
    #
    # insecure_skip_verify: true
  bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token

  kubernetes_sd_configs:
  - api_server: "https://kubernetes.default.svc"
  - role: node

  relabel_configs:
  - action: labelmap
    regex: __meta_kubernetes_node_label_(.+)
  - target_label: __address__
    replacement: kubernetes.default.svc:443
  - source_labels: [__meta_kubernetes_node_name]
    regex: (.+)
    target_label: __metrics_path__
    replacement: /api/v1/nodes/${1}/proxy/metrics

# Scrape config for service endpoints.
#
# The relabeling allows the actual service scrape endpoint to be configured
# via the following annotations:
#
# * `prometheus.io/scrape`: Only scrape services that have a value of `true`
# * `prometheus.io/scheme`: If the metrics endpoint is secured then you will need
# to set this to `https` & most likely set the `tls_config` of the scrape config.
# * `prometheus.io/path`: If the metrics path is not `/metrics` override this.
# * `prometheus.io/port`: If the metrics are exposed on a different port to the
# service then set this appropriately.

# Example scrape config for probing services via the Blackbox Exporter.
#
# The relabeling allows the actual service scrape endpoint to be configured
# via the following annotations:
#
# * `prometheus.io/probe`: Only probe services that have a value of `true`
- job_name: 'kubernetes-services'

  metrics_path: /probe
  params:
    module: [http_2xx]

  kubernetes_sd_configs:
  - api_server: "https://kubernetes.default.svc"
  - role: service

  relabel_configs:
  - source_labels: [__meta_kubernetes_service_annotation_prometheus_io_probe]
    action: keep
    regex: true
  - source_labels: [__address__]
    target_label: __param_target
  - target_label: __address__
    replacement: blackbox
  - source_labels: [__param_target]
    target_label: instance
  - action: labelmap
    regex: __meta_kubernetes_service_label_(.+)
  - source_labels: [__meta_kubernetes_namespace]
    target_label: kubernetes_namespace
  - source_labels: [__meta_kubernetes_service_name]
    target_label: kubernetes_name

# Example scrape config for pods
#
# The relabeling allows the actual pod scrape endpoint to be configured via the
# following annotations:
#
# * `prometheus.io/scrape`: Only scrape pods that have a value of `true`
# * `prometheus.io/path`: If the metrics path is not `/metrics` override this.
# * `prometheus.io/port`: Scrape the pod on the indicated port instead of the
# pod's declared ports (default is a port-free target if none are declared).
- job_name: 'kubernetes-pods'

  kubernetes_sd_configs:
  - api_server: "https://kubernetes.default.svc"
  - role: pod

  relabel_configs:
  - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
    action: keep
    regex: true
  - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path]
    action: replace
    target_label: __metrics_path__
    regex: (.+)
  - source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
    action: replace
    regex: ([^:]+)(?::\d+)?;(\d+)
    replacement: $1:$2
    target_label: __address__
  - action: labelmap
    regex: __meta_kubernetes_pod_label_(.+)
  - source_labels: [__meta_kubernetes_namespace]
    action: replace
    target_label: kubernetes_namespace
  - source_labels: [__meta_kubernetes_pod_name]
    action: replace
    target_label: kubernetes_pod_name
</code>```

答:
Your yaml file is off, try this:</p>

```<code>  - job_name: 'kubernetes-services'

...

    kubernetes_sd_configs:
    - api_server: "https://kubernetes.default.svc"
      role: service

...
</code>```

Body:
I am running prometheus on a kubernetes cluster and trying to scrape pods, nodes, services. I am getting the following error when i reload the config by sending POST request-

failed to reload config: couldn't load configuration (-config.file=/etc/prometheus/conf/prometheus.yml): unknown fields in kubernetes_sd_config: api_server

While trying to follow official docs for writing config file, I am not able to understand the relabel_configs, source_labels, target_labels, action, keep, regex part. Can somebody explain these parts and also the use of labels in prometheus. Thanks in advance.

Following is the prometheus.yml file-

scrape_configs:

- job_name: 'kubernetes-nodes'

  # Default to scraping over https. If required, just disable this or change to
  # `http`.
  scheme: https

  # This TLS & bearer token file config is used to connect to the actual scrape
  # endpoints for cluster components. This is separate to discovery auth
  # configuration because discovery & scraping are two separate concerns in
  # Prometheus. The discovery auth config is automatic if Prometheus runs inside
  # the cluster. Otherwise, more config options have to be provided within the
  # <kubernetes_sd_config>.
  tls_config:
    ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
    # If your node certificates are self-signed or use a different CA to the
    # master CA, then disable certificate verification below. Note that
    # certificate verification is an integral part of a secure infrastructure
    # so this should only be disabled in a controlled environment. You can
    # disable certificate verification by uncommenting the line below.
    #
    # insecure_skip_verify: true
  bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token

  kubernetes_sd_configs:
  - api_server: "https://kubernetes.default.svc"
  - role: node

  relabel_configs:
  - action: labelmap
    regex: __meta_kubernetes_node_label_(.+)
  - target_label: __address__
    replacement: kubernetes.default.svc:443
  - source_labels: [__meta_kubernetes_node_name]
    regex: (.+)
    target_label: __metrics_path__
    replacement: /api/v1/nodes/${1}/proxy/metrics

# Scrape config for service endpoints.
#
# The relabeling allows the actual service scrape endpoint to be configured
# via the following annotations:
#
# * `prometheus.io/scrape`: Only scrape services that have a value of `true`
# * `prometheus.io/scheme`: If the metrics endpoint is secured then you will need
# to set this to `https` & most likely set the `tls_config` of the scrape config.
# * `prometheus.io/path`: If the metrics path is not `/metrics` override this.
# * `prometheus.io/port`: If the metrics are exposed on a different port to the
# service then set this appropriately.

# Example scrape config for probing services via the Blackbox Exporter.
#
# The relabeling allows the actual service scrape endpoint to be configured
# via the following annotations:
#
# * `prometheus.io/probe`: Only probe services that have a value of `true`
- job_name: 'kubernetes-services'

  metrics_path: /probe
  params:
    module: [http_2xx]

  kubernetes_sd_configs:
  - api_server: "https://kubernetes.default.svc"
  - role: service

  relabel_configs:
  - source_labels: [__meta_kubernetes_service_annotation_prometheus_io_probe]
    action: keep
    regex: true
  - source_labels: [__address__]
    target_label: __param_target
  - target_label: __address__
    replacement: blackbox
  - source_labels: [__param_target]
    target_label: instance
  - action: labelmap
    regex: __meta_kubernetes_service_label_(.+)
  - source_labels: [__meta_kubernetes_namespace]
    target_label: kubernetes_namespace
  - source_labels: [__meta_kubernetes_service_name]
    target_label: kubernetes_name

# Example scrape config for pods
#
# The relabeling allows the actual pod scrape endpoint to be configured via the
# following annotations:
#
# * `prometheus.io/scrape`: Only scrape pods that have a value of `true`
# * `prometheus.io/path`: If the metrics path is not `/metrics` override this.
# * `prometheus.io/port`: Scrape the pod on the indicated port instead of the
# pod's declared ports (default is a port-free target if none are declared).
- job_name: 'kubernetes-pods'

  kubernetes_sd_configs:
  - api_server: "https://kubernetes.default.svc"
  - role: pod

  relabel_configs:
  - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
    action: keep
    regex: true
  - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path]
    action: replace
    target_label: __metrics_path__
    regex: (.+)
  - source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
    action: replace
    regex: ([^:]+)(?::\d+)?;(\d+)
    replacement: $1:$2
    target_label: __address__
  - action: labelmap
    regex: __meta_kubernetes_pod_label_(.+)
  - source_labels: [__meta_kubernetes_namespace]
    action: replace
    target_label: kubernetes_namespace
  - source_labels: [__meta_kubernetes_pod_name]
    action: replace
    target_label: kubernetes_pod_name

Body:
Your yaml file is off, try this:

  - job_name: 'kubernetes-services'

...

    kubernetes_sd_configs:
    - api_server: "https://kubernetes.default.svc"
      role: service

...


问:
convert set to map of string with count
My original data is stream of string like

```<code>correctname
abc,def,ghi,jol
abc
def,ghi
zzzzzzzzzz
myname
pppppppppp
jkl
</code>```

Converting it set:

```<code>{correct}
{abc, def,ghi,jkl}
{abc}
{def,ghi}
{invalid}
{correct}
{invalid}
{jkl}
</code>```

I have some Stream.map(…) which is returning me above result

Map<String,Long> answer = Stream.map(...).collect(groupingby??)

Now I want to collect it (collect or map or groupingby) and return result as Map such that my answer should be

Map>
{correct: 2
invalid: 2
others: 8}

答:
Sounds like you're looking for this:</p>

```<code>Map<String, Long> answer = sets.stream()
        .flatMap(Set::stream)
        .collect(Collectors.groupingBy(
                s -> s.matches("invalid|correct") ? s : "others",
                Collectors.counting()));
</code>```

Title: convert set to map of string with count

Body:
My original data is stream of string like

correctname
abc,def,ghi,jol
abc
def,ghi
zzzzzzzzzz
myname
pppppppppp
jkl

Converting it set:

{correct}
{abc, def,ghi,jkl}
{abc}
{def,ghi}
{invalid}
{correct}
{invalid}
{jkl}

I have some Stream.map(…) which is returning me above result

Map<String,Long> answer = Stream.map(...).collect(groupingby??)

Now I want to collect it (collect or map or groupingby) and return result as Map such that my answer should be

Map>
{correct: 2
invalid: 2
others: 8}

Body:
Sounds like you're looking for this:

Map<String, Long> answer = sets.stream()
        .flatMap(Set::stream)
        .collect(Collectors.groupingBy(
                s -> s.matches("invalid|correct") ? s : "others",
                Collectors.counting()));


问:
Aggregator transformation in Informatica
Is it compulsory to select group-by while performing count operation in the aggregator transformation in Informatica</p>

答:
It's not mandatory to select atleast one port as group by. Hiwever, if you don't choose any group by port - Infa will return only last row.

Hope this helps

ContentLicense: CC BY-SA 4.0


问:
Can't import dependency installed with Cocoapods
I've installed FBSDK with Cocoapods but can't import it in my AppDelegate.swift file for some reason. The FBSDK kit appears in my Xcode project so I feel like it should be working.

I'm not an iOS developer by any means, I'm just trying to write a simple native plugin for Flutter SDK. Anyone an idea?

--Here is what the pod file looks like--

```<code># Uncomment this line to define a global platform for your project
# platform :ios, '9.0'

if ENV['FLUTTER_FRAMEWORK_DIR'] == nil
  abort('Please set FLUTTER_FRAMEWORK_DIR to the directory containing Flutter.framework')
end

target 'Runner' do
  use_frameworks!

  # Pods for Runner
pod 'FBSDKCoreKit'
pod 'FBSDKLoginKit'
pod 'FBSDKShareKit'

  # Flutter Pods
  pod 'Flutter', :path => ENV['FLUTTER_FRAMEWORK_DIR']

  if File.exists? '../.flutter-plugins'
    flutter_root = File.expand_path('..')
    File.foreach('../.flutter-plugins') { |line|
      plugin = line.split(pattern='=')
      if plugin.length == 2
        name = plugin[0].strip()
        path = plugin[1].strip()
        resolved_path = File.expand_path("#{path}/ios", flutter_root)
        pod name, :path => resolved_path
      else
        puts "Invalid plugin specification: #{line}"
      end
    }
  end
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['ENABLE_BITCODE'] = 'NO'
    end
  end
end
</code>```

---EDIT---

I''m getting the following error atm: FBSDKCoreKit.framework: No such file or directory.When I open the Frameworks folder in xCode, all file names are in red:

But that exact folder in Finder is empty. So I guess that's why the error is showing. The question is how to fix this...

This is what my embedded binaries and linked frameworks and libraries look like in the project:

答: Are you opening the .xcodeproj or the .xcworkspace? Make sure it is the workspace whenever you install a cocoapod

Body:
I've installed FBSDK with Cocoapods but can't import it in my AppDelegate.swift file for some reason. The FBSDK kit appears in my Xcode project so I feel like it should be working.

I'm not an iOS developer by any means, I'm just trying to write a simple native plugin for Flutter SDK. Anyone an idea?

--Here is what the pod file looks like--

# Uncomment this line to define a global platform for your project
# platform :ios, '9.0'

if ENV['FLUTTER_FRAMEWORK_DIR'] == nil
  abort('Please set FLUTTER_FRAMEWORK_DIR to the directory containing Flutter.framework')
end

target 'Runner' do
  use_frameworks!

  # Pods for Runner
pod 'FBSDKCoreKit'
pod 'FBSDKLoginKit'
pod 'FBSDKShareKit'

  # Flutter Pods
  pod 'Flutter', :path => ENV['FLUTTER_FRAMEWORK_DIR']

  if File.exists? '../.flutter-plugins'
    flutter_root = File.expand_path('..')
    File.foreach('../.flutter-plugins') { |line|
      plugin = line.split(pattern='=')
      if plugin.length == 2
        name = plugin[0].strip()
        path = plugin[1].strip()
        resolved_path = File.expand_path("#{path}/ios", flutter_root)
        pod name, :path => resolved_path
      else
        puts "Invalid plugin specification: #{line}"
      end
    }
  end
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['ENABLE_BITCODE'] = 'NO'
    end
  end
end

---EDIT---

I''m getting the following error atm: FBSDKCoreKit.framework: No such file or directory.When I open the Frameworks folder in xCode, all file names are in red:

But that exact folder in Finder is empty. So I guess that's why the error is showing. The question is how to fix this...

This is what my embedded binaries and linked frameworks and libraries look like in the project:


问:
docker-machine create with digitalocean driver: ssh command error
I´m using docker tools on windows.

create command was working perfectly last week and I managed to create a number of machines on Digital Ocean. Then I tried today with no success. I repeated the same command with different regions and I always get the same result:

```<code>λ docker-machine create -d digitalocean --digitalocean-access-token=MYTOKEN --digitalocean-region=ams2 vmname
Running pre-create checks...
Creating machine...
(fernu) Creating SSH key...
(fernu) Creating Digital Ocean droplet...
(fernu) Waiting for IP address to be assigned to the Droplet...
Waiting for machine to be running, this may take a few minutes...
Detecting operating system of created instance...
Waiting for SSH to be available...
Detecting the provisioner...
Provisioning with ubuntu(systemd)...
Installing Docker...
Copying certs to the local machine directory...
Copying certs to the remote machine...
Setting Docker configuration on the remote daemon...
Error creating machine: Error running provisioning: ssh command error:
command : sudo systemctl -f start docker
err     : exit status 1
output  : Job for docker.service failed because the control process exited with error code. See "systemctl status docker.service" and "journalctl -xe" for details.
</code>```

If I execute the suggested command:

```<code>root@fernu:~# systemctl status docker.service
● docker.service - Docker Application Container Engine
   Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset: enabled)
  Drop-In: /etc/systemd/system/docker.service.d
           └─10-machine.conf
   Active: inactive (dead) (Result: exit-code) since Fri 2017-06-30 20:56:13 UTC; 8min ago
     Docs: https://docs.docker.com
  Process: 4943 ExecStart=/usr/bin/docker daemon -H tcp://0.0.0.0:2376 -H unix:///var/run/docker.sock --storage-driver aufs --tlsverify --tlscacert /etc/docker/ca.pem --tlscert /etc/docker/server.pem --tlskey /etc/docker/server-key.pem --label provider=digitalocean (code=exited, status=1/FAILURE)
 Main PID: 4943 (code=exited, status=1/FAILURE)

Jun 30 20:56:13 fernu systemd[1]: docker.service: Main process exited, code=exited, status=1/FAILURE
Jun 30 20:56:13 fernu systemd[1]: Failed to start Docker Application Container Engine.
Jun 30 20:56:13 fernu systemd[1]: docker.service: Unit entered failed state.
Jun 30 20:56:13 fernu systemd[1]: docker.service: Failed with result 'exit-code'.
Jun 30 20:56:13 fernu systemd[1]: docker.service: Service hold-off time over, scheduling restart.
Jun 30 20:56:13 fernu systemd[1]: Stopped Docker Application Container Engine.
Jun 30 20:56:13 fernu systemd[1]: docker.service: Start request repeated too quickly.
Jun 30 20:56:13 fernu systemd[1]: Failed to start Docker Application Container Engine.
</code>```

Any help would be appreciated

Update

It´s working with ubuntu 14:
--digitalocean-image=ubuntu-14-04-x64 so it seams like a problem with the default image (ubuntu-16-04-x64)

答:
This seems to be hitting a lot of people. TL;DR: There is a bug in docker-machine v0.12.0 and this issue can be resolved by upgrading.

Logging in to the DigitalOcean instance and running journalctl -xe provides more information:

```<code>-- Unit docker.service has begun starting up.
Jul 07 20:03:52 docker-sandbox docker[4930]: `docker daemon` is not supported on Linux. Please run `do
Jul 07 20:03:52 docker-sandbox systemd[1]: docker.service: Main process exited, code=exited, status=1/
Jul 07 20:03:52 docker-sandbox systemd[1]: Failed to start Docker Application Container Engine.
-- Subject: Unit docker.service has failed
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
</code>```

The key here is docker daemon is not supported on Linux. A bug in docker-machine's version comparison code caused an incorrect systemd unit file to be produced (located at /etc/systemd/system/docker.service.d/10-machine.conf) on certain versions of Ubuntu.

A fix has been committed and a new release (v0.12.1) was made.

You can grab the latest release at: https://github.com/docker/machine/releases/tag/v0.12.1

Body:
I´m using docker tools on windows.

create command was working perfectly last week and I managed to create a number of machines on Digital Ocean. Then I tried today with no success. I repeated the same command with different regions and I always get the same result:

λ docker-machine create -d digitalocean --digitalocean-access-token=MYTOKEN --digitalocean-region=ams2 vmname
Running pre-create checks...
Creating machine...
(fernu) Creating SSH key...
(fernu) Creating Digital Ocean droplet...
(fernu) Waiting for IP address to be assigned to the Droplet...
Waiting for machine to be running, this may take a few minutes...
Detecting operating system of created instance...
Waiting for SSH to be available...
Detecting the provisioner...
Provisioning with ubuntu(systemd)...
Installing Docker...
Copying certs to the local machine directory...
Copying certs to the remote machine...
Setting Docker configuration on the remote daemon...
Error creating machine: Error running provisioning: ssh command error:
command : sudo systemctl -f start docker
err     : exit status 1
output  : Job for docker.service failed because the control process exited with error code. See "systemctl status docker.service" and "journalctl -xe" for details.

If I execute the suggested command:

root@fernu:~# systemctl status docker.service
● docker.service - Docker Application Container Engine
   Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset: enabled)
  Drop-In: /etc/systemd/system/docker.service.d
           └─10-machine.conf
   Active: inactive (dead) (Result: exit-code) since Fri 2017-06-30 20:56:13 UTC; 8min ago
     Docs: https://docs.docker.com
  Process: 4943 ExecStart=/usr/bin/docker daemon -H tcp://0.0.0.0:2376 -H unix:///var/run/docker.sock --storage-driver aufs --tlsverify --tlscacert /etc/docker/ca.pem --tlscert /etc/docker/server.pem --tlskey /etc/docker/server-key.pem --label provider=digitalocean (code=exited, status=1/FAILURE)
 Main PID: 4943 (code=exited, status=1/FAILURE)

Jun 30 20:56:13 fernu systemd[1]: docker.service: Main process exited, code=exited, status=1/FAILURE
Jun 30 20:56:13 fernu systemd[1]: Failed to start Docker Application Container Engine.
Jun 30 20:56:13 fernu systemd[1]: docker.service: Unit entered failed state.
Jun 30 20:56:13 fernu systemd[1]: docker.service: Failed with result 'exit-code'.
Jun 30 20:56:13 fernu systemd[1]: docker.service: Service hold-off time over, scheduling restart.
Jun 30 20:56:13 fernu systemd[1]: Stopped Docker Application Container Engine.
Jun 30 20:56:13 fernu systemd[1]: docker.service: Start request repeated too quickly.
Jun 30 20:56:13 fernu systemd[1]: Failed to start Docker Application Container Engine.

Any help would be appreciated

Update

It´s working with ubuntu 14:
--digitalocean-image=ubuntu-14-04-x64 so it seams like a problem with the default image (ubuntu-16-04-x64)

Body:
This seems to be hitting a lot of people. TL;DR: There is a bug in docker-machine v0.12.0 and this issue can be resolved by upgrading.

Logging in to the DigitalOcean instance and running journalctl -xe provides more information:

-- Unit docker.service has begun starting up.
Jul 07 20:03:52 docker-sandbox docker[4930]: `docker daemon` is not supported on Linux. Please run `do
Jul 07 20:03:52 docker-sandbox systemd[1]: docker.service: Main process exited, code=exited, status=1/
Jul 07 20:03:52 docker-sandbox systemd[1]: Failed to start Docker Application Container Engine.
-- Subject: Unit docker.service has failed
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel

The key here is docker daemon is not supported on Linux. A bug in docker-machine's version comparison code caused an incorrect systemd unit file to be produced (located at /etc/systemd/system/docker.service.d/10-machine.conf) on certain versions of Ubuntu.

A fix has been committed and a new release (v0.12.1) was made.

You can grab the latest release at: https://github.com/docker/machine/releases/tag/v0.12.1


问:
How to send requests while receiving responses in IB API?
I don't quite understand how to go about using IB API Wrapper and Client streams. I understand that I am sending out requests to the IB server through the Client stream and am receiving the response through the Wrapper stream, but I would like to be able to implement a menu for the user such as "Press 'p' for open positions, etc." followed by a display of the server response and a prompt for another action.

```<code>from ibapi import wrapper
from ibapi.client import EClient
from ibapi.utils import iswrapper

# types
from ibapi.common import *
from ibapi.contract import *

class TestClient(EClient):
    def __init__(self, wrapper):
        EClient.__init__(self, wrapper)

class TestWrapper(wrapper.EWrapper):
    def __init__(self):
        wrapper.EWrapper.__init__(self)

class TestApp(TestWrapper, TestClient):
    def __init__(self):
        TestWrapper.__init__(self)
        TestClient.__init__(self, wrapper=self)

    def position(self, account: str, contract: Contract, position: float,
                 avgCost: float):
        """This event returns real-time positions for all accounts in
        response to the reqPositions() method."""

        super().position(account, contract, position, avgCost)
        print("Position.", account, "Symbol:", contract.symbol, "SecType:",
              contract.secType, "Currency:", contract.currency,
              "Position:", position, "Avg cost:", avgCost)

def main():
    app = TestApp()
    usr_in = ''

    app.connect("127.0.0.1", 7497, clientId=0)
    print("serverVersion:%s connectionTime:%s" % (app.serverVersion(),
                                              app.twsConnectionTime()))

    while(usr_in != 'exit'):
         usr_in = input('What to do next?')
         if usr_in == 'p':
             app.reqPositions()

    app.run()

if __name__ == '__main__':
    main()
</code>```

What ends up happening now is that the program asks for input, but does not display the server response until I exit the loop, after which it does display the response. I know I can include some logic within the position() function, but this is very limiting and there must be a better way to interact with the two streams. Also, a pointer to any further readings on the topic of streams like the ones used in IB API will be greatly appreciated.

答:
I figured it out! All needs to be done is to start two threads. One will be be handling the run() function of EClient, the other will be running the loop function of the app. Here is what the code would look like:</p>

```<code>from ibapi import wrapper
from ibapi.client import EClient
from ibapi.contract import *

import threading
import time

class TestApp(wrapper.EWrapper, EClient):
    def __init__(self):
        wrapper.EWrapper.__init__(self)
        EClient.__init__(self, wrapper=self)

        self.connect("127.0.0.1", 7497, clientId=0)
        print(f"serverVersion:{self.serverVersion()}
              connectionTime:{self.twsConnectionTime()}")

    def position(self, account: str, contract: Contract, position: float,
                 avgCost: float):
        """This event returns real-time positions for all accounts in
        response to the reqPositions() method."""

        super().position(account, contract, position, avgCost)
        print("Position.", account, "Symbol:", contract.symbol, "SecType:",
              contract.secType, "Currency:", contract.currency,
              "Position:", position, "Avg cost:", avgCost)

    def loop(self):
        while True:
            self.reqPositions()
            time.sleep(15)

def main():
    app = TestApp()

    reader_thread = threading.Thread(target=app.run)
    loop_thread = threading.Thread(target=app.loop)

    reader_thread.start()
    loop_thread.start()

if __name__ == '__main__':
    main()
</code>```

Body:
I don't quite understand how to go about using IB API Wrapper and Client streams. I understand that I am sending out requests to the IB server through the Client stream and am receiving the response through the Wrapper stream, but I would like to be able to implement a menu for the user such as "Press 'p' for open positions, etc." followed by a display of the server response and a prompt for another action.

from ibapi import wrapper
from ibapi.client import EClient
from ibapi.utils import iswrapper

# types
from ibapi.common import *
from ibapi.contract import *

class TestClient(EClient):
    def __init__(self, wrapper):
        EClient.__init__(self, wrapper)

class TestWrapper(wrapper.EWrapper):
    def __init__(self):
        wrapper.EWrapper.__init__(self)

class TestApp(TestWrapper, TestClient):
    def __init__(self):
        TestWrapper.__init__(self)
        TestClient.__init__(self, wrapper=self)

    def position(self, account: str, contract: Contract, position: float,
                 avgCost: float):
        """This event returns real-time positions for all accounts in
        response to the reqPositions() method."""

        super().position(account, contract, position, avgCost)
        print("Position.", account, "Symbol:", contract.symbol, "SecType:",
              contract.secType, "Currency:", contract.currency,
              "Position:", position, "Avg cost:", avgCost)

def main():
    app = TestApp()
    usr_in = ''

    app.connect("127.0.0.1", 7497, clientId=0)
    print("serverVersion:%s connectionTime:%s" % (app.serverVersion(),
                                              app.twsConnectionTime()))

    while(usr_in != 'exit'):
         usr_in = input('What to do next?')
         if usr_in == 'p':
             app.reqPositions()

    app.run()

if __name__ == '__main__':
    main()

What ends up happening now is that the program asks for input, but does not display the server response until I exit the loop, after which it does display the response. I know I can include some logic within the position() function, but this is very limiting and there must be a better way to interact with the two streams. Also, a pointer to any further readings on the topic of streams like the ones used in IB API will be greatly appreciated.

Body:
I figured it out! All needs to be done is to start two threads. One will be be handling the run() function of EClient, the other will be running the loop function of the app. Here is what the code would look like:

from ibapi import wrapper
from ibapi.client import EClient
from ibapi.contract import *

import threading
import time

class TestApp(wrapper.EWrapper, EClient):
    def __init__(self):
        wrapper.EWrapper.__init__(self)
        EClient.__init__(self, wrapper=self)

        self.connect("127.0.0.1", 7497, clientId=0)
        print(f"serverVersion:{self.serverVersion()}
              connectionTime:{self.twsConnectionTime()}")

    def position(self, account: str, contract: Contract, position: float,
                 avgCost: float):
        """This event returns real-time positions for all accounts in
        response to the reqPositions() method."""

        super().position(account, contract, position, avgCost)
        print("Position.", account, "Symbol:", contract.symbol, "SecType:",
              contract.secType, "Currency:", contract.currency,
              "Position:", position, "Avg cost:", avgCost)

    def loop(self):
        while True:
            self.reqPositions()
            time.sleep(15)

def main():
    app = TestApp()

    reader_thread = threading.Thread(target=app.run)
    loop_thread = threading.Thread(target=app.loop)

    reader_thread.start()
    loop_thread.start()

if __name__ == '__main__':
    main()


问:
Run code when pressing on the [x]
I am making a distributed concurrent game online using Java and Swing. I want to remove the player's icon from the game zone when the user press the [x] to close the window. How can i say to the VM to execute a function before terminating the process?</p>

答:
If you're using a JFrame, I think you should better write your own KeyEventDispatcher like described in that post: Unresponsive KeyListener for JFrame
If you're just adding a KeyListener to a JFrame and you have selectable components placed on it, you have to add the listener to all these components too, presumably recursively.

You can then detect when somebody presses x and then call the dispose function of the JFrame. If you're also adding a WindowListener to your JFrame, you can put some code in the windowClosing method that is called before the frame closes.

Title: Run code when pressing on the [x]


问:
Two branches made changes to the same file. How to commit the changes of the file made in one branch and push to github master branch?
I have 2 branches, one branch for a particular feature, and the master branch. Two branches made some changes to the same file. Now I only want to commit the changes made in the master branch and push to github, leaving the changes made in the feature branch behind. What should I do? </p>

答:
You can stash your changes in feature branch and checkout to master branch:

```<code>git stash
git checkout master
git add filename
git commit -m "..."
</code>```

After that, you can return to feature branch, recover your changes stashed, and continue working from there:

```<code>git checkout feature
git stash apply
</code>```

If you want to discard the changes made in that branch, you didn't need the git stash before and you can just delete that branch:

```<code>git branch -D feature
</code>```

Body:
You can stash your changes in feature branch and checkout to master branch:

git stash
git checkout master
git add filename
git commit -m "..."

After that, you can return to feature branch, recover your changes stashed, and continue working from there:

git checkout feature
git stash apply

If you want to discard the changes made in that branch, you didn't need the git stash before and you can just delete that branch:

git branch -D feature


问:
Pandas series case-insensitive matching and partial matching between values
I have the following operation to add a status showing where any string in a column of one dataframe column is present in a specified column of another dataframe. It looks like this:

```<code>df_one['Status'] = np.where(df_one.A.isin(df_two.A), 'Matched','Unmatched')
</code>```

This won't match if the string case is different. Is it possible to perform this operation while being case insensitive?

Also, is it possible return 'Matched' when a value in df_one.A ends with the full string from df_two.A? e.g. df_one.A abcdefghijkl -> df_two.A ijkl = 'Matched'

答:
You can do the first test by converting both strings to lowercase or uppercase (either works) inside the expression (as you aren't reassigning either column back to your DataFrames, the case conversion is only temporary):

```<code>df_one['Status'] = np.where(df_one.A.str.lower().isin(df_two.A.str.lower()), \
                            'Matched', 'Unmatched')
</code>```

You can perform your second test by checking whether each string in df_one.A ends with any of the strings in df_two.A, like so (assuming you still want a case-insensitive match):

```<code>df_one['Endswith_Status'] = np.where(df_one.A.str.lower().apply( \
                                      lambda x: any(x.endswith(i) for i in df_two.A.str.lower())), \
                                      'Matched', 'Unmatched')
</code>```

Body:
I have the following operation to add a status showing where any string in a column of one dataframe column is present in a specified column of another dataframe. It looks like this:

df_one['Status'] = np.where(df_one.A.isin(df_two.A), 'Matched','Unmatched')

This won't match if the string case is different. Is it possible to perform this operation while being case insensitive?

Also, is it possible return 'Matched' when a value in df_one.A ends with the full string from df_two.A? e.g. df_one.A abcdefghijkl -> df_two.A ijkl = 'Matched'

Body:
You can do the first test by converting both strings to lowercase or uppercase (either works) inside the expression (as you aren't reassigning either column back to your DataFrames, the case conversion is only temporary):

df_one['Status'] = np.where(df_one.A.str.lower().isin(df_two.A.str.lower()), \
                            'Matched', 'Unmatched')

You can perform your second test by checking whether each string in df_one.A ends with any of the strings in df_two.A, like so (assuming you still want a case-insensitive match):

df_one['Endswith_Status'] = np.where(df_one.A.str.lower().apply( \
                                      lambda x: any(x.endswith(i) for i in df_two.A.str.lower())), \
                                      'Matched', 'Unmatched')


问:
How to update data in each loop rather that all loop data shown at once in Android
How would I in this code show each loops data separately rather than it working through the loop then displaying the data (I have tried using timers but didn't work).</p>

```<code>int noStart = 20;
int minus = 5;
private void waitUntil(long time) {
    try {
        Thread.sleep(time);
    }
    catch (InterruptedException e) {
        //This is just here to handle an error without crashing
    }
}
public void number(View view){
        for(int loop = 0;noStart<loop;loop+=5){
            noStart -= minus;
            TextView tx  = (TextView) findViewById(R.id.number);
            tx.setText(String.valueOf(noStart));
            waitUntil(500);
        }
    }
</code>```

答:
As mentioned above, you can use a Handler and also set a delay interval in milliseconds.

The code below executes 5 times every 0.5 seconds without blocking the UI thread.

```<code>final Handler h = new Handler();

h.postDelayed(new Runnable() {

    private int counter = 0;

    public void run() {

        // Update your text view here
        ...

        if (++counter < 5) {
            h.postDelayed(this, 500);
        }
    }
}, 500);
</code>```

Body:
How would I in this code show each loops data separately rather than it working through the loop then displaying the data (I have tried using timers but didn't work).

int noStart = 20;
int minus = 5;
private void waitUntil(long time) {
    try {
        Thread.sleep(time);
    }
    catch (InterruptedException e) {
        //This is just here to handle an error without crashing
    }
}
public void number(View view){
        for(int loop = 0;noStart<loop;loop+=5){
            noStart -= minus;
            TextView tx  = (TextView) findViewById(R.id.number);
            tx.setText(String.valueOf(noStart));
            waitUntil(500);
        }
    }

Body:
As mentioned above, you can use a Handler and also set a delay interval in milliseconds.

The code below executes 5 times every 0.5 seconds without blocking the UI thread.

final Handler h = new Handler();

h.postDelayed(new Runnable() {

    private int counter = 0;

    public void run() {

        // Update your text view here
        ...

        if (++counter < 5) {
            h.postDelayed(this, 500);
        }
    }
}, 500);


问:
Why can’t variables be declared in a switch statement?
I want to know more about "Why can’t variables be declared in a switch statement?"

I read the post but i am not getting it exactly.
You can just declare variable inside switch but to decalre and initialize a variable or to declare object of class it gives complie time error.

Please explain me....

答:
There is a conflict here between language syntax and common sense.  For us humans, it looks like this code (taken from 1800 INFORMATION's answer) should work fine:

```<code>class A
{
  // has some non-trivial constructor and destructor
};

switch (x)
{
  case 1:
    A a;
    break;
  default:
    // do something else
}
</code>```

After all, the curly braces define the scope for a; it is only created if we enter case 1, it is destroyed immediately after leaving the case 1 block and it will never be used unless we enter case 1.  In fact, the case labels and the break instruction do not separate scopes, so a exists in all the block afterwards, even though it is logically unreachable.  And sure, there is no such thing as a case 1 block from a syntactic point of view.

If you think of the switch statement as a bunch of (structured) goto instructions in disguise, the scope problem becomes more evident:

```<code>{
  if (x == 1)
    goto 1;
  else
    goto default;

  1:
    A a;
    goto end;

  default:
    // do something else

  end:
}
</code>```

OwnerDisplayName: Omi

LastEditorDisplayName: mark

Body:
There is a conflict here between language syntax and common sense.  For us humans, it looks like this code (taken from 1800 INFORMATION's answer) should work fine:

class A
{
  // has some non-trivial constructor and destructor
};

switch (x)
{
  case 1:
    A a;
    break;
  default:
    // do something else
}

After all, the curly braces define the scope for a; it is only created if we enter case 1, it is destroyed immediately after leaving the case 1 block and it will never be used unless we enter case 1.  In fact, the case labels and the break instruction do not separate scopes, so a exists in all the block afterwards, even though it is logically unreachable.  And sure, there is no such thing as a case 1 block from a syntactic point of view.

If you think of the switch statement as a bunch of (structured) goto instructions in disguise, the scope problem becomes more evident:

{
  if (x == 1)
    goto 1;
  else
    goto default;

  1:
    A a;
    goto end;

  default:
    // do something else

  end:
}

OwnerDisplayName: Gorpik

LastEditorDisplayName: Gorpik


问:
Where clause on linq query against dictionary?
I have fixed the problem of it not listing the data which was related to a wrong field on the spawn dictionary but still i would like to question if the way I am approaching it is ok ?

I have a few checkboxs that if true should add check the item status and include it on the list.

So not really knowing what to do, this is what I came up with:

```<code>        HashSet<int> status = new HashSet<int>();
        if (OptionsForm.filterPlayer.Checked) status.Add(0);
        if (OptionsForm.filterEnemy.Checked) status.Add(1);
        if (OptionsForm.filterSummon.Checked) status.Add(2);
        if (OptionsForm.filterNPC.Checked) status.Add(3);
        if (OptionsForm.filterObject.Checked) status.Add(4);
        if (OptionsForm.filterMonster.Checked) status.Add(5);
        if (OptionsForm.filterGatherable.Checked) status.Add(6);
        if (OptionsForm.filterUnk.Checked) status.Add(7);

        var query = from SpawnList item in spawnEntities.Values
                    where status.Contains(item.Status)
                    orderby item.Name ascending
                    select item;
</code>```

But currently it is not returning me any errors or items that should have been returned.

spawnEntities is a dictionary with uint, SpawnList.

SpawnList is a simple class:

```<code>public class SpawnList
{
    public string Name { get; set; }
    public int Status { get; set; }
    // some more data not needed for the question
}
</code>```

答:
it was my mistake, the status on the
  dictionary was wrong in 1 field and i
  was not getting what I wanted after
  listing all the data I noticed it heh,
  but is it ok to do it like I am doing
  ?

To avoid such mistakes, I would use enumerations instead of ints - just define

```<code>enum SomeStatus
{
    Player,
    Enemy,
    <.etc.>
}
</code>```

and change

```<code>public int Status { get; set; }
</code>```

into

```<code>public SomeStatus Status { get; set; }
</code>```

Body:
I have fixed the problem of it not listing the data which was related to a wrong field on the spawn dictionary but still i would like to question if the way I am approaching it is ok ?

I have a few checkboxs that if true should add check the item status and include it on the list.

So not really knowing what to do, this is what I came up with:

        HashSet<int> status = new HashSet<int>();
        if (OptionsForm.filterPlayer.Checked) status.Add(0);
        if (OptionsForm.filterEnemy.Checked) status.Add(1);
        if (OptionsForm.filterSummon.Checked) status.Add(2);
        if (OptionsForm.filterNPC.Checked) status.Add(3);
        if (OptionsForm.filterObject.Checked) status.Add(4);
        if (OptionsForm.filterMonster.Checked) status.Add(5);
        if (OptionsForm.filterGatherable.Checked) status.Add(6);
        if (OptionsForm.filterUnk.Checked) status.Add(7);

        var query = from SpawnList item in spawnEntities.Values
                    where status.Contains(item.Status)
                    orderby item.Name ascending
                    select item;

But currently it is not returning me any errors or items that should have been returned.

spawnEntities is a dictionary with uint, SpawnList.

SpawnList is a simple class:

public class SpawnList
{
    public string Name { get; set; }
    public int Status { get; set; }
    // some more data not needed for the question
}

Body:
it was my mistake, the status on the
  dictionary was wrong in 1 field and i
  was not getting what I wanted after
  listing all the data I noticed it heh,
  but is it ok to do it like I am doing
  ?

To avoid such mistakes, I would use enumerations instead of ints - just define

enum SomeStatus
{
    Player,
    Enemy,
    <.etc.>
}

and change

public int Status { get; set; }

into

public SomeStatus Status { get; set; }


问:
VBA Excel: How to import CSV data into a range when the data array may differ
My macro imports CSV data saved from a DAQ app into range A2:AC12. The data "typically" includes 16 sets seen in the figure below from D2:D17. The set goes from 0,1,2,etc, and to the max of 15.
(FYI, I use A1 for fixed header info & E2:F17 is to translate the 0-15 set to 1-16 for graphing purposes).

However, the reason I say "typically" is because its possible that the DAQ app user can choose a different set of runs or skip some runs! Here is an example of when they performed the run and skipped sets 0-4, and choose 4-15 only. If I imported that data into my macro as currently is, this is what it would look like.

You can see here the problem where set 5 is at D2 (where set 0 should be). Additionally, a calculation array (N21:AC35) notices the empty spaces and results in DIV/0 error. Due to my limited knowledge of importing data, I use the most basic code for a simple import of the CSV into A2:

```<code> 'Imports CSV Data
With ActiveSheet.QueryTables.Add(Connection:= _
    "TEXT;" & myDirString, Destination:=Range("$A$2"))
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .TextFilePromptOnRefresh = False
    .TextFilePlatform = 437
    .TextFileStartRow = 1
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierDoubleQuote
    .TextFileConsecutiveDelimiter = False
    .TextFileTabDelimiter = False
    .TextFileSemicolonDelimiter = False
    .TextFileCommaDelimiter = True
    .TextFileSpaceDelimiter = False
    .TextFileColumnDataTypes = Array(1, 1, 1)
    .TextFileTrailingMinusNumbers = True
    .Refresh BackgroundQuery:=False
End With
</code>```

So the main question is how can I import the data, (whether it is a 0-15 set, a 5-15 set, or a 2-4-6-8-etc set), and still have it organized appropriately within that 0-15 rows? Should I rely on a FOR loop or IF statements somewhere? I'm perplexed about how to handle wide ranges of data like this and only used to fixed data runs.

Ideally, I would expect it to look like this. I manually manipulated the data as an example and okay with just putting in "n/a" for the empty non-run spaces:

答:
reading your post it and looking at the screenshots it looks like you always expect something in the range A1:A17. if that's so then you can run this after importing the data in your import macro:

```<code>For i = 2 To 17
    If ActiveSheet.Range("d" & i) <> i - 2 Then
        ActiveSheet.Range(i & ":" & i).Insert shift:=xlShiftDown
        With ActiveSheet.Range("a" & i & ":ac" & i)
            .Formula = "=na()"
            .Value = .Value
        End With
        ActiveSheet.Range("d" & i).Value = i - 2
    End If
Next i
'assuming your button is named 'Button 1'
'if you knew it was always the first shape made on the sheet then
'you could also access the button by index: Shapes(1)
with ActiveSheet.Shapes("Button 1")
    .Left = ActiveSheet.Range("b18").Left
    .Top = ActiveSheet.Range("b18").Top
End With
</code>```

Edit

Added a with statement after the for loop to place the top left of your button at cell b18

Body:
My macro imports CSV data saved from a DAQ app into range A2:AC12. The data "typically" includes 16 sets seen in the figure below from D2:D17. The set goes from 0,1,2,etc, and to the max of 15.
(FYI, I use A1 for fixed header info & E2:F17 is to translate the 0-15 set to 1-16 for graphing purposes).

However, the reason I say "typically" is because its possible that the DAQ app user can choose a different set of runs or skip some runs! Here is an example of when they performed the run and skipped sets 0-4, and choose 4-15 only. If I imported that data into my macro as currently is, this is what it would look like.

You can see here the problem where set 5 is at D2 (where set 0 should be). Additionally, a calculation array (N21:AC35) notices the empty spaces and results in DIV/0 error. Due to my limited knowledge of importing data, I use the most basic code for a simple import of the CSV into A2:

 'Imports CSV Data
With ActiveSheet.QueryTables.Add(Connection:= _
    "TEXT;" & myDirString, Destination:=Range("$A$2"))
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .TextFilePromptOnRefresh = False
    .TextFilePlatform = 437
    .TextFileStartRow = 1
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierDoubleQuote
    .TextFileConsecutiveDelimiter = False
    .TextFileTabDelimiter = False
    .TextFileSemicolonDelimiter = False
    .TextFileCommaDelimiter = True
    .TextFileSpaceDelimiter = False
    .TextFileColumnDataTypes = Array(1, 1, 1)
    .TextFileTrailingMinusNumbers = True
    .Refresh BackgroundQuery:=False
End With

So the main question is how can I import the data, (whether it is a 0-15 set, a 5-15 set, or a 2-4-6-8-etc set), and still have it organized appropriately within that 0-15 rows? Should I rely on a FOR loop or IF statements somewhere? I'm perplexed about how to handle wide ranges of data like this and only used to fixed data runs.

Ideally, I would expect it to look like this. I manually manipulated the data as an example and okay with just putting in "n/a" for the empty non-run spaces:

Body:
reading your post it and looking at the screenshots it looks like you always expect something in the range A1:A17. if that's so then you can run this after importing the data in your import macro:

For i = 2 To 17
    If ActiveSheet.Range("d" & i) <> i - 2 Then
        ActiveSheet.Range(i & ":" & i).Insert shift:=xlShiftDown
        With ActiveSheet.Range("a" & i & ":ac" & i)
            .Formula = "=na()"
            .Value = .Value
        End With
        ActiveSheet.Range("d" & i).Value = i - 2
    End If
Next i
'assuming your button is named 'Button 1'
'if you knew it was always the first shape made on the sheet then
'you could also access the button by index: Shapes(1)
with ActiveSheet.Shapes("Button 1")
    .Left = ActiveSheet.Range("b18").Left
    .Top = ActiveSheet.Range("b18").Top
End With

Edit

Added a with statement after the for loop to place the top left of your button at cell b18


答:
You can cherry pick those changes by the unique commit

```<code>git-cherry-pick 'commitId'
</code>```

Documentation found here

Title: Two branches made changes to the same file. How to commit the changes of the file made in one branch and push to github master branch?

Body: I have 2 branches, one branch for a particular feature, and the master branch. Two branches made some changes to the same file. Now I only want to commit the changes made in the master branch and push to github, leaving the changes made in the feature branch behind. What should I do?

Body:
You can cherry pick those changes by the unique commit

git-cherry-pick 'commitId'

Documentation found here


问:
std::set<Key, Comparator, Allocator>
I've tried to use set to keep some configurations in a trie lately.

I've found a doubt on the comparator, for instance :

```<code>    #include <iostream>
    #include <set>

    using namespace std;

    struct Node{
      int position;
      int reference;
      Node(int r, int p){
        this->position = p;
        this->reference = r;
      }
    };

    struct Node_c{
      const bool operator()(const Node& n1, const Node& n2){
        // return n1.reference != n2.reference;
        // i've tried some functions here, like n1.reference != n2.reference ? true : n1.position < n2.position;
      }
    };

    int main(){
      set<Node, Node_c> aNodes;

      aNodes.emplace(1,1);
      aNodes.emplace(1, 2); // i dont want to add this one, the reference already exists and the position is bigger than the last one
      aNodes.emplace(1, 0); // i want to replace the (1,1) for this one

      for(auto nd : aNodes){
        cout << nd.reference << ' ' << nd.position << '\n';
      }
    }
</code>```

How could I keep the nodes with the lesser positions in order but excluding the equals references?

thanks.

答:
This cannot be done with a single method of std::set, because it strictly requires its elements to have unique keys!

set.emplace either inserts an element or it doesn't, but it won't replace an existing element, see the documentation

The best solution for you would probably be either to use a std::map<int, int> where a position is mapped to reference and update the value if it becomes smaller, or keep using a std::set and write a custom method that first checks if the set contains an element and if yes, only replaces it if the new reference is smaller

Also, your comparator should compare for less-than (<), not for inequality (!=)

Title: std::set<Key, Comparator, Allocator>

Body:
I've tried to use set to keep some configurations in a trie lately.

I've found a doubt on the comparator, for instance :

    #include <iostream>
    #include <set>

    using namespace std;

    struct Node{
      int position;
      int reference;
      Node(int r, int p){
        this->position = p;
        this->reference = r;
      }
    };

    struct Node_c{
      const bool operator()(const Node& n1, const Node& n2){
        // return n1.reference != n2.reference;
        // i've tried some functions here, like n1.reference != n2.reference ? true : n1.position < n2.position;
      }
    };

    int main(){
      set<Node, Node_c> aNodes;

      aNodes.emplace(1,1);
      aNodes.emplace(1, 2); // i dont want to add this one, the reference already exists and the position is bigger than the last one
      aNodes.emplace(1, 0); // i want to replace the (1,1) for this one

      for(auto nd : aNodes){
        cout << nd.reference << ' ' << nd.position << '\n';
      }
    }

How could I keep the nodes with the lesser positions in order but excluding the equals references?

thanks.