问:
Nickname to DatabaseID
I started using TeamSpeak 3 PHP Framework from planetteamspeak.com.
I don't get it to add and delete a Servergroup of a client.
It always tells me "invalid ClientID" which means I'm missing something.

I tried many ways to get ID, but nothing worked. Would be nice if i can get the ID by clientname, but i don't know how to do it.

Also a manual entry is called as "invalid". here is my Code:

```<code><?php
require_once ("lib/TeamSpeak3/TeamSpeak3.php");
require_once ("config/config.php");

// goes into config later
date_default_timezone_set($config['timezone']);
// current time
$the_time = date('Y-m-d h:i a');
// setup connection
$ts3_VirtualServer = TeamSpeak3::factory("serverquery://" . $config["Username"] . ":" . $config["Password"] . "@" . $config["IP"] . ":" . $config["qPort"] . "/?server_port=" . $config["Port"] . "&nickname=" . $config["Nickname"] . "");
// query clientlist from virtual server
$arr_clientList = $ts3_VirtualServer->ClientList();
// walk through list of clients
foreach($arr_clientList as $client) {
    if ($client["client_type"] == 1) {
        continue;
    }
    echo $client . " benutzt " . $client["client_platform"] . ".\n";
    // fetch first connection of specified client ^
    $client_created = date('Y-m-d h:i a', $client->client_created);
    echo $the_time . ' Uhr lokal. ';
    echo "\n";
    echo $client_created . ' Client erstellt. ';
    $to_time = strtotime($the_time);
    $from_time = strtotime($client_created);
    echo "\n";
    echo $client . " ist ";
    if (round(abs($to_time - $from_time) / 86400, 2) >= 30) {
        echo "Stammgast. ";
        try {
            $sgid = "7";
            $ts3_VirtualServer->serverGroupClientDel($sgid, '12');
        }
        catch(Exception $e) {
            echo $e->getMessage();
        }
        try {
            $sgid = "13";
            $ts3_VirtualServer->serverGroupClientAdd($sgid, '12');
        }
        catch(Exception $e) {
            echo $e->getMessage();
        }
    }
    else if (round(abs($to_time - $from_time) / 86400, 2) >= 14) {
        echo "Member. ";
        try {
            $sgid = "29";
            $ts3_VirtualServer->serverGroupClientDel($sgid, '12');
        }
        catch(Exception $e) {
            echo $e->getMessage();
        }
        try {
            $sgid = "7";
            $ts3_VirtualServer->serverGroupClientAdd($sgid, '12');
        }
        catch(Exception $e) {
            echo $e->getMessage();
        }
    }
    else if (round(abs($to_time - $from_time) / 86400, 2) >= 7) {
        echo "Rookie. ";
        try {
            $sgid = "29";
            $ts3_VirtualServer->clientGetByName($client)->serverGroupClientAdd($sgid, '12');
        }
        catch(Exception $e) {
            echo $e->getMessage();
        }
    }
    echo "\n";
    echo 'Erster connect war ' . round(abs($to_time - $from_time) / 86400, 2) . ' Tage früher. ';
    echo "\n\n";
}
?>
</code>```

config.php:

```<code><?php

$config = array(); //Creates Config Array
$config["Username"] = "serveradmin";
$config["Password"] = "**********";
$config["IP"] = "***********"; //Server IP/Domain
$config["Port"] = "9987"; //Server Port
$config["qPort"] = "10011"; // Query Port, Default 10011
$config["Nickname"] = rawurlencode("Rangsystem".rand(1, 99)); // Random number & Convertes Botname to a URI friendly Format
$config["timezone"] = 'Europe/Berlin';
?>
</code>```

答:
I found my problem

```<code>$ts3_VirtualServer->serverGroupClientDel($sgid, $client);
</code>```

to

```<code>$ts3_VirtualServer->serverGroupClientDel($sgid, $client['client_database_id']);
</code>```

Title: Nickname to DatabaseID

Body:
I started using TeamSpeak 3 PHP Framework from planetteamspeak.com.
I don't get it to add and delete a Servergroup of a client.
It always tells me "invalid ClientID" which means I'm missing something.

I tried many ways to get ID, but nothing worked. Would be nice if i can get the ID by clientname, but i don't know how to do it.

Also a manual entry is called as "invalid". here is my Code:

<?php
require_once ("lib/TeamSpeak3/TeamSpeak3.php");
require_once ("config/config.php");

// goes into config later
date_default_timezone_set($config['timezone']);
// current time
$the_time = date('Y-m-d h:i a');
// setup connection
$ts3_VirtualServer = TeamSpeak3::factory("serverquery://" . $config["Username"] . ":" . $config["Password"] . "@" . $config["IP"] . ":" . $config["qPort"] . "/?server_port=" . $config["Port"] . "&nickname=" . $config["Nickname"] . "");
// query clientlist from virtual server
$arr_clientList = $ts3_VirtualServer->ClientList();
// walk through list of clients
foreach($arr_clientList as $client) {
    if ($client["client_type"] == 1) {
        continue;
    }
    echo $client . " benutzt " . $client["client_platform"] . ".\n";
    // fetch first connection of specified client ^
    $client_created = date('Y-m-d h:i a', $client->client_created);
    echo $the_time . ' Uhr lokal. ';
    echo "\n";
    echo $client_created . ' Client erstellt. ';
    $to_time = strtotime($the_time);
    $from_time = strtotime($client_created);
    echo "\n";
    echo $client . " ist ";
    if (round(abs($to_time - $from_time) / 86400, 2) >= 30) {
        echo "Stammgast. ";
        try {
            $sgid = "7";
            $ts3_VirtualServer->serverGroupClientDel($sgid, '12');
        }
        catch(Exception $e) {
            echo $e->getMessage();
        }
        try {
            $sgid = "13";
            $ts3_VirtualServer->serverGroupClientAdd($sgid, '12');
        }
        catch(Exception $e) {
            echo $e->getMessage();
        }
    }
    else if (round(abs($to_time - $from_time) / 86400, 2) >= 14) {
        echo "Member. ";
        try {
            $sgid = "29";
            $ts3_VirtualServer->serverGroupClientDel($sgid, '12');
        }
        catch(Exception $e) {
            echo $e->getMessage();
        }
        try {
            $sgid = "7";
            $ts3_VirtualServer->serverGroupClientAdd($sgid, '12');
        }
        catch(Exception $e) {
            echo $e->getMessage();
        }
    }
    else if (round(abs($to_time - $from_time) / 86400, 2) >= 7) {
        echo "Rookie. ";
        try {
            $sgid = "29";
            $ts3_VirtualServer->clientGetByName($client)->serverGroupClientAdd($sgid, '12');
        }
        catch(Exception $e) {
            echo $e->getMessage();
        }
    }
    echo "\n";
    echo 'Erster connect war ' . round(abs($to_time - $from_time) / 86400, 2) . ' Tage früher. ';
    echo "\n\n";
}
?>

config.php:

<?php

$config = array(); //Creates Config Array
$config["Username"] = "serveradmin";
$config["Password"] = "**********";
$config["IP"] = "***********"; //Server IP/Domain
$config["Port"] = "9987"; //Server Port
$config["qPort"] = "10011"; // Query Port, Default 10011
$config["Nickname"] = rawurlencode("Rangsystem".rand(1, 99)); // Random number & Convertes Botname to a URI friendly Format
$config["timezone"] = 'Europe/Berlin';
?>

Body:
I found my problem

$ts3_VirtualServer->serverGroupClientDel($sgid, $client);

to

$ts3_VirtualServer->serverGroupClientDel($sgid, $client['client_database_id']);


来源: stackexchange

问:
How to switch view controllers in swift?
I'm trying to switch from one UIViewController to another using code. Right now I have, </p>

```<code>self.presentViewController(ResultViewController(), animated: true, completion: nil)
</code>```

<p>All this is doing is taking me to a black screen instead of the ResultViewController. Any suggestions? </p>

答:
Swift 3

To present a controller modally

```<code>let vc = self.storyboard!.instantiateWithIdentifier("SecondViewController")
self.present(vc, animate: true, completion: nil)
</code>```

To show a controller

```<code>self.show(vc, sender: self)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to switch from one UIViewController to another using code. Right now I have,

self.presentViewController(ResultViewController(), animated: true, completion: nil)

All this is doing is taking me to a black screen instead of the ResultViewController. Any suggestions?

Body:
Swift 3

To present a controller modally

let vc = self.storyboard!.instantiateWithIdentifier("SecondViewController")
self.present(vc, animate: true, completion: nil)

To show a controller

self.show(vc, sender: self)


问:
Strange Shader Loading Error LWJGL 3
I have recently made a  project using LWJGL 3 but have run into a wall. I have looked all over but cannot seem to figure out why calling GL20.glShaderSource(shaderId, shaderCode) and then subsiquently GL20.glCompileShader(shaderId) returns an error. The error that I receive makes it appear as though lwjgl cannot discern the path to the shader files:

```<code>LWJGL Version 3.1.2 build 13
java.lang.Exception: ERROR COMPILING SHADER CODE: VERTEX SHADER FAILED TO
COMPILE WITH THE FOLLOWING ERRORS:
ERROR: 0:1: ERROR(#132) SYNTAX ERROR: "/" PARSE ERROR
ERROR: ERROR(#273) 1 COMPILATION ERRORS.  NO CODE GENERATED

at com.wilby.model.ShaderProgram.createShader(ShaderProgram.java:47)
at com.wilby.model.ShaderProgram.createVertexShader(ShaderProgram.java:24)
at com.wilby.Renderer.initialise(Renderer.java:62)
at com.wilby.Game.initialise(Game.java:46)
at com.wilby.Game.loop(Game.java:23)
at com.wilby.Main.run(Main.java:27)
at com.wilby.Main.main(Main.java:16)
</code>```

However it still makes this error even when the files do not need any prefix to reach it. Like I say, I am completely stumped.

The link to my project is here.

答: I found the solution. You have to read the file and use that as the string in the shader source method. Facepalm.</p>

Title: Strange Shader Loading Error LWJGL 3

Body:
I have recently made a  project using LWJGL 3 but have run into a wall. I have looked all over but cannot seem to figure out why calling GL20.glShaderSource(shaderId, shaderCode) and then subsiquently GL20.glCompileShader(shaderId) returns an error. The error that I receive makes it appear as though lwjgl cannot discern the path to the shader files:

LWJGL Version 3.1.2 build 13
java.lang.Exception: ERROR COMPILING SHADER CODE: VERTEX SHADER FAILED TO
COMPILE WITH THE FOLLOWING ERRORS:
ERROR: 0:1: ERROR(#132) SYNTAX ERROR: "/" PARSE ERROR
ERROR: ERROR(#273) 1 COMPILATION ERRORS.  NO CODE GENERATED

at com.wilby.model.ShaderProgram.createShader(ShaderProgram.java:47)
at com.wilby.model.ShaderProgram.createVertexShader(ShaderProgram.java:24)
at com.wilby.Renderer.initialise(Renderer.java:62)
at com.wilby.Game.initialise(Game.java:46)
at com.wilby.Game.loop(Game.java:23)
at com.wilby.Main.run(Main.java:27)
at com.wilby.Main.main(Main.java:16)

However it still makes this error even when the files do not need any prefix to reach it. Like I say, I am completely stumped.

The link to my project is here.


问:
How can I determine if an EF5 project is Code-First or Database-First?
I work on project that was created by another programmer the solution contains Entity Framework 5.

I can't figure out which Entity Framework workflow (Code-First or Database-First) it was created with:

Inside my project I have this class:

```<code>//------------------------------------------------------------------------------
// <auto-generated>
//    This code was generated from a template.
//
//    Manual changes to this file may cause unexpected behavior in your application.
//    Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace HummerMobile.Core.Data
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;

    public partial class MobileMapEntities : DbContext
    {
        public MobileMapEntities()
            : base("name=MobileMapEntities")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public DbSet<BaseLayer> BaseLayers { get; set; }
        public DbSet<MapDefinition> MapDefinitions { get; set; }
        public DbSet<MapLayer> MapLayers { get; set; }
        public DbSet<Map> Maps { get; set; }
        public DbSet<SearchConfig> SearchConfigs { get; set; }
        public DbSet<VectorLayer> VectorLayers { get; set; }
        public DbSet<WFSLayer> WFSLayers { get; set; }
        public DbSet<WMSLayer> WMSLayers { get; set; }
        public DbSet<PointFeature> PointFeatures { get; set; }
        public DbSet<PointFeatureAttachment> PointFeatureAttachments { get; set; }
    }
}
</code>```

But also I have some file with edmx extension.

Any idea how can I figure out by which Entity Framework attitude it was created?

答:
If there's an *.edmx file with the same definitions as the DbContext.tt / DbContext.cs files then it is Database-First (as Code-First never creates *.edmx files).

In your case, you said there's an *.edmx file - so it's probably Database-First.

Note that it is very possible the project contains two separate EF entity libraries, one using Database-First and the other using Code-First. Ensure that the classes are generated from .tt files that are reading from the *edmx file to be certain.

However it is not necessarily a choice between just those two - there is also "Code-First from Database" where the entity types are generated as C# directly from the database schema using tooling present in Visual Studio - generally you can spot this from the uniform and less-than-readable style code it generates.

Database-First:

Visual Studio's tooling inspects a live database schema and generates an .edmx file which defines the entities and their relationships.

The DbContext.tt T4 template then reads the edmx file to generate the entity classes in their own .cs files.

This approach can be more maintainable as the EDMX file can be updated incrementally and the entity types automatically regenerated.

Code-First:

No tooling required. You write everything by hand. No database is required.

This approach is only really suitable for smaller projects, in this author's opinion it's very impractical for large and complicated database designs. It has the advantage of supporting "Database Migrations" automatically but it requires extensive babysitting to handle cases where objects are renamed or when custom ETL logic is needed to transform data from one schema to another.

Code-First from Database:

Similar to "Database-First" except rather than generating an intermediate EDMX file the tooling generates the entity classes .cs files directly.

However the lack of an intermediate EDMX file means that incremental changes at design-time are not supported: the entire set of entity classes and DbContext code needs to be regenerated every time the database design changes - which can take a while for complicated databases, which is why Database-First is still very popular in line-of-business applications.

Body:
I work on project that was created by another programmer the solution contains Entity Framework 5.

I can't figure out which Entity Framework workflow (Code-First or Database-First) it was created with:

Inside my project I have this class:

//------------------------------------------------------------------------------
// <auto-generated>
//    This code was generated from a template.
//
//    Manual changes to this file may cause unexpected behavior in your application.
//    Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace HummerMobile.Core.Data
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;

    public partial class MobileMapEntities : DbContext
    {
        public MobileMapEntities()
            : base("name=MobileMapEntities")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public DbSet<BaseLayer> BaseLayers { get; set; }
        public DbSet<MapDefinition> MapDefinitions { get; set; }
        public DbSet<MapLayer> MapLayers { get; set; }
        public DbSet<Map> Maps { get; set; }
        public DbSet<SearchConfig> SearchConfigs { get; set; }
        public DbSet<VectorLayer> VectorLayers { get; set; }
        public DbSet<WFSLayer> WFSLayers { get; set; }
        public DbSet<WMSLayer> WMSLayers { get; set; }
        public DbSet<PointFeature> PointFeatures { get; set; }
        public DbSet<PointFeatureAttachment> PointFeatureAttachments { get; set; }
    }
}

But also I have some file with edmx extension.

Any idea how can I figure out by which Entity Framework attitude it was created?


问:
Click anchor element using javascript function
I know this has been covered elsewhere on this site, as well as many others, but I just can't seem to figure it out.

I have an anchor tag that I use to show a lightbox form:

```<code><a id="aNoData" href="#divNoData" class="fancybox">No Data</a>
</code>```

I want to click it using a javascript function:

```<code>function fnNoData()
{
    //  This line works
    alert("this line works");
    //  Neither of these lines work
    $('#aNoData').click();
     document.getElementById('aNoData').click();
}
</code>```

I'm calling the function from my code behind, like this:

```<code>ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "fnNoData()", true);
</code>```

When I do this, the first line (the alert box) shows fine. However, the other two lines (to click the anchor tag) do not. The non-working lines work great if I put them in my $(document).ready block (the anchor clicks on page load). So it seems that the lines to click my anchor work fine, just not in my function.

Can anyone see what I'm doing wrong?

答:
It took hours, but I finally brute-forced a solution.

As some repliers suggested, my code behind was trying to use the DOM before all elements were fully loaded. I got around that by changing the line in my code behind to this:

```<code>ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "$(window).load(function() {fnNoData();});", true);
</code>```

Body:
I know this has been covered elsewhere on this site, as well as many others, but I just can't seem to figure it out.

I have an anchor tag that I use to show a lightbox form:

No Data

I want to click it using a javascript function:

function fnNoData()
{
    //  This line works
    alert("this line works");
    //  Neither of these lines work
    $('#aNoData').click();
     document.getElementById('aNoData').click();
}

I'm calling the function from my code behind, like this:

ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "fnNoData()", true);

When I do this, the first line (the alert box) shows fine. However, the other two lines (to click the anchor tag) do not. The non-working lines work great if I put them in my $(document).ready block (the anchor clicks on page load). So it seems that the lines to click my anchor work fine, just not in my function.

Can anyone see what I'm doing wrong?

Body:
It took hours, but I finally brute-forced a solution.

As some repliers suggested, my code behind was trying to use the DOM before all elements were fully loaded. I got around that by changing the line in my code behind to this:

ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "$(window).load(function() {fnNoData();});", true);


问:
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>```

答:
Your code is fine, expect that withRowAnimation: doesn't expect a BOOL but a UITableViewRowAnimation member. Eg. UITableViewRowAnimationRight to let it slide out to the right side of the table.

Also: You just fetch the object from the array, you have to delete it! If its an mutable array, you can use [categoryArray removeObjectAtIndex:indexpath.row]

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

ContentLicense: CC BY-SA 2.5


问:
Scroll Div issue in cordova app
Hi i'm developing a cordova application for android and sometimes I have a scroll issue on a div with a table. The scroll has a strange logarithm movement. Someone knows how to solve it?</p>

答:
This issue might be caused by the Android emulator. Check out if that weird scrolling is also present on a real device. It should not.

In my case I used the emulator for the Nexus 5x and got that strange "logarithmic" scrolling. When running my the very same app on a real Nexus 5x everything is fine.

Title: Scroll Div issue in cordova app


问:
Reindexing 5M items in elastic search through Postman: times out
I have around 5 Million items in my index v1. I created a new index v2 with slight changes.
I am trying to reindex all the items in v1 --> v2.

```<code>curl -XPOST 'localhost:9200/_reindex?pretty' -H 'Content-Type: application/json' -d'
{
  "source": {
    "index": "twitter"
  },
  "dest": {
    "index": "new_twitter"
  }
}
'
</code>```

When I tried this, only 1.6 Million items are re indexed. The operation times out. How do I work around it ?

答: You should use the wait_for_completion=false parameter mentioned in the reindex docs. It allows you to run the reindex request in the background without your HTTP client being forced to wait and block and potentially time out.

Body:
I have around 5 Million items in my index v1. I created a new index v2 with slight changes.
I am trying to reindex all the items in v1 --> v2.

curl -XPOST 'localhost:9200/_reindex?pretty' -H 'Content-Type: application/json' -d'
{
  "source": {
    "index": "twitter"
  },
  "dest": {
    "index": "new_twitter"
  }
}
'

When I tried this, only 1.6 Million items are re indexed. The operation times out. How do I work around it ?


问:
Apache storm can't access UI
I have apache-storm-1.1.0,
try to get storm UI on localhost:8080 and have this:

org.apache.storm.utils.NimbusLeaderNotFoundException: Could not find leader nimbus from seed hosts [localhost]. Did you specify a valid list of nimbus hosts for config nimbus.seeds?
    at org.apache.storm.utils.NimbusClient.getConfiguredClientAs(NimbusClient.java:111)

Also can't kill storm topology from comand line,have the same error message
Please help me, my storm.yaml:

```<code>storm.zookeeper.servers:
 - "localhost"
storm.local.dir: "/home/igor/Downloads/apache-storm-1.1.0/bin/data"
nimbus.host: "localhost"
supervisor.slots.ports:
 - 6700
 - 6701
 - 6702
 - 6703
nimbus.seeds : ["localhost"]
</code>```

答:
Sounds like your nimbus server isn't running. Take a look at how to setup a storm cluster.

From your master machine run the following to start nimbus:

```<code>bin/storm nimbus
</code>```

Title: Apache storm can't access UI

Body:
I have apache-storm-1.1.0,
try to get storm UI on localhost:8080 and have this:

org.apache.storm.utils.NimbusLeaderNotFoundException: Could not find leader nimbus from seed hosts [localhost]. Did you specify a valid list of nimbus hosts for config nimbus.seeds?
    at org.apache.storm.utils.NimbusClient.getConfiguredClientAs(NimbusClient.java:111)

Also can't kill storm topology from comand line,have the same error message
Please help me, my storm.yaml:

storm.zookeeper.servers:
 - "localhost"
storm.local.dir: "/home/igor/Downloads/apache-storm-1.1.0/bin/data"
nimbus.host: "localhost"
supervisor.slots.ports:
 - 6700
 - 6701
 - 6702
 - 6703
nimbus.seeds : ["localhost"]

Body:
Sounds like your nimbus server isn't running. Take a look at how to setup a storm cluster.

From your master machine run the following to start nimbus:

bin/storm nimbus


问:
Plot 3D each component of a given function (in Matlab/Octave)
I need to plot each component of a function f over a square Q=[0,1]x[0,1]

```<code>   f   = @(x,y)  [-0.5*x + 0.25  ;  -0.5*y + 0.25];
</code>```

If I have a scalar function (with one component) g:

```<code>   g   = @(x,y)  -0.5*x + 0.25;
</code>```

plot is easy with the following:

```<code>   xxx=[0:0.01:1];
   yyy=[0:0.01:1];
   [xxx yyy]=meshgrid(xxx,yyy);
   surfc(xxx,yyy,g(xxx,yyy))
</code>```

But, how can I plot each component of a vector function f over the same set Q?

```<code>   f   = @(x,y)  [-0.5*x + 0.25  ;  -0.5*y + 0.25];
</code>```

答:
If you're happy visualising the results as a vector field, then you can do it like this:

```<code>f = @(z) -0.5 .* z + 0.25;
[X, Y] = meshgrid (0:0.01:1, 0:0.01:1);
quiver (X, Y, f(X), f(Y));
</code>```

If your f_x and f_y components aren't necessarily identical, you can split them (meshgrid step implied):

```<code>f_x = @(x) -0.5 .* x + 0.25;
f_y = @(y) -0.5 .* y + 0.25;
quiver (X, Y, f_x(X), f_y(Y));
</code>```

If you really, really need to have them both as a single non-vectorizable function, then you can get around this using arrayfun:

```<code>f   = @(x,y)  [-0.5*x + 0.25  ;  -0.5*y + 0.25];
quiver(X, Y, arrayfun(@(x) f(x,0)(1), X), arrayfun(@(y) f(0,y)(2), Y));
</code>```

Result:

Body:
I need to plot each component of a function f over a square Q=[0,1]x[0,1]

   f   = @(x,y)  [-0.5*x + 0.25  ;  -0.5*y + 0.25];

If I have a scalar function (with one component) g:

   g   = @(x,y)  -0.5*x + 0.25;

plot is easy with the following:

   xxx=[0:0.01:1];
   yyy=[0:0.01:1];
   [xxx yyy]=meshgrid(xxx,yyy);
   surfc(xxx,yyy,g(xxx,yyy))

But, how can I plot each component of a vector function f over the same set Q?

   f   = @(x,y)  [-0.5*x + 0.25  ;  -0.5*y + 0.25];

Body:
If you're happy visualising the results as a vector field, then you can do it like this:

f = @(z) -0.5 .* z + 0.25;
[X, Y] = meshgrid (0:0.01:1, 0:0.01:1);
quiver (X, Y, f(X), f(Y));

If your f_x and f_y components aren't necessarily identical, you can split them (meshgrid step implied):

f_x = @(x) -0.5 .* x + 0.25;
f_y = @(y) -0.5 .* y + 0.25;
quiver (X, Y, f_x(X), f_y(Y));

If you really, really need to have them both as a single non-vectorizable function, then you can get around this using arrayfun:

f   = @(x,y)  [-0.5*x + 0.25  ;  -0.5*y + 0.25];
quiver(X, Y, arrayfun(@(x) f(x,0)(1), X), arrayfun(@(y) f(0,y)(2), Y));

Result:


问:
Facing issue with Guava Cache
I'm using Google Guava Cache + Spring cache abstraction for caching purpose.
I'm trying to make use of Guava's Loading Cache interface for the same.

I know Spring provides support for Guava Cache, but I was wondering whether I can make use of spring's cacheable annotation alongwith Loading Cache?

Basically I wanted to keep the business layer separate from the Cache.

Kindly help. Thanks.

答:
Guava Cache is deprecated. If you'd existing code, that'd be another matter, but for new code, use Caffeine.

Put a @Cacheable("myCacheName") on the method that you want to cache the return value for.

Put a @EnableCaching on your application class if using Spring Boot, otherwise on some @Configuration class.

Set the spec in application.properties if using Spring Boot, like so: spring.cache.caffeine.spec=maximumSize=10000,expireAfterWrite=5m. If not using Boot, use @PropertySources annotation on the same class as in #3 above.

Add org.springframework.boot:spring-boot-starter-cache and com.github.ben-manes.caffeine:caffeine to your build file. If not using Boot, you'll need to set up the dependencies differently.

You're done.

Title: Facing issue with Guava Cache


问:
how to use LookUpRecord processor?
I tried to join two csv file based on id with respect to the below reference.

How to join two CSVs with Apache Nifi

i'm using NiFi-1.3.0

Now i have two csv files.

1.custom.csv

```<code>No,Name,ID,Age
1,Hik,2201,33
2,Kio,3300,22
</code>```

2.gender.csv

```<code>ID,Name,Sex
2201,Hik,Male
3300,Kio,Female
</code>```

I try to combine those tables with "ID" like following endresult.

```<code>No,Name,Sex,ID,Age
1,Hik,Male,2201,33
2,Kio,Female,3300,22
</code>```

I have using following processor structure.

```<code>GetFile-SplitText-ExtractText-LookUpRecord-PutFile
</code>```

In that lookup record i have configured

```<code>RecordReader = "CSVReader"
RecordWriter="FreeFormTextRecordSetWriter"
LookUpService="SimpleCSVFileLookUpService"

ResultRecordPath-->/Key
key-->/ID
</code>```

In that LookUpService i have given path of the "gender.csv" and setted LookUpKeyColumn and LookUpValueColumn to be "ID".

In that FreeFormTextRecordSetWriter i have given text value"${No},${Name},${ID},${Age},${Sex}"

It yields below result only.

```<code>No,Name,ID,Age,
1,Hik,2201,33,
2,Kio,3300,22,
</code>```

It doesn't have "sex" column.

I think i haven't configured correctly.

i don't know how to use ResultRecordPath & one dynamic attribute(Key)  specification in LookUpRecord?

Can anyone guide me to solve my issue?

答:
This was asked and responded to on the apache nifi mailing list.

https://lists.apache.org/thread.html/5041018de5a5be773055bb2709427eed4131c3923262b55051fb1324@%3Cusers.nifi.apache.org%3E

Title: how to use LookUpRecord processor?

Body:
I tried to join two csv file based on id with respect to the below reference.

How to join two CSVs with Apache Nifi

i'm using NiFi-1.3.0

Now i have two csv files.

1.custom.csv

No,Name,ID,Age
1,Hik,2201,33
2,Kio,3300,22

2.gender.csv

ID,Name,Sex
2201,Hik,Male
3300,Kio,Female

I try to combine those tables with "ID" like following endresult.

No,Name,Sex,ID,Age
1,Hik,Male,2201,33
2,Kio,Female,3300,22

I have using following processor structure.

GetFile-SplitText-ExtractText-LookUpRecord-PutFile

In that lookup record i have configured

RecordReader = "CSVReader"
RecordWriter="FreeFormTextRecordSetWriter"
LookUpService="SimpleCSVFileLookUpService"

ResultRecordPath-->/Key
key-->/ID

In that LookUpService i have given path of the "gender.csv" and setted LookUpKeyColumn and LookUpValueColumn to be "ID".

In that FreeFormTextRecordSetWriter i have given text value"${No},${Name},${ID},${Age},${Sex}"

It yields below result only.

No,Name,ID,Age,
1,Hik,2201,33,
2,Kio,3300,22,

It doesn't have "sex" column.

I think i haven't configured correctly.

i don't know how to use ResultRecordPath & one dynamic attribute(Key)  specification in LookUpRecord?

Can anyone guide me to solve my issue?


问:
Cross in Zapf Dingbats not rendering in iText 7 PDF
I'm constructing a PDF file using iText 7, in an ASP.NET web application written in VB.

Using the following code to render a tick/check mark in a table cell works correctly:

```<code>Dim symbolFont = PdfFontFactory.CreateFont(FontConstants.ZAPFDINGBATS, PdfEncodings.ZAPFDINGBATS)

New Cell().Add(New Paragraph().Add(New Text(Convert.ToChar(&H2713)))).SetFont(symbolFont)
</code>```

However, when I replace the unicode with &H2715 nothing is rendered. 2715 should be a cross, as per this PDF: http://www.unicode.org/charts/PDF/U2700.pdf

1) Why does a cross not render when I change the code to 2715?

2) How do I render a tick or cross using iText 7?

答:
Use this code for a check mark:

```<code>Dim symbolFont = PdfFontFactory.CreateFont(FontConstants.ZAPFDINGBATS, PdfEncodings.WINANSI)

New Cell().Add(New Paragraph().Add(New Text(Convert.ToChar(&H51)))).SetFont(symbolFont)
</code>```

And this piece for cross:

```<code>New Cell().Add(New Paragraph().Add(New Text(Convert.ToChar(&H53)))).SetFont(symbolFont)
</code>```

Body:
I'm constructing a PDF file using iText 7, in an ASP.NET web application written in VB.

Using the following code to render a tick/check mark in a table cell works correctly:

Dim symbolFont = PdfFontFactory.CreateFont(FontConstants.ZAPFDINGBATS, PdfEncodings.ZAPFDINGBATS)

New Cell().Add(New Paragraph().Add(New Text(Convert.ToChar(&H2713)))).SetFont(symbolFont)

However, when I replace the unicode with &H2715 nothing is rendered. 2715 should be a cross, as per this PDF: http://www.unicode.org/charts/PDF/U2700.pdf

1) Why does a cross not render when I change the code to 2715?

2) How do I render a tick or cross using iText 7?

Body:
Use this code for a check mark:

Dim symbolFont = PdfFontFactory.CreateFont(FontConstants.ZAPFDINGBATS, PdfEncodings.WINANSI)

New Cell().Add(New Paragraph().Add(New Text(Convert.ToChar(&H51)))).SetFont(symbolFont)

And this piece for cross:

New Cell().Add(New Paragraph().Add(New Text(Convert.ToChar(&H53)))).SetFont(symbolFont)


问:
watchOS SKScene.convertPoint(fromView:) unavailable?
I'm working on a watchOS SpriteKit project. I know I can get the location of a tap within the displayed scene using WKTapGestureRecognizer, but I noticed that SKScene.convertPoint(fromView point:) is unavailable in watchOS.

So, how do I convert the CGPoint provided by WKTapGestureRecognizer.locationInObject() to a point in the SpriteKit scene?

答:
See https://developer.apple.com/library/content/samplecode/HelloGameKit/Listings/HelloGameKit_WatchKit_Extension_GameScene_swift.html

It will show you how to develop SpriteKit apps for apple watch.  There is too much code to explain what is going on here.  But the basic jist of it looks like your node.position is your location's position, no need to convert


问:
WPF/MVVM - how to handle double-click on TreeViewItems in the ViewModel?
(Note - this is a re-post as my first question got posted under wrong headline: Here Sorry!)

I have a standard WPF treeview and have bound items to view model classes.

I now wish to handle behaviour when items are double-clicked (opening documents visual-studio-style).

I can get event-handler to fire in the control housing the treeview (xaml shown), but how do I bind to specific behaviour on the view model classes - e.g. ProjectViewModel?

Preferable bound to ICommand-implementer, as this is used elsewhere...

```<code><TreeView ItemsSource="{Binding Projects}" MouseDoubleClick="TreeView_MouseDoubleClick">
    <TreeView.ItemContainerStyle>
        <!--
This Style binds a TreeViewItem to a TreeViewItemViewModel.
-->
        <Style TargetType="{x:Type TreeViewItem}">
            <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" />
            <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
            <Setter Property="FontWeight" Value="Normal" />
            <Style.Triggers>
                <Trigger Property="IsSelected" Value="True">
                    <Setter Property="FontWeight" Value="Bold" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </TreeView.ItemContainerStyle>

    <TreeView.Resources>
        <HierarchicalDataTemplate DataType="{x:Type Implementations:ProjectViewModel}" ItemsSource="{Binding Children}">
            <StackPanel Orientation="Horizontal">
                <Image Width="16" Height="16" Margin="3,0" Source="Images\Region.png" />
                <TextBlock Text="{Binding DisplayName}" />
            </StackPanel>
        </HierarchicalDataTemplate>

        <HierarchicalDataTemplate DataType="{x:Type Implementations:PumpViewModel}" ItemsSource="{Binding Children}">
            <StackPanel Orientation="Horizontal">
                <Image Width="16" Height="16" Margin="3,0" Source="Images\State.png" />
                <TextBlock Text="{Binding Name}" />
            </StackPanel>
        </HierarchicalDataTemplate>

        <DataTemplate DataType="{x:Type Implementations:PumpDesignViewModel}">
            <StackPanel Orientation="Horizontal">
                <Image Width="16" Height="16" Margin="3,0" Source="Images\City.png" />
                <TextBlock Text="{Binding Name}" />
            </StackPanel>
        </DataTemplate>
    </TreeView.Resources>
</TreeView>
</code>```

答:
Updating my answer a bit.

I've tried alot of different approaches for this and I still feel like Attached Behaviors is the best solution. Although it might look like alot of overhead in the begining it really isn't. I keep all of my behaviors for ICommands in the same place and whenever I need support for another event it is just a matter of copy/paste and change the event in the PropertyChangedCallback.

I also added the optional support for CommandParameter.

In the designer it is just a matter of selecting the desired event

You can set this either on TreeView, TreeViewItem or any other place that you like.

Example. Set it on the TreeView

```<code><TreeView commandBehaviors:MouseDoubleClick.Command="{Binding YourCommand}"
          commandBehaviors:MouseDoubleClick.CommandParameter="{Binding}"
          .../>
</code>```

Example. Set it on TreeViewItem

```<code><TreeView ItemsSource="{Binding Projects}">
    <TreeView.ItemContainerStyle>
        <Style TargetType="{x:Type TreeViewItem}">
            <Setter Property="commandBehaviors:MouseDoubleClick.Command"
                    Value="{Binding YourCommand}"/>
            <Setter Property="commandBehaviors:MouseDoubleClick.CommandParameter"
                    Value="{Binding}"/>
        </Style>
    </TreeView.ItemContainerStyle>
</TreeView>
</code>```

And here is the Attached Behavior MouseDoubleClick

```<code>public class MouseDoubleClick
{
    public static DependencyProperty CommandProperty =
        DependencyProperty.RegisterAttached("Command",
        typeof(ICommand),
        typeof(MouseDoubleClick),
        new UIPropertyMetadata(CommandChanged));

    public static DependencyProperty CommandParameterProperty =
        DependencyProperty.RegisterAttached("CommandParameter",
                                            typeof(object),
                                            typeof(MouseDoubleClick),
                                            new UIPropertyMetadata(null));

    public static void SetCommand(DependencyObject target, ICommand value)
    {
        target.SetValue(CommandProperty, value);
    }

    public static void SetCommandParameter(DependencyObject target, object value)
    {
        target.SetValue(CommandParameterProperty, value);
    }
    public static object GetCommandParameter(DependencyObject target)
    {
        return target.GetValue(CommandParameterProperty);
    }

    private static void CommandChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
    {
        Control control = target as Control;
        if (control != null)
        {
            if ((e.NewValue != null) && (e.OldValue == null))
            {
                control.MouseDoubleClick += OnMouseDoubleClick;
            }
            else if ((e.NewValue == null) && (e.OldValue != null))
            {
                control.MouseDoubleClick -= OnMouseDoubleClick;
            }
        }
    }

    private static void OnMouseDoubleClick(object sender, RoutedEventArgs e)
    {
        Control control = sender as Control;
        ICommand command = (ICommand)control.GetValue(CommandProperty);
        object commandParameter = control.GetValue(CommandParameterProperty);
        command.Execute(commandParameter);
    }
}
</code>```

Body:
(Note - this is a re-post as my first question got posted under wrong headline: Here Sorry!)

I have a standard WPF treeview and have bound items to view model classes.

I now wish to handle behaviour when items are double-clicked (opening documents visual-studio-style).

I can get event-handler to fire in the control housing the treeview (xaml shown), but how do I bind to specific behaviour on the view model classes - e.g. ProjectViewModel?

Preferable bound to ICommand-implementer, as this is used elsewhere...

<TreeView ItemsSource="{Binding Projects}" MouseDoubleClick="TreeView_MouseDoubleClick">
    <TreeView.ItemContainerStyle>

        </Style>
    </TreeView.ItemContainerStyle>

    <TreeView.Resources>
        <HierarchicalDataTemplate DataType="{x:Type Implementations:ProjectViewModel}" ItemsSource="{Binding Children}">
            <StackPanel Orientation="Horizontal">
                <Image Width="16" Height="16" Margin="3,0" Source="Images\Region.png" />
                <TextBlock Text="{Binding DisplayName}" />
            </StackPanel>
        </HierarchicalDataTemplate>

        <HierarchicalDataTemplate DataType="{x:Type Implementations:PumpViewModel}" ItemsSource="{Binding Children}">
            <StackPanel Orientation="Horizontal">
                <Image Width="16" Height="16" Margin="3,0" Source="Images\State.png" />
                <TextBlock Text="{Binding Name}" />
            </StackPanel>
        </HierarchicalDataTemplate>

        <DataTemplate DataType="{x:Type Implementations:PumpDesignViewModel}">
            <StackPanel Orientation="Horizontal">
                <Image Width="16" Height="16" Margin="3,0" Source="Images\City.png" />
                <TextBlock Text="{Binding Name}" />
            </StackPanel>
        </DataTemplate>
    </TreeView.Resources>
</TreeView>

Body:
Updating my answer a bit.

I've tried alot of different approaches for this and I still feel like Attached Behaviors is the best solution. Although it might look like alot of overhead in the begining it really isn't. I keep all of my behaviors for ICommands in the same place and whenever I need support for another event it is just a matter of copy/paste and change the event in the PropertyChangedCallback.

I also added the optional support for CommandParameter.

In the designer it is just a matter of selecting the desired event

You can set this either on TreeView, TreeViewItem or any other place that you like.

Example. Set it on the TreeView

<TreeView commandBehaviors:MouseDoubleClick.Command="{Binding YourCommand}"
          commandBehaviors:MouseDoubleClick.CommandParameter="{Binding}"
          .../>

Example. Set it on TreeViewItem

<TreeView ItemsSource="{Binding Projects}">
    <TreeView.ItemContainerStyle>
        <Style TargetType="{x:Type TreeViewItem}">
            <Setter Property="commandBehaviors:MouseDoubleClick.Command"
                    Value="{Binding YourCommand}"/>
            <Setter Property="commandBehaviors:MouseDoubleClick.CommandParameter"
                    Value="{Binding}"/>
        </Style>
    </TreeView.ItemContainerStyle>
</TreeView>

And here is the Attached Behavior MouseDoubleClick

public class MouseDoubleClick
{
    public static DependencyProperty CommandProperty =
        DependencyProperty.RegisterAttached("Command",
        typeof(ICommand),
        typeof(MouseDoubleClick),
        new UIPropertyMetadata(CommandChanged));

    public static DependencyProperty CommandParameterProperty =
        DependencyProperty.RegisterAttached("CommandParameter",
                                            typeof(object),
                                            typeof(MouseDoubleClick),
                                            new UIPropertyMetadata(null));

    public static void SetCommand(DependencyObject target, ICommand value)
    {
        target.SetValue(CommandProperty, value);
    }

    public static void SetCommandParameter(DependencyObject target, object value)
    {
        target.SetValue(CommandParameterProperty, value);
    }
    public static object GetCommandParameter(DependencyObject target)
    {
        return target.GetValue(CommandParameterProperty);
    }

    private static void CommandChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
    {
        Control control = target as Control;
        if (control != null)
        {
            if ((e.NewValue != null) && (e.OldValue == null))
            {
                control.MouseDoubleClick += OnMouseDoubleClick;
            }
            else if ((e.NewValue == null) && (e.OldValue != null))
            {
                control.MouseDoubleClick -= OnMouseDoubleClick;
            }
        }
    }

    private static void OnMouseDoubleClick(object sender, RoutedEventArgs e)
    {
        Control control = sender as Control;
        ICommand command = (ICommand)control.GetValue(CommandProperty);
        object commandParameter = control.GetValue(CommandParameterProperty);
        command.Execute(commandParameter);
    }
}


问:
Opening a PDF embedded in iframe in chrome with content security policy > plugin-types
I have the CSP (Content-security-policy) plugin-types policy set to white-list pdf type as below. When trying to open a PDF file in iframe with src attribute, It is working well with browsers IE 11, and Firefox 47+ but failing in Chrome 50+. What else is required to make it working in chrome?

```<code>Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; object-src 'self'; style-src 'self'; frame-src 'self' plugin-types application/pdf;
</code>```

Error in chrome console

```<code>Resource interpreted as Document but transferred with MIME type application/pdf
Refused to load 'http://127.0.0.1/module123/open.do?id=10000' (MIME type '') because it violates the following Content Security Policy Directive: 'plugin-types application/pdf'. When enforcing the 'plugin-types' directive, the plugin's media type must be explicitly declared with a 'type' attribute on the containing element (e.g. '<object type="[TYPE GOES HERE]" ...>').
</code>```

答:
I had a similar problem.

To resolve the problem, I needed to add blob: to the object-src directive.

Also, I did not need to specify plugin-type.

So it would be:

Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; object-src 'self' blob:; style-src 'self'; frame-src 'self';

Body:
I have the CSP (Content-security-policy) plugin-types policy set to white-list pdf type as below. When trying to open a PDF file in iframe with src attribute, It is working well with browsers IE 11, and Firefox 47+ but failing in Chrome 50+. What else is required to make it working in chrome?

Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; object-src 'self'; style-src 'self'; frame-src 'self' plugin-types application/pdf;

Error in chrome console

Resource interpreted as Document but transferred with MIME type application/pdf
Refused to load 'http://127.0.0.1/module123/open.do?id=10000' (MIME type '') because it violates the following Content Security Policy Directive: 'plugin-types application/pdf'. When enforcing the 'plugin-types' directive, the plugin's media type must be explicitly declared with a 'type' attribute on the containing element (e.g. '<object type="[TYPE GOES HERE]" ...>').


问:
can I add paramter to uri in kong api
I want to add a paramter to the uri defined in kong...

example: http://localhost:8000/gam/v1/start/{topic}

is it possible to perform this with kong apis?

答: Have a look at https://github.com/Mashape/kong/issues/677#issuecomment-313798340 - I think that'll help once it is released in Kong.</p>

Title: can I add paramter to uri in kong api


问:
List Of - Insert only if GUID doesn't exist
Before I add an item to my List (Of clsUser), I check if no clsUser with the same GUID exists in my list.

Currently I check for the existance like this:

```<code>Public Function GUIDExists(ByRef uList As List (Of clsUser), ByVal uGUID As String) As Boolean

    For Each nItem As clsUser In uList
        If nItem.GUID = uGUID Then
            Return True
        End If
    Next

    Return False

End Function
</code>```

I would very much like simplify it and add this check to the List (Of clsUser) so that I don't have to write the same code over and over again.

Some like MyList.AddIfGUIDDoesntExists(nNewUser)

Is this possible?
If yes, could anybody tell me how this would be done?

答:
```<code>Imports System.Runtime.CompilerServices

Public Module ExtensionMethods
    <Extension()>
    Public Sub AddIfGUIDDoesntExists(ByRef inputList As List(Of clsUser), _
             ByVal item As clsUser)
        Dim contains As Boolean = False
        For Each i As clsUser In inputList
            If (i.GUID = item.GUID) Then
                 contains = True
                 Exit For
            End If
        Next
        If Not contains
            inputList.Add(item)
        End If
    End Sub
End Module
</code>```

Usage:

```<code>MyList.AddIfGUIDDoesntExists(nNewUser)
</code>```

Body:
Before I add an item to my List (Of clsUser), I check if no clsUser with the same GUID exists in my list.

Currently I check for the existance like this:

Public Function GUIDExists(ByRef uList As List (Of clsUser), ByVal uGUID As String) As Boolean

    For Each nItem As clsUser In uList
        If nItem.GUID = uGUID Then
            Return True
        End If
    Next

    Return False

End Function

I would very much like simplify it and add this check to the List (Of clsUser) so that I don't have to write the same code over and over again.

Some like MyList.AddIfGUIDDoesntExists(nNewUser)

Is this possible?
If yes, could anybody tell me how this would be done?

Body:
Imports System.Runtime.CompilerServices

Public Module ExtensionMethods
    <Extension()>
    Public Sub AddIfGUIDDoesntExists(ByRef inputList As List(Of clsUser), _
             ByVal item As clsUser)
        Dim contains As Boolean = False
        For Each i As clsUser In inputList
            If (i.GUID = item.GUID) Then
                 contains = True
                 Exit For
            End If
        Next
        If Not contains
            inputList.Add(item)
        End If
    End Sub
End Module

Usage:

MyList.AddIfGUIDDoesntExists(nNewUser)


问:
How to avoid repeated data in a query?
What's the best way to create a query that returns a dynamic result, in my postgresql i have three tables:

```<code>contacts |contact_emails| contact_numbers
id       | id           | id
descrip  | id_contact   | id_contact
name     | email        | number
</code>```

and i want to create a result something like:

```<code>contact_name| contact_emailx| contact_numbersx
</code>```

Those "x" are the emails and the numbers that can have a contact

I was trying using left join, this is my code:

```<code>SELECT c.id, c.contact_name, cn.number, ce.email
FROM contacts c
LEFT JOIN contact_numbers cn ON c.id = cn.contact_id
LEFT JOIN contact_emails ce ON c.id = ce.contact_id
WHERE c.user_id = 1
</code>```

But it returns

I expect something like:

```<code> contact_name |number1  | number2  |email
LA MEJOR      | 25445877| 25845877 |AMEJOR@GMAIL.COM
</code>```

or

```<code> contact_name    |number1  | number2  |email1          | email2
EDIFICADORA JUANA| 24602254| 55655545 |oipoa@gmaio.com |rst008@guan.com
</code>```

I appreciate any help!

答:
You can use PostgreSQL array_agg to aggregate all your emails and all your numbers into two arrays:

```<code>SELECT
    c.id, c.contact_name, array_agg(DISTINCT cn.number) AS numbers, array_agg(DISTINCT ce.email) AS emails
FROM
    contacts c
    LEFT JOIN contact_numbers cn ON c.id = cn.contact_id
    LEFT JOIN contact_emails ce  ON c.id = ce.contact_id
WHERE
    c.user_id = 1
GROUP BY
    c.id
ORDER BY
    c.id ;
</code>```

```
id | contact_name      | numbers             | emails
-: | :---------------- | :------------------ | :----------------------------------
 2 | LA MEJOR          | {25445877}          | {AHEJOR@GMAIL.COM,AMEJOR@GMAIL.COM}
 3 | EDIFICADORA JUANA | {24602254}          | {oipoa@gmaio.com,rst008@guan.com}
 4 | EDIFICADORA JUANA | {24602254,55655545} | {oipoa@gmaio.com,rst008@guan.com}
 5 | EDIFICADORA JUANA | {24602254,55655545} | {oipoa@gmaio.com,rst008@guan.com}
```

As an alternative, you can subqueries (which might be faster under some circumstances):

```<code>SELECT
    c.id, c.contact_name,
    (SELECT array_agg(DISTINCT cn.number) FROM contact_numbers cn WHERE cn.contact_id = c.id) AS numbers,
    (SELECT array_agg(DISTINCT ce.email)  FROM contact_emails  ce WHERE ce.contact_id = c.id) AS emails
FROM
    contacts c
WHERE
    c.user_id = 1
ORDER BY
    c.id ;
</code>```

```
id | contact_name      | numbers             | emails
-: | :---------------- | :------------------ | :----------------------------------
 2 | LA MEJOR          | {25445877}          | {AHEJOR@GMAIL.COM,AMEJOR@GMAIL.COM}
 3 | EDIFICADORA JUANA | {24602254}          | {oipoa@gmaio.com,rst008@guan.com}
 4 | EDIFICADORA JUANA | {24602254,55655545} | {oipoa@gmaio.com,rst008@guan.com}
 5 | EDIFICADORA JUANA | {24602254,55655545} | {oipoa@gmaio.com,rst008@guan.com}
```

If you want to separate the (first) two emails and numbers, you can do it by wrapping up the previous query:

```<code>SELECT
    id, contact_name,
    numbers[1] AS number1,
    numbers[2] AS number2,
    emails[1]  AS email1,
    emails[2]  AS email2
FROM
(
    SELECT
        c.id, c.contact_name,
        (SELECT array_agg(DISTINCT cn.number) FROM contact_numbers cn WHERE cn.contact_id = c.id) AS numbers,
        (SELECT array_agg(DISTINCT ce.email)  FROM contact_emails  ce WHERE ce.contact_id = c.id) AS emails
    FROM
        contacts c
    WHERE
        c.user_id = 1
) AS q
ORDER BY
    id ;
</code>```

```
id | contact_name      |  number1 |  number2 | email1           | email2
-: | :---------------- | -------: | -------: | :--------------- | :---------------
 2 | LA MEJOR          | 25445877 |     <em>null</em> | AHEJOR@GMAIL.COM | AMEJOR@GMAIL.COM
 3 | EDIFICADORA JUANA | 24602254 |     <em>null</em> | oipoa@gmaio.com  | rst008@guan.com
 4 | EDIFICADORA JUANA | 24602254 | 55655545 | oipoa@gmaio.com  | rst008@guan.com
 5 | EDIFICADORA JUANA | 24602254 | 55655545 | oipoa@gmaio.com  | rst008@guan.com
```

You can check everything online at dbfiddle here

Tables and data used:

```<code>CREATE TABLE contacts
(
    id INTEGER PRIMARY KEY,
    user_id INTEGER NOT NULL /* REFERENCES users(id) */,
    descrip text,
    contact_name character varying(255)
) ;

CREATE TABLE contact_emails
(
    contact_id  INTEGER NOT NULL REFERENCES contacts(id),
    email character varying(255) NOT NULL,
    PRIMARY KEY(contact_id, email)   -- This is the natural key for this table, no need for synthetic id
) ;

CREATE TABLE contact_numbers
(
    contact_id  INTEGER NOT NULL REFERENCES contacts(id),
    number integer,
    PRIMARY KEY(contact_id, number)   -- Again...
) ;
</code>```

... and data

```<code>INSERT INTO
    contacts
    (id, user_id, descrip, contact_name)
VALUES
    (2, 1, '', 'LA MEJOR'),
    (3, 1, '', 'EDIFICADORA JUANA'),
    (4, 1, '', 'EDIFICADORA JUANA'),
    (5, 1, '', 'EDIFICADORA JUANA') ;

INSERT INTO
    contact_emails
    (contact_id, email)
VALUES
    (2, 'AMEJOR@GMAIL.COM'),
    (2, 'AHEJOR@GMAIL.COM'),
    (3, 'oipoa@gmaio.com'),
    (3, 'rst008@guan.com'),
    (4, 'oipoa@gmaio.com'),
    (4, 'rst008@guan.com'),
    (5, 'oipoa@gmaio.com'),
    (5, 'rst008@guan.com') ;

INSERT INTO
    contact_numbers
    (contact_id, number)
VALUES
    (2, '25445877'),
    (3, '24602254'),
    (4, '24602254'),
    (4, '55655545'),
    (5, '24602254'),
    (5, '55655545') ;
</code>```

NOTE: There are lots of repeated values, infered from the data on your image.

Title: How to avoid repeated data in a query?

Body:
What's the best way to create a query that returns a dynamic result, in my postgresql i have three tables:

contacts |contact_emails| contact_numbers
id       | id           | id
descrip  | id_contact   | id_contact
name     | email        | number

and i want to create a result something like:

contact_name| contact_emailx| contact_numbersx

Those "x" are the emails and the numbers that can have a contact

I was trying using left join, this is my code:

SELECT c.id, c.contact_name, cn.number, ce.email
FROM contacts c
LEFT JOIN contact_numbers cn ON c.id = cn.contact_id
LEFT JOIN contact_emails ce ON c.id = ce.contact_id
WHERE c.user_id = 1

But it returns

I expect something like:

 contact_name |number1  | number2  |email
LA MEJOR      | 25445877| 25845877 |AMEJOR@GMAIL.COM

or

 contact_name    |number1  | number2  |email1          | email2
EDIFICADORA JUANA| 24602254| 55655545 |oipoa@gmaio.com |rst008@guan.com

I appreciate any help!

Body:
You can use PostgreSQL array_agg to aggregate all your emails and all your numbers into two arrays:

SELECT
    c.id, c.contact_name, array_agg(DISTINCT cn.number) AS numbers, array_agg(DISTINCT ce.email) AS emails
FROM
    contacts c
    LEFT JOIN contact_numbers cn ON c.id = cn.contact_id
    LEFT JOIN contact_emails ce  ON c.id = ce.contact_id
WHERE
    c.user_id = 1
GROUP BY
    c.id
ORDER BY
    c.id ;

id | contact_name      | numbers             | emails
-: | :---------------- | :------------------ | :----------------------------------
 2 | LA MEJOR          | {25445877}          | {AHEJOR@GMAIL.COM,AMEJOR@GMAIL.COM}
 3 | EDIFICADORA JUANA | {24602254}          | {oipoa@gmaio.com,rst008@guan.com}
 4 | EDIFICADORA JUANA | {24602254,55655545} | {oipoa@gmaio.com,rst008@guan.com}
 5 | EDIFICADORA JUANA | {24602254,55655545} | {oipoa@gmaio.com,rst008@guan.com}

As an alternative, you can subqueries (which might be faster under some circumstances):

SELECT
    c.id, c.contact_name,
    (SELECT array_agg(DISTINCT cn.number) FROM contact_numbers cn WHERE cn.contact_id = c.id) AS numbers,
    (SELECT array_agg(DISTINCT ce.email)  FROM contact_emails  ce WHERE ce.contact_id = c.id) AS emails
FROM
    contacts c
WHERE
    c.user_id = 1
ORDER BY
    c.id ;

id | contact_name      | numbers             | emails
-: | :---------------- | :------------------ | :----------------------------------
 2 | LA MEJOR          | {25445877}          | {AHEJOR@GMAIL.COM,AMEJOR@GMAIL.COM}
 3 | EDIFICADORA JUANA | {24602254}          | {oipoa@gmaio.com,rst008@guan.com}
 4 | EDIFICADORA JUANA | {24602254,55655545} | {oipoa@gmaio.com,rst008@guan.com}
 5 | EDIFICADORA JUANA | {24602254,55655545} | {oipoa@gmaio.com,rst008@guan.com}

If you want to separate the (first) two emails and numbers, you can do it by wrapping up the previous query:

SELECT
    id, contact_name,
    numbers[1] AS number1,
    numbers[2] AS number2,
    emails[1]  AS email1,
    emails[2]  AS email2
FROM
(
    SELECT
        c.id, c.contact_name,
        (SELECT array_agg(DISTINCT cn.number) FROM contact_numbers cn WHERE cn.contact_id = c.id) AS numbers,
        (SELECT array_agg(DISTINCT ce.email)  FROM contact_emails  ce WHERE ce.contact_id = c.id) AS emails
    FROM
        contacts c
    WHERE
        c.user_id = 1
) AS q
ORDER BY
    id ;

id | contact_name      |  number1 |  number2 | email1           | email2
-: | :---------------- | -------: | -------: | :--------------- | :---------------
 2 | LA MEJOR          | 25445877 |     null | AHEJOR@GMAIL.COM | AMEJOR@GMAIL.COM
 3 | EDIFICADORA JUANA | 24602254 |     null | oipoa@gmaio.com  | rst008@guan.com
 4 | EDIFICADORA JUANA | 24602254 | 55655545 | oipoa@gmaio.com  | rst008@guan.com
 5 | EDIFICADORA JUANA | 24602254 | 55655545 | oipoa@gmaio.com  | rst008@guan.com

You can check everything online at dbfiddle here

Tables and data used:

CREATE TABLE contacts
(
    id INTEGER PRIMARY KEY,
    user_id INTEGER NOT NULL /* REFERENCES users(id) */,
    descrip text,
    contact_name character varying(255)
) ;

CREATE TABLE contact_emails
(
    contact_id  INTEGER NOT NULL REFERENCES contacts(id),
    email character varying(255) NOT NULL,
    PRIMARY KEY(contact_id, email)   -- This is the natural key for this table, no need for synthetic id
) ;

CREATE TABLE contact_numbers
(
    contact_id  INTEGER NOT NULL REFERENCES contacts(id),
    number integer,
    PRIMARY KEY(contact_id, number)   -- Again...
) ;

... and data

INSERT INTO
    contacts
    (id, user_id, descrip, contact_name)
VALUES
    (2, 1, '', 'LA MEJOR'),
    (3, 1, '', 'EDIFICADORA JUANA'),
    (4, 1, '', 'EDIFICADORA JUANA'),
    (5, 1, '', 'EDIFICADORA JUANA') ;

INSERT INTO
    contact_emails
    (contact_id, email)
VALUES
    (2, 'AMEJOR@GMAIL.COM'),
    (2, 'AHEJOR@GMAIL.COM'),
    (3, 'oipoa@gmaio.com'),
    (3, 'rst008@guan.com'),
    (4, 'oipoa@gmaio.com'),
    (4, 'rst008@guan.com'),
    (5, 'oipoa@gmaio.com'),
    (5, 'rst008@guan.com') ;

INSERT INTO
    contact_numbers
    (contact_id, number)
VALUES
    (2, '25445877'),
    (3, '24602254'),
    (4, '24602254'),
    (4, '55655545'),
    (5, '24602254'),
    (5, '55655545') ;

NOTE: There are lots of repeated values, infered from the data on your image.


问:
Different Jersey 2 response depending on media type (JSON/XML)
In a RESTful Glassfish 4 application (JERSEY 2.22.2, MOXY as JSON Provider), we have a resource method that is able to produce both JSON and XML outputs.

The method response passes through a MessageBodyWriter, but it's used to build an Object Graph only in certain cases. In these cases, independently from the requested media type from the client, the graph is applied correctly.

On the other hand, when the isWriteable() method of our MessageBodyWirter returns false, therefore passing on to the next writer in the writers list of the MessageBodyFactory, the behavior is different between a JSON media type request and an XML media type request (i.e. Accept: application/json and Accept: application/xml respectively in the request headers).

In the first case, the FilteringMoxyJsonProvider is selected as response writer, because the EntityFilteringFeature is registered. The response is written based on the entity filtering annotations.

Though when the client asks for an XML response, another MessageBodyWriter (org.glassfish.jersey.jaxb.internal.XmlRootElementJaxbProvider) is selected.
This is due to the ordering of the WriterModels in the MessageBodyFactory in which the FilteringMoxyJsonProvider is positioned after  XmlRootElementJaxbProvider.

In this situation the XML response is written without having any filters applied to it.

We tried to look for a way to change the writers order, also tried to access to the EntityFieldProcessor class, without luck.

Is it possible to have both scenarios (i.e. JSON and XML response requests) work in the same way? Is it possible to exclude some writers from being registered or to change their order in the MessageBodyFactory?

Any help will be appreciated.

```<code>    //Configuration
    public class ApplicationConfigVersione1 extends ResourceConfig {
    ....

    register(EntityFilteringFeature.class);
    register(MyCustomWriter.class);

    ------------------------

    @Produces({"application/json", "application/xml"})
    public class MyCustomWriter implements MessageBodyWriter<MyCustomObject> {
    ....

    @Override
    public boolean isWriteable(Class<?> type, Type genericType,
                Annotation[] annotations, MediaType mediaType) {
        if (mustUseCustomWriter()) {
                return true;
            } else {
          return false;
        //In this case, with request header accept=application/xml, the xml response is not filtered.
        }
    }

    @Override
    public void writeTo(MyCustomObject customObject, Class<?> type, Type genericType, Annotation[] annotations,
    MediaType mediaType,
        MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
            throws IOException, WebApplicationException {

            objectGraph = buildObjectGraph();

            marshaller.setProperty(MarshallerProperties.OBJECT_GRAPH, objectGraph);
            marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, mediaType.toString());

            //**** objectGraph applies to XML and JSON media types
            marshaller.marshall(object, entityStream);
</code>```

答:
I have also tried to use Jersey's Entity Filtering mechanism with resources producing both application/json and application/xml responses and see different result information according to the repsonse type.

I suspect this closed/wont-fix github issue for the moxy component is the cause of the behaviour we are seeing with filtering:  https://github.com/jersey/jersey/issues/3036

Body:
In a RESTful Glassfish 4 application (JERSEY 2.22.2, MOXY as JSON Provider), we have a resource method that is able to produce both JSON and XML outputs.

The method response passes through a MessageBodyWriter, but it's used to build an Object Graph only in certain cases. In these cases, independently from the requested media type from the client, the graph is applied correctly.

On the other hand, when the isWriteable() method of our MessageBodyWirter returns false, therefore passing on to the next writer in the writers list of the MessageBodyFactory, the behavior is different between a JSON media type request and an XML media type request (i.e. Accept: application/json and Accept: application/xml respectively in the request headers).

In the first case, the FilteringMoxyJsonProvider is selected as response writer, because the EntityFilteringFeature is registered. The response is written based on the entity filtering annotations.

Though when the client asks for an XML response, another MessageBodyWriter (org.glassfish.jersey.jaxb.internal.XmlRootElementJaxbProvider) is selected.
This is due to the ordering of the WriterModels in the MessageBodyFactory in which the FilteringMoxyJsonProvider is positioned after  XmlRootElementJaxbProvider.

In this situation the XML response is written without having any filters applied to it.

We tried to look for a way to change the writers order, also tried to access to the EntityFieldProcessor class, without luck.

Is it possible to have both scenarios (i.e. JSON and XML response requests) work in the same way? Is it possible to exclude some writers from being registered or to change their order in the MessageBodyFactory?

Any help will be appreciated.

    //Configuration
    public class ApplicationConfigVersione1 extends ResourceConfig {
    ....

    register(EntityFilteringFeature.class);
    register(MyCustomWriter.class);

    ------------------------

    @Produces({"application/json", "application/xml"})
    public class MyCustomWriter implements MessageBodyWriter<MyCustomObject> {
    ....

    @Override
    public boolean isWriteable(Class<?> type, Type genericType,
                Annotation[] annotations, MediaType mediaType) {
        if (mustUseCustomWriter()) {
                return true;
            } else {
          return false;
        //In this case, with request header accept=application/xml, the xml response is not filtered.
        }
    }

    @Override
    public void writeTo(MyCustomObject customObject, Class<?> type, Type genericType, Annotation[] annotations,
    MediaType mediaType,
        MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
            throws IOException, WebApplicationException {

            objectGraph = buildObjectGraph();

            marshaller.setProperty(MarshallerProperties.OBJECT_GRAPH, objectGraph);
            marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, mediaType.toString());

            //**** objectGraph applies to XML and JSON media types
            marshaller.marshall(object, entityStream);


问:
Querying (Wordpress) MySQL Database using asp.net OR sending data from wordpress to asp.net
I'm working on a Press Release website that currently has an existing distribution platform built on ASP.NET - the site that I have built is utilizes Wordpress Multi-site and BuddyPress, and I need to share information between Wordpress & the existing ASP.NET CMS.

The information that needs to be shared between both platforms is 1) Press release information (which is a custom post type in Wordpress) and 2) The login information.

Is there a way to have ASP.NET get the information from the Wordpress MYSQL database?  Or is the best way to write a plugin for wordpress that will send information to the ASP.NET each time a new press release is written, and each time a new user account is created.

I can go either way - having ASP.NET grab the info, or Wordpress send the info out.  Please help!

答: Check out the WordPress XML-RPC API documentation to see e.g. how to create, read, update & delete posts.</p>


问:
How to handle an Exception while opening a new intent in Notification?
I have a notification messenger, I want user to have an access to Google Play Store when they press "push Notification", otherwise, redirect them to url.
So my code is this:

```<code>Intent intent = new Intent(new Intent(Intent.ACTION_VIEW, Uri.parse("market://dev?id=" + appPackageName2)));
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
    notificationBuilder.setContentTitle("FCM Notification")
            .setContentText(remoteMessage.getNotification().getBody())
            .setAutoCancel(true)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentIntent(pendingIntent);
    NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0, notificationBuilder.build());
</code>```

I want something like this on the above code:

```<code>try {
      startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://dev?id=" + appPackageName2)));
} catch (android.content.ActivityNotFoundException anfe) {
      startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/dev?id=" + appPackageName2)));
  }
</code>```

答:
You can use PackageManager.resolveActivity to determine if there is an app installed that can handle a specific intent. You can use that to check if the market: URI can be handled.

Make sure you carefully read the associated javadoc since it has some notes on implicit/explicit intents.

Body:
I have a notification messenger, I want user to have an access to Google Play Store when they press "push Notification", otherwise, redirect them to url.
So my code is this:

Intent intent = new Intent(new Intent(Intent.ACTION_VIEW, Uri.parse("market://dev?id=" + appPackageName2)));
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
    notificationBuilder.setContentTitle("FCM Notification")
            .setContentText(remoteMessage.getNotification().getBody())
            .setAutoCancel(true)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentIntent(pendingIntent);
    NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0, notificationBuilder.build());

I want something like this on the above code:

try {
      startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://dev?id=" + appPackageName2)));
} catch (android.content.ActivityNotFoundException anfe) {
      startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/dev?id=" + appPackageName2)));
  }


问:
jqgrid: editData not being sent to server
I'm using guriddo jqGrid 5.2.1

I've followed the answers provided to these questions:

jqGrid: sending edit data

Add additional param to post data using jqGrid when adding new row with modal form

How to post variable data with editData or onclickSubmit in jqgrid

But the editData I've defined is not getting sent to the endpoint.

Here is the code in my jqgrid pager definition:

```<code>$('#jqGrid').navGrid('#jqGridPager',
            // the buttons to appear on the toolbar of the grid
            { edit: true,
                add: true,
                del: true,
                search: false,
                refresh: false,
                view: false,
                position: "left",
                cloneToTop: false,
                mtype: 'POST',
                editData: {
                    mediaPlanId : function() { return mpId; }
                }},
            // options for the Edit Dialog
            {
                editCaption: "Edit Item",
                recreateForm: true,
                checkOnUpdate : true,
                checkOnSubmit : true,
                closeAfterEdit: true,
                errorTextFormat: function (data) {
                    return 'Error: ' + data.responseText;
                }
            },
            // options for the Add Dialog
            {
                closeAfterAdd: true,
                recreateForm: true,
                errorTextFormat: function (data) {
                    return 'Error: ' + data.responseText;
                }
            },
            // options for the Delete Dailog
            {
                errorTextFormat: function (data) {
                    return 'Error: ' + data.responseText;
                }
            }

    );
</code>```

mpId is defined outside of the jqGrid and jqGridPager functions, at the page level.  I tried sending a value of 1, but that doesn't work either.  I suspect I've missed something simple, but I can't figure out what.

答: I think that the better approach is to read first the documentation of Guriddo jqGrid, which will guide you where to put the parameter.</p>

Body:
I'm using guriddo jqGrid 5.2.1

I've followed the answers provided to these questions:

jqGrid: sending edit data

Add additional param to post data using jqGrid when adding new row with modal form

How to post variable data with editData or onclickSubmit in jqgrid

But the editData I've defined is not getting sent to the endpoint.

Here is the code in my jqgrid pager definition:

$('#jqGrid').navGrid('#jqGridPager',
            // the buttons to appear on the toolbar of the grid
            { edit: true,
                add: true,
                del: true,
                search: false,
                refresh: false,
                view: false,
                position: "left",
                cloneToTop: false,
                mtype: 'POST',
                editData: {
                    mediaPlanId : function() { return mpId; }
                }},
            // options for the Edit Dialog
            {
                editCaption: "Edit Item",
                recreateForm: true,
                checkOnUpdate : true,
                checkOnSubmit : true,
                closeAfterEdit: true,
                errorTextFormat: function (data) {
                    return 'Error: ' + data.responseText;
                }
            },
            // options for the Add Dialog
            {
                closeAfterAdd: true,
                recreateForm: true,
                errorTextFormat: function (data) {
                    return 'Error: ' + data.responseText;
                }
            },
            // options for the Delete Dailog
            {
                errorTextFormat: function (data) {
                    return 'Error: ' + data.responseText;
                }
            }

    );

mpId is defined outside of the jqGrid and jqGridPager functions, at the page level.  I tried sending a value of 1, but that doesn't work either.  I suspect I've missed something simple, but I can't figure out what.


问:
Swift detect when returned from UIApplication.shared.open
Originally I wanted to display google map directions in my app but I don't think that is possible to do. So what I'm going to do is have my app open Google Maps app when needed.

I can open Google Maps just fine however I would like to have my app segue to another screen once they have reached their destination.

Is there any way of detecting that? If not what's the best way to segue to another view controller once the user returns to my app?

Here is my code:

```<code>  override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
    if let cell = tableView.cellForRow(at: indexPath) as? LocationCell {
        if(indexPath.row == 0){
            cell.selectionStyle = .none
            browseVillages(cell.villageBtn)
        }

        else{
            cell.selectionStyle = .none

            let googleMaps = URL(string: "comgooglemaps-x-callback://")!
            if UIApplication.shared.canOpenURL(googleMaps) {
                let directionsRequest = "comgooglemaps-x-callback://" +
                    "?daddr=\(bars[indexPath.row]["Latitude"]!),\(bars[indexPath.row]["Longitude"]!)&saddr=\(currentLocation!.coordinate.latitude),\(currentLocation!.coordinate.longitude)" +
                "&x-success=MYAPP://?resume=true&x-source=AirApp"

                let directionsURL = URL(string: directionsRequest)!
                UIApplication.shared.open(directionsURL, options: [:], completionHandler: nil)
            }
            else {
                let alert = UIAlertController(title: "Error", message: "MYAPP uses Google Maps to display accurate directions to \(bars[indexPath.row]["Name"]).", preferredStyle: UIAlertControllerStyle.alert)
                alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
                self.present(alert, animated: true, completion: {  })
            }
        }
    }
}
</code>```

答:
Maybe you can type the next to get the message:</p>

```<code>let options = [UIApplicationOpenURLOptionUniversalLinksOnly : false]
        UIApplication.shared.open(directionsURL as URL, options: options, completionHandler: { (success) in
            print("Open url : \(success)")
        })
</code>```

Body:
Originally I wanted to display google map directions in my app but I don't think that is possible to do. So what I'm going to do is have my app open Google Maps app when needed.

I can open Google Maps just fine however I would like to have my app segue to another screen once they have reached their destination.

Is there any way of detecting that? If not what's the best way to segue to another view controller once the user returns to my app?

Here is my code:

  override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
    if let cell = tableView.cellForRow(at: indexPath) as? LocationCell {
        if(indexPath.row == 0){
            cell.selectionStyle = .none
            browseVillages(cell.villageBtn)
        }

        else{
            cell.selectionStyle = .none

            let googleMaps = URL(string: "comgooglemaps-x-callback://")!
            if UIApplication.shared.canOpenURL(googleMaps) {
                let directionsRequest = "comgooglemaps-x-callback://" +
                    "?daddr=\(bars[indexPath.row]["Latitude"]!),\(bars[indexPath.row]["Longitude"]!)&saddr=\(currentLocation!.coordinate.latitude),\(currentLocation!.coordinate.longitude)" +
                "&x-success=MYAPP://?resume=true&x-source=AirApp"

                let directionsURL = URL(string: directionsRequest)!
                UIApplication.shared.open(directionsURL, options: [:], completionHandler: nil)
            }
            else {
                let alert = UIAlertController(title: "Error", message: "MYAPP uses Google Maps to display accurate directions to \(bars[indexPath.row]["Name"]).", preferredStyle: UIAlertControllerStyle.alert)
                alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
                self.present(alert, animated: true, completion: {  })
            }
        }
    }
}

Body:
Maybe you can type the next to get the message:

let options = [UIApplicationOpenURLOptionUniversalLinksOnly : false]
        UIApplication.shared.open(directionsURL as URL, options: options, completionHandler: { (success) in
            print("Open url : \(success)")
        })


问:
How can I make this JS code more functional using setTimeout and promises?
I'm trying to learn how to code using more functions and less loops and just in a more functional way. I want to implement a time out between calling connectBing. I was wondering if it's possible not to use the i variable and still get a 1 second time out between iterations. My code currently works but I'm looking for other ways to write it without using i.

This is my code:

```<code>// MAIN
getAllPosts().then((posts) => {
    posts
        .forEach( (post, i) => {
            setTimeout(() => {
                connectBing(anchorText,console.log).then()
            } ,i * 1000)
        })

// CONNECT TO BING WITH KW AND DO SOMETHING
function connectBing(anchorText,doSomethingWithBing) {
    var deferred = q.defer();
    request('https://www.cnn.com/search?q=' + anchorText, function (error, response, body) {
        error ? console.log('error:', error) :
        console.log('statusCode:', response && response.statusCode);
        (doSomethingWithBing) ? doSomethingWithBing(body) : "You didn't give connectBing anything to do!"
    })
    return deferred.promise
}
</code>```

答:
You could take an array of async functions and chain each to run after the other. I will use native promises to demonstrate, and you can map it to the library you are using.

First create a function which takes in an array of async fucntions. It will chain one after the other, returning the last:

```<code>function chainAsyncFns(fns) {
    // Ensure we have at least one promise to return

    let promise = Promise.resolve();

    fns.forEach(fn => promise = promise.then(fn));

    return promise;
}
</code>```

Then for each post, create an async function which will call connectBing and then wait for a timeout:

```<code>function connectBing() {
    // Pretend we are connecting to a data source

    return Promise.resolve();
}

function delay(ms) {
    // Return a promise that resolves when the timeout is up

    return new Promise(resolve => setTimeout(resolve, ms));
}

let fns = posts.map(post => () => {
    return connectBing()
        .then(() => delay(1000))
        .catch(() => console.log('error'));
});
</code>```

Chain the functions to run one after the other:

```<code>chainAsyncFns(fns).then(() => console.log('done'));
</code>```

Body:
I'm trying to learn how to code using more functions and less loops and just in a more functional way. I want to implement a time out between calling connectBing. I was wondering if it's possible not to use the i variable and still get a 1 second time out between iterations. My code currently works but I'm looking for other ways to write it without using i.

This is my code:

// MAIN
getAllPosts().then((posts) => {
    posts
        .forEach( (post, i) => {
            setTimeout(() => {
                connectBing(anchorText,console.log).then()
            } ,i * 1000)
        })

// CONNECT TO BING WITH KW AND DO SOMETHING
function connectBing(anchorText,doSomethingWithBing) {
    var deferred = q.defer();
    request('https://www.cnn.com/search?q=' + anchorText, function (error, response, body) {
        error ? console.log('error:', error) :
        console.log('statusCode:', response && response.statusCode);
        (doSomethingWithBing) ? doSomethingWithBing(body) : "You didn't give connectBing anything to do!"
    })
    return deferred.promise
}

Body:
You could take an array of async functions and chain each to run after the other. I will use native promises to demonstrate, and you can map it to the library you are using.

First create a function which takes in an array of async fucntions. It will chain one after the other, returning the last:

function chainAsyncFns(fns) {
    // Ensure we have at least one promise to return

    let promise = Promise.resolve();

    fns.forEach(fn => promise = promise.then(fn));

    return promise;
}

Then for each post, create an async function which will call connectBing and then wait for a timeout:

function connectBing() {
    // Pretend we are connecting to a data source

    return Promise.resolve();
}

function delay(ms) {
    // Return a promise that resolves when the timeout is up

    return new Promise(resolve => setTimeout(resolve, ms));
}

let fns = posts.map(post => () => {
    return connectBing()
        .then(() => delay(1000))
        .catch(() => console.log('error'));
});

Chain the functions to run one after the other:

chainAsyncFns(fns).then(() => console.log('done'));