问:
Launch application to ViewController inside of nav controller
I'd like to launch my app via a 3D touch quick action, and have it launch to a view that has a back button to my main view.

Here are the views:

The one with the table is my main view, if you tap that, it presents the view to the right, with a back button to the main view. However if I launch just the second view via AppDelegate, obviously the nav bar is gone, along with any way to get back to that previous view.

I wanted to avoid manually adding buttons, as it would detract from the natural feel.

```<code>let mainStoryboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let initialViewController : UIViewController = mainStoryboard.instantiateViewController(withIdentifier: "secondView") as UIViewController

        let nav = UINavigationController(rootViewController: initialViewController)
        self.window = UIWindow(frame: UIScreen.main.bounds)
        self.window?.rootViewController = nav
        self.window?.makeKeyAndVisible()
</code>```

This gives the nav bar, but no back button (which is expected).

My question is, how to I make it so it simulates the user tapping on the table cell, so it shows the second view, with both a button and a swipe-to-go-back to go back to the previous view.

答:
The easiest way is to simply show the View that contains your table view chained to the other views you want to show.

To explain it easily.

Present your Table -> View Controller with Animated set to false. On completion present your NEXT view controller (the one you want to actually show) but with animated set to TRUE.

This way the user will only see the target one, but it will be as if he had come from the one that has your tableview.

NOTICE: I might be mixing which one goes with animated true. It might be that the one that goes with true is the first one, and the rest go with false.

Body:
I'd like to launch my app via a 3D touch quick action, and have it launch to a view that has a back button to my main view.

Here are the views:

The one with the table is my main view, if you tap that, it presents the view to the right, with a back button to the main view. However if I launch just the second view via AppDelegate, obviously the nav bar is gone, along with any way to get back to that previous view.

I wanted to avoid manually adding buttons, as it would detract from the natural feel.

let mainStoryboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let initialViewController : UIViewController = mainStoryboard.instantiateViewController(withIdentifier: "secondView") as UIViewController

        let nav = UINavigationController(rootViewController: initialViewController)
        self.window = UIWindow(frame: UIScreen.main.bounds)
        self.window?.rootViewController = nav
        self.window?.makeKeyAndVisible()

This gives the nav bar, but no back button (which is expected).

My question is, how to I make it so it simulates the user tapping on the table cell, so it shows the second view, with both a button and a swipe-to-go-back to go back to the previous view.


来源: stackexchange

问:
popto page after few seconds in Ionic 3
I am very new to ionic. Just learning it. Basically I have two pages, welcome and home. First welcome page gets loaded.

I want to load home page after 2-3 seconds when welcome page load. Same I have done using setTimeout in JavaScript.

```<code>ionViewDidLoad() {
    console.log('ionViewDidLoad WelcomePage');
    setTimeout(() => {
        this.navCtrl.popToRoot(home);
    }, 2500);
}
</code>```

The above code not working. Seems like typo error in poptoroot. What can I try to fix this?

答: First you need to declare your variable "home" since it's not defined. Then to have the home page loaded when you get to the welcome page you need to use "ionViewDidEnter". Your problem is that "ionViewDidLoad" only runs once, which is when the page is created, but "ionViewDidEnter" will run even if the page is created or cached.</p>

ContentLicense: CC BY-SA 4.0

Title: popto page after few seconds in Ionic 3

Body:
I am very new to ionic. Just learning it. Basically I have two pages, welcome and home. First welcome page gets loaded.

I want to load home page after 2-3 seconds when welcome page load. Same I have done using setTimeout in JavaScript.

ionViewDidLoad() {
    console.log('ionViewDidLoad WelcomePage');
    setTimeout(() => {
        this.navCtrl.popToRoot(home);
    }, 2500);
}

The above code not working. Seems like typo error in poptoroot. What can I try to fix this?

ContentLicense: CC BY-SA 3.0


问:
Tick and label alignment for Highcharts datetime
I have a chart with multiple samples but all at the same time. How do I get Highcharts to put a tick and corresponding label on each value? I've tried explicitly setting the tickPoints with the datetimes but it doesn't work.

Invalid tick alignment example

答:
Worked this out. Essentially, I implemented a custom tickPositioner function that puts ticks (if enabled) and their respective labels on each value.

```
xAxis: {
  tickPositioner: function() {
    var ticks = [1496275200000, 1496880000000, 1497484800000, 1499299200000];
    // this line makes highcharts aware the values are dates
    ticks.info = this.tickPositions.info;
    return ticks;
  }
}
```

You would of course make the tick array values match your data..

An example here

Body:
Worked this out. Essentially, I implemented a custom tickPositioner function that puts ticks (if enabled) and their respective labels on each value.

xAxis: {
  tickPositioner: function() {
    var ticks = [1496275200000, 1496880000000, 1497484800000, 1499299200000];
    // this line makes highcharts aware the values are dates
    ticks.info = this.tickPositions.info;
    return ticks;
  }
}

You would of course make the tick array values match your data..

An example here


问:
Podio api - how to set category field when create item
I am using php wrapper, try create an item, all is ok, item is creating, but I can't change status, tried different ways, but can't find right way.

Need change status to "Closed" - http://prntscr.com/fsrwc3

Codes not works:

```<code>$fields = new PodioItemFieldCollection([
    new PodioCategoryItemField(['external_id'=>'status', 'values'=>13]),
]);
$item = new PodioItem([
    'app' => new PodioApp($app_id),
    'fields' => $fields
]);
$item->save();
</code>```

or

```<code>$fields = new PodioItemFieldCollection([
    new PodioCategoryItemField(['external_id'=>'status', 'values'=>13]),
]);
$item = new PodioItem([
    'app' => new PodioApp($app_id),
    'fields' => $fields
]);
$item->save();
$get_item = PodioItem::get_basic($item->item_id);
$get_item->fields['status']->values = ['id'=>13];
$get_item->save();
</code>```

After create item (after new PodioItem...), if I get fields after this code (just get $item->fields or PodioItem::get_basic...), I can see correct status, only in the code, only immediatly after create item, but if I get this item in the another code (just PodioItem::get_basic...) I will see default value, so code don't change status, looks like I just see some cache.

If I create item on the one script:

```<code>$fields = new PodioItemFieldCollection([
    new PodioCategoryItemField(['external_id'=>'status', 'values'=>13]),
]);
$item = new PodioItem([
    'app' => new PodioApp($app_id),
    'fields' => $fields
]);
$item->save();
</code>```

Then, in the another script update field, it will be change:

```<code>$get_item = PodioItem::get_basic('639637317');
$get_item->fields['status']->values = ['id'=>13];
$get_item->save();
</code>```

Update - debug information:

Get log by test code -

```<code>PodioItem::create($app_id, ['fields' => ['status'=>[13], 'category'=>[3], 'contract-type'=>[4]]]);
</code>```

(simple variant for creating an item, have the same problems like new PodioItem... )

All fields have category type, but:

status - have inline show type - don't chnages

category - have dropdown show type - Is changing

contract-type - have dropdown show type - Is changing

Log:

```<code>2017-07-08 11:07:22 200 POST /item/app/12152727/
2017-07-08 11:07:22 Request body: {"fields":{"status":[8],"category":[3],"contract-type":[4]}}
2017-07-08 11:07:22 Reponse: {
"presence": {
    "ref_type": "item",
    "ref_id": 641331142,
    "user_id": 4194774,
    "signature": "c165b85090e6ad28e74ae4baf93ee56113f88bc9"
},
"app": {
    "status": "active",
    "sharefile_vault_url": null,
    "name": "Projects",
    "default_view_id": null,
    "url_add": "https:\/\/podio.com\/acs-1com\/project-management\/apps\/projects\/items\/new",
    "icon_id": 378,
    "link_add": "https:\/\/podio.com\/acs-1com\/project-management\/apps\/projects\/items\/new",
    "app_id": 12152727,
    "current_revision": 141,
    "item_name": "Project",
    "link": "https:\/\/podio.com\/acs-1com\/project-management\/apps\/projects",
    "url": "https:\/\/podio.com\/acs-1com\/project-management\/apps\/projects",
    "url_label": "projects",
    "config": {
        "item_name": "Project",
        "icon_id": 378,
        "type": "standard",
        "name": "Projects",
        "icon": "378.png"
    },
    "space_id": 3466816,
    "icon": "378.png"
},
"created_on": "2017-07-10 15:31:16",
"last_event_on": "2017-07-10 15:31:16",
"linked_account_data": null,
"sharefile_vault_folder_id": null,
"app_item_id_formatted": "3988",
"recurrence": null,
"title": "ACSC",
"participants": {},
"created_by": {
    "user_id": 4194774,
    "name": "Anton Mikhailov",
    "url": "https:\/\/podio.com\/users\/4194774",
    "type": "user",
    "image": null,
    "avatar_type": "file",
    "avatar": null,
    "id": 4194774,
    "avatar_id": null,
    "last_seen_on": "2017-07-10 15:31:15"
},
"priority": 641331142.0,
"created_via": {
    "url": null,
    "auth_client_id": 25162,
    "display": true,
    "name": "importer",
    "id": 25162
},
"subscribed_count": 1,
"reminder": null,
"ref": null,
"revision": 0,
"app_item_id": 3988,
"link": "https:\/\/podio.com\/acs-1com\/project-management\/apps\/projects\/items\/3988",
"item_id": 641331142,
"sharefile_vault_url": null,
"rights": ["subscribe", "grant", "add_conversation", "rate", "update", "delete", "add_file", "grant_view", "view", "comment", "add_task"],
"fields": [{
    "status": "active",
    "type": "category",
    "field_id": 93352415,
    "label": "Division",
    "values": [{
        "value": {
            "status": "active",
            "text": "ACSC",
            "id": 3,
            "color": "D2E4EB"
        }
    }],
    "config": {
        "default_value": null,
        "unique": false,
        "description": null,
        "hidden_create_view_edit": false,
        "required": true,
        "mapping": null,
        "label": "Division",
        "visible": true,
        "delta": 5,
        "hidden": false,
        "settings": {
            "multiple": false,
            "options": [{
                "status": "active",
                "text": "ACSE",
                "id": 1,
                "color": "DCEBD8"
            }, {
                "status": "active",
                "text": "ACSB",
                "id": 2,
                "color": "F7F0C5"
            }, {
                "status": "active",
                "text": "ACSC",
                "id": 3,
                "color": "D2E4EB"
            }],
            "display": "dropdown"
        }
    },
    "external_id": "category"
}, {
    "status": "active",
    "type": "category",
    "field_id": 148215928,
    "label": "Contract Type",
    "values": [{
        "value": {
            "status": "active",
            "text": "No Contract",
            "id": 4,
            "color": "DDDDDD"
        }
    }],
    "config": {
        "default_value": null,
        "unique": false,
        "description": null,
        "hidden_create_view_edit": false,
        "required": true,
        "mapping": null,
        "label": "Contract Type",
        "visible": true,
        "delta": 7,
        "hidden": false,
        "settings": {
            "multiple": false,
            "options": [{
                "status": "active",
                "text": "PO \/ Purchase \/ T&M",
                "id": 1,
                "color": "FFD5C2"
            }, {
                "status": "active",
                "text": "Original Contract",
                "id": 2,
                "color": "D2E4EB"
            }, {
                "status": "active",
                "text": "Service Rider",
                "id": 3,
                "color": "DCEBD8"
            }, {
                "status": "active",
                "text": "No Contract",
                "id": 4,
                "color": "DDDDDD"
            }],
            "display": "dropdown"
        }
    },
    "external_id": "contract-type"
}, {
    "status": "active",
    "type": "category",
    "field_id": 93034840,
    "label": "Instal Status",
    "values": [{
        "value": {
            "status": "active",
            "text": "Closed",
            "id": 13,
            "color": "E1D8ED"
        }
    }],
    "config": {
        "default_value": null,
        "unique": false,
        "description": null,
        "hidden_create_view_edit": false,
        "required": true,
        "mapping": null,
        "label": "Instal Status",
        "visible": true,
        "delta": 13,
        "hidden": false,
        "settings": {
            "multiple": false,
            "options": [{
                "status": "deleted",
                "text": "To Be Reviewed",
                "id": 2,
                "color": "F7F0C5"
            }, {
                "status": "deleted",
                "text": "ACS Accounting Review",
                "id": 5,
                "color": "FFD5C2"
            }, {
                "status": "deleted",
                "text": "Ignite Setup",
                "id": 10,
                "color": "DCEBD8"
            }, {
                "status": "active",
                "text": "To Be Scheduled",
                "id": 8,
                "color": "D2E4EB"
            }, {
                "status": "active",
                "text": "In Progress",
                "id": 6,
                "color": "DCEBD8"
            }, {
                "status": "active",
                "text": "Warranty",
                "id": 11,
                "color": "F7F0C5"
            }, {
                "status": "active",
                "text": "Complete",
                "id": 3,
                "color": "D1F3EC"
            }, {
                "status": "deleted",
                "text": "Closed",
                "id": 7,
                "color": "DDDDDD"
            }, {
                "status": "active",
                "text": "Cancelled",
                "id": 9,
                "color": "DDDDDD"
            }, {
                "status": "deleted",
                "text": "VA in Progress",
                "id": 4,
                "color": "E1D8ED"
            }, {
                "status": "deleted",
                "text": "Submitted",
                "id": 1,
                "color": "F7F0C5"
            }, {
                "status": "active",
                "text": "On Hold",
                "id": 12,
                "color": "F7D1D0"
            }, {
                "status": "active",
                "text": "Closed",
                "id": 13,
                "color": "E1D8ED"
            }],
            "display": "inline"
        }
    },
    "external_id": "status"
}],
"initial_revision": {
    "item_revision_id": 1664054437,
    "created_via": {
        "url": null,
        "auth_client_id": 25162,
        "display": true,
        "name": "importer",
        "id": 25162
    },
    "created_by": {
        "user_id": 4194774,
        "name": "Anton Mikhailov",
        "url": "https:\/\/podio.com\/users\/4194774",
        "type": "user",
        "image": null,
        "avatar_type": "file",
        "avatar": null,
        "id": 4194774,
        "avatar_id": null,
        "last_seen_on": "2017-07-10 15:31:15"
    },
    "created_on": "2017-07-10 15:31:16",
    "user": {
        "user_id": 4194774,
        "name": "Anton Mikhailov",
        "url": "https:\/\/podio.com\/users\/4194774",
        "type": "user",
        "image": null,
        "avatar_type": "file",
        "avatar": null,
        "id": 4194774,
        "avatar_id": null,
        "last_seen_on": "2017-07-10 15:31:15"
    },
    "type": "creation",
    "revision": 0
},
"current_revision": {
    "item_revision_id": 1664054437,
    "created_via": {
        "url": null,
        "auth_client_id": 25162,
        "display": true,
        "name": "importer",
        "id": 25162
    },
    "created_by": {
        "user_id": 4194774,
        "name": "Anton Mikhailov",
        "url": "https:\/\/podio.com\/users\/4194774",
        "type": "user",
        "image": null,
        "avatar_type": "file",
        "avatar": null,
        "id": 4194774,
        "avatar_id": null,
        "last_seen_on": "2017-07-10 15:31:15"
    },
    "created_on": "2017-07-10 15:31:16",
    "user": {
        "user_id": 4194774,
        "name": "Anton Mikhailov",
        "url": "https:\/\/podio.com\/users\/4194774",
        "type": "user",
        "image": null,
        "avatar_type": "file",
        "avatar": null,
        "id": 4194774,
        "avatar_id": null,
        "last_seen_on": "2017-07-10 15:31:15"
    },
    "type": "creation",
    "revision": 0
},
"linked_account_id": null,
"push": {
    "timestamp": 1499700676,
    "expires_in": 21600,
    "channel": "\/item\/641331142",
    "signature": "b8a816ff367da6bc730071c875ca3fdca2d2c344"
},
"external_id": null
}
</code>```

答:
Have you tried http://podio.github.io/podio-php/fields/#category-field ?

Setting values

  Set a single value by using the option_id. You can also
  add a value with add_value()

```<code>$item = PodioItem::get_basic(123);
$field_id = 'category';

// Set value to a single option
$item->fields[$field_id]->values = 4; // option_id=4

// Add value to existing selection
$item->fields[$field_id]->add_value(4); // option_id=4
</code>```

Use an array to set multiple values

```<code>$item = PodioItem::get_basic(123);
$field_id = 'category';
$item->fields[$field_id]->values = array(4,5,6); // option_ids: 4, 5 and 6
</code>```

Creating item with value:

```<code>$fields = new PodioItemFieldCollection([
    new PodioCategoryItemField(['external_id'=>'status', 'values'=>array(13)]),
]);
$item = new PodioItem([
    'app' => new PodioApp($app_id),
    'fields' => $fields
]);
$item->save();
</code>```

Body:
I am using php wrapper, try create an item, all is ok, item is creating, but I can't change status, tried different ways, but can't find right way.

Need change status to "Closed" - http://prntscr.com/fsrwc3

Codes not works:

$fields = new PodioItemFieldCollection([
    new PodioCategoryItemField(['external_id'=>'status', 'values'=>13]),
]);
$item = new PodioItem([
    'app' => new PodioApp($app_id),
    'fields' => $fields
]);
$item->save();

or

$fields = new PodioItemFieldCollection([
    new PodioCategoryItemField(['external_id'=>'status', 'values'=>13]),
]);
$item = new PodioItem([
    'app' => new PodioApp($app_id),
    'fields' => $fields
]);
$item->save();
$get_item = PodioItem::get_basic($item->item_id);
$get_item->fields['status']->values = ['id'=>13];
$get_item->save();

After create item (after new PodioItem...), if I get fields after this code (just get $item->fields or PodioItem::get_basic...), I can see correct status, only in the code, only immediatly after create item, but if I get this item in the another code (just PodioItem::get_basic...) I will see default value, so code don't change status, looks like I just see some cache.

If I create item on the one script:

$fields = new PodioItemFieldCollection([
    new PodioCategoryItemField(['external_id'=>'status', 'values'=>13]),
]);
$item = new PodioItem([
    'app' => new PodioApp($app_id),
    'fields' => $fields
]);
$item->save();

Then, in the another script update field, it will be change:

$get_item = PodioItem::get_basic('639637317');
$get_item->fields['status']->values = ['id'=>13];
$get_item->save();

Update - debug information:

Get log by test code -

PodioItem::create($app_id, ['fields' => ['status'=>[13], 'category'=>[3], 'contract-type'=>[4]]]);

(simple variant for creating an item, have the same problems like new PodioItem... )

All fields have category type, but:

status - have inline show type - don't chnages

category - have dropdown show type - Is changing

contract-type - have dropdown show type - Is changing

Log:

2017-07-08 11:07:22 200 POST /item/app/12152727/
2017-07-08 11:07:22 Request body: {"fields":{"status":[8],"category":[3],"contract-type":[4]}}
2017-07-08 11:07:22 Reponse: {
"presence": {
    "ref_type": "item",
    "ref_id": 641331142,
    "user_id": 4194774,
    "signature": "c165b85090e6ad28e74ae4baf93ee56113f88bc9"
},
"app": {
    "status": "active",
    "sharefile_vault_url": null,
    "name": "Projects",
    "default_view_id": null,
    "url_add": "https:\/\/podio.com\/acs-1com\/project-management\/apps\/projects\/items\/new",
    "icon_id": 378,
    "link_add": "https:\/\/podio.com\/acs-1com\/project-management\/apps\/projects\/items\/new",
    "app_id": 12152727,
    "current_revision": 141,
    "item_name": "Project",
    "link": "https:\/\/podio.com\/acs-1com\/project-management\/apps\/projects",
    "url": "https:\/\/podio.com\/acs-1com\/project-management\/apps\/projects",
    "url_label": "projects",
    "config": {
        "item_name": "Project",
        "icon_id": 378,
        "type": "standard",
        "name": "Projects",
        "icon": "378.png"
    },
    "space_id": 3466816,
    "icon": "378.png"
},
"created_on": "2017-07-10 15:31:16",
"last_event_on": "2017-07-10 15:31:16",
"linked_account_data": null,
"sharefile_vault_folder_id": null,
"app_item_id_formatted": "3988",
"recurrence": null,
"title": "ACSC",
"participants": {},
"created_by": {
    "user_id": 4194774,
    "name": "Anton Mikhailov",
    "url": "https:\/\/podio.com\/users\/4194774",
    "type": "user",
    "image": null,
    "avatar_type": "file",
    "avatar": null,
    "id": 4194774,
    "avatar_id": null,
    "last_seen_on": "2017-07-10 15:31:15"
},
"priority": 641331142.0,
"created_via": {
    "url": null,
    "auth_client_id": 25162,
    "display": true,
    "name": "importer",
    "id": 25162
},
"subscribed_count": 1,
"reminder": null,
"ref": null,
"revision": 0,
"app_item_id": 3988,
"link": "https:\/\/podio.com\/acs-1com\/project-management\/apps\/projects\/items\/3988",
"item_id": 641331142,
"sharefile_vault_url": null,
"rights": ["subscribe", "grant", "add_conversation", "rate", "update", "delete", "add_file", "grant_view", "view", "comment", "add_task"],
"fields": [{
    "status": "active",
    "type": "category",
    "field_id": 93352415,
    "label": "Division",
    "values": [{
        "value": {
            "status": "active",
            "text": "ACSC",
            "id": 3,
            "color": "D2E4EB"
        }
    }],
    "config": {
        "default_value": null,
        "unique": false,
        "description": null,
        "hidden_create_view_edit": false,
        "required": true,
        "mapping": null,
        "label": "Division",
        "visible": true,
        "delta": 5,
        "hidden": false,
        "settings": {
            "multiple": false,
            "options": [{
                "status": "active",
                "text": "ACSE",
                "id": 1,
                "color": "DCEBD8"
            }, {
                "status": "active",
                "text": "ACSB",
                "id": 2,
                "color": "F7F0C5"
            }, {
                "status": "active",
                "text": "ACSC",
                "id": 3,
                "color": "D2E4EB"
            }],
            "display": "dropdown"
        }
    },
    "external_id": "category"
}, {
    "status": "active",
    "type": "category",
    "field_id": 148215928,
    "label": "Contract Type",
    "values": [{
        "value": {
            "status": "active",
            "text": "No Contract",
            "id": 4,
            "color": "DDDDDD"
        }
    }],
    "config": {
        "default_value": null,
        "unique": false,
        "description": null,
        "hidden_create_view_edit": false,
        "required": true,
        "mapping": null,
        "label": "Contract Type",
        "visible": true,
        "delta": 7,
        "hidden": false,
        "settings": {
            "multiple": false,
            "options": [{
                "status": "active",
                "text": "PO \/ Purchase \/ T&M",
                "id": 1,
                "color": "FFD5C2"
            }, {
                "status": "active",
                "text": "Original Contract",
                "id": 2,
                "color": "D2E4EB"
            }, {
                "status": "active",
                "text": "Service Rider",
                "id": 3,
                "color": "DCEBD8"
            }, {
                "status": "active",
                "text": "No Contract",
                "id": 4,
                "color": "DDDDDD"
            }],
            "display": "dropdown"
        }
    },
    "external_id": "contract-type"
}, {
    "status": "active",
    "type": "category",
    "field_id": 93034840,
    "label": "Instal Status",
    "values": [{
        "value": {
            "status": "active",
            "text": "Closed",
            "id": 13,
            "color": "E1D8ED"
        }
    }],
    "config": {
        "default_value": null,
        "unique": false,
        "description": null,
        "hidden_create_view_edit": false,
        "required": true,
        "mapping": null,
        "label": "Instal Status",
        "visible": true,
        "delta": 13,
        "hidden": false,
        "settings": {
            "multiple": false,
            "options": [{
                "status": "deleted",
                "text": "To Be Reviewed",
                "id": 2,
                "color": "F7F0C5"
            }, {
                "status": "deleted",
                "text": "ACS Accounting Review",
                "id": 5,
                "color": "FFD5C2"
            }, {
                "status": "deleted",
                "text": "Ignite Setup",
                "id": 10,
                "color": "DCEBD8"
            }, {
                "status": "active",
                "text": "To Be Scheduled",
                "id": 8,
                "color": "D2E4EB"
            }, {
                "status": "active",
                "text": "In Progress",
                "id": 6,
                "color": "DCEBD8"
            }, {
                "status": "active",
                "text": "Warranty",
                "id": 11,
                "color": "F7F0C5"
            }, {
                "status": "active",
                "text": "Complete",
                "id": 3,
                "color": "D1F3EC"
            }, {
                "status": "deleted",
                "text": "Closed",
                "id": 7,
                "color": "DDDDDD"
            }, {
                "status": "active",
                "text": "Cancelled",
                "id": 9,
                "color": "DDDDDD"
            }, {
                "status": "deleted",
                "text": "VA in Progress",
                "id": 4,
                "color": "E1D8ED"
            }, {
                "status": "deleted",
                "text": "Submitted",
                "id": 1,
                "color": "F7F0C5"
            }, {
                "status": "active",
                "text": "On Hold",
                "id": 12,
                "color": "F7D1D0"
            }, {
                "status": "active",
                "text": "Closed",
                "id": 13,
                "color": "E1D8ED"
            }],
            "display": "inline"
        }
    },
    "external_id": "status"
}],
"initial_revision": {
    "item_revision_id": 1664054437,
    "created_via": {
        "url": null,
        "auth_client_id": 25162,
        "display": true,
        "name": "importer",
        "id": 25162
    },
    "created_by": {
        "user_id": 4194774,
        "name": "Anton Mikhailov",
        "url": "https:\/\/podio.com\/users\/4194774",
        "type": "user",
        "image": null,
        "avatar_type": "file",
        "avatar": null,
        "id": 4194774,
        "avatar_id": null,
        "last_seen_on": "2017-07-10 15:31:15"
    },
    "created_on": "2017-07-10 15:31:16",
    "user": {
        "user_id": 4194774,
        "name": "Anton Mikhailov",
        "url": "https:\/\/podio.com\/users\/4194774",
        "type": "user",
        "image": null,
        "avatar_type": "file",
        "avatar": null,
        "id": 4194774,
        "avatar_id": null,
        "last_seen_on": "2017-07-10 15:31:15"
    },
    "type": "creation",
    "revision": 0
},
"current_revision": {
    "item_revision_id": 1664054437,
    "created_via": {
        "url": null,
        "auth_client_id": 25162,
        "display": true,
        "name": "importer",
        "id": 25162
    },
    "created_by": {
        "user_id": 4194774,
        "name": "Anton Mikhailov",
        "url": "https:\/\/podio.com\/users\/4194774",
        "type": "user",
        "image": null,
        "avatar_type": "file",
        "avatar": null,
        "id": 4194774,
        "avatar_id": null,
        "last_seen_on": "2017-07-10 15:31:15"
    },
    "created_on": "2017-07-10 15:31:16",
    "user": {
        "user_id": 4194774,
        "name": "Anton Mikhailov",
        "url": "https:\/\/podio.com\/users\/4194774",
        "type": "user",
        "image": null,
        "avatar_type": "file",
        "avatar": null,
        "id": 4194774,
        "avatar_id": null,
        "last_seen_on": "2017-07-10 15:31:15"
    },
    "type": "creation",
    "revision": 0
},
"linked_account_id": null,
"push": {
    "timestamp": 1499700676,
    "expires_in": 21600,
    "channel": "\/item\/641331142",
    "signature": "b8a816ff367da6bc730071c875ca3fdca2d2c344"
},
"external_id": null
}

Body:
Have you tried http://podio.github.io/podio-php/fields/#category-field ?

Setting values

  Set a single value by using the option_id. You can also
  add a value with add_value()

$item = PodioItem::get_basic(123);
$field_id = 'category';

// Set value to a single option
$item->fields[$field_id]->values = 4; // option_id=4

// Add value to existing selection
$item->fields[$field_id]->add_value(4); // option_id=4

Use an array to set multiple values

$item = PodioItem::get_basic(123);
$field_id = 'category';
$item->fields[$field_id]->values = array(4,5,6); // option_ids: 4, 5 and 6

Creating item with value:

$fields = new PodioItemFieldCollection([
    new PodioCategoryItemField(['external_id'=>'status', 'values'=>array(13)]),
]);
$item = new PodioItem([
    'app' => new PodioApp($app_id),
    'fields' => $fields
]);
$item->save();


问:
Pixel-wise dryness/wetness frequencies for RasterBrick R
Given a rasterbrick a with monthly time series data of standardized rainfall for about 60 years, how can I compute the following on the rasterbrick without having to resort to collapsing the data into a dataframe:

```<code>Q = negative/positive number of severely dry/wet months per total months of severely dry/wet events × 100
</code>```

where severely wet includes values in the range 1.50 to 1.99 and severely dry includes values in the range −1.99 to −1.50

I will prefer Q to be in raster format.  Download the data set and do:

```<code>dd=spei03_df
dd[1:2]<-dd[2:1]#swap lat and lon
a=rasterFromXYZ(dd)
</code>```

Any thoughts? Thanks.

Example data set can be found here

答:
You can use raster algebra from the raster package. Here is an example calculating the severe wet. The final output, a_wet_perc is a raster layer with cell values ranging from 0 to 100 (expressed as percentage). You can follow the same logic to create a raster layer summarizing the severe dry condition.

```<code>library(raster)

# Calculate the Severe Wet
a_wet <- a

# Replace vlaues >= 1.5 and <= 1.99 to 100
# (Does not need to be 100. A very large number should be good)
a_wet[a_wet >= 1.5 & a_wet <= 1.99] <- 100
# Replace other values to 0
a_wet[a_wet < 100] <- 0
# Replace 100 to 1
a_wet[a_wet == 100] <- 1

# Calculate the percentage of severe wet
a_wet_perc <- mean(a_wet) * 100
</code>```

Body:
Given a rasterbrick a with monthly time series data of standardized rainfall for about 60 years, how can I compute the following on the rasterbrick without having to resort to collapsing the data into a dataframe:

Q = negative/positive number of severely dry/wet months per total months of severely dry/wet events × 100

where severely wet includes values in the range 1.50 to 1.99 and severely dry includes values in the range −1.99 to −1.50

I will prefer Q to be in raster format.  Download the data set and do:

dd=spei03_df
dd[1:2]<-dd[2:1]#swap lat and lon
a=rasterFromXYZ(dd)

Any thoughts? Thanks.

Example data set can be found here

Body:
You can use raster algebra from the raster package. Here is an example calculating the severe wet. The final output, a_wet_perc is a raster layer with cell values ranging from 0 to 100 (expressed as percentage). You can follow the same logic to create a raster layer summarizing the severe dry condition.

library(raster)

# Calculate the Severe Wet
a_wet <- a

# Replace vlaues >= 1.5 and <= 1.99 to 100
# (Does not need to be 100. A very large number should be good)
a_wet[a_wet >= 1.5 & a_wet <= 1.99] <- 100
# Replace other values to 0
a_wet[a_wet < 100] <- 0
# Replace 100 to 1
a_wet[a_wet == 100] <- 1

# Calculate the percentage of severe wet
a_wet_perc <- mean(a_wet) * 100


问:
how to get parent div data-attribute javascript
I have a HTML structure like this :

```<code><div class="page" data-page-number="29" data-page-label="18" data-loaded="true" style="width: 816px; height: 1056px;">
   <div class="canvasWrapper" style="width: 816px; height: 1056px;">
      <canvas id="page29" width="1632" height="2112" style="width: 816px; height: 1056px;"></canvas>
   </div>
   <div class="textLayer" style="width: 816px; height: 1056px;">
        some content
   </div>
</div>

    <div class="page" data-page-number="29" data-page-label="18" data-loaded="true" style="width: 816px; height: 1056px;">
       <div class="canvasWrapper" style="width: 816px; height: 1056px;">
          <canvas id="page29" width="1632" height="2112" style="width: 816px; height: 1056px;"></canvas>
       </div>
       <div class="textLayer" style="width: 816px; height: 1056px;">
            some content
       </div>
    </div>
</code>```

I want to know that when I click on any textLayer class, I will get data-page-number="x" attribute from its parent .page div.

Only javascript solution required here.

This is basically PDF.js structure.

答:
```<code>$(".textLayer").on("click",function() {
   $(this).parent().attr("data-page-number");
});
</code>```

pure js:

```<code>var classname = document.getElementsByClassName("textLayer");

var myFunction = function() {
    var attribute = this.parentElement.getAttribute("data-page-number");
};

for (var i = 0; i < classname.length; i++) {
    classname[i].addEventListener('click', myFunction, false);
}
</code>```

// even shorter version

```<code>var elems = document.getElementsByClassName("textLayer").forEach(function(element){
    element.addEventListener('click', function(){
        var attribute = this.parentElement.getAttribute("data-page-number");
    }, false);
});
</code>```

Body:
I have a HTML structure like this :

      <canvas id="page29" width="1632" height="2112" style="width: 816px; height: 1056px;"></canvas>

        some content

          <canvas id="page29" width="1632" height="2112" style="width: 816px; height: 1056px;"></canvas>

            some content

I want to know that when I click on any textLayer class, I will get data-page-number="x" attribute from its parent .page div.

Only javascript solution required here.

This is basically PDF.js structure.

Body:
$(".textLayer").on("click",function() {
   $(this).parent().attr("data-page-number");
});

pure js:

var classname = document.getElementsByClassName("textLayer");

var myFunction = function() {
    var attribute = this.parentElement.getAttribute("data-page-number");
};

for (var i = 0; i < classname.length; i++) {
    classname[i].addEventListener('click', myFunction, false);
}

// even shorter version

var elems = document.getElementsByClassName("textLayer").forEach(function(element){
    element.addEventListener('click', function(){
        var attribute = this.parentElement.getAttribute("data-page-number");
    }, false);
});


问:
Can I use Google API without Google Compute Engine? (Cloud SDK)
https://www.youtube.com/watch?v=chk2rRjSn5o
https://www.youtube.com/watch?v=nMY0qDg16y4&t=491s

These series of videos use Google Compute Engine to access Google Cloud vision API.

But, I only want to use Google cloud vision API on my local computer.

I found Cloud SDK is an option but I don't understand how it works.
Does it link my computer to Google Compute Engine?
Then, do I still have to pay for the Engine?

To Sum up the question.

Is there any way that I only pay for Google Cloud Vision API without paying for Google Compute Engine?

答:
TL;DR - Yes you can - they are separate services and you can use them either independently or combine them if needed. You pay only for what you use.

Google Compute Engine

The first youtube video link you shared is for using Google Compute Engine (GCE), which is an IaaS (Infrastructure as a Service) option in Google Cloud. You can use this to set up VMs, custom networks, instance groups, load balancers and other infrastructure.

Google Cloud Vision

Google Cloud Vision is a more specific service which helps you with just Image analysis. It is a service independent of Google Compute Engine and you need not use Google Compute Engine to use the Cloud Vision APIs (although you can do that too if you wish in the future).

In other words - yes, you need not pay for Google Compute Engine to use just the Cloud Vision APIs.

Both Cloud Vision and Google Compute Engine are cloud services part of Google Cloud Platform. Both of them require first creating a project (using Google Cloud Console) and setting up billing before you can use either of those services (or in fact any of the Google Cloud services).

Trying the Cloud Vision API

Here is a quickstart tutorial with detailed steps to try Cloud Vision API directly in the browser.

If you prefer using Cloud SDK and the Cloud client libraries, here is a detailed example with steps.


问:
Spring cache - "Null key returned for cache operation"
```<code>@Transactional
@Repository
@RepositoryDefinition(domainClass = UserApi.class, idClass = String.class)
public interface UserApiRepository{

    @Cacheable(value="byUserId",key="#userId")
    List<UserApi> findByUserId(String userId);

    @CacheEvict(value="byUserId",key="#userApi.userId")
    void save(UserApi userApi);
}
</code>```

UsrApi.java

```<code>@Entity
@Table(name = "user_api")
public class UserApi {
    private String id;
    private String userId;
    private String api;
    private String platform;
    private String apiType;

    @Id
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getApi() {
        return api;
    }

    public void setApi(String api) {
        this.api = api;
    }

    public String getPlatform() {
        return platform;
    }

    public void setPlatform(String platform) {
        this.platform = platform;
    }

    public String getApiType() {
        return apiType;
    }

    public void setApiType(String apiType) {
        this.apiType = apiType;
    }
}
</code>```

It's ERROR When I add key="#userId".

```<code>java.lang.IllegalArgumentException: Null key returned for cache operation
(maybe you are using named params on classes without debug info?)
Builder[public abstract java.util.List com.awinson.repository.UserApiRepository.findByUserId(java.lang.String)]
caches=[byUserId] | key='#userId' | keyGenerator='' | cacheManager='' | cacheResolver='' | condition='' | unless='' | sync='false'
</code>```

It's doesn't update the cache when I use "save" method.

答:
you could try to replace key with p0

@Transactional
    @Repository
    @RepositoryDefinition(domainClass = UserApi.class, idClass = String.class)
    public interface UserApiRepository{

```<code>    @Cacheable(value="byUserId",key="#p0")
    List<UserApi> findByUserId(String userId);

    @CacheEvict(value="byUserId",key="#p0.userId")
    void save(UserApi userApi);
}
</code>```

reference from
Spring Cache Abstraction VS interfaces VS key param ("Null key returned for cache operation" error)

Body:
@Transactional
@Repository
@RepositoryDefinition(domainClass = UserApi.class, idClass = String.class)
public interface UserApiRepository{

    @Cacheable(value="byUserId",key="#userId")
    List<UserApi> findByUserId(String userId);

    @CacheEvict(value="byUserId",key="#userApi.userId")
    void save(UserApi userApi);
}

UsrApi.java

@Entity
@Table(name = "user_api")
public class UserApi {
    private String id;
    private String userId;
    private String api;
    private String platform;
    private String apiType;

    @Id
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getApi() {
        return api;
    }

    public void setApi(String api) {
        this.api = api;
    }

    public String getPlatform() {
        return platform;
    }

    public void setPlatform(String platform) {
        this.platform = platform;
    }

    public String getApiType() {
        return apiType;
    }

    public void setApiType(String apiType) {
        this.apiType = apiType;
    }
}

It's ERROR When I add key="#userId".

java.lang.IllegalArgumentException: Null key returned for cache operation
(maybe you are using named params on classes without debug info?)
Builder[public abstract java.util.List com.awinson.repository.UserApiRepository.findByUserId(java.lang.String)]
caches=[byUserId] | key='#userId' | keyGenerator='' | cacheManager='' | cacheResolver='' | condition='' | unless='' | sync='false'

It's doesn't update the cache when I use "save" method.

Body:
you could try to replace key with p0

@Transactional
    @Repository
    @RepositoryDefinition(domainClass = UserApi.class, idClass = String.class)
    public interface UserApiRepository{

    @Cacheable(value="byUserId",key="#p0")
    List<UserApi> findByUserId(String userId);

    @CacheEvict(value="byUserId",key="#p0.userId")
    void save(UserApi userApi);
}

reference from
Spring Cache Abstraction VS interfaces VS key param ("Null key returned for cache operation" error)


问:
Core Data - Relationships between Multiple Core Data Models

Platform

iOS 10, Xcode 8.3.3

Background

I have built a Notes application that takes advantage of Core Data and I'd like to use this app in my next application, which will also use Core Data. For simplicity, lets call my next application, "ListApp", and my notes application, "NotesApp". This ListApp has list items each of which can have one or more notes.

Here's what I've done so far:

Removed all unnecessary files from the NotesApp and compiled a "NotesApp Framework".

Linked the NotesApp Framework to the ListApp.

Designed the Core Data Model for ListApp. Specifically, I created an entity called "ListItem" and an entity called "Note". The ListItem has a to-many relationship with the Note (one list item can have multiple notes). The Note entity contains a "noteID" field to reference the note in the NotesApp model and, of course, the inverse relationship.

Problem

I need to form a "relationship" between an entity in the ListApp model and an entity in the NotesApp model.

I've researched configurations and that seems to be more for storing objects in the same model to different persistent stores unless there's something I'm missing. So, that doesn't help.

Then, I found that fetched properties can be used to form weak relationships between multiple stores. So, that doesn't help either.

Next, I found in the documentation that there's a method called NSManagedObjectModel.mergedModel(from:) so I'm assuming this is possible. Or maybe that's only for migration?

That's where I'm stuck.

Reason

I'd rather not redesign everything in the NotesApp model in to the ListApp model. I prefer to keep everything separate.

Questions

Is there a way to form a relationship between two entities in different models? Should I just add a function in the ListItem entity class to fetch the notes in the NotesApp model manually? Am I even going down the right path or is there a better option?

NOTE: What I mean by "relationship" is the ability to call on a property in the ListItem entity to fetch the notes and somehow "relate" specific notes to a specific ListItem.

P.S. If you know of any pitfalls, have any general advice, or know of any reading material please feel free to let me know.

Also, I've been researching this topic for a couple of hours and I can't seem to find anything about it. I'm assuming that's either because it's not possible, it's a terrible practice, or I'm not using the right keywords.

If anyone needs any more information feel free to let me know!

答:
Alright, so turns out I had a slight misunderstanding of the Core Data Stack but, this is an extremely simple task. I was able to get this to work very easily based on some research and @Jerry Krinock's answer.

Create a framework containing the needed files from the NotesApp.

Link the framework to the ListApp.

Grab mutable references to the ListApp and NotesApp NSManagedObjectModel.

Programmatically add a NSRelationshipDescription between the ListItem entity in the ListApp Model and the Note entity in the NotesApp Model (and vice versa for the inverse).

Create a NSManagedObjectModel by merging the ListApp and NotesApp models.

NOTE: As @Jerry Krinock mentioned this only needs to be done once since we are merging the two models together and storing them in the same persistent store. This is the same as doing it through the CoreData Model Builder UI except programmatically since it doesn't support referencing entities from separate models (at least not that I know of or could find).

References:

Core Data Programming Guide

Core Data stack

Universal Cocoa Touch Frameworks for iOS8 – (Remix)

Adding relationships in NSManagedObjectModel to programmatically created NSEntityDescription

Objective-C:

```<code>    NSManagedObjectModel * listModel = [[[NSManagedObjectModel alloc] initWithContentsOfURL:[self listModelURL]] mutableCopy];
    NSManagedObjectModel * notesModel = [[[NSManagedObjectModel alloc] initWithContentsOfURL:[self notesModelURL]] mutableCopy];

    NSEntityDescription * listEntity = [listModel.entitiesByName objectForKey:NSStringFromClass([JBListItemMO class])];

    // The framework name is prepended to the class name. Remove it before getting the note's entityDescription.
    NSString * noteClassName = [NSStringFromClass([JPSNoteMO class]) componentsSeparatedByString:@"."].lastObject;
    NSEntityDescription * noteEntity = [notesModel.entitiesByName objectForKey:noteClassName];

    NSRelationshipDescription * whichListRelationship = [[NSRelationshipDescription alloc] init];
    whichListRelationship.minCount = 0;
    whichListRelationship.maxCount = 1;
    whichListRelationship.optional = NO;
    whichListRelationship.name = @"whichList";
    whichListRelationship.destinationEntity = listEntity;
    whichListRelationship.deleteRule = NSNullifyDeleteRule;

    NSRelationshipDescription * notesRelationship = [[NSRelationshipDescription alloc] init];
    notesRelationship.ordered = NO;
    notesRelationship.maxCount = 0;
    notesRelationship.minCount = 0;
    notesRelationship.optional = YES;
    notesRelationship.name = @"notes";
    notesRelationship.destinationEntity = noteEntity;
    notesRelationship.deleteRule = NSCascadeDeleteRule;
    notesRelationship.inverseRelationship = whichListRelationship;

    whichListRelationship.inverseRelationship = notesRelationship;

    listEntity.properties = [listEntity.properties arrayByAddingObject: notesRelationship];
    noteEntity.properties = [noteEntity.properties arrayByAddingObject: whichListRelationship];

    self.managedObjectModel = [NSManagedObjectModel modelByMergingModels:@[listModel, notesModel]];
</code>```

I'll post the Swift 3 code when I've finished converting my CoreDataStack class.

Body:
Alright, so turns out I had a slight misunderstanding of the Core Data Stack but, this is an extremely simple task. I was able to get this to work very easily based on some research and @Jerry Krinock's answer.

Create a framework containing the needed files from the NotesApp.

Link the framework to the ListApp.

Grab mutable references to the ListApp and NotesApp NSManagedObjectModel.

Programmatically add a NSRelationshipDescription between the ListItem entity in the ListApp Model and the Note entity in the NotesApp Model (and vice versa for the inverse).

Create a NSManagedObjectModel by merging the ListApp and NotesApp models.

NOTE: As @Jerry Krinock mentioned this only needs to be done once since we are merging the two models together and storing them in the same persistent store. This is the same as doing it through the CoreData Model Builder UI except programmatically since it doesn't support referencing entities from separate models (at least not that I know of or could find).

References:

Core Data Programming Guide

Core Data stack

Universal Cocoa Touch Frameworks for iOS8 – (Remix)

Adding relationships in NSManagedObjectModel to programmatically created NSEntityDescription

Objective-C:

    NSManagedObjectModel * listModel = [[[NSManagedObjectModel alloc] initWithContentsOfURL:[self listModelURL]] mutableCopy];
    NSManagedObjectModel * notesModel = [[[NSManagedObjectModel alloc] initWithContentsOfURL:[self notesModelURL]] mutableCopy];

    NSEntityDescription * listEntity = [listModel.entitiesByName objectForKey:NSStringFromClass([JBListItemMO class])];

    // The framework name is prepended to the class name. Remove it before getting the note's entityDescription.
    NSString * noteClassName = [NSStringFromClass([JPSNoteMO class]) componentsSeparatedByString:@"."].lastObject;
    NSEntityDescription * noteEntity = [notesModel.entitiesByName objectForKey:noteClassName];

    NSRelationshipDescription * whichListRelationship = [[NSRelationshipDescription alloc] init];
    whichListRelationship.minCount = 0;
    whichListRelationship.maxCount = 1;
    whichListRelationship.optional = NO;
    whichListRelationship.name = @"whichList";
    whichListRelationship.destinationEntity = listEntity;
    whichListRelationship.deleteRule = NSNullifyDeleteRule;

    NSRelationshipDescription * notesRelationship = [[NSRelationshipDescription alloc] init];
    notesRelationship.ordered = NO;
    notesRelationship.maxCount = 0;
    notesRelationship.minCount = 0;
    notesRelationship.optional = YES;
    notesRelationship.name = @"notes";
    notesRelationship.destinationEntity = noteEntity;
    notesRelationship.deleteRule = NSCascadeDeleteRule;
    notesRelationship.inverseRelationship = whichListRelationship;

    whichListRelationship.inverseRelationship = notesRelationship;

    listEntity.properties = [listEntity.properties arrayByAddingObject: notesRelationship];
    noteEntity.properties = [noteEntity.properties arrayByAddingObject: whichListRelationship];

    self.managedObjectModel = [NSManagedObjectModel modelByMergingModels:@[listModel, notesModel]];

I'll post the Swift 3 code when I've finished converting my CoreDataStack class.


问:
Didn't find class "adaptive-icon" on path: DexPathList after adding adaptive icons
Like the title says, I get that error after switching to adaptive icons and trying to load R.ic_launcher. What am I doing wrong here? The icons also shows up as the default green android in the launcher.</p>

答: The issue is that apis lower than 26 don't support the class. To fix, rename the folder with the ic_launcher.xml file to mipmap-anydpi-v26.</p>


问:
Cocos2d: Detect touch on rotated sprite?
How would one detect a touch on a rotated CCSprite?

I am familiar with the general technique of using ccTouchesBegan and contentSize, anchorPoint etc. to have a sprite detect if a touch was within its bounds ... but I am not sure how to proceed once the sprite has been rotated by some angle.

I want the sprite itself to detect the touch (encapsulation) and report the event via a delegate to another object.

If anyone has some code to share ... would be great.

答: @Dad's code transforms the node's bbox into world. For a rotated node, this expands the bbox and can return true for touches that are outside the actual node but inside the world bbox. To avoid this, transform the world point into the node's coordinate space, and test the local point there.</p>

ContentLicense: CC BY-SA 2.5


问:
Google Sheet scripts
I created the following script to sort data on certain pages in google sheets, and it will only run the second function and not the first one. I am new to programming and switching over to sheets from excel. I am sure its something small and obvious, but i can't figure it out. I appreciate any help.</p>

```<code>function onEdit(event){
var sheet = event.source.getActiveSheet();
if(sheet.getName() ==='ADMIN')
var editedCell = sheet.getActiveCell();

var columnToSortBy = 1;
var tableRange = "A2:G48"; // What to sort.

if(editedCell.getColumn() == columnToSortBy){
var range = sheet.getRange(tableRange);
range.sort( { column : columnToSortBy, ascending: true } );
}
}

function onEdit(event){
var sheet = event.source.getActiveSheet();
if(sheet.getName() ==='HQ', 'ARMT', 'MAINT', 'AVNX', 'SHOPS')
var editedCell = sheet.getActiveCell();

var columnToSortBy = 2;
var tableRange = "A4:D40"; // What to sort.

if(editedCell.getColumn() == columnToSortBy){
var range = sheet.getRange(tableRange);
range.sort( { column : columnToSortBy, ascending: true } );
 }
}
</code>```

答:
In javascript and google scripts, functions are objects. What you are doing here is creating an object (function onEdit) and then creating it again.  It's like setting a variable named xyz to 4 and then setting the same variable to 14.  The last one set is all that matters.  You can accomplish what you want by merging the functions together so you have one onEdit, or naming one(or both) differently and having the onEdit call them.</p>

```<code> function onEdit(event) {
     first(event);
     second(event);
 }

 function first(event) {
     var sheet = event.source.getActiveSheet();
     if (sheet.getName() === 'ADMIN')
         var editedCell = sheet.getActiveCell();

     var columnToSortBy = 1;
     var tableRange = "A2:G48"; // What to sort.

     if (editedCell.getColumn() == columnToSortBy) {
         var range = sheet.getRange(tableRange);
         range.sort({
             column: columnToSortBy,
             ascending: true
         });
     }
 }

 function second(event) {
     var sheet = event.source.getActiveSheet();
     if (sheet.getName() === 'HQ', 'ARMT', 'MAINT', 'AVNX', 'SHOPS')
         var editedCell = sheet.getActiveCell();

     var columnToSortBy = 2;
     var tableRange = "A4:D40"; // What to sort.

     if (editedCell.getColumn() == columnToSortBy) {
         var range = sheet.getRange(tableRange);
         range.sort({
             column: columnToSortBy,
             ascending: true
         });
     }
 }
</code>```

Title: Google Sheet scripts

Body:
I created the following script to sort data on certain pages in google sheets, and it will only run the second function and not the first one. I am new to programming and switching over to sheets from excel. I am sure its something small and obvious, but i can't figure it out. I appreciate any help.

function onEdit(event){
var sheet = event.source.getActiveSheet();
if(sheet.getName() ==='ADMIN')
var editedCell = sheet.getActiveCell();

var columnToSortBy = 1;
var tableRange = "A2:G48"; // What to sort.

if(editedCell.getColumn() == columnToSortBy){
var range = sheet.getRange(tableRange);
range.sort( { column : columnToSortBy, ascending: true } );
}
}

function onEdit(event){
var sheet = event.source.getActiveSheet();
if(sheet.getName() ==='HQ', 'ARMT', 'MAINT', 'AVNX', 'SHOPS')
var editedCell = sheet.getActiveCell();

var columnToSortBy = 2;
var tableRange = "A4:D40"; // What to sort.

if(editedCell.getColumn() == columnToSortBy){
var range = sheet.getRange(tableRange);
range.sort( { column : columnToSortBy, ascending: true } );
 }
}

Body:
In javascript and google scripts, functions are objects. What you are doing here is creating an object (function onEdit) and then creating it again.  It's like setting a variable named xyz to 4 and then setting the same variable to 14.  The last one set is all that matters.  You can accomplish what you want by merging the functions together so you have one onEdit, or naming one(or both) differently and having the onEdit call them.

 function onEdit(event) {
     first(event);
     second(event);
 }

 function first(event) {
     var sheet = event.source.getActiveSheet();
     if (sheet.getName() === 'ADMIN')
         var editedCell = sheet.getActiveCell();

     var columnToSortBy = 1;
     var tableRange = "A2:G48"; // What to sort.

     if (editedCell.getColumn() == columnToSortBy) {
         var range = sheet.getRange(tableRange);
         range.sort({
             column: columnToSortBy,
             ascending: true
         });
     }
 }

 function second(event) {
     var sheet = event.source.getActiveSheet();
     if (sheet.getName() === 'HQ', 'ARMT', 'MAINT', 'AVNX', 'SHOPS')
         var editedCell = sheet.getActiveCell();

     var columnToSortBy = 2;
     var tableRange = "A4:D40"; // What to sort.

     if (editedCell.getColumn() == columnToSortBy) {
         var range = sheet.getRange(tableRange);
         range.sort({
             column: columnToSortBy,
             ascending: true
         });
     }
 }


问:
Jquery and Javascript combined. Code not working
I have written the below code to display a selection of images within a
 tag when a certain button is clicked on a page. The Jquery to hide the
 elements on page load works, but the rest of the code does nothing. Can anyone help me figure this out please?

```<code>    $(document).ready(function(){
    //Create Array for images
    var vanImgArr = new Array("<img src='img\yvr\coalharbour.jpg'>", "<img src='img\yvr\lgbridge.jpg'>", "<img src='img/yvr/yaletown.jpg'/>", "<img src='img\yvr\lgbridge2.jpg'>");
    var sgpImgArr = new Array("<img src='img\sgp\elginbridge.jpg'>", "<img src='img\sgp\mbfc.jpg'>", "<img src='img\sgp\sgpdusk.jpg'>", "<img src='img\sgp\sgppano.jpg'>");
    var aniImgArr = new Array("<img src='img\ani\cat1.jpg'>", "<img src='img\ani\cat2.jpg'>", "<img src='img\ani\dog1.jpg'>", "<img src='img\ani\tandd.jpg'>");
    var absImgArr = new Array("<img src='img\abs\abs1.jpg'>", "<img src='img\abs\abs2.jpg'>", "<img src='img\abs\abs3.jpg'>", "<img src='img\abs\abs4.jpg'>");
    var clickedId;
    var idx = 0;
    //to display images
    function displayImgs(arr)
    {

        if(idx <= arr.length)
        {
            ('#pic').hide();
            ('#pic').html(arr[idx]);
            ('#pic').fadeIn('slow');
            if(idx > arr.length)
            {
                idx = 0;
            }
            else
            {
                idx++;
            }
        };  //button click close
    }//displayImgs method close

    //on page load
    $('p').hide();

    //More info Action
    $('#more').hover(function(){
        $('#info, #info2').fadeIn('slow');
    });

    //Button Click Action
    $(':button').click(function(){
        clickedId = this.id;
        alert(clickedId); //testing
        switch(clickedId)
        {
            case 'yvr':
                displayImgs(vanImgArr);
                break;

            case 'sgp':
                displayImgs(sgpImgArr);
                break;

            case 'ani':
                displayImgs(aniImgArr);
                break;

            case 'abs':
                displayImgs(absImgArr);
                break;
        }//switch/case close
    });//button click close
});
</code>```

Here is my HTML code to go with the above

```<code><!DOCTYPE html>
</code>```

```<code><title>Ricky Deacon CSIS3380-001, Assignment 2, Summer 2017</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="script.js"></script>
</code>```

```<code><table class="t1">

    <tr>
        <th width="25%" rowspan="3"><img src="img\rick2.JPG" alt="RD portrait goes here"></th>
        <th width="50%" colspan="2">Rick Deacon</th>
        <th width="25%" rowspan="3"><img src="img\rick1.JPG" alt="RD portrait goes here"></th>
    </tr>
    <tr>
        <td id="subtitle" colspan="2">Photography Showcase</td>
    </tr>
    <tr>
        <td id="desc" colspan="2">Click the corresponding button to display images from your chosen category.</td>
    </tr>
</table>
<br/>
<br/>
<table class="t2">
    <tr>
        <th>
             <input id="van" type="button" name="submit" value="Show Vancouver Images"/>
         </th>
         <th>
             <input id="sgp" type="button" name="submit" value="Show Singapore Images"/>
         </th>
         <th>
             <input id="ani" type="button" name="submit" value="Show Animal Images"/>
         </th>
         <th>
             <input id="abs" type="button" name="submit" value="Show Abstract Images"/>
         </th>
    </tr>
    <tr>
        <th>
             <p id="info"><a href="https://flickr.com/rick-deacon">Rick Deacon's Flickr</a></p>
        </th>
        <th colspan="2">
            <h1 id="more">More Info and Portfolio Links</h1>
        </th>
        <th>
             <p id="info2"><a href="https://rick-deacon.pixels.com/">Prints For Sale</a></p>
        </th>
    </tr>
</table>
<br/>
<br/>
<p id="pic" align="center">Image Goes Here</p>
</code>```

答:
Your JavaScript refers to elements which don't exist in your markup.

First, there are no elements with the id of "more", so the "More Info" action will never run.  Second, you are targeting a button element in your "Button Click" action, but I see no button elements either--just <input type="button" />, which you must specify using $(":button, input[type='button']") (Either one of those two selectors will work).

Body:
I have written the below code to display a selection of images within a
 tag when a certain button is clicked on a page. The Jquery to hide the
 elements on page load works, but the rest of the code does nothing. Can anyone help me figure this out please?

    $(document).ready(function(){
    //Create Array for images
    var vanImgArr = new Array("", "", "", "");
    var sgpImgArr = new Array("", "", "", "");
    var aniImgArr = new Array("", "", "", "");
    var absImgArr = new Array("", "", "", "");
    var clickedId;
    var idx = 0;
    //to display images
    function displayImgs(arr)
    {

        if(idx <= arr.length)
        {
            ('#pic').hide();
            ('#pic').html(arr[idx]);
            ('#pic').fadeIn('slow');
            if(idx > arr.length)
            {
                idx = 0;
            }
            else
            {
                idx++;
            }
        };  //button click close
    }//displayImgs method close

    //on page load
    $('p').hide();

    //More info Action
    $('#more').hover(function(){
        $('#info, #info2').fadeIn('slow');
    });

    //Button Click Action
    $(':button').click(function(){
        clickedId = this.id;
        alert(clickedId); //testing
        switch(clickedId)
        {
            case 'yvr':
                displayImgs(vanImgArr);
                break;

            case 'sgp':
                displayImgs(sgpImgArr);
                break;

            case 'ani':
                displayImgs(aniImgArr);
                break;

            case 'abs':
                displayImgs(absImgArr);
                break;
        }//switch/case close
    });//button click close
});

Here is my HTML code to go with the above

<!DOCTYPE html>

<title>Ricky Deacon CSIS3380-001, Assignment 2, Summer 2017</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css"/>

        Rick Deacon

        Photography Showcase

        Click the corresponding button to display images from your chosen category.

             <input id="van" type="button" name="submit" value="Show Vancouver Images"/>

             <input id="sgp" type="button" name="submit" value="Show Singapore Images"/>

             <input id="ani" type="button" name="submit" value="Show Animal Images"/>

             <input id="abs" type="button" name="submit" value="Show Abstract Images"/>

Rick Deacon's Flickr

More Info and Portfolio Links

Prints For Sale

Image Goes Here


问:
Identifying which element invoked the event
I have following html code

```<code><input type="button"  id ="b1" value="Click me" onclick="msg()" />
<input type="button" id="b2"   value="Click me" onclick="msg()" />
</code>```

now in my javascript i want to identify whether button one was clicked or button 2. How can i do it?

答:
Have your msg() function take in an object.  Then when you call it, pass in </p>

```<code>msg(this);
</code>```

Body:
I have following html code

<input type="button"  id ="b1" value="Click me" onclick="msg()" />
<input type="button" id="b2"   value="Click me" onclick="msg()" />

now in my javascript i want to identify whether button one was clicked or button 2. How can i do it?

Body:
Have your msg() function take in an object.  Then when you call it, pass in

msg(this);


问:
colors and border setting in itextsharp
I am trying to set the border and color for my pdf cells.

```<code>PdfPCell[] headingcell = new PdfPCell[] {
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc_abc_abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
            };

            headingcell[0].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[1].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[2].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[3].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[4].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[5].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[6].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[7].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[8].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[9].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[10].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[11].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[12].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[13].BackgroundColor = BaseColor.DARK_GRAY;

            headingcell[0].BorderWidth = 0;
            headingcell[1].BorderWidth = 0;
            headingcell[2].BorderWidth = 0;
            headingcell[3].BorderWidth = 0;
            headingcell[4].BorderWidth = 0;
            headingcell[5].BorderWidth = 0;
            headingcell[6].BorderWidth = 0;
            headingcell[7].BorderWidth = 0;
            headingcell[8].BorderWidth = 0;
            headingcell[9].BorderWidth = 0;
            headingcell[10].BorderWidth = 0;
            headingcell[11].BorderWidth = 0;
            headingcell[12].BorderWidth = 0;
            headingcell[13].BorderWidth = 0;
            table.Rows.Add(new PdfPRow(headingcell));
</code>```

I am able to achieve what I want with this coding, but I would like to ask is there a more efficient way to achieve this? Because these codes is so long only for this small thing.

答:
You can use a for loop:</p>

```<code>for (var i = 0; i <= 13; i++)
{
    headingcell[i].BackgroundColor = BaseColor.DARK_GRAY;
    headingcell[i].BorderWidth = 0;
}
</code>```

Title: colors and border setting in itextsharp

Body:
I am trying to set the border and color for my pdf cells.

PdfPCell[] headingcell = new PdfPCell[] {
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc_abc_abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
                new PdfPCell(new Phrase("abc", font9)),
            };

            headingcell[0].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[1].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[2].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[3].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[4].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[5].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[6].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[7].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[8].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[9].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[10].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[11].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[12].BackgroundColor = BaseColor.DARK_GRAY;
            headingcell[13].BackgroundColor = BaseColor.DARK_GRAY;

            headingcell[0].BorderWidth = 0;
            headingcell[1].BorderWidth = 0;
            headingcell[2].BorderWidth = 0;
            headingcell[3].BorderWidth = 0;
            headingcell[4].BorderWidth = 0;
            headingcell[5].BorderWidth = 0;
            headingcell[6].BorderWidth = 0;
            headingcell[7].BorderWidth = 0;
            headingcell[8].BorderWidth = 0;
            headingcell[9].BorderWidth = 0;
            headingcell[10].BorderWidth = 0;
            headingcell[11].BorderWidth = 0;
            headingcell[12].BorderWidth = 0;
            headingcell[13].BorderWidth = 0;
            table.Rows.Add(new PdfPRow(headingcell));

I am able to achieve what I want with this coding, but I would like to ask is there a more efficient way to achieve this? Because these codes is so long only for this small thing.

Body:
You can use a for loop:

for (var i = 0; i <= 13; i++)
{
    headingcell[i].BackgroundColor = BaseColor.DARK_GRAY;
    headingcell[i].BorderWidth = 0;
}


问:
Bulk Excel data import with nested relationships
I am getting slow performance issue in excel data import with nested relationships.

I have two main tables to insert and other four tables which have one-to-many and many-to-many relationships with main tables.

I check imported data for four tables are existing or new before data is inserted for two main tables as imported file may have same data for four tables and same data cannot insert multiple times.

That's why performance is slow.

How could I solve this issue?

答:
I have had to deal with this situation with bulk data that includes million of records. From many wasted weeks of experience:

1) Do everything in your power not to use excel. It is slow and eats up loads of memory. A single sheet with 500,00 records can end up eating up over 2 gigabytes of memory just to load the file. The imports then take 30-40-50 minutes or more for a single sheet. Consider converting the data to CSV and importing it using SqlBulkCopy. It can handle a massive amount of records on the order of seconds to a few minutes as opposed to hours.

2) There's not much you can do when it comes to improving the performance o Entity Framework in this situation. I found the best and fastest approach was to load each sheet into its own temp table in the Database. Then I constructed SQL to do the bulk inserts into their end tables. Results of intermediate inserts can be captured into output tables so you can access the keys necessary to perform any joins from the temp table or inserts into related tables.  You can of course "steal` some of the auto generated EF SQL but then you'll need to fine tune it.

3) Even though SQL hates loops, I coded my sql statements to run in a loop and inserts of say 100,000 records at a time. It made the inserts run much faster.

To give you an idea, after bulk importing each sheet form CSV:

First define your variables and types stored in related tables as needed:

```<code>DECLARE @Max INT = @RecordsPerLoop
DECLARE @Min INT = 0
DECLARE @TotalRECORD INT = (
        SELECT count(*)
        FROM TempClassMemberRecords
        )
DECLARE @Country VARCHAR(50)

SET @Country = 'USA'

-- Const variables for class member inserts
DECLARE @DefaultCommPreference VARCHAR(50) = (
        SELECT TOP 1 CommPreference
        FROM Actors
        WHERE PKID = 0
        )
    ,@PrimaryActorTypeId INT = (
        SELECT TOP 1 PKId
        FROM ActorTypes
        WHERE ActorTypeName = 'PrimaryClaimant'
        )
    ,@SecondaryActorTypeId INT = (
        SELECT TOP 1 PKId
        FROM ActorTypes
        WHERE ActorTypeName = 'CoClaimant'
        )
    ,@HomePhoneTypeId INT = (
        SELECT TOP 1 PKId
        FROM PhoneTypes
        WHERE PhoneTypeName = 'Home'
        )
    ,@WorkPhoneTypeId INT = (
        SELECT TOP 1 PKId
        FROM PhoneTypes
        WHERE PhoneTypeName = 'Work'
        )
    ,@PrimaryCountryId INT = IsNull((
            SELECT TOP 1 PKId
            FROM Countries
            WHERE @Country IN (
                    CountryName
                    ,CountryCode
                    )
            ), 0)
    ,@DefaultCountryId INT = IsNull((
            SELECT TOP 1 PKId
            FROM Countries
            WHERE CountryCode = 'USA'
            ), 0)
    ,@SubmitTypeId INT = (
        SELECT TOP 1 PKId
        FROM ClaimSubmitTypes
        WHERE SubmitTypeName = 'Bulk'
        )
    ,@ClaimStatusId INT = (
        SELECT TOP 1 PKId
        FROM ClaimStatusTypes
        WHERE StatusName = 'Active'
        )
    ,@ModifiedBy VARCHAR(20) = @uploadUser
    ,@ModifiedDate DATETIME = GETDATE()
    ,@CaseCode VARCHAR(50) = (
        SELECT TOP 1 CaseCode
        FROM Cases
        ORDER BY PKId DESC
        ) + ''
    ,@IndividualClaimantType INT = (
        SELECT TOP 1 PKId
        FROM claimanttypes
        WHERE ClaimantTypeName = 'Individual'
        )
    ,@CompanyClaimantType INT = (
        SELECT TOP 1 PKId
        FROM claimanttypes
        WHERE ClaimantTypeName = 'Corporation'
        )
    ,@Checked BIT = 0
    ,@startingPKId INT = (
        SELECT max(PKId) + 1
        FROM dbo.Entities WITH (NOLOCK)
        );

--Record per group insert
IF (@TotalRECORD <= @RecordsPerLoop)
    SET @max = @TotalRECORD
</code>```

The run your insert loop:

```<code>-- our main loop
WHILE (@min <= @TotalRECORD)
BEGIN
    IF OBJECT_ID('tempdb..#EntityIds') IS NOT NULL
        DROP TABLE #EntityIds

    IF OBJECT_ID('tempdb..#RefNumRepository') IS NOT NULL
        DROP TABLE #RefNumRepository

    IF OBJECT_ID('tempdb..#ActorIds') IS NOT NULL
        DROP TABLE #ActorIds

    IF OBJECT_ID('tempdb..#SecondaryActorIds') IS NOT NULL
        DROP TABLE #SecondaryActorIds

    CREATE TABLE #EntityIds (
        pkid INT identity(1, 1) NOT NULL
        ,mid INT
        ,eid INT
        )

    CREATE TABLE #ActorIds (
        pkid INT identity(1, 1) NOT NULL
        ,mid INT
        ,aid INT
        )

    CREATE TABLE #SecondaryActorIds (
        pkid INT identity(1, 1) NOT NULL
        ,mid INT
        ,aid INT
        )

    CREATE TABLE #RefNumRepository (
        pkid INT identity(1, 1) NOT NULL
        ,RefNum VARCHAR(50)
        )

    BEGIN TRANSACTION

    BEGIN TRY
        UPDATE TOP (@RecordsPerLoop + 1) RefNumRepository
        SET IsUsed = 1
        OUTPUT deleted.RefNum
        INTO #RefNumRepository(RefNum)
        WHERE IsUsed = 0;

        PRINT 'Entities'
        INSERT INTO Entities (
            ModifiedBy
            ,ModifiedDate
            ,RecordOwnerName
            ,IsConflictOfInterest
            ,FKClaimantTypeId
            ,OtherClaimantType
            ,InstitutionAccountNumber
            ,RefNum
            ,FKSubmitTypeId
            ,FKClaimStatusTypeId
            ,RecordType
            ,ClaimNum
            ,FilingDate
            ,FirstName
            ,Lastname
            ,Email
            ,SSN
            ,Source
            ,ClaimDataCertifiedDate
            )
        OUTPUT Inserted.pkid
            ,Inserted.source
        INTO #EntityIds(eid, mid)
        SELECT @ModifiedBy
            ,@ModifiedDate
            ,NULL
            ,1
            ,CASE
                WHEN IsNull(company, '') = ''
                    THEN @IndividualClaimantType
                ELSE @CompanyClaimantType
                END
            ,NULL
            ,NULL
            ,''
            ,@SubmitTypeId
            ,@ClaimStatusId
            ,'CM'
            ,NULL
            ,@ModifiedDate
            ,IsNull(fname, '')
            ,IsNull(lname, '')
            ,IsNull(Email, '')
            ,IsNull(ssn, '')
            ,rawID
            ,@ModifiedDate
        FROM TempClassMemberRecords
        WHERE rawID BETWEEN @min
                AND @max
            AND IsProcessed IS NULL

        EXEC dbo.[USP_AssignClassMemberRefNums] @startingPKId

        PRINT 'Actors'
        -- bulk insert our range of class members into Actors while inserting the primary key into our temp table
        INSERT INTO Actors (
            FKActorTypeId
            ,ModifiedBy
            ,ModifiedDate
            ,LastName
            ,FirstName
            ,MiddleName
            ,CommPreference
            ,IsPayee
            ,IsUSCitizen
            ,ein
            ,ssn
            ,company
            ,attention
            ,NotificationsBlocked
            ,SearchName
            ,ClientAcctNumber
            )
        OUTPUT Inserted.pkid
            ,inserted.attention
        INTO #ActorIds(aid, mid)
        SELECT @PrimaryActorTypeId
            ,@ModifiedBy
            ,@ModifiedDate
            ,IsNull(lname, '')
            ,IsNull(fname, '')
            ,''
            ,IsNull(@DefaultCommPreference, 'Mail')
            ,1
            ,NULL
            ,IsNull(ein, '')
            ,IsNull(ssn, '')
            ,IsNull(company, '')
            ,rawid
            ,0
            ,CASE WHEN len(ISNULL(company, '')) > 0 THEN company
            ELSE
            CASE WHEN (len(ISNULL(lname, '')) > 0 OR len(ISNULL(fname, '')) > 0)
            THEN lname + ', ' +  fname
            ELSE ''
            END
            END
            ,ACCTNUM
        FROM TempClassMemberRecords
        WHERE (
                isnull(company, '') <> ''
                OR isNull(fname, '') <> ''
                OR isNull(lname, '') <> ''
                )
            AND rawid BETWEEN @Min
                AND @Max
            AND IsProcessed IS NULL

    PRINT 'Entities2Actors'
    -- bulk insert the relations of Entities to Actors in Entities2Actors
    INSERT INTO Entities2Actors (
        FKEntityId
        ,FKActorId
        ,IsActorBeneficiary
        ,ModifiedBy
        ,ModifiedDate
        )
    SELECT e.eid
        ,a.aid
        ,1
        ,@ModifiedBy
        ,@ModifiedDate
    FROM #EntityIds e
    INNER JOIN #ActorIds a ON e.mid = a.mid
    -- etc...
    PRINT 'Addressed'
    --Bulk Insert into Address table for Primary Actor Address
    INSERT INTO Addresses (
        FKActorId
        ,ModifiedBy
        ,ModifiedDate
        ,Address1
        ,Address2
        ,City
        ,STATE
        ,Zip
        ,Zip4
        ,FKCountryId
        )
    SELECT a.aid
        ,@ModifiedBy
        ,@ModifiedDate
        ,IsNull(Address, '')
        ,IsNull(Address2, '')
        ,IsNull(City, '')
        ,IsNull([State], '')
        ,IsNull(Zip, '')
        ,IsNull(Zip4, '')
        ,ISNULL(@PrimaryCountryId, @DefaultCountryId)
    FROM #ActorIds a
    INNER JOIN TempClassMemberRecords c ON a.mid = c.rawId
-- etc...
UPDATE tempClassMemberRecords
    SET IsProcessed = 1
    WHERE rawid BETWEEN @Min
            AND @Max
        AND IsProcessed IS NULL

    SET @Min = @max + 1
    SET @max = @max + @RecordsPerloop

    COMMIT TRANSACTION

    WAITFOR DELAY '000:00:00.400'
END TRY

BEGIN CATCH
    ROLLBACK TRANSACTION

    RAISERROR (N'Error in moving data from Temporary table to Main tables.', -- Message text.
       1,
       1);

    PRINT 'Failed with error: ' + ERROR_MESSAGE()
END CATCH
</code>```

Body:
I have had to deal with this situation with bulk data that includes million of records. From many wasted weeks of experience:

1) Do everything in your power not to use excel. It is slow and eats up loads of memory. A single sheet with 500,00 records can end up eating up over 2 gigabytes of memory just to load the file. The imports then take 30-40-50 minutes or more for a single sheet. Consider converting the data to CSV and importing it using SqlBulkCopy. It can handle a massive amount of records on the order of seconds to a few minutes as opposed to hours.

2) There's not much you can do when it comes to improving the performance o Entity Framework in this situation. I found the best and fastest approach was to load each sheet into its own temp table in the Database. Then I constructed SQL to do the bulk inserts into their end tables. Results of intermediate inserts can be captured into output tables so you can access the keys necessary to perform any joins from the temp table or inserts into related tables.  You can of course "steal` some of the auto generated EF SQL but then you'll need to fine tune it.

3) Even though SQL hates loops, I coded my sql statements to run in a loop and inserts of say 100,000 records at a time. It made the inserts run much faster.

To give you an idea, after bulk importing each sheet form CSV:

First define your variables and types stored in related tables as needed:

DECLARE @Max INT = @RecordsPerLoop
DECLARE @Min INT = 0
DECLARE @TotalRECORD INT = (
        SELECT count(*)
        FROM TempClassMemberRecords
        )
DECLARE @Country VARCHAR(50)

SET @Country = 'USA'

-- Const variables for class member inserts
DECLARE @DefaultCommPreference VARCHAR(50) = (
        SELECT TOP 1 CommPreference
        FROM Actors
        WHERE PKID = 0
        )
    ,@PrimaryActorTypeId INT = (
        SELECT TOP 1 PKId
        FROM ActorTypes
        WHERE ActorTypeName = 'PrimaryClaimant'
        )
    ,@SecondaryActorTypeId INT = (
        SELECT TOP 1 PKId
        FROM ActorTypes
        WHERE ActorTypeName = 'CoClaimant'
        )
    ,@HomePhoneTypeId INT = (
        SELECT TOP 1 PKId
        FROM PhoneTypes
        WHERE PhoneTypeName = 'Home'
        )
    ,@WorkPhoneTypeId INT = (
        SELECT TOP 1 PKId
        FROM PhoneTypes
        WHERE PhoneTypeName = 'Work'
        )
    ,@PrimaryCountryId INT = IsNull((
            SELECT TOP 1 PKId
            FROM Countries
            WHERE @Country IN (
                    CountryName
                    ,CountryCode
                    )
            ), 0)
    ,@DefaultCountryId INT = IsNull((
            SELECT TOP 1 PKId
            FROM Countries
            WHERE CountryCode = 'USA'
            ), 0)
    ,@SubmitTypeId INT = (
        SELECT TOP 1 PKId
        FROM ClaimSubmitTypes
        WHERE SubmitTypeName = 'Bulk'
        )
    ,@ClaimStatusId INT = (
        SELECT TOP 1 PKId
        FROM ClaimStatusTypes
        WHERE StatusName = 'Active'
        )
    ,@ModifiedBy VARCHAR(20) = @uploadUser
    ,@ModifiedDate DATETIME = GETDATE()
    ,@CaseCode VARCHAR(50) = (
        SELECT TOP 1 CaseCode
        FROM Cases
        ORDER BY PKId DESC
        ) + ''
    ,@IndividualClaimantType INT = (
        SELECT TOP 1 PKId
        FROM claimanttypes
        WHERE ClaimantTypeName = 'Individual'
        )
    ,@CompanyClaimantType INT = (
        SELECT TOP 1 PKId
        FROM claimanttypes
        WHERE ClaimantTypeName = 'Corporation'
        )
    ,@Checked BIT = 0
    ,@startingPKId INT = (
        SELECT max(PKId) + 1
        FROM dbo.Entities WITH (NOLOCK)
        );

--Record per group insert
IF (@TotalRECORD <= @RecordsPerLoop)
    SET @max = @TotalRECORD

The run your insert loop:

-- our main loop
WHILE (@min <= @TotalRECORD)
BEGIN
    IF OBJECT_ID('tempdb..#EntityIds') IS NOT NULL
        DROP TABLE #EntityIds

    IF OBJECT_ID('tempdb..#RefNumRepository') IS NOT NULL
        DROP TABLE #RefNumRepository

    IF OBJECT_ID('tempdb..#ActorIds') IS NOT NULL
        DROP TABLE #ActorIds

    IF OBJECT_ID('tempdb..#SecondaryActorIds') IS NOT NULL
        DROP TABLE #SecondaryActorIds

    CREATE TABLE #EntityIds (
        pkid INT identity(1, 1) NOT NULL
        ,mid INT
        ,eid INT
        )

    CREATE TABLE #ActorIds (
        pkid INT identity(1, 1) NOT NULL
        ,mid INT
        ,aid INT
        )

    CREATE TABLE #SecondaryActorIds (
        pkid INT identity(1, 1) NOT NULL
        ,mid INT
        ,aid INT
        )

    CREATE TABLE #RefNumRepository (
        pkid INT identity(1, 1) NOT NULL
        ,RefNum VARCHAR(50)
        )

    BEGIN TRANSACTION

    BEGIN TRY
        UPDATE TOP (@RecordsPerLoop + 1) RefNumRepository
        SET IsUsed = 1
        OUTPUT deleted.RefNum
        INTO #RefNumRepository(RefNum)
        WHERE IsUsed = 0;

        PRINT 'Entities'
        INSERT INTO Entities (
            ModifiedBy
            ,ModifiedDate
            ,RecordOwnerName
            ,IsConflictOfInterest
            ,FKClaimantTypeId
            ,OtherClaimantType
            ,InstitutionAccountNumber
            ,RefNum
            ,FKSubmitTypeId
            ,FKClaimStatusTypeId
            ,RecordType
            ,ClaimNum
            ,FilingDate
            ,FirstName
            ,Lastname
            ,Email
            ,SSN
            ,Source
            ,ClaimDataCertifiedDate
            )
        OUTPUT Inserted.pkid
            ,Inserted.source
        INTO #EntityIds(eid, mid)
        SELECT @ModifiedBy
            ,@ModifiedDate
            ,NULL
            ,1
            ,CASE
                WHEN IsNull(company, '') = ''
                    THEN @IndividualClaimantType
                ELSE @CompanyClaimantType
                END
            ,NULL
            ,NULL
            ,''
            ,@SubmitTypeId
            ,@ClaimStatusId
            ,'CM'
            ,NULL
            ,@ModifiedDate
            ,IsNull(fname, '')
            ,IsNull(lname, '')
            ,IsNull(Email, '')
            ,IsNull(ssn, '')
            ,rawID
            ,@ModifiedDate
        FROM TempClassMemberRecords
        WHERE rawID BETWEEN @min
                AND @max
            AND IsProcessed IS NULL

        EXEC dbo.[USP_AssignClassMemberRefNums] @startingPKId

        PRINT 'Actors'
        -- bulk insert our range of class members into Actors while inserting the primary key into our temp table
        INSERT INTO Actors (
            FKActorTypeId
            ,ModifiedBy
            ,ModifiedDate
            ,LastName
            ,FirstName
            ,MiddleName
            ,CommPreference
            ,IsPayee
            ,IsUSCitizen
            ,ein
            ,ssn
            ,company
            ,attention
            ,NotificationsBlocked
            ,SearchName
            ,ClientAcctNumber
            )
        OUTPUT Inserted.pkid
            ,inserted.attention
        INTO #ActorIds(aid, mid)
        SELECT @PrimaryActorTypeId
            ,@ModifiedBy
            ,@ModifiedDate
            ,IsNull(lname, '')
            ,IsNull(fname, '')
            ,''
            ,IsNull(@DefaultCommPreference, 'Mail')
            ,1
            ,NULL
            ,IsNull(ein, '')
            ,IsNull(ssn, '')
            ,IsNull(company, '')
            ,rawid
            ,0
            ,CASE WHEN len(ISNULL(company, '')) > 0 THEN company
            ELSE
            CASE WHEN (len(ISNULL(lname, '')) > 0 OR len(ISNULL(fname, '')) > 0)
            THEN lname + ', ' +  fname
            ELSE ''
            END
            END
            ,ACCTNUM
        FROM TempClassMemberRecords
        WHERE (
                isnull(company, '') <> ''
                OR isNull(fname, '') <> ''
                OR isNull(lname, '') <> ''
                )
            AND rawid BETWEEN @Min
                AND @Max
            AND IsProcessed IS NULL

    PRINT 'Entities2Actors'
    -- bulk insert the relations of Entities to Actors in Entities2Actors
    INSERT INTO Entities2Actors (
        FKEntityId
        ,FKActorId
        ,IsActorBeneficiary
        ,ModifiedBy
        ,ModifiedDate
        )
    SELECT e.eid
        ,a.aid
        ,1
        ,@ModifiedBy
        ,@ModifiedDate
    FROM #EntityIds e
    INNER JOIN #ActorIds a ON e.mid = a.mid
    -- etc...
    PRINT 'Addressed'
    --Bulk Insert into Address table for Primary Actor Address
    INSERT INTO Addresses (
        FKActorId
        ,ModifiedBy
        ,ModifiedDate
        ,Address1
        ,Address2
        ,City
        ,STATE
        ,Zip
        ,Zip4
        ,FKCountryId
        )
    SELECT a.aid
        ,@ModifiedBy
        ,@ModifiedDate
        ,IsNull(Address, '')
        ,IsNull(Address2, '')
        ,IsNull(City, '')
        ,IsNull([State], '')
        ,IsNull(Zip, '')
        ,IsNull(Zip4, '')
        ,ISNULL(@PrimaryCountryId, @DefaultCountryId)
    FROM #ActorIds a
    INNER JOIN TempClassMemberRecords c ON a.mid = c.rawId
-- etc...
UPDATE tempClassMemberRecords
    SET IsProcessed = 1
    WHERE rawid BETWEEN @Min
            AND @Max
        AND IsProcessed IS NULL

    SET @Min = @max + 1
    SET @max = @max + @RecordsPerloop

    COMMIT TRANSACTION

    WAITFOR DELAY '000:00:00.400'
END TRY

BEGIN CATCH
    ROLLBACK TRANSACTION

    RAISERROR (N'Error in moving data from Temporary table to Main tables.', -- Message text.
       1,
       1);

    PRINT 'Failed with error: ' + ERROR_MESSAGE()
END CATCH


问:
Height for tableView.headerView(forSection: 0) is nil
I'm trying to change the height of the header view as the user scrolls following this tutorial. However, when I try to access self.songsTable.headerView(forSection: 0)?.frame.size.height (so I can update the height of the header view), the value is nil and the debugger tells me "header view has no height". I created my header view programmatically using heightForHeaderInSection and viewForHeaderInSection.

Code

```<code>class SongsViewController {
var currentHeaderHeight: CGFloat = 136

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        //Throws error
        guard let currentHeaderHeight = self.songsTable.headerView(forSection: 0)?.frame.size.height else {
            print("header view has no height")
            return
        }
    }

    public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return currentHeaderHeight
    }

    public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = UIView()
        headerView.frame = CGRect(x: 0, y: 0, width: Screen.width, height: maxHeaderHeight)
        return headerView
    }
}
</code>```

答:
This may just be missing in your code snippet, but have you set up your viewController as the TableViewDataSource?</p>

```<code>class SongsViewController: UIViewController, UITableViewDataSource {

    override func viewDidLoad() {
        super.viewDidLoad()
        songsTable.dataSource = self
    }

    // ... the rest of your code ...
}
</code>```

Body:
I'm trying to change the height of the header view as the user scrolls following this tutorial. However, when I try to access self.songsTable.headerView(forSection: 0)?.frame.size.height (so I can update the height of the header view), the value is nil and the debugger tells me "header view has no height". I created my header view programmatically using heightForHeaderInSection and viewForHeaderInSection.

Code

class SongsViewController {
var currentHeaderHeight: CGFloat = 136

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        //Throws error
        guard let currentHeaderHeight = self.songsTable.headerView(forSection: 0)?.frame.size.height else {
            print("header view has no height")
            return
        }
    }

    public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return currentHeaderHeight
    }

    public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerView = UIView()
        headerView.frame = CGRect(x: 0, y: 0, width: Screen.width, height: maxHeaderHeight)
        return headerView
    }
}

Body:
This may just be missing in your code snippet, but have you set up your viewController as the TableViewDataSource?

class SongsViewController: UIViewController, UITableViewDataSource {

    override func viewDidLoad() {
        super.viewDidLoad()
        songsTable.dataSource = self
    }

    // ... the rest of your code ...
}