问:
How to create a SocialMedia TimeLine with JSON and PHP?
I am creating a website where I like to get a timeline of my socialmedia accounts. Currently, I have 2 PHP classes (Youtube-plugin, Instagram-Plugin)  that get me JSON Files of each network.

```<code>class PersonalinstagramPlugin{
    public $myAccesToken;
    public $myUsername;
    public $myUserID;

public function __construct($accesToken,$Username) {
    $this->myAccesToken = $accesToken;
    $this->myUsername = $Username;
    $this->myUserID = $this->curlConnect("https://api.instagram.com/v1/users/search?q=" . $this->myUsername . "&access_token=" . $this->myAccesToken)->data[0]->id; }

public function curlConnect($api_url)
{
    $connection_c = curl_init(); // initializing
    curl_setopt( $connection_c, CURLOPT_URL, $api_url ); // API URL to connect
    curl_setopt( $connection_c, CURLOPT_RETURNTRANSFER, 1 ); // return the result, do not print
    curl_setopt( $connection_c, CURLOPT_TIMEOUT, 20 );
    $json_return = curl_exec( $connection_c ); // connect and get json data
    curl_close( $connection_c ); // close connection
    return json_decode( $json_return ); // decode and return
}
public function getLatestPosts()
{
     $response = $this->curlConnect("https://api.instagram.com/v1/users/".$this->myUserID."/media/recent?access_token=".$this->myAccesToken);
     return $response;
}
</code>```

For a the youtube plugin it is the same.
What is the best way to combine the data you get from each plugin (JSON) and combine them in one timeline sorted by date?

答:
Taking this from an OO approach, I would suggest you look into inheritance. The result you get from youtube and the result you get from instagram likely have some common fields such as an ID, postdate, last modified and content. Create an object that can store these common fields and call it something like SocialMediaPost. This can be used to represent every single social media post. </p>

<p>You can then create 2 objects specific to each network that contain the custom fields and these classes can inherit from the SocialMediaPost class. You can parse the json to the custom objects and store them in an array. Using a loop you can then cast each post to the base type and order them by the post date or something like that. </p>

Body:
I am creating a website where I like to get a timeline of my socialmedia accounts. Currently, I have 2 PHP classes (Youtube-plugin, Instagram-Plugin)  that get me JSON Files of each network.

class PersonalinstagramPlugin{
    public $myAccesToken;
    public $myUsername;
    public $myUserID;

public function __construct($accesToken,$Username) {
    $this->myAccesToken = $accesToken;
    $this->myUsername = $Username;
    $this->myUserID = $this->curlConnect("https://api.instagram.com/v1/users/search?q=" . $this->myUsername . "&access_token=" . $this->myAccesToken)->data[0]->id; }

public function curlConnect($api_url)
{
    $connection_c = curl_init(); // initializing
    curl_setopt( $connection_c, CURLOPT_URL, $api_url ); // API URL to connect
    curl_setopt( $connection_c, CURLOPT_RETURNTRANSFER, 1 ); // return the result, do not print
    curl_setopt( $connection_c, CURLOPT_TIMEOUT, 20 );
    $json_return = curl_exec( $connection_c ); // connect and get json data
    curl_close( $connection_c ); // close connection
    return json_decode( $json_return ); // decode and return
}
public function getLatestPosts()
{
     $response = $this->curlConnect("https://api.instagram.com/v1/users/".$this->myUserID."/media/recent?access_token=".$this->myAccesToken);
     return $response;
}

For a the youtube plugin it is the same.
What is the best way to combine the data you get from each plugin (JSON) and combine them in one timeline sorted by date?

Body:
Taking this from an OO approach, I would suggest you look into inheritance. The result you get from youtube and the result you get from instagram likely have some common fields such as an ID, postdate, last modified and content. Create an object that can store these common fields and call it something like SocialMediaPost. This can be used to represent every single social media post.

You can then create 2 objects specific to each network that contain the custom fields and these classes can inherit from the SocialMediaPost class. You can parse the json to the custom objects and store them in an array. Using a loop you can then cast each post to the base type and order them by the post date or something like that.


来源: stackexchange

问:
What is wrong with putting Using Blocks in Repository?
I have using blocks in each method of my repository. If I want to cross reference methods, it seems it would be against best practices to initialize another Datacontext  What am i doing wrong? If I declare a Datacontext in the class instead of using blocks in methods will I not lose power to dispose ??</p>

```<code>public IList<something> GetSomething()
{
   using (DB db=new DB())

   { ...GetListofSomethingElse(id)

   }
}

public IList<somethingelse> GetListofSomethingElse(int id)
{
    using (DB db=new DB())
   {
     ... return IList

   }
}
</code>```

答:
If you don't use a using statement, you can still dispose explicitly. Even if you don't dispose of the data context though, cross-referencing these methods will still create a new data context. That may or may not be a good thing, depending on your usage. Think about the state management aspect of the data context, and whether you want to isolate the methods from each other or not. If you want to avoid creating a new context all the time, overload the methods with versions which take the context as a parameter.

Note that you don't usually need to dispose of a data context, although I tend to dispose of anything implementing IDisposable.

OwnerDisplayName: zsharp

ContentLicense: CC BY-SA 2.5

Body:
I have using blocks in each method of my repository. If I want to cross reference methods, it seems it would be against best practices to initialize another Datacontext  What am i doing wrong? If I declare a Datacontext in the class instead of using blocks in methods will I not lose power to dispose ??

public IList<something> GetSomething()
{
   using (DB db=new DB())

   { ...GetListofSomethingElse(id)

   }
}

public IList<somethingelse> GetListofSomethingElse(int id)
{
    using (DB db=new DB())
   {
     ... return IList

   }
}

OwnerDisplayName: Jon Skeet


问:
How can I detect browser and OS of user and use this to dynamically modify my MySQL database query from a PHP page
I need to be able to run a mysql query and omit certain results if the user is using a certain browser on a certain OS. My database query takes place from an AMFPHP service and I have a javascript browserDetect script that I can use to get user browser and OS.

Ideally I want to run the browserDetect script when the user arrives at my page and then store this in the PHP session variables but I cannot see how to pass the javascript vars to the PHP session. This would allow my database query script to look up the session and modify the query accordingly. I also tried to include the browser detect script in the AMFPHP script but this did not work - I realise that this a serverside vs client side problem.

What other solutions would work for me?

thanks

答:
As @thedom said, just use $_SERVER['HTTP_USER_AGENT'] in PHP. Your user agent (Unless modified by the user) will contain the browser, browser version and os.
Here's mine:

```<code>Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.15 (KHTML, like Gecko) Chrome/10.0.612.1 Safari/534.15
</code>```

BUT if you want to use javascript, you'll have to do something similar to what I did to implement ajax logins.

I basically put this at the top of the script (login.php)

```<code>session_id($_POST['PHPSESSID']);
session_start();
</code>```

And this in the page the javascript will be run from to detect session (index.php)

```<code>$sessionid = ($_COOKIE['PHPSESSID']) ? $_COOKIE['PHPSESSID'] : $_GET['PHPSESSID'];
<script type="text/javascript">var session = "$sessionid";</script>
</code>```

And then I post to the other script (login.php) (To log you in via ajax in this case)

```<code>$.post("ajax/login.php",PHPSESSID=" + session);
</code>```

Using JQuery.

Body:
As @thedom said, just use $_SERVER['HTTP_USER_AGENT'] in PHP. Your user agent (Unless modified by the user) will contain the browser, browser version and os.
Here's mine:

Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.15 (KHTML, like Gecko) Chrome/10.0.612.1 Safari/534.15

BUT if you want to use javascript, you'll have to do something similar to what I did to implement ajax logins.

I basically put this at the top of the script (login.php)

session_id($_POST['PHPSESSID']);
session_start();

And this in the page the javascript will be run from to detect session (index.php)

$sessionid = ($_COOKIE['PHPSESSID']) ? $_COOKIE['PHPSESSID'] : $_GET['PHPSESSID'];
<script type="text/javascript">var session = "$sessionid";</script>

And then I post to the other script (login.php) (To log you in via ajax in this case)

$.post("ajax/login.php",PHPSESSID=" + session);

Using JQuery.


问:
HTML input not updating value
I have a very strange problem (at least to me).
I dynamically create textboxes, and it works fine. But the problem is when I try to write in those, if I check the html code, values that I write do not appear. I have no idea why this is happening or how to work arround this.
Here is my code example.

```<code><ul class="ml4 js-sortable-buttons list flex flex-column list-reset" data-disabled="false" id="page-content">
    <li class="p1 mb1 blue bg-white" id="id"><input type="text" class="textbox" /></li>
</ul>
<div class="center py2 ml4">
    <div class="js-add-textbox-button button blue bg-white" >add textbox</div>
    <div class="show_html_button blue bg-white">show html</div>
</div>

<!-- <script src="../src/html.sortable.js"></script> -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="html.sortable.min.js"></script>
<script  type="text/javascript">
        sortable('.js-sortable-buttons', {
            forcePlaceholderSize: true,
            items: 'li',
            placeholderClass: 'border border-white mb1'

        });
        // buttons to add items and reload the list
        // separately to showcase issue without reload
        document.querySelector('.js-add-textbox-button').addEventListener('click', function () {
            doc = new DOMParser().parseFromString(`<li class="p1 mb1 blue bg-white"><input type="text" class="textbox"></li>`, "text/html").body.firstChild;
            document.querySelector('.js-sortable-buttons').appendChild(doc);
            sortable('.js-sortable-buttons');
            window.stop();
        });
</script>

    <script  type="text/javascript">
        $(".show_html_button").click(function () {
            var optionTexts = $("#page-content").clone(true);
            alert(optionTexts.html());
        });
</script>
</code>```

Any help would be greatly appreciated.

答:
That's not how javascript works. A webpage's HTML doesn't automatically update when an input field's value changes.

If you want such functionality, you could do this:

$(function(){
  $('.js-sortable-buttons').on('keyup change paste','input',function(){
    $(this).attr('value', $(this).val());
  });
});```

ContentLicense: CC BY-SA 3.0

Title: HTML input not updating value

Body:
I have a very strange problem (at least to me).
I dynamically create textboxes, and it works fine. But the problem is when I try to write in those, if I check the html code, values that I write do not appear. I have no idea why this is happening or how to work arround this.
Here is my code example.

<input type="text" class="textbox" />

add textbox

show html

Any help would be greatly appreciated.


问:
Xcode error "Could not find Developer Disk Image"
When attempting to run a build on a connected iOS device in Xcode I get the error:

Could not find Developer Disk Image

I saw that there was a public beta for Xcode, so I installed it.

One of the new features is that you don't need to have a Developer Program Account Dingus to upload your app directly to your iPhone.

However, on my iPhone 4s, I also did a public beta update to iOS 8.4, problem being, that there's no Developer Disk Image available for it.

Where do I to find it or how can it be fixed?

答:
This problem is fundamentally rooted in the mismatch of your iOS version and Xcode version.

Check the compatibility of iOS and Xcode.

Go To Application folder (In finder) -> right click on Xcode -> click on show package contents -> Double click contents folder -> Double click developers folder -> Double click platforms folder -> Double click iPhoneOS.platform folder -> Double click device support folder -> then add latest developer disk image.

Or

Download Latest version of Xcode.


问:
How do I make decision based on arch in Ansible playbooks?
I have been trying to write playbooks where I can run different tasks based on the arch (i.e amd64, arm, ppc64le) that the playbook is running on. I am not able to figure out how do I get the arch of the system I am running it on.

Can you please help me with figuring out the arch of the system in Ansible playbook.

答:
To get the architecture of the system

At the command line:

```<code>ansible HOST -m setup -a 'filter=ansible_architecture'
</code>```

For an x86 architecture host, this would return:

```<code>HOST | SUCCESS => {
    "ansible_facts": {
        "ansible_architecture": "x86_64"
    },
    "changed": false
}
</code>```

Here’s a sample playbook that will print out the architecture of all hosts in your inventory:

```<code>- name: print out hosts architectures
  hosts: all
  gather_facts: True
  tasks:
  - debug: var= ansible_architecture
</code>```

To run tasks based off the architecture

Use a when clause:

```<code>- name: task to run for x86 architecture
  shell: echo "x86 arch found here"
  when: ansible_architecture == "x86_64"
</code>```

Body:
To get the architecture of the system

At the command line:

ansible HOST -m setup -a 'filter=ansible_architecture'

For an x86 architecture host, this would return:

HOST | SUCCESS => {
    "ansible_facts": {
        "ansible_architecture": "x86_64"
    },
    "changed": false
}

Here’s a sample playbook that will print out the architecture of all hosts in your inventory:

- name: print out hosts architectures
  hosts: all
  gather_facts: True
  tasks:
  - debug: var= ansible_architecture

To run tasks based off the architecture

Use a when clause:

- name: task to run for x86 architecture
  shell: echo "x86 arch found here"
  when: ansible_architecture == "x86_64"


问:
Hibernate Search and Relations
I have an object called MyItemBean which can have 0 or more associated KeywordBean objects.  The resulting classes look like this:

```<code>@Entity
public class MyItemBean {

   ...stuff...

   @ManyToMany(targetEntity = KeywordBean.class, cascade = CascadeType.PERSIST)
   @JoinTable(name = "tbl_item_keyword", joinColumns = @JoinColumn(name = "item_id"), inverseJoinColumns = @JoinColumn(name = "keyword_id"))
   private List<KeywordBean> keywords = null;

   ...more stuff...
}

@Entity
public class KeywordBean {

   ...stuff...

   private String value=null;

   ...more stuff...
}
</code>```

I'm using JBoss Seam/Hibernate Search to index these objects so I can perform search queries against them.  I'd like to be able to search for MyItemBean instances with a given keyword value.  This relation, however, is unidirectional because I apply KeywordBean objects to more than just MyItemBean.  I've looked in the Hibernate Search documentation for examples on how to index relations, but all of the examples they provide are bi-directional.  Can anyone tell me what annotations I need to apply on MyItemBean.keywords to index the keyword values properly?

答:
The annotation to use is IndexedEmbedded. It works fine with unidirectional associations as well. A problem can occur if you are changing the value of KeywordBean Hibernate Search does not have a way to update the index for the MyItemBean instances which reference the changed KeywordBean. In bidirectional relations you can use @ContainedIn to fix this problem, but you don't really need this. Provided on your usecase this index updating constraint might not be an issue. Maybe your KeywordBean is not changing. Or if it changes you can re-index all *KeywordBean*s which are affected manually.

--Hardy

Title: Hibernate Search and Relations

Body:
I have an object called MyItemBean which can have 0 or more associated KeywordBean objects.  The resulting classes look like this:

@Entity
public class MyItemBean {

   ...stuff...

   @ManyToMany(targetEntity = KeywordBean.class, cascade = CascadeType.PERSIST)
   @JoinTable(name = "tbl_item_keyword", joinColumns = @JoinColumn(name = "item_id"), inverseJoinColumns = @JoinColumn(name = "keyword_id"))
   private List<KeywordBean> keywords = null;

   ...more stuff...
}

@Entity
public class KeywordBean {

   ...stuff...

   private String value=null;

   ...more stuff...
}

I'm using JBoss Seam/Hibernate Search to index these objects so I can perform search queries against them.  I'd like to be able to search for MyItemBean instances with a given keyword value.  This relation, however, is unidirectional because I apply KeywordBean objects to more than just MyItemBean.  I've looked in the Hibernate Search documentation for examples on how to index relations, but all of the examples they provide are bi-directional.  Can anyone tell me what annotations I need to apply on MyItemBean.keywords to index the keyword values properly?


问:
Node.js: callback is not a function
I am kinda new to Node JS. I get an error with my callback. This is my code:

```<code>var list=['382813587410259968','881413399304863744'];
var content=[];
var dataj;
list.forEach(function(value,callback){
Twitter.get('statuses/oembed', { id:value},  function (err, data, response) {
if(err)
{callback(err,null,null);}
dataj=data.html.toString;
callback(null,dataj,null);
        });
function func(dataj)
{
content.push(dataj);
console.log(content);
}
});
</code>```

The callback(null,data,null) returns error. I would be very glad if you could help me out here.

答:
Issue with  line

list.forEach(function(value,callback)

No need to pass value. It is available internally.

For Demo Try following code snippet

```<code>   var list=['382813587410259968','881413399304863744'];
   function callback(item, index) {
      console.log("index[" + index + "]: " + item );
   }
   list.forEach(callback);
</code>```

You can also refer following link for more clarity

https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_foreach

Title: Node.js: callback is not a function

Body:
I am kinda new to Node JS. I get an error with my callback. This is my code:

var list=['382813587410259968','881413399304863744'];
var content=[];
var dataj;
list.forEach(function(value,callback){
Twitter.get('statuses/oembed', { id:value},  function (err, data, response) {
if(err)
{callback(err,null,null);}
dataj=data.html.toString;
callback(null,dataj,null);
        });
function func(dataj)
{
content.push(dataj);
console.log(content);
}
});

The callback(null,data,null) returns error. I would be very glad if you could help me out here.

Body:
Issue with  line

list.forEach(function(value,callback)

No need to pass value. It is available internally.

For Demo Try following code snippet

   var list=['382813587410259968','881413399304863744'];
   function callback(item, index) {
      console.log("index[" + index + "]: " + item );
   }
   list.forEach(callback);

You can also refer following link for more clarity

https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_foreach


问:
Foreach cast skip?
I have a list of some List<Building> playersBuildings containing objects all deriving from Bulilding class and I came across something that is quite unintuitive to me.

The following code:

```<code>foreach (Factory f in playersBuildings) {
    f.Update (deltaTime);
}
</code>```

tries to cast every element of playersBuildings to Factory and yields InvalidCastException error. While it has some sense, while writing the code I hoped that foreach will just omit elements that does not match specified type.

My first thought of solution was this:

```<code>foreach (Building f in playersBuildings) {
    if ((f is Factory) == false)
        continue;
    (f as Factory).Update (deltaTime);
}
</code>```

but I don't like having to use as keyword. Need to type in additional +10 characters every time I want to do something with my f under it's iteration is frustrating.

Is there any more elegant way to skip elements not matching the right type?

答:
As you already have to type is we can replace that by as:

```<code>var q = f as Factory;
if(q != null)
    f.Update(deltaTime);
</code>```

This is a bit shorter then your double check (is and as)

Title: Foreach cast skip?

Body:
I have a list of some List<Building> playersBuildings containing objects all deriving from Bulilding class and I came across something that is quite unintuitive to me.

The following code:

foreach (Factory f in playersBuildings) {
    f.Update (deltaTime);
}

tries to cast every element of playersBuildings to Factory and yields InvalidCastException error. While it has some sense, while writing the code I hoped that foreach will just omit elements that does not match specified type.

My first thought of solution was this:

foreach (Building f in playersBuildings) {
    if ((f is Factory) == false)
        continue;
    (f as Factory).Update (deltaTime);
}

but I don't like having to use as keyword. Need to type in additional +10 characters every time I want to do something with my f under it's iteration is frustrating.

Is there any more elegant way to skip elements not matching the right type?

Body:
As you already have to type is we can replace that by as:

var q = f as Factory;
if(q != null)
    f.Update(deltaTime);

This is a bit shorter then your double check (is and as)


问:
jenkins - plugin (credentials) install manually
I'm trying to setup jenkins version 1.651.3 with manual installation of credentials plugin.

But failed to install the plugin.
Here is what I tried;

Download jenkins from http://pkg.jenkins-ci.org/debian-stable/binary/jenkins_1.651.3_all.deb.

Install jenkins_1.651.3_all.deb on Ubuntu 16.04.

I can see the default credentials plugin version is 1.18.

Delete old files; rm -rf /var/lib/jenkins/plugins/credentials*.

Download latest credentials plugin from https://updates.jenkins-ci.org/download/plugins/credentials/2.1.13/credentials.hpi.

Restart jenkins; service jenkins restart.

Still the credentials version is 1.18 not 2.1.13.

How can I install the latest credentials plugin manually? I mean without accessing web UI (Manage Jenkins -> Manage plugins)?

答:
Jenkins creates a directory named after the plugin for every .hpi file you have in your $JENKINS_HOME/plugins/.

Try to find that directory (name should be 'credentials') and delete it.


问:
SQL Server 2016 Full-Text Index suddenly stops working
We are successfully using Full-Text Indexing, but multiple times a week it suddenly stops working.

Going to the affected table and disabling the Full-Text Index, then
enabling it again brings it back to life. But that's no good in a production environment!

I've checked the event log and there doesn't seem to be any error from SQL Server that might be an indication as to the cause.

Any ideas? Thanks for any input!

答:
I tested the sql statement of @RaduGheorghiu, the result for the table in question is completely empty, but it delivers results for a table where fulltext is operational.

As @BobFindlay said, the only way to get the results back is to de- and reactivate the Full-Text Index, refill won't work.
I also found the reason to this behaviour in another topic:
SMSS is responsible for destroying the catalog
When you use SMSS to add a column, SMSS will drop and recreate this and every related table (including Full-Text Index).

So you have two options if you want to prevent that from happening:

Never use SMSS for altering anything, use DDL commands instead.
Or manually disable and enable Full-Text Index every time you made any change to your table (Or any related table).


问:
How to black out everything outside a circle in Open CV
I am currently trying to black out everything outside a circle.
I am drawing the circle using the following lines of code:

```<code>cv::Point center(cvRound(circles[i][0]), cvRound(circles[i][1])); // CVRound converts floating numbers to integer
int radius = cvRound(circles[i][2]);                              // Radius is the third parameter [i][0] = x [i][1]= y [i][2] = radius
circle( image, center, 3, cv::Scalar(0,255,0), -1, 8, 0 );        // Drawing little circle to Image Center , next Line of Code draws the real circle
circle( image, center, radius, cv::Scalar(0,0,255), 3, 8, 0 );    // Circle(img, center, radius, color, thickness=1, lineType=8, shift=0)
</code>```

What is the best approach of painting everything of the circly black, if I have a radius and the center of my circle?
Does OpenCV provide an easy mechanism of doing this or should I iterate through all the pixels of my image and depending on the position color them black or not?

答:
Just tried your code snippet and it works.
Also if you want to change the background color instead of black, according to opencv docs here, before copyTo the destination mat will be initialized if needed, so just add code below:

```<code>cv::Mat maskedImage(srcImageForDimensions.size(), srcImageForDimensions.type()); // stores masked Image
maskedImage.setTo(cv::Scalar(0,0,255)); // set background color to red
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am currently trying to black out everything outside a circle.
I am drawing the circle using the following lines of code:

cv::Point center(cvRound(circles[i][0]), cvRound(circles[i][1])); // CVRound converts floating numbers to integer
int radius = cvRound(circles[i][2]);                              // Radius is the third parameter [i][0] = x [i][1]= y [i][2] = radius
circle( image, center, 3, cv::Scalar(0,255,0), -1, 8, 0 );        // Drawing little circle to Image Center , next Line of Code draws the real circle
circle( image, center, radius, cv::Scalar(0,0,255), 3, 8, 0 );    // Circle(img, center, radius, color, thickness=1, lineType=8, shift=0)

What is the best approach of painting everything of the circly black, if I have a radius and the center of my circle?
Does OpenCV provide an easy mechanism of doing this or should I iterate through all the pixels of my image and depending on the position color them black or not?

Body:
Just tried your code snippet and it works.
Also if you want to change the background color instead of black, according to opencv docs here, before copyTo the destination mat will be initialized if needed, so just add code below:

cv::Mat maskedImage(srcImageForDimensions.size(), srcImageForDimensions.type()); // stores masked Image
maskedImage.setTo(cv::Scalar(0,0,255)); // set background color to red


问:
how to change image name while uploading into folder in coldfusion

i am implementing a application in coldfusion in whis i have to store image with user defined name not actual name, i am able to store image into folder with actual name but not with user defined name ,i have to upload image into folder named "user_images", how can i change actual name with user defined name.

it will be better if any one provide code.

thanks

Yugal

答: You can provide a specific file name when you upload the file using the cffile tag.  Whatever filename you use in the destination attribute will be used to save the file.


问:
bottom layout deprecated since ios 11.0
What can I do to fix Bottom layout is deprecated iOS 11, I am using Xcode 9 beta 2.

答:
According to this, in iOS 11, IB replaces bottomLayoutGuide by safeAreaLayoutGuide.

Interface Builder uses UIView.safeAreaLayoutGuide as a replacement for
  the deprecated Top and Bottom layout guides in UIViewController. To
  use the new safe area, select Safe Area Layout Guides in the File
  inspector for the view controller, and then add constraints between
  your content and the new safe area anchors. This prevents your content
  from being obscured by top and bottom bars, and by the overscan region
  on tvOS. Constraints to the safe area are converted to Top and Bottom
  when deploying to earlier versions of iOS. (29323293)

Title: bottom layout deprecated since ios 11.0


问:
JavaScript - Find an object among an array of objects, inside an array of objects
I'm using Vue, lodash, etc.

```<code>{
  "street": {
    "id": "1",
    "streetName": "test",
    "buildings": [
      {
        "id": "1",
        "buildingName": "test"
      }
    ]
  }
}
</code>```

I have a setup similar to this. This is a singular object, I basically have an array of these.

All I get is a building.id value.

From it, I need to be able to find the building it belongs to, and there isn't any direct list of buildings for me to access.

Currently

I'm using a nested loop to loop through each site until I find the one that has a building with that id. I don't know if I'm doing it correctly, it doesn't feel correct.

```<code>for(var i = 0; i < streets.length; i++){
    for(var x = 0; x < streets[i].buildings.length;x++){
        if(streets[i].buildings[x].id == '2aec6bed-8cdd-4043-9041-3db4681c6d08'){

        }
    }
}
</code>```

Any tips? Thanks.

答:
You might be missing street property, right?
I mean it should be: streets[i].street.buildings[x].id

Body:
I'm using Vue, lodash, etc.

{
  "street": {
    "id": "1",
    "streetName": "test",
    "buildings": [
      {
        "id": "1",
        "buildingName": "test"
      }
    ]
  }
}

I have a setup similar to this. This is a singular object, I basically have an array of these.

All I get is a building.id value.

From it, I need to be able to find the building it belongs to, and there isn't any direct list of buildings for me to access.

Currently

I'm using a nested loop to loop through each site until I find the one that has a building with that id. I don't know if I'm doing it correctly, it doesn't feel correct.

for(var i = 0; i < streets.length; i++){
    for(var x = 0; x < streets[i].buildings.length;x++){
        if(streets[i].buildings[x].id == '2aec6bed-8cdd-4043-9041-3db4681c6d08'){

        }
    }
}

Any tips? Thanks.


问:
VBScript slow byte array copy
I am using the following code to read in a binary file in VBScript and store it in a byte array which I then access from Javascript and copy to a JS array, basically just a sneaky way (the only way!) i've found of reading binary data in my JS.

```<code>Function readBinaryFile(fileName)
    dim inStream,buff

    set inStream=CreateObject("ADODB.Stream")
    inStream.Open
    inStream.type=1

    inStream.LoadFromFile fileName

    buff=inStream.Read()
    inStream.Close

    Dim byteArray()

    Dim i
    Dim len
    len = LenB(buff)

    ReDim byteArray(len)

    For i = 1 To len
        byteArray(i-1) = AscB(MidB(buff, i, 1))
    Next

    readBinaryFile=byteArray
End Function
</code>```

It appears to work exactly as expected, the only problem being it seems extremely slow. For example, reading in a 300kb file can take over 2 minutes. I am expecting to read files up to around 2meg.

Could anyone explain why this is such a slow operation and if there's anything I can do to speed it up?

Thanks.

答:
The problem is the loop. Try using disconnected recordset to do the conversion:

```<code>Function RSBinaryToString(xBinary)
    'Antonin Foller, http://www.motobit.com
    'RSBinaryToString converts binary data (VT_UI1 | VT_ARRAY Or MultiByte string)
    'to a string (BSTR) using ADO recordset

    Dim Binary
    'MultiByte data must be converted To VT_UI1 | VT_ARRAY first.
    If vartype(xBinary)=8 Then Binary = MultiByteToBinary(xBinary) Else Binary = xBinary

    Dim RS, LBinary
    Const adLongVarChar = 201
    Set RS = CreateObject("ADODB.Recordset")
    LBinary = LenB(Binary)

    If LBinary>0 Then
        RS.Fields.Append "mBinary", adLongVarChar, LBinary
        RS.Open
        RS.AddNew
        RS("mBinary").AppendChunk Binary
        RS.Update
        RSBinaryToString = RS("mBinary")
    Else
        RSBinaryToString = ""
    End If
End Function

Function MultiByteToBinary(MultiByte)
    '© 2000 Antonin Foller, http://www.motobit.com
    ' MultiByteToBinary converts multibyte string To real binary data (VT_UI1 | VT_ARRAY)
    ' Using recordset
    Dim RS, LMultiByte, Binary
    Const adLongVarBinary = 205
    Set RS = CreateObject("ADODB.Recordset")
    LMultiByte = LenB(MultiByte)
    If LMultiByte>0 Then
        RS.Fields.Append "mBinary", adLongVarBinary, LMultiByte
        RS.Open
        RS.AddNew
        RS("mBinary").AppendChunk MultiByte & ChrB(0)
        RS.Update
        Binary = RS("mBinary").GetChunk(LMultiByte)
    End If
    MultiByteToBinary = Binary
End Function
</code>```

In your case have readBinaryFile return the "ASCII contents" of the file and use it instead of the array: readBinaryFile = RSBinaryToString(buf)

Title: VBScript slow byte array copy

Body:
I am using the following code to read in a binary file in VBScript and store it in a byte array which I then access from Javascript and copy to a JS array, basically just a sneaky way (the only way!) i've found of reading binary data in my JS.

Function readBinaryFile(fileName)
    dim inStream,buff

    set inStream=CreateObject("ADODB.Stream")
    inStream.Open
    inStream.type=1

    inStream.LoadFromFile fileName

    buff=inStream.Read()
    inStream.Close

    Dim byteArray()

    Dim i
    Dim len
    len = LenB(buff)

    ReDim byteArray(len)

    For i = 1 To len
        byteArray(i-1) = AscB(MidB(buff, i, 1))
    Next

    readBinaryFile=byteArray
End Function

It appears to work exactly as expected, the only problem being it seems extremely slow. For example, reading in a 300kb file can take over 2 minutes. I am expecting to read files up to around 2meg.

Could anyone explain why this is such a slow operation and if there's anything I can do to speed it up?

Thanks.

Body:
The problem is the loop. Try using disconnected recordset to do the conversion:

Function RSBinaryToString(xBinary)
    'Antonin Foller, http://www.motobit.com
    'RSBinaryToString converts binary data (VT_UI1 | VT_ARRAY Or MultiByte string)
    'to a string (BSTR) using ADO recordset

    Dim Binary
    'MultiByte data must be converted To VT_UI1 | VT_ARRAY first.
    If vartype(xBinary)=8 Then Binary = MultiByteToBinary(xBinary) Else Binary = xBinary

    Dim RS, LBinary
    Const adLongVarChar = 201
    Set RS = CreateObject("ADODB.Recordset")
    LBinary = LenB(Binary)

    If LBinary>0 Then
        RS.Fields.Append "mBinary", adLongVarChar, LBinary
        RS.Open
        RS.AddNew
        RS("mBinary").AppendChunk Binary
        RS.Update
        RSBinaryToString = RS("mBinary")
    Else
        RSBinaryToString = ""
    End If
End Function

Function MultiByteToBinary(MultiByte)
    '© 2000 Antonin Foller, http://www.motobit.com
    ' MultiByteToBinary converts multibyte string To real binary data (VT_UI1 | VT_ARRAY)
    ' Using recordset
    Dim RS, LMultiByte, Binary
    Const adLongVarBinary = 205
    Set RS = CreateObject("ADODB.Recordset")
    LMultiByte = LenB(MultiByte)
    If LMultiByte>0 Then
        RS.Fields.Append "mBinary", adLongVarBinary, LMultiByte
        RS.Open
        RS.AddNew
        RS("mBinary").AppendChunk MultiByte & ChrB(0)
        RS.Update
        Binary = RS("mBinary").GetChunk(LMultiByte)
    End If
    MultiByteToBinary = Binary
End Function

In your case have readBinaryFile return the "ASCII contents" of the file and use it instead of the array: readBinaryFile = RSBinaryToString(buf)


问:
Get WordPress Custom Post Type Excerpt to appear in RESt API
Does anyone know how to get the excerpt of a custom post type to appear in the WordPress REST API?</p>

答:
You can get excerpt in REST API response like below, This is the default excerpt of post,

Example response JSON data,

```<code>"excerpt":{
         "rendered":"<p>Welcome to WordPress. This is your first post. Edit or delete it, then start writing!<\/p>\n",
         "protected":false
      },
</code>```

Body:
You can get excerpt in REST API response like below, This is the default excerpt of post,

Example response JSON data,

"excerpt":{
         "rendered":"<p>Welcome to WordPress. This is your first post. Edit or delete it, then start writing!<\/p>\n",
         "protected":false
      },


问:
How can I calculate Cosine similarity between two strings vectors
I have 2 vectors of dimensions 6 and I would like to have a number between 0 and 1.

```<code>a=c("HDa","2Pb","2","BxU","BuQ","Bve")

b=c("HCK","2Pb","2","09","F","G")
</code>```

Can anyone explain what I should do?

答:
```<code>CSString_vector <- c("Hi Hello","Hello");
corp <- tm::VCorpus(VectorSource(CSString_vector));
controlForMatrix <- list(removePunctuation = TRUE,wordLengths = c(1, Inf), weighting = weightTf)
dtm <- DocumentTermMatrix(corp,control = controlForMatrix);
matrix_of_vector = as.matrix(dtm);
res <- lsa::cosine(matrix_of_vector[1,], matrix_of_vector[2,]);
</code>```

could be the better one for the larger data set.

Body:
I have 2 vectors of dimensions 6 and I would like to have a number between 0 and 1.

a=c("HDa","2Pb","2","BxU","BuQ","Bve")

b=c("HCK","2Pb","2","09","F","G")

Can anyone explain what I should do?

Body:
CSString_vector <- c("Hi Hello","Hello");
corp <- tm::VCorpus(VectorSource(CSString_vector));
controlForMatrix <- list(removePunctuation = TRUE,wordLengths = c(1, Inf), weighting = weightTf)
dtm <- DocumentTermMatrix(corp,control = controlForMatrix);
matrix_of_vector = as.matrix(dtm);
res <- lsa::cosine(matrix_of_vector[1,], matrix_of_vector[2,]);

could be the better one for the larger data set.


问:
Angular UI-Router: How to call child state without its parent?
We have recently move our application to Ui-Router from ng-route. And we are trying to refactor some points in our code regarding routing.

We have a list view and a detail view in our application. The detail view will be shown as a pop-up on top of the list view, so in order not to initialize all list controller logic again and again, we have defined our detail view as a child view-state. It looks like this:

```<code>  $stateProvider
    .state('list',
      {
        url: "/",
        template: '<list-directive></list-directive>'
      })
    .state('list.detail',
      {
        url: "/detail/{item_id}",
        template: '<detail-directive></detail-directive>'
      })
</code>```

It actually works as expected. When i open a detail view from a list view, the list view (i mean the controller) does not run again, and when i close the detail view, the list view remains.

But now we would also like to call the detail view DIRECTLY, without revoking the parent. Currently when i directly call the detail state, the parent controller runs also.. How can i achieve this?

Is a parent - child relationship not a appropriate one for our scenario?

答:
It did work like this:

```<code>$stateProvider
    .state('list',
      {
        url: "/",
        template: '<list-directive></list-directive>'
      })
     .state('detail',
      {
        url: "/detail/{item_id}",
        template: '<detail-directive></detail-directive>'
      })
    .state('list.detail',
      {
        url: "detail/{item_id}",
        template: '<detail-directive></detail-directive>'
      })
</code>```

But the angular is very fragile.. and behaves very different with very small changes.. the slashes are the problem.

Child state list.detail does not have a leading slash in its URL. But our new state detail (which has exctly the same content as the list.detail) should have a leading slash so it can be called directly. So We have the same state both as child and as parent.

Now when we call directly the URL "host/detail/5" we go to detail view without revoking the parent. And we we call ui-sref=".detail(5)" we go to child state (list.detail) within the parent

Body:
We have recently move our application to Ui-Router from ng-route. And we are trying to refactor some points in our code regarding routing.

We have a list view and a detail view in our application. The detail view will be shown as a pop-up on top of the list view, so in order not to initialize all list controller logic again and again, we have defined our detail view as a child view-state. It looks like this:

  $stateProvider
    .state('list',
      {
        url: "/",
        template: '<list-directive></list-directive>'
      })
    .state('list.detail',
      {
        url: "/detail/{item_id}",
        template: '<detail-directive></detail-directive>'
      })

It actually works as expected. When i open a detail view from a list view, the list view (i mean the controller) does not run again, and when i close the detail view, the list view remains.

But now we would also like to call the detail view DIRECTLY, without revoking the parent. Currently when i directly call the detail state, the parent controller runs also.. How can i achieve this?

Is a parent - child relationship not a appropriate one for our scenario?

Body:
It did work like this:

$stateProvider
    .state('list',
      {
        url: "/",
        template: '<list-directive></list-directive>'
      })
     .state('detail',
      {
        url: "/detail/{item_id}",
        template: '<detail-directive></detail-directive>'
      })
    .state('list.detail',
      {
        url: "detail/{item_id}",
        template: '<detail-directive></detail-directive>'
      })

But the angular is very fragile.. and behaves very different with very small changes.. the slashes are the problem.

Child state list.detail does not have a leading slash in its URL. But our new state detail (which has exctly the same content as the list.detail) should have a leading slash so it can be called directly. So We have the same state both as child and as parent.

Now when we call directly the URL "host/detail/5" we go to detail view without revoking the parent. And we we call ui-sref=".detail(5)" we go to child state (list.detail) within the parent


问:
Display data from JSON in alphabetical sections in Table View in Swift
I am pretty new to Xcode and Swift. I am trying to display data (restaurants names) in alphabetical order in TableView. I have a JSON file that sorts each restaurant into the correct neighborhood.The code works perfectly in the view controller where I m displaying the name of the neighborhood in sections and the name of the restaurant in rows. My problem is that I am trying to sort all the restaurants names in a different view controller where the sections display the Alphabet (A,B,C...) and under each sections I am trying to display the restaurants alphabetically with index on the side. Something similar to the Contact App on the iPhone but instate of contact names I need to show the restaurant names. Hope I make sense.
My code looks like this:

```<code>class BarsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, SWRevealViewControllerDelegate, UISearchBarDelegate {

@IBOutlet var btnMenuButton: UIBarButtonItem!
@IBOutlet var tableView: UITableView!
@IBOutlet var searchButton: UIBarButtonItem!

var noDataLabel = UILabel()

let urlString = "http://barhoppersf.com/json/neighborhoods.json"

var restaurantArray = Array<Restaurant>()

var filteredRestaurants = [Restaurant]()

var shouldShowSearchResults = false

var searchBar = UISearchBar()
var logoImageView: UIImageView!

let restaurantsName = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","#"]
let indexName = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","#"]
let voidIndex = [""]

var restSections = [String]()
var restDictionary = [String : [String]]()

    override func viewDidLoad() {
    super.viewDidLoad()

    self.downloadJsonWithURL() // This loads tableview with data from url

tableView.reloadData()
}
   **//JSON FUNC**
func downloadJsonWithURL() {

    let url = NSURL(string: urlString)

    URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in

        if let error = error {

            print(error.localizedDescription)

            return
        }

        if let data = data {

            guard let json = try? JSONSerialization.jsonObject(with: data) else { return }

            guard let dict = json as? Dictionary<String,Dictionary<String,Dictionary<String,Array<Dictionary<String,String>>>>> else { return }

            guard let hoods = dict["hoods"] else { return }

            guard let names = hoods["neighborhoodNames"] else { return }

            for (key, value) in names {

                let neighborhood = NeighborhoodRestaurants(name: key, data: value)

                self.tableData.append(neighborhood)

                self.tableData.sort { $0.name < $1.name }

                self.filteredRestaurants = self.tableData

            }

            DispatchQueue.main.async {

                self.tableView.reloadData()
            }

        }

    }).resume()
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return self.restaurantArray[section].restaurants.count

}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

    return self.restaurantArray[section].name
}

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    tableView.rowHeight = 40

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! RestaurantsTableViewCell

    cell.barLabel.text = self.restaurantArray[indexPath.section].restaurants[indexPath.row].name

    return cell
}
</code>```

I have a separate swift file with all the structure for the JSON

```<code>struct Restaurant {

var name: String
var cuisine: String
var hours: String
var description: String
var address: String
var phone: String
var website: String
var sports: String
var image: String

init?(dict:Dictionary<String,String>) {

    guard

        let name = dict["name"],
        let cuisine = dict["cuisine"],
        let hours = dict["hours"],
        let description = dict["description"],
        let address = dict["address"],
        let phone = dict["phone"],
        let website = dict["website"],
        let sports = dict["sports"],
        let image = dict["image"]

        else {
            return nil
    }

    self.name = name
    self.cuisine = cuisine
    self.hours = hours
    self.description = description
    self.address = address
    self.phone = phone
    self.website = website
    self.sports = sports
    self.image = image

}

//MARK: Function for the data from ViewControler
}

struct NeighborhoodRestaurants {

var name: String

var restaurants: Array<Restaurant>

init(name:String, data:Array<Dictionary<String,String>>) {

    self.name = name

    self.restaurants = Array<Restaurant>()

    for dict in data {

        if let restaurant = Restaurant(dict: dict) {

            self.restaurants.append(restaurant)

            self.restaurants.sort { $0.name < $1.name }

        }

    }
}

}
</code>```

This is the JSON file: http://barhoppersf.com/json/neighborhoods.json

This is a image of the neighborhoods view controller that works great. You can get the idea!
Thanks again in advance!!

答:
I tried to solve your problem using some different approach. Here is the Sample I made.

Here is my controller code and tried to make it as similar to contact app as per the data provided by the API. I just took restaurant name in model as It will only be needed for sorting in alphabetical order. All the other details and explanation are mentioned in comments within the code.

```<code>import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var restaurantsTableView: UITableView!

    //The main array for tableView
    var dataArray = [(String,[Restaurant])]()

    var indexTitles = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()
        getData()
    }

    func getData() {

        let url = URL(string: "http://barhoppersf.com/json/neighborhoods.json")
        URLSession.shared.dataTask(with: url!) { (data, response, error) in

            guard let data = data else {return}

            let json = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String : AnyObject]

            guard let hoods = json?["hoods"] else { return }

            guard let names = hoods["neighborhoodNames"] as? [String:[AnyObject]] else { return }

            self.makeDataSource(names: names)

            DispatchQueue.main.async {
                self.restaurantsTableView.reloadData()
            }
        }.resume()
    }

    // The main logic for sorting and making the data like Contacts App tableView
    func makeDataSource(names:[String:[AnyObject]]) {
        //Temporary array to hold restaurants on different indexes
        var dict = [String:[Restaurant]]()

        //Character set taken to check whether the starting key is alphabet or any other character
        let letters = NSCharacterSet.letters

        for (_,value) in names {
            //Iterating Restaurants
            for resObj in value {
                if let restaurantName = resObj["name"] as? String {
                    let restaurant = Restaurant(name: restaurantName)
                    var key = String(describing: restaurant.name.characters.first!)

                    key = isKeyCharacter(key: key, letters: letters) ? key : "#"

                    if let keyValue = dict[key] {
                        //Already value exists for that key
                        var filtered = keyValue
                        filtered.append(restaurant)

                        //Sorting of restaurant names alphabetically
                        filtered = filtered.sorted(by: {$0.0.name < $0.1.name})
                        dict[key] = filtered
                    } else {
                        let filtered = [restaurant]
                        dict[key] = filtered
                    }
                }
            }
        }
        //To sort the key header values
        self.dataArray = Array(dict).sorted(by: { $0.0 < $1.0 })

        //Logic to shift the # category to bottom
        let temp = self.dataArray[0]
        self.dataArray.removeFirst()
        self.dataArray.append(temp)

        //For setting index titles
        self.indexTitles = Array(dict.keys.sorted(by: <))

        //Making the index title # at the bottom
        let tempIndex = self.indexTitles[0]
        self.indexTitles.removeFirst()
        self.indexTitles.append(tempIndex
    }
}

//Function to check whether key is alphabet or not
func isKeyCharacter(key:String,letters:CharacterSet) -> Bool {
    let range = key.rangeOfCharacter(from: letters)
    if let _ = range {
        //Your key is an alphabet
        return true
    }
    return false
}

extension ViewController: UITableViewDataSource, UITableViewDelegate {

    func numberOfSections(in tableView: UITableView) -> Int {
        return dataArray.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray[section].1.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "RestaurantsTableCell") as! RestaurantsTableCell
        let restaurant = dataArray[indexPath.section].1[indexPath.row]
        cell.restaurantNameLabel.text = restaurant.name
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        //Pass this model to detail VC
        let restaurant = dataArray[indexPath.section].1[indexPath.row]

        let detailVC = self.storyboard?.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
        detailVC.restaurant = restaurant
        self.navigationController?.pushViewController(detailVC, animated: true)
    }

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

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return dataArray[section].0
    }

    //For index titles
    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        return self.indexTitles
    }
}
</code>```

The Restaurant class is now separated. Also modified the Sample in the link and created a new DetailViewController class.

```<code>import Foundation

class Restaurant {
    var name = ""

    init(name:String) {
        self.name = name
    }
}
</code>```

This code can be improved in the sort logic. Improvements are welcome.

Here is the Output:

Here is the detail controller:

Body:
I am pretty new to Xcode and Swift. I am trying to display data (restaurants names) in alphabetical order in TableView. I have a JSON file that sorts each restaurant into the correct neighborhood.The code works perfectly in the view controller where I m displaying the name of the neighborhood in sections and the name of the restaurant in rows. My problem is that I am trying to sort all the restaurants names in a different view controller where the sections display the Alphabet (A,B,C...) and under each sections I am trying to display the restaurants alphabetically with index on the side. Something similar to the Contact App on the iPhone but instate of contact names I need to show the restaurant names. Hope I make sense.
My code looks like this:

class BarsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, SWRevealViewControllerDelegate, UISearchBarDelegate {

@IBOutlet var btnMenuButton: UIBarButtonItem!
@IBOutlet var tableView: UITableView!
@IBOutlet var searchButton: UIBarButtonItem!

var noDataLabel = UILabel()

let urlString = "http://barhoppersf.com/json/neighborhoods.json"

var restaurantArray = Array<Restaurant>()

var filteredRestaurants = [Restaurant]()

var shouldShowSearchResults = false

var searchBar = UISearchBar()
var logoImageView: UIImageView!

let restaurantsName = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","#"]
let indexName = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","#"]
let voidIndex = [""]

var restSections = [String]()
var restDictionary = [String : [String]]()

    override func viewDidLoad() {
    super.viewDidLoad()

    self.downloadJsonWithURL() // This loads tableview with data from url

tableView.reloadData()
}
   **//JSON FUNC**
func downloadJsonWithURL() {

    let url = NSURL(string: urlString)

    URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: {(data, response, error) -> Void in

        if let error = error {

            print(error.localizedDescription)

            return
        }

        if let data = data {

            guard let json = try? JSONSerialization.jsonObject(with: data) else { return }

            guard let dict = json as? Dictionary<String,Dictionary<String,Dictionary<String,Array<Dictionary<String,String>>>>> else { return }

            guard let hoods = dict["hoods"] else { return }

            guard let names = hoods["neighborhoodNames"] else { return }

            for (key, value) in names {

                let neighborhood = NeighborhoodRestaurants(name: key, data: value)

                self.tableData.append(neighborhood)

                self.tableData.sort { $0.name < $1.name }

                self.filteredRestaurants = self.tableData

            }

            DispatchQueue.main.async {

                self.tableView.reloadData()
            }

        }

    }).resume()
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return self.restaurantArray[section].restaurants.count

}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

    return self.restaurantArray[section].name
}

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    tableView.rowHeight = 40

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! RestaurantsTableViewCell

    cell.barLabel.text = self.restaurantArray[indexPath.section].restaurants[indexPath.row].name

    return cell
}

I have a separate swift file with all the structure for the JSON

struct Restaurant {

var name: String
var cuisine: String
var hours: String
var description: String
var address: String
var phone: String
var website: String
var sports: String
var image: String

init?(dict:Dictionary<String,String>) {

    guard

        let name = dict["name"],
        let cuisine = dict["cuisine"],
        let hours = dict["hours"],
        let description = dict["description"],
        let address = dict["address"],
        let phone = dict["phone"],
        let website = dict["website"],
        let sports = dict["sports"],
        let image = dict["image"]

        else {
            return nil
    }

    self.name = name
    self.cuisine = cuisine
    self.hours = hours
    self.description = description
    self.address = address
    self.phone = phone
    self.website = website
    self.sports = sports
    self.image = image

}

//MARK: Function for the data from ViewControler
}

struct NeighborhoodRestaurants {

var name: String

var restaurants: Array<Restaurant>

init(name:String, data:Array<Dictionary<String,String>>) {

    self.name = name

    self.restaurants = Array<Restaurant>()

    for dict in data {

        if let restaurant = Restaurant(dict: dict) {

            self.restaurants.append(restaurant)

            self.restaurants.sort { $0.name < $1.name }

        }

    }
}

}

This is the JSON file: http://barhoppersf.com/json/neighborhoods.json

This is a image of the neighborhoods view controller that works great. You can get the idea!
Thanks again in advance!!

Body:
I tried to solve your problem using some different approach. Here is the Sample I made.

Here is my controller code and tried to make it as similar to contact app as per the data provided by the API. I just took restaurant name in model as It will only be needed for sorting in alphabetical order. All the other details and explanation are mentioned in comments within the code.

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var restaurantsTableView: UITableView!

    //The main array for tableView
    var dataArray = [(String,[Restaurant])]()

    var indexTitles = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()
        getData()
    }

    func getData() {

        let url = URL(string: "http://barhoppersf.com/json/neighborhoods.json")
        URLSession.shared.dataTask(with: url!) { (data, response, error) in

            guard let data = data else {return}

            let json = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String : AnyObject]

            guard let hoods = json?["hoods"] else { return }

            guard let names = hoods["neighborhoodNames"] as? [String:[AnyObject]] else { return }

            self.makeDataSource(names: names)

            DispatchQueue.main.async {
                self.restaurantsTableView.reloadData()
            }
        }.resume()
    }

    // The main logic for sorting and making the data like Contacts App tableView
    func makeDataSource(names:[String:[AnyObject]]) {
        //Temporary array to hold restaurants on different indexes
        var dict = [String:[Restaurant]]()

        //Character set taken to check whether the starting key is alphabet or any other character
        let letters = NSCharacterSet.letters

        for (_,value) in names {
            //Iterating Restaurants
            for resObj in value {
                if let restaurantName = resObj["name"] as? String {
                    let restaurant = Restaurant(name: restaurantName)
                    var key = String(describing: restaurant.name.characters.first!)

                    key = isKeyCharacter(key: key, letters: letters) ? key : "#"

                    if let keyValue = dict[key] {
                        //Already value exists for that key
                        var filtered = keyValue
                        filtered.append(restaurant)

                        //Sorting of restaurant names alphabetically
                        filtered = filtered.sorted(by: {$0.0.name < $0.1.name})
                        dict[key] = filtered
                    } else {
                        let filtered = [restaurant]
                        dict[key] = filtered
                    }
                }
            }
        }
        //To sort the key header values
        self.dataArray = Array(dict).sorted(by: { $0.0 < $1.0 })

        //Logic to shift the # category to bottom
        let temp = self.dataArray[0]
        self.dataArray.removeFirst()
        self.dataArray.append(temp)

        //For setting index titles
        self.indexTitles = Array(dict.keys.sorted(by: <))

        //Making the index title # at the bottom
        let tempIndex = self.indexTitles[0]
        self.indexTitles.removeFirst()
        self.indexTitles.append(tempIndex
    }
}

//Function to check whether key is alphabet or not
func isKeyCharacter(key:String,letters:CharacterSet) -> Bool {
    let range = key.rangeOfCharacter(from: letters)
    if let _ = range {
        //Your key is an alphabet
        return true
    }
    return false
}

extension ViewController: UITableViewDataSource, UITableViewDelegate {

    func numberOfSections(in tableView: UITableView) -> Int {
        return dataArray.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray[section].1.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "RestaurantsTableCell") as! RestaurantsTableCell
        let restaurant = dataArray[indexPath.section].1[indexPath.row]
        cell.restaurantNameLabel.text = restaurant.name
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        //Pass this model to detail VC
        let restaurant = dataArray[indexPath.section].1[indexPath.row]

        let detailVC = self.storyboard?.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
        detailVC.restaurant = restaurant
        self.navigationController?.pushViewController(detailVC, animated: true)
    }

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

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return dataArray[section].0
    }

    //For index titles
    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        return self.indexTitles
    }
}

The Restaurant class is now separated. Also modified the Sample in the link and created a new DetailViewController class.

import Foundation

class Restaurant {
    var name = ""

    init(name:String) {
        self.name = name
    }
}

This code can be improved in the sort logic. Improvements are welcome.

Here is the Output:

Here is the detail controller:


问:
hide-unhide with radio button
Im trying to unhide div id=Q3 with my first 2 radio inputs (id= Q1 & id = Q2)

if   (Q1 = Ja and Q2 = Ja) show Q3.

Can somebody please help me!

See my html code below (sorry for the bad coding im a totally noob!).

HTML

```<code><body>

<header>
    <h2>Helpdesk</h2>
    <div>Wat is u probleem?</div>
</header>

<form>

<h4>Kunt computer normaal aanzetten?<span class = "req" id= "req_Q1">*</span></h4>
<input type="radio" name="A1" id="A1" value ="Ja" /> : Ja<br />
<input type="radio" name="A1" id="A2" value ="Nee" /> : Nee<br />

<p class= "instruct" id="instruct_Q1">
<small>Controleer eerst de kabels!</small>
</p>

<h4 id= "Q2">Geeft de monitor normaal beeld?<span class = "req" id= "req_Q2">*</span> </h4>
<input type="radio" name="A2" id="A3" /> : Ja<br />
<input type="radio" name="A2" id="A4"/> : Nee<br />

<p class= "instruct" id="instruct_Q2">
<small>Controleer eerst de kabels!</small>
</p>
</div>

<div id= "Q3" style="display: none;">
<label for ="Q3.1" ><h4>Start windows normaal op?</h4></label>
<select name="Q3.1">
    <option value="A3.1" >Ja, geen probleem</option>
    <option value="A3.2" >Ja, maar met foutmelding</option>
    <option value="A3.3" >Nee, zwart scherm</option>
    <option value="A3.4" >Nee, blauw scherm</option>
</select>
</div>

<div style="display: none;">
<h4>Kunt u inloggen?</h4>
<input type="radio" name="Q4" />Ja, geen probleem<br />
<input type="radio" name="Q4" /> Nee, ik krijg een foutmelding<br />
</div>

<div style="display: none;">
<h4>Ik krijg de volgende foutmelding <span class = "req" id= "req_Q5">*</span></h4>
<input type="radio" name="Q5" />Kan u niet aanmelden bij het domein. Controleer of uw gebruikersnaam en/of toegangscode correct zijn.<br />
<input type="radio" name="Q5" />Kan u niet aanmelden omdat het domein niet beschikbaar is. <br />
<input type="radio" name="Q5" />Uw account is geblokkeerd. Neem contact op met de beheerder. <br />
</div>
</code>```

Javascript

```<code>  $("input[name=A1]").click(function()
  {
  if(this.id =="A1"){
    $("#Q3").show('slow');
  }
  else {
  $("#Q3").hide('slow');
  }
  });
</code>```

答:
You can use a ternary instead of an if statement to make a little more elegant

```<code>/* get the status of the answers */
var status = $("#A1").is(':checked') && $("#A3").is(':checked');
/* let the status decide which $ method to use */
$("#Q3")[status ? 'fadeIn' : 'fadeOut'](500);
</code>```

$("#helpdesk :input").change(function() {
  var status = $("#A1").is(':checked') && $("#A3").is(':checked');
  $("#Q3")[status ? 'fadeIn' : 'fadeOut'](500);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header>
  <h2>Helpdesk</h2>
  <div>Wat is u probleem?</div>
</header>

<form id="helpdesk">

  <h4>Kunt computer normaal aanzetten?<span class="req" id="req_Q1">*</span></h4>
  <input type="radio" name="A1" id="A1" value="Ja" /> : Ja<br />
  <input type="radio" name="A1" id="A2" value="Nee" /> : Nee<br />

  <p class="instruct" id="instruct_Q1">
    <small>Controleer eerst de kabels!</small>
  </p>

  <h4 id="Q2">Geeft de monitor normaal beeld?<span class="req" id="req_Q2">*</span> </h4>
  <input type="radio" name="A2" id="A3" /> : Ja<br />
  <input type="radio" name="A2" id="A4" /> : Nee<br />

  <p class="instruct" id="instruct_Q2">
    <small>Controleer eerst de kabels!</small>
  </p>

  <div id="Q3" style="display: none;">
    <label for="Q3.1"><h4>Start windows normaal op?</h4></label>
    <select name="Q3.1">
    <option value="A3.1" >Ja, geen probleem</option>
    <option value="A3.2" >Ja, maar met foutmelding</option>
    <option value="A3.3" >Nee, zwart scherm</option>
    <option value="A3.4" >Nee, blauw scherm</option>
</select>
  </div>

  <div style="display: none;">
    <h4>Kunt u inloggen?</h4>
    <input type="radio" name="Q4" />Ja, geen probleem<br />
    <input type="radio" name="Q4" /> Nee, ik krijg een foutmelding<br />
  </div>

  <div style="display: none;">
    <h4>Ik krijg de volgende foutmelding <span class="req" id="req_Q5">*</span></h4>
    <input type="radio" name="Q5" />Kan u niet aanmelden bij het domein. Controleer of uw gebruikersnaam en/of toegangscode correct zijn.<br />
    <input type="radio" name="Q5" />Kan u niet aanmelden omdat het domein niet beschikbaar is. <br />
    <input type="radio" name="Q5" />Uw account is geblokkeerd. Neem contact op met de beheerder. <br />
  </div></code>```

Title: hide-unhide with radio button

Body:
Im trying to unhide div id=Q3 with my first 2 radio inputs (id= Q1 & id = Q2)

if   (Q1 = Ja and Q2 = Ja) show Q3.

Can somebody please help me!

See my html code below (sorry for the bad coding im a totally noob!).

HTML

Helpdesk

Wat is u probleem?

<form>

Kunt computer normaal aanzetten?*

<input type="radio" name="A1" id="A1" value ="Ja" /> : Ja

<input type="radio" name="A1" id="A2" value ="Nee" /> : Nee

Controleer eerst de kabels!

Geeft de monitor normaal beeld?*

<input type="radio" name="A2" id="A3" /> : Ja

<input type="radio" name="A2" id="A4"/> : Nee

Controleer eerst de kabels!

Start windows normaal op?

<select name="Q3.1">
    <option value="A3.1" >Ja, geen probleem</option>
    <option value="A3.2" >Ja, maar met foutmelding</option>
    <option value="A3.3" >Nee, zwart scherm</option>
    <option value="A3.4" >Nee, blauw scherm</option>
</select>

Kunt u inloggen?

<input type="radio" name="Q4" />Ja, geen probleem

<input type="radio" name="Q4" /> Nee, ik krijg een foutmelding

Ik krijg de volgende foutmelding *

<input type="radio" name="Q5" />Kan u niet aanmelden bij het domein. Controleer of uw gebruikersnaam en/of toegangscode correct zijn.

<input type="radio" name="Q5" />Kan u niet aanmelden omdat het domein niet beschikbaar is.

<input type="radio" name="Q5" />Uw account is geblokkeerd. Neem contact op met de beheerder.

Javascript

  $("input[name=A1]").click(function()
  {
  if(this.id =="A1"){
    $("#Q3").show('slow');
  }
  else {
  $("#Q3").hide('slow');
  }
  });

Body:
You can use a ternary instead of an if statement to make a little more elegant

/* get the status of the answers */
var status = $("#A1").is(':checked') && $("#A3").is(':checked');
/* let the status decide which $ method to use */
$("#Q3")[status ? 'fadeIn' : 'fadeOut'](500);

$("#helpdesk :input").change(function() {
  var status = $("#A1").is(':checked') && $("#A3").is(':checked');
  $("#Q3")[status ? 'fadeIn' : 'fadeOut'](500);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header>
  <h2>Helpdesk</h2>
  <div>Wat is u probleem?</div>
</header>

<form id="helpdesk">

  <h4>Kunt computer normaal aanzetten?<span class="req" id="req_Q1">*</span></h4>
  <input type="radio" name="A1" id="A1" value="Ja" /> : Ja<br />
  <input type="radio" name="A1" id="A2" value="Nee" /> : Nee<br />

  <p class="instruct" id="instruct_Q1">
    <small>Controleer eerst de kabels!</small>
  </p>

  <h4 id="Q2">Geeft de monitor normaal beeld?<span class="req" id="req_Q2">*</span> </h4>
  <input type="radio" name="A2" id="A3" /> : Ja<br />
  <input type="radio" name="A2" id="A4" /> : Nee<br />

  <p class="instruct" id="instruct_Q2">
    <small>Controleer eerst de kabels!</small>
  </p>

  <div id="Q3" style="display: none;">
    <label for="Q3.1"><h4>Start windows normaal op?</h4></label>
    <select name="Q3.1">
    <option value="A3.1" >Ja, geen probleem</option>
    <option value="A3.2" >Ja, maar met foutmelding</option>
    <option value="A3.3" >Nee, zwart scherm</option>
    <option value="A3.4" >Nee, blauw scherm</option>
</select>
  </div>

  <div style="display: none;">
    <h4>Kunt u inloggen?</h4>
    <input type="radio" name="Q4" />Ja, geen probleem<br />
    <input type="radio" name="Q4" /> Nee, ik krijg een foutmelding<br />
  </div>

  <div style="display: none;">
    <h4>Ik krijg de volgende foutmelding <span class="req" id="req_Q5">*</span></h4>
    <input type="radio" name="Q5" />Kan u niet aanmelden bij het domein. Controleer of uw gebruikersnaam en/of toegangscode correct zijn.<br />
    <input type="radio" name="Q5" />Kan u niet aanmelden omdat het domein niet beschikbaar is. <br />
    <input type="radio" name="Q5" />Uw account is geblokkeerd. Neem contact op met de beheerder. <br />
  </div>


问:
Linq.Dynamic throws exception attempting to convert nullable int to string
I'm using the System.Linq.Dynamic library DynamicQuery as part of a solution using EF on .NET Framework 4.0 to try and convert a Nullable (int?) to String within the Select similar to:

```<code>query= "new(Convert.ToString(columnName) as stringColumn)";
IQueryable result = queryable.Select(query, parameters[]);
</code>```

How do I get the Expression.Call to work and return the string equivalent of a Nullable column?

Thanks,
John

Things I've tried:

I've tried sending Convert.ToString(columnName) as part of the query:

System.ArgumentException: Expression of type 'System.Nullable1[System.Int32]' cannot be used for parameter of type 'System.Object' of method 'System.String ToString(System.Object)'
   at System.Linq.Expressions.Expression.ValidateOneArgument(MethodBase method, ExpressionType nodeKind, Expression arg, ParameterInfo pi)
   at System.Linq.Expressions.Expression.ValidateArgumentTypes(MethodBase method, ExpressionType nodeKind, ReadOnlyCollection1& arguments)
   at System.Linq.Expressions.Expression.Call(Expression instance, MethodInfo method, IEnumerable`1 arguments)
   at System.Linq.Expressions.Expression.Call(Expression instance, MethodInfo method, Expression[] arguments)
   at System.Linq.Dynamic.ExpressionParser.ParseMemberAccess(Type type, Expression instance) in c:\Projects\DynamicQuery.cs:line 3461

I've tried using (columnName).toString() and receive the following:

System.Linq.Dynamic.ParseException: Methods on type 'Int32?' are not accessible
   at System.Linq.Dynamic.ExpressionParser.ParseMemberAccess(Type type, Expression instance) in c:\Projects\DynamicQuery.cs:line 3453

答:
Try to use

```<code>query = "new(Convert.ToString(Int32(columnName)))"
</code>```

or

```<code>query = "new((Int32(columnName)).ToString())"
</code>```

Body:
I'm using the System.Linq.Dynamic library DynamicQuery as part of a solution using EF on .NET Framework 4.0 to try and convert a Nullable (int?) to String within the Select similar to:

query= "new(Convert.ToString(columnName) as stringColumn)";
IQueryable result = queryable.Select(query, parameters[]);

How do I get the Expression.Call to work and return the string equivalent of a Nullable column?

Thanks,
John

Things I've tried:

I've tried sending Convert.ToString(columnName) as part of the query:

System.ArgumentException: Expression of type 'System.Nullable1[System.Int32]' cannot be used for parameter of type 'System.Object' of method 'System.String ToString(System.Object)'
   at System.Linq.Expressions.Expression.ValidateOneArgument(MethodBase method, ExpressionType nodeKind, Expression arg, ParameterInfo pi)
   at System.Linq.Expressions.Expression.ValidateArgumentTypes(MethodBase method, ExpressionType nodeKind, ReadOnlyCollection1& arguments)
   at System.Linq.Expressions.Expression.Call(Expression instance, MethodInfo method, IEnumerable`1 arguments)
   at System.Linq.Expressions.Expression.Call(Expression instance, MethodInfo method, Expression[] arguments)
   at System.Linq.Dynamic.ExpressionParser.ParseMemberAccess(Type type, Expression instance) in c:\Projects\DynamicQuery.cs:line 3461

I've tried using (columnName).toString() and receive the following:

System.Linq.Dynamic.ParseException: Methods on type 'Int32?' are not accessible
   at System.Linq.Dynamic.ExpressionParser.ParseMemberAccess(Type type, Expression instance) in c:\Projects\DynamicQuery.cs:line 3453

Body:
Try to use

query = "new(Convert.ToString(Int32(columnName)))"

or

query = "new((Int32(columnName)).ToString())"


问:
How to represent functions in flowchart?
I define some function in my Ansi C Program (simple program). I don't known how to represent a function in flowchart. Anybody can help me?</p>

答:
In my opinion, a flowchart is more of a functional description of your algorithm and not where you would "define" a function in the sense of your program.  Yes,  a functional aspect represented in your flowchart may directly map to a single function in your C program, but it may be that multiple functions or multiple threads are used to accomplish it as well.  The flowchart isn't where you would describe these.

In short, the flowchart is not where you should be "defining" functions for your C program.  It should be a high-level representation of functional aspects of your program, not the implementation of it.


问:
Javascript indexOf() finds the index of one character, but not that of another character, from a string. Why?
I am trying to use the Javascript indexOf() function to find the index position of two characters, viz. [ and ] in a string. But it shows strange behavior, i.e. It finds the index of opening-bracket [ but returns empty string as index of ].

There is no error in the Console tab of Google Chrome Inspector.

So this is the question. Why is this happening and how should I fix this?

var string = 'allPeoplesArray[0][peopleNameInput]';

var indexOfFirstOpeningBracket = string.indexOf('[');
alert('indexOfFirstOpeningBracket: ' + indexOfFirstOpeningBracket);//check

var indexOfFirstClosingBracket = string.indexOf(']');
alert('indexOfFirstClosingBracket') + indexOfFirstClosingBracket;//check```

答:
you closed alert parentheses too soon

var string = 'allPeoplesArray[0][peopleNameInput]';

var indexOfFirstOpeningBracket = string.indexOf('[');
alert('indexOfFirstOpeningBracket: ' + indexOfFirstOpeningBracket);//check

var indexOfFirstClosingBracket = string.indexOf(']');
alert('indexOfFirstClosingBracket' + indexOfFirstClosingBracket);//check```


问:
PopupWindow how to change icon and background programmatically?
Have is xml file for PopupWindow:

How to programmatically replace the icon and Backgroud in this xml?

答:
XML layout for popup menu is normally created in a menu folder

You have to change it just before calling the popup.show()

```<code>    MenuInflater inflater = popup.getMenuInflater();
    inflater.inflate(R.menu.name_of_xml_layout, popup.getMenu());
    popup.getMenu().findItem(R.id.editmenubtn).setIcon(R.drawable.newicon);  //this line will change the icon of popup menu
    popup.show();
</code>```

Body:
XML layout for popup menu is normally created in a menu folder

You have to change it just before calling the popup.show()

    MenuInflater inflater = popup.getMenuInflater();
    inflater.inflate(R.menu.name_of_xml_layout, popup.getMenu());
    popup.getMenu().findItem(R.id.editmenubtn).setIcon(R.drawable.newicon);  //this line will change the icon of popup menu
    popup.show();


问:
Query using NLP [PYTHON]
I'm working on a project where I need to extract "inputs" and "query intent" from text.

For example "What is the status of asset X26TH?"

In this case the main issue is to extract asset id which is X26TH, but how can I make my code understand that it's an id?

The other thing is to understand the query intent which is asset status. I found a good library for this called quepy, but it's meant for linux and I couldn't set it up on windows.

Please help me with the techniques and libraries.

答:
So you have two problems, ID extraction and intent detection.

ID Extraction

If your IDs follow a regular pattern and definitely don't look like English, you can catch them with a regex - if that's possible, that's great since it's very easy to do. If you have a fixed list of product IDs, just check to see if any of them are in the input. If neither of those work then you'll have to get more sophisticated.

Can you get your users to remember a little syntax? If you can request that they write things with a prefix like id:X26TH or similar that would make your job easier. You may find the way the plumber in Plan9 works informative.

If you need to work with whatever the users throw at you, you should look into using a sequence labeller or Named Entity Recognition (NER) system to get IDs. CRFs are probably a good fit for this task; here's a good technial introduction, and the New York Times also used one with success. Besides being trickier to set up a downside of this is that it will require training data, but there's really no way to avoid that.

Intent Detection

This is usually modelled as a text classification problem. You can find an overview of how to do that here. Here's some training examples from the article:

training_data.append({"class":"greeting", "sentence":"how are you?"})
training_data.append({"class":"greeting", "sentence":"how is your day?"})
training_data.append({"class":"greeting", "sentence":"good day"})
training_data.append({"class":"greeting", "sentence":"how is it going today?"})

training_data.append({"class":"goodbye", "sentence":"have a nice day"})
training_data.append({"class":"goodbye", "sentence":"see you later"})
training_data.append({"class":"goodbye", "sentence":"have a nice day"})
training_data.append({"class":"goodbye", "sentence":"talk to you soon"})

training_data.append({"class":"sandwich", "sentence":"make me a sandwich"})
training_data.append({"class":"sandwich", "sentence":"can you make a sandwich?"})
training_data.append({"class":"sandwich", "sentence":"having a sandwich today?"})
training_data.append({"class":"sandwich", "sentence":"what's for lunch?"})
```

Title: Query using NLP [PYTHON]


问:
Creating an App that Contains a Group of Applications
Hello and thanks in advance for the help

I have a series of Android apps that I am using.  Whenever I recommend these apps to someone, I have to go over each one individually.

I wanted to know if it was possible to create a single application that will:

Download all of the individual apps all at once and install them

Create an app icon that when launched creates a submenu with all of the related apps and a help file to walk the user through each one.

Is this possible?  If so, how difficult is it to do?

Thanks again for your help

Dave

答:
"background batch app install" is not possible on a basic (not rooted) device.

But you can easily create a "launcher app" listing all the app you want to share and, using "Intents" and "PackageManager", letting the user open it if it's already installed of downloaded the app if it's not.


问:
Percentile_disc() for a non round values
I'm trying to find a solution for this with no luck.

In my query, im selecting the count(*) and the percentile_disc(.9) to find the 90th position of this.
The case is, when the count is 29, the 90th percentile is closer to the number 26 than 27 but still returning the 27th object.

There is any way to say, if 5 < Nth <10 reduce by one the result?

Table for reference

```<code>ID    Count    90th
-------------------
1     50       45
2     40       36
3     27       25     <-- Should be 24
4      9        9     <-- Should be  8
</code>```

90% of 9 is 0.9, it should delete 1 and resulting 8.

---Till here is my understanding of Nth percentile---

Now what I have:

My table have a los of entries (+ 100k at day) so I want to run this query on daily basis.

```<code>Service_id   start_time      end_time
-------------------------------------
Service1    1499025651614    1499025651648
Service2    1499025655145    1499025655434
Service3    1499025656029    1499025656112
Service2    1499025658755    1499025659135
Service3    1499025726862    1499025728346
Service1    1499025748782    1499025750032
Service3    1499025749277    1499025749900
Service3    1499025757681    1499025758517
Service2    1499025775000    1499025775101
Service1    1499025785556    1499025785633
...
</code>```

I have a query to select the min, max and avg for every service

```<code> select mt.SERVICE_ID as SERVICE_ID,
           count(*) as COUNT,
           round(avg((mt.end_time - mt.start_time) / 1000), 2) as Avg,
           round(min((mt.end_time - mt.start_time) / 1000), 2) AS Min,
           round(max((mt.end_time - mt.start_time) / 1000), 2) AS Max
      from myTable mt
     group by mt.service_id
</code>```

And I want to incorporate the 90th percentile discused before using a join.

```<code>select service_id, round(percentile_disc(.90) within group(order by elapsed), 2) as perc
from (select mt.service_id, ((mt.end_time - mt.start_time) / 1000) as elapsed
      from myTable mt)
group by service_id
</code>```

The issue comes when the count is (lets say) 9, in this case, the MAX and the Perc is the same (due the percentile is not removing anything) but I need in this particular case, to remove the last one, giving me as result the timming in the position 8th.

There is any way to remove one more position in this case?

答:
PERCENTILE_DISC() does not quite do what you think it does.

Oracle Documentation:

Purpose

PERCENTILE_DISC is an inverse distribution function that assumes a discrete distribution model. It takes a percentile value and a sort specification and returns an element from the set. Nulls are ignored in the calculation.

...

For a given percentile value P, PERCENTILE_DISC sorts the values of the expression in the ORDER BY clause and returns the value with the smallest CUME_DIST value (with respect to the same sort specification) that is greater than or equal to P.

Analytic Example

The following example calculates the median discrete percentile of the salary of each employee in the sample table hr.employees:

```<code>SELECT last_name, salary, department_id,
   PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY salary DESC)
      OVER (PARTITION BY department_id) "Percentile_Disc",
   CUME_DIST() OVER (PARTITION BY department_id
      ORDER BY salary DESC) "Cume_Dist"
FROM employees where department_id in (30, 60);

LAST_NAME         SALARY DEPARTMENT_ID Percentile_Disc  Cume_Dist
------------- ---------- ------------- --------------- ----------
Raphaely           11000            30            2900 .166666667
Khoo                3100            30            2900 .333333333
Baida               2900            30            2900         .5
Tobias              2800            30            2900 .666666667
Himuro              2600            30            2900 .833333333
Colmenares          2500            30            2900          1
Hunold              9000            60            4800         .2
Ernst               6000            60            4800         .4
Austin              4800            60            4800         .8
Pataballa           4800            60            4800         .8
Lorentz             4200            60            4800          1
</code>```

The median value for Department 30 is 2900, which is the value whose
  corresponding percentile (Cume_Dist) is the smallest value greater
  than or equal to 0.5. The median value for Department 60 is 4800,
  which is the value whose corresponding percentile is the smallest
  value greater than or equal to 0.5.

In the example they gave in the documentation, if the percentile was set to 0.9 (rather than 0.5) then you can see that the CUME_DIST goes from 0.8 to 1 (for department 60) so PERCENTILE_DISC(0.9) ... would give 4200 since this is the value with the smallest CUME_DIST greater than or equal to 0.9. To get the penultimate value you would need a percentile of 0.8 in that case.

The issue comes when the count is (lets say) 9, in this case, the MAX and the Perc is the same (due the percentile is not removing anything) but I need in this particular case, to remove the last one, giving me as result the timing in the position 8th.

For 9 items, the CUME_DIST values for each row will be:

```<code>ROW_NUMBER CUME_DIST
---------- ---------
         1      .111
         2      .222
         3      .333
         4      .444
         5      .556
         6      .667
         7      .778
         8      .889
         9     1.000
</code>```

If you use PERCENTILE_DISC( 0.9 ) then it will look for the value which has the lowest CUME_DIST greater than or equal to that value - there is only a single value 1.000 which is also the maximum value.

If you want a different value then you need to use a lower percentile.

Update:

You can try something like this:

```<code>select service_id,
       elapsed as perc
from (
  select service_id,
         (end_time - start_time) / 1000 as elapsed,
         ROW_NUMBER() OVER ( PARTITION BY service_id ORDER BY (end_time - start_time) )
           AS rn,
         COUNT() OVER ( PARTITION BY service_id ) AS ct
  from   myTable
)
WHERE rn = ROUND( 0.9 * ct );
</code>```

Change the last line to use ROUND, FLOOR or CEIL as appropriate to your business logic. If I have determined the logic correctly, CEIL will give the same answer as using PERCENTILE_DISC.

What I need is the count is 7, remove the last record and return the 6th value (90% of 7 is 0.7 , round to 1), is the count is 21, remove the last 2 records and return the 19th position-value (90% of 21 is 2.1 round to 2) and so on.

Using rn = ROUND( 0.9 * ct ):

If the count is 7 then 0.9 * 7 = 6.3 so ROUND( 6.3 ) will give the 6th row

If the count is 21 then 0.9 * 21 = 18.9 so ROUND( 18.9 ) will give the 19th row

If the count is 3 then 0.9 * 3 = 2.7 so ROUND( 2.7 ) will give the 3rd row (the maximum value).

It is unclear what you expect to be returned for small sets - if you never want the maximum row (except when there is only one row) then something like:

```<code>WHERE rn = GREATEST( 1, LEAST( ct - 1, ROUND( 0.9 * ct ) ) )
</code>```

Body:
I'm trying to find a solution for this with no luck.

In my query, im selecting the count(*) and the percentile_disc(.9) to find the 90th position of this.
The case is, when the count is 29, the 90th percentile is closer to the number 26 than 27 but still returning the 27th object.

There is any way to say, if 5 < Nth <10 reduce by one the result?

Table for reference

ID    Count    90th
-------------------
1     50       45
2     40       36
3     27       25     <-- Should be 24
4      9        9     <-- Should be  8

90% of 9 is 0.9, it should delete 1 and resulting 8.

---Till here is my understanding of Nth percentile---

Now what I have:

My table have a los of entries (+ 100k at day) so I want to run this query on daily basis.

Service_id   start_time      end_time
-------------------------------------
Service1    1499025651614    1499025651648
Service2    1499025655145    1499025655434
Service3    1499025656029    1499025656112
Service2    1499025658755    1499025659135
Service3    1499025726862    1499025728346
Service1    1499025748782    1499025750032
Service3    1499025749277    1499025749900
Service3    1499025757681    1499025758517
Service2    1499025775000    1499025775101
Service1    1499025785556    1499025785633
...

I have a query to select the min, max and avg for every service

 select mt.SERVICE_ID as SERVICE_ID,
           count(*) as COUNT,
           round(avg((mt.end_time - mt.start_time) / 1000), 2) as Avg,
           round(min((mt.end_time - mt.start_time) / 1000), 2) AS Min,
           round(max((mt.end_time - mt.start_time) / 1000), 2) AS Max
      from myTable mt
     group by mt.service_id

And I want to incorporate the 90th percentile discused before using a join.

select service_id, round(percentile_disc(.90) within group(order by elapsed), 2) as perc
from (select mt.service_id, ((mt.end_time - mt.start_time) / 1000) as elapsed
      from myTable mt)
group by service_id

The issue comes when the count is (lets say) 9, in this case, the MAX and the Perc is the same (due the percentile is not removing anything) but I need in this particular case, to remove the last one, giving me as result the timming in the position 8th.

There is any way to remove one more position in this case?

Body:
PERCENTILE_DISC() does not quite do what you think it does.

Oracle Documentation:

Purpose

PERCENTILE_DISC is an inverse distribution function that assumes a discrete distribution model. It takes a percentile value and a sort specification and returns an element from the set. Nulls are ignored in the calculation.

...

For a given percentile value P, PERCENTILE_DISC sorts the values of the expression in the ORDER BY clause and returns the value with the smallest CUME_DIST value (with respect to the same sort specification) that is greater than or equal to P.

Analytic Example

The following example calculates the median discrete percentile of the salary of each employee in the sample table hr.employees:

SELECT last_name, salary, department_id,
   PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY salary DESC)
      OVER (PARTITION BY department_id) "Percentile_Disc",
   CUME_DIST() OVER (PARTITION BY department_id
      ORDER BY salary DESC) "Cume_Dist"
FROM employees where department_id in (30, 60);

LAST_NAME         SALARY DEPARTMENT_ID Percentile_Disc  Cume_Dist
------------- ---------- ------------- --------------- ----------
Raphaely           11000            30            2900 .166666667
Khoo                3100            30            2900 .333333333
Baida               2900            30            2900         .5
Tobias              2800            30            2900 .666666667
Himuro              2600            30            2900 .833333333
Colmenares          2500            30            2900          1
Hunold              9000            60            4800         .2
Ernst               6000            60            4800         .4
Austin              4800            60            4800         .8
Pataballa           4800            60            4800         .8
Lorentz             4200            60            4800          1

The median value for Department 30 is 2900, which is the value whose
  corresponding percentile (Cume_Dist) is the smallest value greater
  than or equal to 0.5. The median value for Department 60 is 4800,
  which is the value whose corresponding percentile is the smallest
  value greater than or equal to 0.5.

In the example they gave in the documentation, if the percentile was set to 0.9 (rather than 0.5) then you can see that the CUME_DIST goes from 0.8 to 1 (for department 60) so PERCENTILE_DISC(0.9) ... would give 4200 since this is the value with the smallest CUME_DIST greater than or equal to 0.9. To get the penultimate value you would need a percentile of 0.8 in that case.

The issue comes when the count is (lets say) 9, in this case, the MAX and the Perc is the same (due the percentile is not removing anything) but I need in this particular case, to remove the last one, giving me as result the timing in the position 8th.

For 9 items, the CUME_DIST values for each row will be:

ROW_NUMBER CUME_DIST
---------- ---------
         1      .111
         2      .222
         3      .333
         4      .444
         5      .556
         6      .667
         7      .778
         8      .889
         9     1.000

If you use PERCENTILE_DISC( 0.9 ) then it will look for the value which has the lowest CUME_DIST greater than or equal to that value - there is only a single value 1.000 which is also the maximum value.

If you want a different value then you need to use a lower percentile.

Update:

You can try something like this:

select service_id,
       elapsed as perc
from (
  select service_id,
         (end_time - start_time) / 1000 as elapsed,
         ROW_NUMBER() OVER ( PARTITION BY service_id ORDER BY (end_time - start_time) )
           AS rn,
         COUNT() OVER ( PARTITION BY service_id ) AS ct
  from   myTable
)
WHERE rn = ROUND( 0.9 * ct );

Change the last line to use ROUND, FLOOR or CEIL as appropriate to your business logic. If I have determined the logic correctly, CEIL will give the same answer as using PERCENTILE_DISC.

What I need is the count is 7, remove the last record and return the 6th value (90% of 7 is 0.7 , round to 1), is the count is 21, remove the last 2 records and return the 19th position-value (90% of 21 is 2.1 round to 2) and so on.

Using rn = ROUND( 0.9 * ct ):

If the count is 7 then 0.9 * 7 = 6.3 so ROUND( 6.3 ) will give the 6th row

If the count is 21 then 0.9 * 21 = 18.9 so ROUND( 18.9 ) will give the 19th row

If the count is 3 then 0.9 * 3 = 2.7 so ROUND( 2.7 ) will give the 3rd row (the maximum value).

It is unclear what you expect to be returned for small sets - if you never want the maximum row (except when there is only one row) then something like:

WHERE rn = GREATEST( 1, LEAST( ct - 1, ROUND( 0.9 * ct ) ) )


问:
What are the disadvantages of using ng-style?
I have used ng-style in code, but my manager said not to use ng-style since it will create problem.

I still don't know what problem he faced before and I would like to know what are the disadvantages of using ng-style?

答:
You cannot reuse the styles anywhere else.

The html markup of the page becomes cumbersome, and tough to parse for the naked eye.

Since, they are not stored at a single place, they are tough to be edited

This approach does not provide consistency across your application. The inline styles on elements can cause a major headache.

It does not provide you with the browser cache advantage. The files are repeatedly downloaded by the client on every request. Instead, consider using External style sheets.

Inline styles take precedence over page-level style declarations and external style sheets. So you could accidentally override styles that you did not intend.

It's impossible to style pseudo-elements and -classes with inline styles. For example, with external and internal style sheets, you can style the visited, hover, active, and link color of an anchor tag.

Please refer

Inline style disadvantages

Other link


问:
what is the difference of the output between use getsizeof and st_size?
What is the difference of the output between use getsizeof and st_size ?
When I use getsizeof the output is 144 but when I use st_size is 148. Anybody knows why this happening.

Any help will greatly appreciated.

答:
From How to check file size in python?:

Note: the implementation of os.path.getsize is simply return os.stat(filename).st_size – wim Mar 21 '13 at 11:20

So it really should return the same...


问:
Replace import of constant/method by static import in IntelliJ Idea
I have a code with some constants in format ClassName.CONSTANT_NAME. I want to quickly replace this by CONSTANT_NAME. But I have not found any efficient way of doing that.

Every time I want to static import something I have to remove class name manually then open static import tooltip which might contain several matches for constant name... It is inefficient.

Is there any quick way of converting an import to a static import? Ideally I would assign a shortcut for this.

答:
Put the cursor on the constant (ClassName.CONSTANT_NAME).

Then use the shortcut for the action Show the list of available intention actions.

On windows or Linux:  alt + enter

On mac os: ⌥⏎

Then select:

Add on demand static import for ....