问:
Scrapy FormRequest How to check if URL is needed
I am new to scrapy and in general web tech.

While working on a scrapy example to perform auto login. I came across 1 field , referrer url . I am wondering when do i need to this.

```<code>        return scrapy.FormRequest.from_response(
            response,
            url='www.myreferrer.com', #when do i need this ???
            formnumber=1,
            formdata=self.data['formdata'],
            callback=self.after_login
        )
</code>```

I tested with and without it and it works in both instances.

I understand that referrer url is for security but how do i determine from html code that i need or dont need this ?
ADDON
The following html form required the url to be defined  :

```<code>    <form id="login" enctype="multipart/form-data" method="post" action="https:///myshop.com/login/index.php?route=account/login">
        I am a returning customer.<br>
        <br>
        <b>E-Mail Address:</b><br>
        <input type="text" name="email">
        <br>
        <br>
        <b>Password:</b><br>
        <input type="password" name="password">
        <br>
        <a href="https:///myshop.com/login/index.php?route=account/forgotten">Forgotten Password</a><br>
        <div style="text-align: right;"><a class="button" onclick="$('#login').submit();"><span>Login</span></a></div>
                  </form>`
</code>```

答:
```<code>class FormRequest(Request):

# delete some code here

    @classmethod
    def from_response(cls, response, formname=None, formid=None, formnumber=0, formdata=None,
                  clickdata=None, dont_click=False, formxpath=None, formcss=None, **kwargs):
    url = _get_form_url(form, kwargs.pop('url', None))

    def _get_form_url(form, url):
        if url is None:
            return urljoin(form.base_url, form.action)
        return urljoin(form.base_url, url)
</code>```

if the url is empty, it uses form tag's action attribute to get the URL.

if the url is not empty, then it use the URL you give to it.

the base_url comes from the response.

```<code>def _get_form(response, formname, formid, formnumber, formxpath):
    """Find the form element """
    root = create_root_node(response.text, lxml.html.HTMLParser,
                            base_url=get_base_url(response))
</code>```

so, when the action attribute does not exist or the login requests is not sent to the action URL, you need to pass the argument.

Body:
I am new to scrapy and in general web tech.

While working on a scrapy example to perform auto login. I came across 1 field , referrer url . I am wondering when do i need to this.

        return scrapy.FormRequest.from_response(
            response,
            url='www.myreferrer.com', #when do i need this ???
            formnumber=1,
            formdata=self.data['formdata'],
            callback=self.after_login
        )

I tested with and without it and it works in both instances.

I understand that referrer url is for security but how do i determine from html code that i need or dont need this ?
ADDON
The following html form required the url to be defined  :

    <form id="login" enctype="multipart/form-data" method="post" action="https:///myshop.com/login/index.php?route=account/login">
        I am a returning customer.

        E-Mail Address:

        <input type="text" name="email">

        Password:

        <input type="password" name="password">

        Forgotten Password

Login

                  </form>`

Body:
class FormRequest(Request):

# delete some code here

    @classmethod
    def from_response(cls, response, formname=None, formid=None, formnumber=0, formdata=None,
                  clickdata=None, dont_click=False, formxpath=None, formcss=None, **kwargs):
    url = _get_form_url(form, kwargs.pop('url', None))

    def _get_form_url(form, url):
        if url is None:
            return urljoin(form.base_url, form.action)
        return urljoin(form.base_url, url)

if the url is empty, it uses form tag's action attribute to get the URL.

if the url is not empty, then it use the URL you give to it.

the base_url comes from the response.

def _get_form(response, formname, formid, formnumber, formxpath):
    """Find the form element """
    root = create_root_node(response.text, lxml.html.HTMLParser,
                            base_url=get_base_url(response))

so, when the action attribute does not exist or the login requests is not sent to the action URL, you need to pass the argument.


来源: stackexchange

问:
Counting zeroes in binary representation of decimal number
Here is my code: *edited

```<code>private static long zeros(long y){
    int count= 0;

    for(long i= y; i<=0; i/=2){
        if((i%2)==0) {
        count+=1;
   }
    return count;
  }
</code>```

It has to count all the zeros that given decimal number (long y) when method is called contains in binary form by using just one for loop, but I can't figure out why this won't work

答:
Why you simply not use :

```<code>long l = 853;//You Long value

//Convert Long to Binary then count the number of 0
StringUtils.countMatches(Long.toBinaryString(l), "0");
</code>```

Example :

```<code>System.out.println("toBinaryString = " + Long.toBinaryString(l));
System.out.println("Nbr = " + StringUtils.countMatches(Long.toBinaryString(l), "0"));
</code>```

This will print :

```<code>toBinaryString = 1101010101
Nbr = 4
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here is my code: *edited

private static long zeros(long y){
    int count= 0;

    for(long i= y; i<=0; i/=2){
        if((i%2)==0) {
        count+=1;
   }
    return count;
  }

It has to count all the zeros that given decimal number (long y) when method is called contains in binary form by using just one for loop, but I can't figure out why this won't work

Body:
Why you simply not use :

long l = 853;//You Long value

//Convert Long to Binary then count the number of 0
StringUtils.countMatches(Long.toBinaryString(l), "0");

Example :

System.out.println("toBinaryString = " + Long.toBinaryString(l));
System.out.println("Nbr = " + StringUtils.countMatches(Long.toBinaryString(l), "0"));

This will print :

toBinaryString = 1101010101
Nbr = 4


问:
OneNote API (REST) -- How to maintain the line breaks and spacing of the OneNote page while updating the content of page using PATCH service?
I am getting the HTML of the OneNote page using GET pages REST API of OneNote. Here is the dummy code --

```<code><html lang="nl-NL"> <head>
<title>Sales meeting III</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="created" content="2017-03-14T17:30:00.0000000" />
</head>
<body data-absolute-enabled="true" style="font-family:Calibri;font-size:11pt">
<div id="div:{e5d84e97-3676-4df2-9bc6-b9583ebae493}{50}" style="position:absolute;left:48px;top:115px;width:625px">
<p id="p:{e5d84e97-3676-4df2-9bc6-b9583ebae493}{34}" style="font-size:17pt;margin-top:0pt;margin-bottom:0pt">Sales Meeting</p>
<p id="p:{e5d84e97-3676-4df2-9bc6-b9583ebae493}{36}" style="font-size:10pt;color:gray;margin-top:0pt;margin-bottom:0pt">donderdag 9 maart 2017</p>
<p id="p:{e5d84e97-3676-4df2-9bc6-b9583ebae493}{38}" style="font-size:10pt;color:gray;margin-top:0pt;margin-bottom:0pt">20:00</p>
<p id="p:{d6174a59-03a8-4010-9ad9-e5a2e6f57bb3}{28}" lang="en-US" data-tag="to-do" data-id="p:{e5d84e97-3676-4df2-9bc6-b9583ebae493}{40}" style="margin-top:0pt;margin-bottom:0pt">Send draft press release to marketing team</p><br/><br/>
<p id="p:{d6174a59-03a8-4010-9ad9-e5a2e6f57bb3}{33}" lang="en-US" data-tag="to-do" data-id="p:{e5d84e97-3676-4df2-9bc6-b9583ebae493}{43}" style="margin-top:0pt;margin-bottom:0pt">Schedule briefing</p><br/><br/>
<p id="p:{d6174a59-03a8-4010-9ad9-e5a2e6f57bb3}{38}" lang="en-US" data-tag="to-do" data-id="p:{e5d84e97-3676-4df2-9bc6-b9583ebae493}{45}" style="margin-top:0pt;margin-bottom:0pt">Jack is the greatest</p>
<p id="p:{b1177410-4d6e-4ef7-b82c-32695a02218b}{13}" lang="en-US" style="margin-top:0pt;margin-bottom:0pt"></p> <br/><br/>
<br/><br/>
<p id="p:{b1177410-4d6e-4ef7-b82c-32695a02218b}{13}" lang="en-US" style="margin-top:0pt;margin-bottom:0pt">This is Testing</p> <br/><br/>
</div> </body> </html>
</code>```

Now, I am updating only "p" (paragraph) tag using their unique id by "replace" method in PATCH API. This action is not at all related to rest of the HTML of the page as per my knowledge. Content is getting updated properly and I am getting successfull response from the API but it is removing br tags as well. Which disturbs the indentation of the page.

How can I maintain the indentation of page or how to avoid the removal of br tags or line breaks of the page, I want them as it is on the page.

Thanks in advance.

答:
Hi Anupam
How are you creating your OneNote page?
I've just tried creating a page both programmatically and by direct editing in OneNote Online and the br tags are confined to paragraph tags and survive patching.

Body:
I am getting the HTML of the OneNote page using GET pages REST API of OneNote. Here is the dummy code --

<title>Sales meeting III</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="created" content="2017-03-14T17:30:00.0000000" />

Sales Meeting

donderdag 9 maart 2017

20:00

Send draft press release to marketing team

Schedule briefing

Jack is the greatest

This is Testing

Now, I am updating only "p" (paragraph) tag using their unique id by "replace" method in PATCH API. This action is not at all related to rest of the HTML of the page as per my knowledge. Content is getting updated properly and I am getting successfull response from the API but it is removing br tags as well. Which disturbs the indentation of the page.

How can I maintain the indentation of page or how to avoid the removal of br tags or line breaks of the page, I want them as it is on the page.

Thanks in advance.


问:
Beginner: How to return user input?
I'm new to Java and I'm having trouble with this bit of code:

```<code>import java.util.Scanner;

public class BattleshipLogic {

    private final int rows;
    private final int cols;

    private final boolean[][] hits;
    private final boolean[][] ships;

    public BattleshipLogic(int numRows, int numCols) {
        this.rows = numRows;
        this.cols = numCols;

        this.hits = new boolean[rows][cols];
        this.ships = new boolean[rows][cols];
    }

    public void startGame() {
        placeShips();
        boolean gameOver = false;
        // draw field for the first time
        drawUI();

        while (!gameOver) {
            Target target = askForTarget();
            processTarget(target);
            drawUI();
        }
    }

    private Target askForTarget() {
        Target t = new Target();
        Scanner input = new Scanner(System.in);
        System.out.print("Please enter your target:");
        t = input.nextInt();
        return t;
    }

    /*
     * This is just an example. You have to draw the ships by yourself.
     * If you don't like the way the UI is drawn, make your own stuff!
     */
    private void drawUI() {
        // draw the ui, see blatt01/oberflÃ¤che.txt for an example
        System.out.println("Schiffeversenken");
        System.out.println("================");
        System.out.println();

        // columns
        System.out.print("    ");
        for (int col = 0; col < this.cols; col++) {
            System.out.print(col + " ");
        }
        System.out.println();
        System.out.print("   _");
        for (int col = 0; col < this.cols; col++) {
            System.out.print("__");
        }
        System.out.println();
        for (int row = 0; row < this.rows; row++) {
            System.out.print(Character.toChars(3 + row));
            System.out.print(" |");

            System.out.println();
        }
    }

    private void placeShips() {
        // do useful stuff to place the ships here
        // see Blatt01 for rules
    }

    private void processTarget(Target target) {

    }

    /**
     * This class only holds the position
     * of a target.
     */
    private class Target {

        public int row;
        public int col;
    }
}
</code>```

Everytime I try to compile this error comes up:

error: incompatible types: int cannot be converted to BattleshipLogic.Target

I know that the types are different, but what kind of a type is Target? How can I get the user input to be assigned to t?

Thanks so much in advance!

答:
to assign the int value to

t of type Target

you need a

getter and setter method

on your t

e.g.

```<code>public class Target
{
  private int myValue;
  public void setMyValue(int myValue)
  {
     this.myValue=myValue;
  }
  public int getMyValue()
 {
      return myValue;
 }
}
</code>```

then in your askForTarget() method

```<code>t.setMyValue(input.nextInt());
return t;
</code>```

if you ever want to use the int in t in other calling method you can use the t method

```<code>t.getMyValue();
</code>```

Title: Beginner: How to return user input?

Body:
I'm new to Java and I'm having trouble with this bit of code:

import java.util.Scanner;

public class BattleshipLogic {

    private final int rows;
    private final int cols;

    private final boolean[][] hits;
    private final boolean[][] ships;

    public BattleshipLogic(int numRows, int numCols) {
        this.rows = numRows;
        this.cols = numCols;

        this.hits = new boolean[rows][cols];
        this.ships = new boolean[rows][cols];
    }

    public void startGame() {
        placeShips();
        boolean gameOver = false;
        // draw field for the first time
        drawUI();

        while (!gameOver) {
            Target target = askForTarget();
            processTarget(target);
            drawUI();
        }
    }

    private Target askForTarget() {
        Target t = new Target();
        Scanner input = new Scanner(System.in);
        System.out.print("Please enter your target:");
        t = input.nextInt();
        return t;
    }

    /*
     * This is just an example. You have to draw the ships by yourself.
     * If you don't like the way the UI is drawn, make your own stuff!
     */
    private void drawUI() {
        // draw the ui, see blatt01/oberflÃ¤che.txt for an example
        System.out.println("Schiffeversenken");
        System.out.println("================");
        System.out.println();

        // columns
        System.out.print("    ");
        for (int col = 0; col < this.cols; col++) {
            System.out.print(col + " ");
        }
        System.out.println();
        System.out.print("   _");
        for (int col = 0; col < this.cols; col++) {
            System.out.print("__");
        }
        System.out.println();
        for (int row = 0; row < this.rows; row++) {
            System.out.print(Character.toChars(3 + row));
            System.out.print(" |");

            System.out.println();
        }
    }

    private void placeShips() {
        // do useful stuff to place the ships here
        // see Blatt01 for rules
    }

    private void processTarget(Target target) {

    }

    /**
     * This class only holds the position
     * of a target.
     */
    private class Target {

        public int row;
        public int col;
    }
}

Everytime I try to compile this error comes up:

error: incompatible types: int cannot be converted to BattleshipLogic.Target

I know that the types are different, but what kind of a type is Target? How can I get the user input to be assigned to t?

Thanks so much in advance!

Body:
to assign the int value to

t of type Target

you need a

getter and setter method

on your t

e.g.

public class Target
{
  private int myValue;
  public void setMyValue(int myValue)
  {
     this.myValue=myValue;
  }
  public int getMyValue()
 {
      return myValue;
 }
}

then in your askForTarget() method

t.setMyValue(input.nextInt());
return t;

if you ever want to use the int in t in other calling method you can use the t method

t.getMyValue();


问:
How to translate strings in JS
I have a project which I want to translate into multiple languages for the PHP Part I use Zend Frameworks Zend_Translate with GetText. Now I want to translate the JS part too.

I am using the jQuery JS Framework and would love to hear your thoughts on translation for JS files

答: http://plugins.jquery.com/project/jquery-localize found this, which is used by and for letmegooglethatforyou.com also found this http://plugins.jquery.com/project/l10n whichone is better?</p>

OwnerDisplayName: Thomaschaaf

ContentLicense: CC BY-SA 2.5

Title: How to translate strings in JS

LastEditorDisplayName: Thomaschaaf


问:
how i can count the element who have the class "goo"
i want to check how much element have class "goo".

are i can check for specific element or all using jQuery. show me how i can do this task in jQuery

答: Maybe $(".goo").length

OwnerDisplayName: Steven Spielberg

Body: Maybe $(".goo").length


问:
Custom user-data reservation in ansi-c
I have a library with the following structure:

```<code>struct frame_meta_data
{
    uint8_t id;
    uint8_t general_field_1;
    uint8_t general_field_2;
    ...
    uint8_t user_data[16];
};
</code>```

And I would like users of the library to be able to save custom data into frame objects (that's what the user_data field is for).

However when trying to cast user_data into a custom structure:

```<code>frame_meta_data cur_frame;
...
#define USER_HDR ((struct my_user_header*)cur_frame.user_data)
</code>```

I get the following error:

```
warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]
#define USER_HDR ((struct my_user_header*)cur_frame.user_data)
```

How can I work around this?

Thanks in advance.

答:
I suspect it's because you're involving copies of this USR_DATA macro expression in multiple accesses to the data area, and it's confusing the compiler. Or perhaps you're even mixing USR_DATA accesses with manipulations of the underlying char array.

If the data area is only being initialized and accessed as that given user data type, there isn't any aliasing going on. Ensure you use it that way.

I would provide an external (as in, non-inlined, external linkage) API function which, given a frame object, returns a void * to the associated user data:

```<code>struct foobar *fbs = (struct foobar *) frame_get_userdata(fr);

// now work just with fbs
</code>```

The cast isn't necessary; that's my style.

Depending on what precedes the user data, it might not be suitably aligned for arbitrary use. One easy way to fix that would be to make it the first struct member, if that option is available. Otherwise there are various fairly portable tricks involving making a union between a char array and various types like long double and whatnot, or else using compiler-specific constructs, like __attribute__((aligned)) with GCC.

Title: Custom user-data reservation in ansi-c

Body:
I have a library with the following structure:

struct frame_meta_data
{
    uint8_t id;
    uint8_t general_field_1;
    uint8_t general_field_2;
    ...
    uint8_t user_data[16];
};

And I would like users of the library to be able to save custom data into frame objects (that's what the user_data field is for).

However when trying to cast user_data into a custom structure:

frame_meta_data cur_frame;
...
#define USER_HDR ((struct my_user_header*)cur_frame.user_data)

I get the following error:

warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]
#define USER_HDR ((struct my_user_header*)cur_frame.user_data)

How can I work around this?

Thanks in advance.

Body:
I suspect it's because you're involving copies of this USR_DATA macro expression in multiple accesses to the data area, and it's confusing the compiler. Or perhaps you're even mixing USR_DATA accesses with manipulations of the underlying char array.

If the data area is only being initialized and accessed as that given user data type, there isn't any aliasing going on. Ensure you use it that way.

I would provide an external (as in, non-inlined, external linkage) API function which, given a frame object, returns a void * to the associated user data:

struct foobar *fbs = (struct foobar *) frame_get_userdata(fr);

// now work just with fbs

The cast isn't necessary; that's my style.

Depending on what precedes the user data, it might not be suitably aligned for arbitrary use. One easy way to fix that would be to make it the first struct member, if that option is available. Otherwise there are various fairly portable tricks involving making a union between a char array and various types like long double and whatnot, or else using compiler-specific constructs, like __attribute__((aligned)) with GCC.


问:
Why I obtain this error trying to define a query with parameter in this old PHP application? (Fatal error: Cannot pass parameter 2 by reference in...)
I am pretty new in PHP and I have the following problem trying to define a simple query with parameter on an old PHP application. I have done in this way (mimic the other working query in this application that was made by someone else):

```<code>$result_facility_list = $db->prepare("select name from pm_facility where lang = :id_lang");
$result_hotel_file->bindParam(":id_lang", 2);
</code>```

Then

The problem is that when it try to perform the second line that bind the integer value 2 to the :id_lang parameter I obtain this error message:

```<code>( ! ) Fatal error: Cannot pass parameter 2 by reference in C:\xampp\htdocs\BeTrivius-Panda\templates\default\models\booking.php on line 534
Call Stack
#   Time    Memory  Function    Location
1   0.0326  165272  {main}( )   ..\index.php:0
2   8.2043  835656  include( 'C:\xampp\htdocs\BeTrivius-Panda\templates\default\models\booking.php' )   ..\index.php:146
</code>```

What could be the problem? What am I missing? How can I fix this issue?

答:
change this line

```<code>$result_hotel_file->bindParam(":id_lang", 2);
</code>```

to

```<code>$id=2;
$result_hotel_file->bindParam(":id_lang", $id);
</code>```

because you need to pass values to bindparam as variables

Body:
I am pretty new in PHP and I have the following problem trying to define a simple query with parameter on an old PHP application. I have done in this way (mimic the other working query in this application that was made by someone else):

$result_facility_list = $db->prepare("select name from pm_facility where lang = :id_lang");
$result_hotel_file->bindParam(":id_lang", 2);

Then

The problem is that when it try to perform the second line that bind the integer value 2 to the :id_lang parameter I obtain this error message:

( ! ) Fatal error: Cannot pass parameter 2 by reference in C:\xampp\htdocs\BeTrivius-Panda\templates\default\models\booking.php on line 534
Call Stack
#   Time    Memory  Function    Location
1   0.0326  165272  {main}( )   ..\index.php:0
2   8.2043  835656  include( 'C:\xampp\htdocs\BeTrivius-Panda\templates\default\models\booking.php' )   ..\index.php:146

What could be the problem? What am I missing? How can I fix this issue?

Body:
change this line

$result_hotel_file->bindParam(":id_lang", 2);

to

$id=2;
$result_hotel_file->bindParam(":id_lang", $id);

because you need to pass values to bindparam as variables


问:
Send massage to group devices in Firebase Cloud Messaging
I am building a chat and I want to send message in FCM to 1000 clients in a group. The message would sent from client to group of 1000 clients (the message not pass through server). I can use the topic method, but if I want to remove a client by the group admin it's not possible. Anyone can propose a solution?

Help me please.

答:
Topics are indeed public: you (as the developer/administrator of the app) cannot prevent your app's users from subscribing to a topic.

If you want to control the devices that do (and don't) receive your messages, you'll have to send the message to those specific devices. You do this by tracking the instance ID tokens for those devices in a database and then targeting the list of tokens when you send the downstream message.

There is an example of how to manage device tokens and send messages in the Cloud Messaging for Firebase documentation.


问:
Event triggered before data is inserted into page (After AJAX call)
This site (http://nelation.net/) loads pages by using AJAX and pushState. AJAX retrieves the contents of section#body and the path for the new CSS.

The following code sends the AJAX request, retrieves the new contents of section#body (page contents) and a new CSS path. Then it inserts those into the page, and after that it calls the "pageLoad" event - That's the event I believe is triggered too early.

```<code>function loadPage(url) {
    var target = document.getElementById("body");
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    xhr.onreadystatechange = function() {
        if (xhr.readyState < 4) {
            target.innerHTML = "";
        }
        if (xhr.readyState == 4 && xhr.status == 200) {
            // Function to decode the new page
            var decodeEntities = (function() {
                // this prevents any overhead from creating the object each time
                var element = document.createElement('div');
                function decodeHTMLEntities (str) {
                    if(str && typeof str === 'string') {
                        // strip script/html tags
                        str = str.replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, '');
                        str = str.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, '');
                        element.innerHTML = str;
                        str = element.textContent;
                        element.textContent = '';
                    }
                    return str;
                }
                return decodeHTMLEntities;
            })();

            var resultJSON = JSON.parse(xhr.responseText);
            var page = decodeEntities(resultJSON.page);
            // Remove existing CSS and insert new one
            $(".page-css").remove();
            if (resultJSON.css != "none") {
                $("<link/>", {
                    "class": "page-css",
                    rel: "stylesheet",
                    type: "text/css",
                    href: resultJSON.css
                }).appendTo("head");
            }
            // Insert page contents, then trigger the pageLoad event
            $(target).html(page);
            $("body").trigger("pageLoad");
        }
    };
    xhr.send();
}
// Detect link clicks, and make AJAX calls out of them + pushState.
$("body").on("click", '[data-ajax="true"]', function(event) {
    event.preventDefault();
    // detect which page has been selected
    var newPage = $(this).attr("href");
    if (newPage != window.location) {
        window.history.pushState({path: newPage}, "", newPage);
    }
    loadPage(newPage);
});
</code>```

The "pageLoad" event handler is found in this script. It re-executes most of the script, most notably the centerPlayButton_Featured() function if you're in the home page. That function resizes the overlay you see when you hover the image on the home page; It works fine when you load the page normally, but when you get to the page via AJAX it will not. The function is still executed (Logs to console), but I suspect it executes before the content is loaded properly into the page.

```<code>// DOES NOT RE-EXECUTE ON AJAX
function centerPlayButton_Featured() {
    console.log("centerPlayButton_Featured() just executed");
    var coverWidth = $("section.home-latest-release img.cover").width();
    var coverHeight = $("section.home-latest-release img.cover").height();
    $("section.home-latest-release div.cover-overlay").css({
        "height": coverWidth + "px",
        "width": coverHeight + "px"
    });
}

$("body").click(function(e) {
    if ($(e.target).hasClass("dropdown-text")) {
        if ($(e.target).siblings(".menu").hasClass("open")) {
            $(e.target).siblings(".menu").removeClass("open");
            $(e.target).removeClass("open");
        } else {
            $(".dropdown .menu, .dropdown .dropdown-text").removeClass("open");
            $(e.target).siblings(".menu").addClass("open");
            $(e.target).addClass("open");
        }
    } else {
        $(".dropdown .menu, .dropdown .dropdown-text").removeClass("open");
    }
});
// RE-EXECUTES ON AJAX
$("body").on("pageLoad", function() {
    $(function() {
        // HOME PAGE
        if ($("#body").children().hasClass("home-latest-release")) {

            centerPlayButton_Featured();
            $(window).on('resize', function() {
                centerPlayButton_Featured();
            });

        }
        // MUSIC PAGE
        if ($("#body").children().hasClass("music-tracks")) {

            //...

        }
        // CONTACT PAGE
        $(function() {
            if ($("#body").children().hasClass("contact")) {

                $("textarea").bind("input", function() {
                    var offset = this.offsetHeight - this.clientHeight;
                    $(this).css("height", "auto").css("height", this.scrollHeight + offset);
                });

            }
        });
    });
});
$("body").trigger("pageLoad");
</code>```

I appreciate any help/feedback. Go to the link to see more of the code, and tell me if you need to see the back-end. I apologize if the code is messy and comment-lacking. Thank you very much for the help.

Another problem I'm having is when you go to the music page, you may see all the dropdown menus fading out. Not as important as the main question, but help would be appreciated :)

答:
The pageLoad event is not triggered because it is bound to the window load event:

```<code>    $(window).bind("load", function() {
        $("body").trigger("pageLoad");
    });
</code>```

load happens only once during the lifetime of a window, and that time has long passed when an ajax request can even start. Trigger pageLoad directly.

$(function () {...}) is executed once when the DOM has finished loading. Effectively, you are wrapping the code to be executed twice with the same event load which only happens once. Execute your setup code directly inside the pageLoad event handler. I'd write it like this:

```<code>function pageSetup () {
    // HOME/MUSIC/CONTACT PAGE setup code
}

$("body").on("pageLoad", pageSetup);
pageSetup();
</code>```

Body:
This site (http://nelation.net/) loads pages by using AJAX and pushState. AJAX retrieves the contents of section#body and the path for the new CSS.

The following code sends the AJAX request, retrieves the new contents of section#body (page contents) and a new CSS path. Then it inserts those into the page, and after that it calls the "pageLoad" event - That's the event I believe is triggered too early.

function loadPage(url) {
    var target = document.getElementById("body");
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    xhr.onreadystatechange = function() {
        if (xhr.readyState < 4) {
            target.innerHTML = "";
        }
        if (xhr.readyState == 4 && xhr.status == 200) {
            // Function to decode the new page
            var decodeEntities = (function() {
                // this prevents any overhead from creating the object each time
                var element = document.createElement('div');
                function decodeHTMLEntities (str) {
                    if(str && typeof str === 'string') {
                        // strip script/html tags
                        str = str.replace(/

Body:
The pageLoad event is not triggered because it is bound to the window load event:

    $(window).bind("load", function() {
        $("body").trigger("pageLoad");
    });

load happens only once during the lifetime of a window, and that time has long passed when an ajax request can even start. Trigger pageLoad directly.

$(function () {...}) is executed once when the DOM has finished loading. Effectively, you are wrapping the code to be executed twice with the same event load which only happens once. Execute your setup code directly inside the pageLoad event handler. I'd write it like this:

function pageSetup () {
    // HOME/MUSIC/CONTACT PAGE setup code
}

$("body").on("pageLoad", pageSetup);
pageSetup();


问:
Rails render regular erb partial to active admin layout (arb)
I'm trying to add a view that LOOKS like active admin, but doesn't need to take advantage of active admin's automatic page creations (in fact I can't because I'm not using a model for these views). In my controller, I've added

```<code>render "reports/index", layout: "active_admin"
</code>```

I've seen this done in several other forums. However, I'm getting this error: undefined local variable or method 'view_factory' for :Arbre::Context
which I'm assuming is because I'm not using a full active admin page object or something. Any ideas on how to make this work?

答: If you don't have a model then use a custom page.</p>

Body:
I'm trying to add a view that LOOKS like active admin, but doesn't need to take advantage of active admin's automatic page creations (in fact I can't because I'm not using a model for these views). In my controller, I've added

render "reports/index", layout: "active_admin"

I've seen this done in several other forums. However, I'm getting this error: undefined local variable or method 'view_factory' for :Arbre::Context
which I'm assuming is because I'm not using a full active admin page object or something. Any ideas on how to make this work?


问:
How to auto start docker when synology restart
When you restart your Synology Nas The docker container stops.
Tell us how you can be restarted automatically turn on the docker container.</p>

答: When launching an image in Docker > Image, you can find "Enable auto-restart" behind the "Advanced Settings" button.</p>


问:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to mutate immutable object with appendFormat:'
I am trying to do a console line calculator and there is a problem with my program. I call a method (startParsing) and pass a user input. My method works during the first iteration (when i=0) and it adds a number into my number property (which is @property (nonatomic, strong) NSMutableString *number; in my .h file) and adds an operator to the NSMutableArray. So if I pass 2+3+7, the method adds "2" to the number property and "+" to the array of operators. Then the second iteration begins and when this line is called [self.number appendFormat:@"%c", symbol]; the error appears:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to mutate immutable object with appendFormat:'.

Can you please help me a little bit to understand what's wrong and how I can fix it?

```<code>- (void)startParsing:(NSMutableString *)userInput {

int operatorCounter = 1;
for (int i = 0; i < [userInput length]; i++)
{
    char symbol = (char) [userInput characterAtIndex:(NSUInteger) i];

    if ([self isSymbolNumber:symbol])
    {
        [self.number appendFormat:@"%c", symbol];
        operatorCounter = 0;
    }
    else
    {
        if ([self isOperatorSymbol:symbol])
        {
            //checks if the symbol is a unary operator.
            if ((symbol == '-' || symbol == '+') && ([self isSymbolNumber:(char) [userInput characterAtIndex:(NSUInteger) i + 1]])
                    && (operatorCounter == 1))
            {
                [self.number appendFormat:@"%c", symbol];
                operatorCounter = 0;

            }
            else if (operatorCounter == 0)
            {
                [self convertNumberToIntAndAddToArray:self.number];

                NSMutableString *singleCharacter  = [NSMutableString stringWithFormat:@"%c", symbol];
                [self.arrayOfOperators addObject:singleCharacter];

                operatorCounter++;
            }
            else [self printErrorWith:@"Invalid input operatorCounter == 0 "];
        }
        else
        {
            [self printErrorWith:@"Invalid input operatorCounter == 0 below"];
        }
    }
}
</code>```

答:
First, using char for the result of "characterAtIndex" is just awful. char is 8 bits, characterAtIndex is 16 bits. As soon as there are any non-ASCII characters, things will go badly wrong. </p>

<p>self.number is most likely an immutable string (NSString), so trying to append a char to it is not going to work. Methods starting with "stringBy" create and return a new string; look for something suitable. </p>

Body:
I am trying to do a console line calculator and there is a problem with my program. I call a method (startParsing) and pass a user input. My method works during the first iteration (when i=0) and it adds a number into my number property (which is @property (nonatomic, strong) NSMutableString *number; in my .h file) and adds an operator to the NSMutableArray. So if I pass 2+3+7, the method adds "2" to the number property and "+" to the array of operators. Then the second iteration begins and when this line is called [self.number appendFormat:@"%c", symbol]; the error appears:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to mutate immutable object with appendFormat:'.

Can you please help me a little bit to understand what's wrong and how I can fix it?

- (void)startParsing:(NSMutableString *)userInput {

int operatorCounter = 1;
for (int i = 0; i < [userInput length]; i++)
{
    char symbol = (char) [userInput characterAtIndex:(NSUInteger) i];

    if ([self isSymbolNumber:symbol])
    {
        [self.number appendFormat:@"%c", symbol];
        operatorCounter = 0;
    }
    else
    {
        if ([self isOperatorSymbol:symbol])
        {
            //checks if the symbol is a unary operator.
            if ((symbol == '-' || symbol == '+') && ([self isSymbolNumber:(char) [userInput characterAtIndex:(NSUInteger) i + 1]])
                    && (operatorCounter == 1))
            {
                [self.number appendFormat:@"%c", symbol];
                operatorCounter = 0;

            }
            else if (operatorCounter == 0)
            {
                [self convertNumberToIntAndAddToArray:self.number];

                NSMutableString *singleCharacter  = [NSMutableString stringWithFormat:@"%c", symbol];
                [self.arrayOfOperators addObject:singleCharacter];

                operatorCounter++;
            }
            else [self printErrorWith:@"Invalid input operatorCounter == 0 "];
        }
        else
        {
            [self printErrorWith:@"Invalid input operatorCounter == 0 below"];
        }
    }
}

Body:
First, using char for the result of "characterAtIndex" is just awful. char is 8 bits, characterAtIndex is 16 bits. As soon as there are any non-ASCII characters, things will go badly wrong.

self.number is most likely an immutable string (NSString), so trying to append a char to it is not going to work. Methods starting with "stringBy" create and return a new string; look for something suitable.


问:
Convert NSDate to JSON Date?
I need to post a NSDate object using HTTP post to parse.com.

I don't know how to convert it.

```<code>//1  nsdate
[params setObject:date forKey:kKeyDate];

//2 nsstring
 NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
 [dateFormat setDateFormat:@"yyyy-MM-dd T HH : mm : ss.SSSZ"];
 NSString *newString = [dateFormat stringFromDate:date];
 [params setObject:newString forKey:kKeyDate];
</code>```

Params are serialized in the body of the Http request. I know that everything else I'm doing is correct because if I comment out adding the NSDate to the params, then it works.

答: If you are using iOS 10.0 or above, use the ISO8601DateFormatter class.</p>

Title: Convert NSDate to JSON Date?

Body:
I need to post a NSDate object using HTTP post to parse.com.

I don't know how to convert it.

//1  nsdate
[params setObject:date forKey:kKeyDate];

//2 nsstring
 NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
 [dateFormat setDateFormat:@"yyyy-MM-dd T HH : mm : ss.SSSZ"];
 NSString *newString = [dateFormat stringFromDate:date];
 [params setObject:newString forKey:kKeyDate];

Params are serialized in the body of the Http request. I know that everything else I'm doing is correct because if I comment out adding the NSDate to the params, then it works.


问:
Using two entity sets in single table
I have a normal table inside smart table. Inside normal table, I have 2 columns for order and operation.

```<code><smartTable:SmartTable id="table" entitySet="entityset1" >
    <Table>
        <columns>
                    <Column>
                        <header>
                            <Text text="{order}"/>
                        </header>
                    </Column>
                    <Column>
                        <header>
                            <Text text="{operation}"/>
                        </header>
                    </Column>

        </columns>
    </Table>
</smartTable:SmartTable>
</code>```

My problem is, order is coming from entityset1 and operation in coming from entityset2. Is it possible to use two different entity sets in single table?

答:
If the entities have a navigation property and the OData service supports is you can use the $expand to get the data in a form you can use to bind to the table.

Look at 4.6 on here

Here is an example by Atanu Mallik of it used in a table binding

If this is not supported on you service or you do not have access to change your service then in the controller you can read both entitysets and create a JSON array with your related data in it. Create a JSON model out of your JSON object and use that model to bind to your table. But this is not ideal

https://sapui5.hana.ondemand.com/sdk/#docs/guide/96804e3315ff440aa0a50fd290805116.html#loio96804e3315ff440aa0a50fd290805116

Hopes this helps

Title: Using two entity sets in single table

Body:
I have a normal table inside smart table. Inside normal table, I have 2 columns for order and operation.

<smartTable:SmartTable id="table" entitySet="entityset1" >

        <columns>
                    <Column>

                            <Text text="{order}"/>

                    </Column>
                    <Column>

                            <Text text="{operation}"/>

                    </Column>

        </columns>

</smartTable:SmartTable>

My problem is, order is coming from entityset1 and operation in coming from entityset2. Is it possible to use two different entity sets in single table?


问:
TensorFlow version 1.0.0-rc2 on Windows: "OpKernel ('op: "BestSplits" device_type: "CPU"') for unknown op: BestSplits" with test code
I installed TensorFlow version 1.0.0-rc2 on Windows 7 SP1 x64 Ultimate (Python 3.5.2 |Anaconda custom (64-bit)) using:

```<code>pip install --upgrade https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow-1.0.0rc2-cp35-cp35m-win_amd64.whl
</code>```

When I try running the test script from https://web.archive.org/web/20170214034751/https://www.tensorflow.org/get_started/os_setup#test_the_tensorflow_installation in Eclipse 4.5 or in the console:

```<code>import tensorflow as tf
print('TensorFlow version: {0}'.format(tf.__version__))
hello = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(hello))
</code>```

I obtain some error message:

```<code>TensorFlow version: 1.0.0-rc2
'Hello, TensorFlow!'
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflob
w\core\framework\op_kernel.cc:943] OpKernel ('op: "BestSplits" device_type: "CPU"') for unknown op: BestSplits
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "CountExtremelyRandomStats" device_type: "CPU"') for unknown op: CountExtremelyRandomStats
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "FinishedNodes" device_type: "CPU"') for unknown op: FinishedNodes
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "GrowTree" device_type: "CPU"') for unknown op: GrowTree
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "ReinterpretStringToFloat" device_type: "CPU"') for unknown op: ReinterpretStringToFloat
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "SampleInputs" device_type: "CPU"') for unknown op: SampleInputs
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "ScatterAddNdim" device_type: "CPU"') for unknown op: ScatterAddNdim
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "TopNInsert" device_type: "CPU"') for unknown op: TopNInsert
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "TopNRemove" device_type: "CPU"') for unknown op: TopNRemove
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "TreePredictions" device_type: "CPU"') for unknown op: TreePredictions
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "UpdateFertileSlots" device_type: "CPU"') for unknown op: UpdateFertileSlots
</code>```

Why?

I didn't have such issues with TensorFlow 0.12.1  (installed with pip install tensorflow==0.12.1):

```<code>TensorFlow version: 0.12.1
b'Hello, TensorFlow!'
</code>```

答:
Seems the issue is fixed in the version 1.1.0rc0 and later.

Find the latest version of tensorflow:

```<code>pip search --version tensorflow
</code>```

Upgrade tensorflow:

```<code>pip install --upgrade tensorflow==1.1.0rc1
</code>```

Body:
I installed TensorFlow version 1.0.0-rc2 on Windows 7 SP1 x64 Ultimate (Python 3.5.2 |Anaconda custom (64-bit)) using:

pip install --upgrade https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow-1.0.0rc2-cp35-cp35m-win_amd64.whl

When I try running the test script from https://web.archive.org/web/20170214034751/https://www.tensorflow.org/get_started/os_setup#test_the_tensorflow_installation in Eclipse 4.5 or in the console:

import tensorflow as tf
print('TensorFlow version: {0}'.format(tf.__version__))
hello = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print(sess.run(hello))

I obtain some error message:

TensorFlow version: 1.0.0-rc2
'Hello, TensorFlow!'
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflob
w\core\framework\op_kernel.cc:943] OpKernel ('op: "BestSplits" device_type: "CPU"') for unknown op: BestSplits
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "CountExtremelyRandomStats" device_type: "CPU"') for unknown op: CountExtremelyRandomStats
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "FinishedNodes" device_type: "CPU"') for unknown op: FinishedNodes
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "GrowTree" device_type: "CPU"') for unknown op: GrowTree
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "ReinterpretStringToFloat" device_type: "CPU"') for unknown op: ReinterpretStringToFloat
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "SampleInputs" device_type: "CPU"') for unknown op: SampleInputs
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "ScatterAddNdim" device_type: "CPU"') for unknown op: ScatterAddNdim
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "TopNInsert" device_type: "CPU"') for unknown op: TopNInsert
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "TopNRemove" device_type: "CPU"') for unknown op: TopNRemove
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "TreePredictions" device_type: "CPU"') for unknown op: TreePredictions
E c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\framework\op_kernel.cc:943] OpKernel ('op: "UpdateFertileSlots" device_type: "CPU"') for unknown op: UpdateFertileSlots

Why?

I didn't have such issues with TensorFlow 0.12.1  (installed with pip install tensorflow==0.12.1):

TensorFlow version: 0.12.1
b'Hello, TensorFlow!'

Body:
Seems the issue is fixed in the version 1.1.0rc0 and later.

Find the latest version of tensorflow:

pip search --version tensorflow

Upgrade tensorflow:

pip install --upgrade tensorflow==1.1.0rc1


问:
Parsing data outside brackets in JSON in PHP
So I'm trying to parse some JSON that the Youtube API returns. I've been breaking my head over understanding how to parse JSON in PHP and I can't seem to figure it out.

This is basically the output of the API:

```<code>{
 "kind": "youtube#channelListResponse",
 "etag": "\"uQc-MPTsstrHkQcRXL3IWLmeNsM/mgiCAEvrnAFhKSCga80wVfAbUtc\"",
 "pageInfo": {
  "totalResults": 1,
  "resultsPerPage": 1
 },
 "items": [
  {
   "kind": "youtube#channel",
   "etag": "\"uQc-MPTsstrHkQcRXL3IWLmeNsM/cndol6pHIKmkRCizokwycOOUr2E\"",
   "id": "SWMb9NxQL9I6c",
   "snippet": {
    "title": "Koffee With Karan",
    "description": "Catch Karan Johar chat up Bollywood, secrets revealed and stories told , that's how the world will remember Koffee with Karan",
    "thumbnails": {
     "default": {
      "url": "https://i.ytimg.com/sh/554333074/showposter_thumb.jpg"
     },
     "medium": {
      "url": "https://i.ytimg.com/sh/554333074/showposter.jpg"
     },
     "high": {
      "url": "https://i.ytimg.com/sh/554333074/showposter_hq.jpg"
     }
    }
   }
  }
 ]
}
</code>```

What I want to get is pretty much everything in "snippet", I need the title, description and thumbnails. I've been trying to access it like this:

```<code>$getjson = file_get_contents('https://www.googleapis.com/youtube/v3/channels?part=snippet&id=SWMb9NxQL9I6c&key=mykey');
$data = json_decode($getjson,true);

echo $data['items'][0]['snippet'][0]['title'];
</code>```

or even trying something like

```<code>echo $data['items']->snippet->title;
</code>```

I've found numerous articles explaining how but nothing seems to work or make sense. First of all, the "items" data is outside of the starting { } brackets, which I haven't really been able to find anything about.

Any help and primarily an explanation about how this works would be awesome. I just want to understand the syntax needed to access this stuff.

答:
You are almost there. Try $data['items'][0]['snippet']['title']

json_decode(..., true). true will returns an associative array.

Use [] to access array values.

Anything in {} means, you can access using key, something like ['snippet'] & Anything in [] you can access using index something like [0] or [1]

This may not the good explanation. Hope it is somewhat understandable.

Body:
So I'm trying to parse some JSON that the Youtube API returns. I've been breaking my head over understanding how to parse JSON in PHP and I can't seem to figure it out.

This is basically the output of the API:

{
 "kind": "youtube#channelListResponse",
 "etag": "\"uQc-MPTsstrHkQcRXL3IWLmeNsM/mgiCAEvrnAFhKSCga80wVfAbUtc\"",
 "pageInfo": {
  "totalResults": 1,
  "resultsPerPage": 1
 },
 "items": [
  {
   "kind": "youtube#channel",
   "etag": "\"uQc-MPTsstrHkQcRXL3IWLmeNsM/cndol6pHIKmkRCizokwycOOUr2E\"",
   "id": "SWMb9NxQL9I6c",
   "snippet": {
    "title": "Koffee With Karan",
    "description": "Catch Karan Johar chat up Bollywood, secrets revealed and stories told , that's how the world will remember Koffee with Karan",
    "thumbnails": {
     "default": {
      "url": "https://i.ytimg.com/sh/554333074/showposter_thumb.jpg"
     },
     "medium": {
      "url": "https://i.ytimg.com/sh/554333074/showposter.jpg"
     },
     "high": {
      "url": "https://i.ytimg.com/sh/554333074/showposter_hq.jpg"
     }
    }
   }
  }
 ]
}

What I want to get is pretty much everything in "snippet", I need the title, description and thumbnails. I've been trying to access it like this:

$getjson = file_get_contents('https://www.googleapis.com/youtube/v3/channels?part=snippet&id=SWMb9NxQL9I6c&key=mykey');
$data = json_decode($getjson,true);

echo $data['items'][0]['snippet'][0]['title'];

or even trying something like

echo $data['items']->snippet->title;

I've found numerous articles explaining how but nothing seems to work or make sense. First of all, the "items" data is outside of the starting { } brackets, which I haven't really been able to find anything about.

Any help and primarily an explanation about how this works would be awesome. I just want to understand the syntax needed to access this stuff.


问:
Org Chart - Cluster Layout V3 to V4
I'm trying to update this Org Chart visualisation to use V4 of d3 but I'm hitting problems. This JSFiddle uses V3 while this JSFiddle uses V4.

I've run into a few things that have changed, for instance the CSV parsing (lines 53-54):

```<code>// var data = d3.csv.parse(csvData);
var data = d3.csvParse(csvData);
</code>```

And the calculation of diagonal (discussed here, lines 79-97):

```<code>/*
var diagonal = d3.svg.diagonal.radial()
    .projection(function(d) {
        return [d.y, d.x / 180 * Math.PI];
    });
*/
var diagonal = function n(n, i) {
    var u = t.call(this, n, i),
        o = e.call(this, n, i),
        a = (u.y + o.y) / 2,
        l = [u, {
            x: u.x,
            y: a
        }, {
            x: o.x,
            y: a
        }, o];
    return l = l.map(r), "M" + l[0] + "C" + l[1] + " " + l[2] + " " + l[3]
}
</code>```

And the geting of nodes has changed (lines 211-212):

```<code>//var nodes = cluster.nodes(root);
var nodes = d3.hierarchy(root);
</code>```

Now I seem to be hitting an issue with those nodes with this error message for line 216:

```<code>Uncaught TypeError: cluster.links is not a function
</code>```

Any help greatly appreciated, I'm no slouch when it comes to JS but this is my first foray into d3 and I'm getting really rather lost :-(.

答:
Live demo:

var csvData = `Associate,Manager
Matt Herman,John Smith
Jane Doe,John Smith
Adam Brown,John Smith
Susan Harris,John Smith
Mike Jones,John Smith
John Smith,Colin Krauss
Colin Krauss,Ashley Carlin
Ashley Carlin,Lia McDermott
Evan Park,Lia McDermott
Lauren Werner,Evan Park
Shane Waterson,Evan Park
Emma Smith,Evan Park
Mike Gregory,Evan Park
Jose Biggleman,Evan Park
Michelle Spektor,Evan Park
Juan Branch,Evan Park
John Orbase,Evan Park
Matt McCloud,Evan Park
Kelsey Carsen,Evan Park
Kelli Krazwinski,Colin Krauss
Stephanie Goldstien,Colin Krauss
Ryan Woolwine,Colin Krauss
Kyle Bohm,Colin Krauss
Sydney Yellen,Colin Krauss
Shankar Murjhree,Colin Krauss
Wayne Ellington,Colin Krauss
Dwight Folds,Colin Krauss
Ellen McGlynn,Colin Krauss
Nicolas Smith,Colin Krauss
Molly Ercole,Colin Krauss
Scott Hane,Colin Krauss
Regina McMahon,Colin Krauss
Skip Holden,Colin Krauss
Kadeem McPherson,Colin Krauss
Ray Ortiz,Colin Krauss
Janet Barnes,Colin Krauss
Holly Gold,Colin Krauss
Lance Martinez,Ashley Carlin
Mike Lubow,Ashley Carlin
Jordan Belsin,Ashley Carlin
Tom Strithers,Ashley Carlin
Jamie Raleigh,Ellen McGlynn
Joseph Bowman,Ellen McGlynn
Kylie Branch,Ellen McGlynn
Lars Randall,Ellen McGlynn
Carlos Barndt,Lia McDermott
Leo Hastings,Lia McDermott
Jaime Kellemen,Lia McDermott
Harvey Klien,Lia McDermott
Lia McDermott,Lia McDermott`;

var data = d3.csvParse(csvData);

var height = document.getElementById("tree-container").offsetHeight;
var width = document.getElementById("tree-container").offsetWidth;
var avatarRadius = 20;
var translateOffset = 25;
var radius = d3.min([height, width]) / 2;
var cluster = d3.cluster()
    .size([360, radius / 1.33])
    // .separation(function(a,b){return (a.parent == b.parent ? 1:2)/a.depth;});

var svg = d3.select("#tree-container").append("svg")
    .attr("width", radius * 2)
    .attr("height", radius * 2)
    .attr("id", "tree-container-svg")
    .append("g")
    .attr("transform", "translate(" + radius + "," + height / 2 + ")");

//Clip path needed for cicrular SVG avatars
var defs = svg.append('defs');
var clipPath = defs.append('clipPath')
    .attr('id', 'clip-circle')
    .append('circle')
    .attr('r', avatarRadius - 2.5);

function project(x, y) {
        var angle = (x - 90) / 180 * Math.PI,
            radius = y;
        return [radius * Math.cos(angle), radius * Math.sin(angle)];
}
var diagonal = function (d) {
    return "M" + project(d.x, d.y) + "C" + project(d.x, (d.y + d.parent.y) / 2) +
        " " + project(d.parent.x, (d.y + d.parent.y) / 2) +
        " " + project(d.parent.x, d.parent.y);
}
d3.selection.prototype.moveToFront = function () {
    return this.each(function () {
        this.parentNode.appendChild(this);
    });
};

d3.selection.prototype.moveToBack = function () {
    return this.each(function () {
        var firstChild = this.parentNode.firstChild;
        if (firstChild) {
            this.parentNode.insertBefore(this, firstChild);
        }
    });
};

//http://www.d3noob.org/2014/01/tree-diagrams-in-d3js_11.html
function treeify(list, callback) {

    var dataMap = list.reduce(function (map, node) {
        map[node.Associate] = node;
        return map;
    }, {});

    var treeData = [];
    list.forEach(function (node) {
        //Assuming the highest node is the last in the csv file
        if (node.Manager === node.Associate) {
            node.Manager = "Board of Directors"
            callback(node);
        }
        // add to parent
        var parent = dataMap[node.Manager];

        if (parent) {
            // create child array if it doesn't exist
            (parent.children || (parent.children = []))
            // add node to child array
            .push(node);
        } else {
            // parent is null or missing
            treeData.push(node);
        }
    });
};

function findItem(root, name, callback) {
    var stack = [];
    stack.push(root);
    while (stack.length !== 0) {
        var element = stack.pop();
        if (element.Associate === name) {
            callback(element);
            return;
        }
        //The up, uncompressed case
        else if (element.children !== undefined && element.children.length > 0) {
            for (var i = 0; i < element.children.length; i++) {
                stack.push(element.children[i]);
            }
        }
        //The down (compressed) case
        else if (element._children !== undefined && element._children.length > 0) {
            for (var j = 0; j < element._children.length; j++) {
                stack.push(element._children[j]);
            }
        }
    }
}

function defaultPlot(root, elem) {
    findItem(root, elem, function (d) {
        //Showing 1 up and below
        findItem(root, d.Manager, function (x) {
            (x.children) ? x.children.forEach(collapse): x.children = x._children;
            drawIt(x, root);
        })
    })
}

function collapse(d) {
    if (d.children) {
        d._children = d.children;
        d._children.forEach(collapse);
        d.children = undefined;
    }
}

//For the buggy transition interruption with many nodes
function showAllCurrentPathsAndNodes() {
    d3.selectAll(".link").style("opacity", 1);
    d3.selectAll(".node").style("opacity", 1);
}

// Toggle children on click.
function clickedNode(d, root) {
    //Accounting for the transition bug on the delay
    showAllCurrentPathsAndNodes();

    if (d.children) {
        d._children = d.children;
        d.children = undefined;
        drawIt(root)
    } else {
        d.children = d._children;
        d._children = undefined;
        drawIt(root)
    }
}

//http://bl.ocks.org/syntagmatic/4092944
function drawIt(root) {
    var nodes = d3.hierarchy(root);
    cluster(nodes);

    var links = nodes.descendants().slice(1);

    var link = svg.selectAll("path.link").data(links);

    var node = svg.selectAll("g.node").data(nodes.descendants(),function(d){
        return d.data.Associate;
    });

    link.transition().duration(1000).attr("d", diagonal);

    d3.selectAll(".node-cicle").classed("highlight", false);

    showAllCurrentPathsAndNodes();

    link.enter().append("path")
        .attr("class", "link")
        .attr("d", diagonal)
        .attr("", function (d) {
            d3.select(this).moveToBack();
        })
        .style("opacity", 0)
        .transition()
        .duration(300)
        .delay(function (d, i) {
            return 28 * i;
        }).style("opacity", 1);

    node.transition().duration(800).attr("transform", function (d) {
        return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")";
    });

    var g = node.enter().append("g")
        .attr("class", "node")
        .attr("transform", function (d) {
            return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")";
        })
        .style("opacity", 0)
        .style("cursor", function (d) {
            d=d.data;
            return ((d._children || d.children) && d.Manager !== "Board of Directors") ? "pointer" : "not-allowed";
        })
        .on("mouseover", function () {
            d3.select(this).moveToFront();
        })

    //Cant trust the enter append here, reassign the event listener for all nodes each draw
    d3.selectAll(".node")
        .on("click", function (d) {
            d=d.data;
            return ((d._children || d.children) && d.Manager !== "Board of Directors") ? clickedNode(d, root) : "";
        });

    g.transition().duration(300)
        .delay(function (d, i) {
            return 28 * i;
        })
        .style("opacity", 1);

    g.append("circle")
        .attr("r", avatarRadius)
        .attr("class", "circle-marker")
        .style("stroke", function (d) {
            d = d.data;
            return ((d._children || d.children) && d.Manager !== "Board of Directors") ? "steelblue" : "gray";
        })
        .style("fill", function (d) {
            d = d.data;
            return ((d._children || d.children) && d.Manager !== "Board of Directors") ? "steelblue" : "#fff";
        });

    g.append("svg:image")
        .attr("class", "node-avatar")
        .attr("xlink:href", "http://safariuganda.com/wp-content/uploads/2014/12/480px-Facebook-default-no-profile-pic.jpg")
        .attr("height", avatarRadius * 2)
        .attr("width", avatarRadius * 2)
        .attr("x", "-" + avatarRadius)
        .attr("y", "-" + avatarRadius)
        .attr('clip-path', 'url(#clip-circle)');

    //Might want to tween this?
    d3.selectAll(".node-avatar")
        .attr("transform", function (d) {
            return "rotate(" + (-1 * (d.x - 90)) + ")";
        });

    g.append("text")
        .attr("dy", ".31em")
        .attr("class", "label-text")
        .text(function (d) {
            return d.data.Associate;
        })

    //search all labels to ensure they are right side up (cant rely on the enter append here)
    d3.selectAll(".label-text")
        .attr("text-anchor", function (d) {
            return d.x < 180 ? "start" : "end";
        })
        .attr("transform", function (d) {
            return d.x < 180 ? "translate(" + translateOffset + ")" : "rotate(180)translate(-" + translateOffset + ")";
        })

    link.exit().transition().duration(0).style("opacity", 0).remove();
    node.exit().transition().duration(0).style("opactiy", 0).remove();

}

treeify(data, function (treeReturn) {
    var root = treeReturn;
    defaultPlot(root, root.children[0].Associate)
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body {
    font-family: 'Open Sans', sans-serif;
    font-size: 12px;
    background-color: #fff;
    height: 100%;
    width: 100%;
    background-color: #f1f1f1;
    position: relative;
    display: block;
}

#tree-container {
    position: relative;
    display: block;
    margin-left: 100px;
    height: 100%;
    width: 100%;
}

.node circle {
    stroke-width: 1.5px;
}

.node {
    font: 10px sans-serif;
}

.link {
    fill: none;
    stroke: #ccc;
    stroke-width: 1.5px;
}

.label-text {
    -webkit-user-select: none;
    /* Chrome/Safari */
    -moz-user-select: none;
    /* Firefox */
    -ms-user-select: none;
    /* IE10+ */
    /* Rules below not implemented in browsers yet */
    -o-user-select: none;
    user-select: none;
}</code>```

<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>test</title>

    <link rel="stylesheet" href="style.css">

```
</div>
</div>
</p>

<h3>How to migrate</h3>

```var diagonal = d3.svg.diagonal.radial()
.projection(function(d) {
    return [d.y, d.x / 180 * Math.PI];
});
```

<p>to </p>

```function project(x, y) {
    var angle = (x - 90) / 180 * Math.PI, radius = y;
    return [radius * Math.cos(angle), radius * Math.sin(angle)];
}

var diagonal = function (d) {
    return "M" + project(d.x, d.y) + "C" + project(d.x, (d.y + d.parent.y) / 2) +
    " " + project(d.parent.x, (d.y + d.parent.y) / 2) +
    " " + project(d.parent.x, d.parent.y);
}
```

And there're many changes in the drawIt method. Just refer to https://bl.ocks.org/mbostock/4739610f6d96aaad2fb1e78a72b385ab

Title: Org Chart - Cluster Layout V3 to V4

Body:
I'm trying to update this Org Chart visualisation to use V4 of d3 but I'm hitting problems. This JSFiddle uses V3 while this JSFiddle uses V4.

I've run into a few things that have changed, for instance the CSV parsing (lines 53-54):

// var data = d3.csv.parse(csvData);
var data = d3.csvParse(csvData);

And the calculation of diagonal (discussed here, lines 79-97):

/*
var diagonal = d3.svg.diagonal.radial()
    .projection(function(d) {
        return [d.y, d.x / 180 * Math.PI];
    });
*/
var diagonal = function n(n, i) {
    var u = t.call(this, n, i),
        o = e.call(this, n, i),
        a = (u.y + o.y) / 2,
        l = [u, {
            x: u.x,
            y: a
        }, {
            x: o.x,
            y: a
        }, o];
    return l = l.map(r), "M" + l[0] + "C" + l[1] + " " + l[2] + " " + l[3]
}

And the geting of nodes has changed (lines 211-212):

//var nodes = cluster.nodes(root);
var nodes = d3.hierarchy(root);

Now I seem to be hitting an issue with those nodes with this error message for line 216:

Uncaught TypeError: cluster.links is not a function

Any help greatly appreciated, I'm no slouch when it comes to JS but this is my first foray into d3 and I'm getting really rather lost :-(.

Body:
Live demo:

var csvData = `Associate,Manager
Matt Herman,John Smith
Jane Doe,John Smith
Adam Brown,John Smith
Susan Harris,John Smith
Mike Jones,John Smith
John Smith,Colin Krauss
Colin Krauss,Ashley Carlin
Ashley Carlin,Lia McDermott
Evan Park,Lia McDermott
Lauren Werner,Evan Park
Shane Waterson,Evan Park
Emma Smith,Evan Park
Mike Gregory,Evan Park
Jose Biggleman,Evan Park
Michelle Spektor,Evan Park
Juan Branch,Evan Park
John Orbase,Evan Park
Matt McCloud,Evan Park
Kelsey Carsen,Evan Park
Kelli Krazwinski,Colin Krauss
Stephanie Goldstien,Colin Krauss
Ryan Woolwine,Colin Krauss
Kyle Bohm,Colin Krauss
Sydney Yellen,Colin Krauss
Shankar Murjhree,Colin Krauss
Wayne Ellington,Colin Krauss
Dwight Folds,Colin Krauss
Ellen McGlynn,Colin Krauss
Nicolas Smith,Colin Krauss
Molly Ercole,Colin Krauss
Scott Hane,Colin Krauss
Regina McMahon,Colin Krauss
Skip Holden,Colin Krauss
Kadeem McPherson,Colin Krauss
Ray Ortiz,Colin Krauss
Janet Barnes,Colin Krauss
Holly Gold,Colin Krauss
Lance Martinez,Ashley Carlin
Mike Lubow,Ashley Carlin
Jordan Belsin,Ashley Carlin
Tom Strithers,Ashley Carlin
Jamie Raleigh,Ellen McGlynn
Joseph Bowman,Ellen McGlynn
Kylie Branch,Ellen McGlynn
Lars Randall,Ellen McGlynn
Carlos Barndt,Lia McDermott
Leo Hastings,Lia McDermott
Jaime Kellemen,Lia McDermott
Harvey Klien,Lia McDermott
Lia McDermott,Lia McDermott`;

var data = d3.csvParse(csvData);

var height = document.getElementById("tree-container").offsetHeight;
var width = document.getElementById("tree-container").offsetWidth;
var avatarRadius = 20;
var translateOffset = 25;
var radius = d3.min([height, width]) / 2;
var cluster = d3.cluster()
    .size([360, radius / 1.33])
    // .separation(function(a,b){return (a.parent == b.parent ? 1:2)/a.depth;});

var svg = d3.select("#tree-container").append("svg")
    .attr("width", radius * 2)
    .attr("height", radius * 2)
    .attr("id", "tree-container-svg")
    .append("g")
    .attr("transform", "translate(" + radius + "," + height / 2 + ")");

//Clip path needed for cicrular SVG avatars
var defs = svg.append('defs');
var clipPath = defs.append('clipPath')
    .attr('id', 'clip-circle')
    .append('circle')
    .attr('r', avatarRadius - 2.5);

function project(x, y) {
        var angle = (x - 90) / 180 * Math.PI,
            radius = y;
        return [radius * Math.cos(angle), radius * Math.sin(angle)];
}
var diagonal = function (d) {
    return "M" + project(d.x, d.y) + "C" + project(d.x, (d.y + d.parent.y) / 2) +
        " " + project(d.parent.x, (d.y + d.parent.y) / 2) +
        " " + project(d.parent.x, d.parent.y);
}
d3.selection.prototype.moveToFront = function () {
    return this.each(function () {
        this.parentNode.appendChild(this);
    });
};

d3.selection.prototype.moveToBack = function () {
    return this.each(function () {
        var firstChild = this.parentNode.firstChild;
        if (firstChild) {
            this.parentNode.insertBefore(this, firstChild);
        }
    });
};

//http://www.d3noob.org/2014/01/tree-diagrams-in-d3js_11.html
function treeify(list, callback) {

    var dataMap = list.reduce(function (map, node) {
        map[node.Associate] = node;
        return map;
    }, {});

    var treeData = [];
    list.forEach(function (node) {
        //Assuming the highest node is the last in the csv file
        if (node.Manager === node.Associate) {
            node.Manager = "Board of Directors"
            callback(node);
        }
        // add to parent
        var parent = dataMap[node.Manager];

        if (parent) {
            // create child array if it doesn't exist
            (parent.children || (parent.children = []))
            // add node to child array
            .push(node);
        } else {
            // parent is null or missing
            treeData.push(node);
        }
    });
};

function findItem(root, name, callback) {
    var stack = [];
    stack.push(root);
    while (stack.length !== 0) {
        var element = stack.pop();
        if (element.Associate === name) {
            callback(element);
            return;
        }
        //The up, uncompressed case
        else if (element.children !== undefined && element.children.length > 0) {
            for (var i = 0; i < element.children.length; i++) {
                stack.push(element.children[i]);
            }
        }
        //The down (compressed) case
        else if (element._children !== undefined && element._children.length > 0) {
            for (var j = 0; j < element._children.length; j++) {
                stack.push(element._children[j]);
            }
        }
    }
}

function defaultPlot(root, elem) {
    findItem(root, elem, function (d) {
        //Showing 1 up and below
        findItem(root, d.Manager, function (x) {
            (x.children) ? x.children.forEach(collapse): x.children = x._children;
            drawIt(x, root);
        })
    })
}

function collapse(d) {
    if (d.children) {
        d._children = d.children;
        d._children.forEach(collapse);
        d.children = undefined;
    }
}

//For the buggy transition interruption with many nodes
function showAllCurrentPathsAndNodes() {
    d3.selectAll(".link").style("opacity", 1);
    d3.selectAll(".node").style("opacity", 1);
}

// Toggle children on click.
function clickedNode(d, root) {
    //Accounting for the transition bug on the delay
    showAllCurrentPathsAndNodes();

    if (d.children) {
        d._children = d.children;
        d.children = undefined;
        drawIt(root)
    } else {
        d.children = d._children;
        d._children = undefined;
        drawIt(root)
    }
}

//http://bl.ocks.org/syntagmatic/4092944
function drawIt(root) {
    var nodes = d3.hierarchy(root);
    cluster(nodes);

    var links = nodes.descendants().slice(1);

    var link = svg.selectAll("path.link").data(links);

    var node = svg.selectAll("g.node").data(nodes.descendants(),function(d){
        return d.data.Associate;
    });

    link.transition().duration(1000).attr("d", diagonal);

    d3.selectAll(".node-cicle").classed("highlight", false);

    showAllCurrentPathsAndNodes();

    link.enter().append("path")
        .attr("class", "link")
        .attr("d", diagonal)
        .attr("", function (d) {
            d3.select(this).moveToBack();
        })
        .style("opacity", 0)
        .transition()
        .duration(300)
        .delay(function (d, i) {
            return 28 * i;
        }).style("opacity", 1);

    node.transition().duration(800).attr("transform", function (d) {
        return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")";
    });

    var g = node.enter().append("g")
        .attr("class", "node")
        .attr("transform", function (d) {
            return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")";
        })
        .style("opacity", 0)
        .style("cursor", function (d) {
            d=d.data;
            return ((d._children || d.children) && d.Manager !== "Board of Directors") ? "pointer" : "not-allowed";
        })
        .on("mouseover", function () {
            d3.select(this).moveToFront();
        })

    //Cant trust the enter append here, reassign the event listener for all nodes each draw
    d3.selectAll(".node")
        .on("click", function (d) {
            d=d.data;
            return ((d._children || d.children) && d.Manager !== "Board of Directors") ? clickedNode(d, root) : "";
        });

    g.transition().duration(300)
        .delay(function (d, i) {
            return 28 * i;
        })
        .style("opacity", 1);

    g.append("circle")
        .attr("r", avatarRadius)
        .attr("class", "circle-marker")
        .style("stroke", function (d) {
            d = d.data;
            return ((d._children || d.children) && d.Manager !== "Board of Directors") ? "steelblue" : "gray";
        })
        .style("fill", function (d) {
            d = d.data;
            return ((d._children || d.children) && d.Manager !== "Board of Directors") ? "steelblue" : "#fff";
        });

    g.append("svg:image")
        .attr("class", "node-avatar")
        .attr("xlink:href", "http://safariuganda.com/wp-content/uploads/2014/12/480px-Facebook-default-no-profile-pic.jpg")
        .attr("height", avatarRadius * 2)
        .attr("width", avatarRadius * 2)
        .attr("x", "-" + avatarRadius)
        .attr("y", "-" + avatarRadius)
        .attr('clip-path', 'url(#clip-circle)');

    //Might want to tween this?
    d3.selectAll(".node-avatar")
        .attr("transform", function (d) {
            return "rotate(" + (-1 * (d.x - 90)) + ")";
        });

    g.append("text")
        .attr("dy", ".31em")
        .attr("class", "label-text")
        .text(function (d) {
            return d.data.Associate;
        })

    //search all labels to ensure they are right side up (cant rely on the enter append here)
    d3.selectAll(".label-text")
        .attr("text-anchor", function (d) {
            return d.x < 180 ? "start" : "end";
        })
        .attr("transform", function (d) {
            return d.x < 180 ? "translate(" + translateOffset + ")" : "rotate(180)translate(-" + translateOffset + ")";
        })

    link.exit().transition().duration(0).style("opacity", 0).remove();
    node.exit().transition().duration(0).style("opactiy", 0).remove();

}

treeify(data, function (treeReturn) {
    var root = treeReturn;
    defaultPlot(root, root.children[0].Associate)
});

html,
body {
    font-family: 'Open Sans', sans-serif;
    font-size: 12px;
    background-color: #fff;
    height: 100%;
    width: 100%;
    background-color: #f1f1f1;
    position: relative;
    display: block;
}

#tree-container {
    position: relative;
    display: block;
    margin-left: 100px;
    height: 100%;
    width: 100%;
}

.node circle {
    stroke-width: 1.5px;
}

.node {
    font: 10px sans-serif;
}

.link {
    fill: none;
    stroke: #ccc;
    stroke-width: 1.5px;
}

.label-text {
    -webkit-user-select: none;
    /* Chrome/Safari */
    -moz-user-select: none;
    /* Firefox */
    -ms-user-select: none;
    /* IE10+ */
    /* Rules below not implemented in browsers yet */
    -o-user-select: none;
    user-select: none;
}

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <title>test</title>

</head>

<body>
    <div id="tree-container"></div>
    <link rel="stylesheet" href="style.css">
    <script src="https://d3js.org/d3.v4.min.js"></script>
    <script src="index.js"></script>
</body>

</html>

How to migrate

var diagonal = d3.svg.diagonal.radial()
.projection(function(d) {
    return [d.y, d.x / 180 * Math.PI];
});

to

function project(x, y) {
    var angle = (x - 90) / 180 * Math.PI, radius = y;
    return [radius * Math.cos(angle), radius * Math.sin(angle)];
}

var diagonal = function (d) {
    return "M" + project(d.x, d.y) + "C" + project(d.x, (d.y + d.parent.y) / 2) +
    " " + project(d.parent.x, (d.y + d.parent.y) / 2) +
    " " + project(d.parent.x, d.parent.y);
}

And there're many changes in the drawIt method. Just refer to https://bl.ocks.org/mbostock/4739610f6d96aaad2fb1e78a72b385ab


答:
```<code>var amountOfGoo = $('.goo').length;
</code>```

Title: how i can count the element who have the class "goo"

Body:
i want to check how much element have class "goo".

are i can check for specific element or all using jQuery. show me how i can do this task in jQuery

Body: var amountOfGoo = $('.goo').length;


问:
How can i show left shift operator on my button in android?
I tried using this code but it's showing an error "Tag Name Expected".I don't want to use an image to show that in background of button i wan't to use the symbol ">>" itself.</p>

```<code>XML code:-
 <Button
        android:layout_width="120dp"
        android:layout_height="50dp"
        android:background="@drawable/shape"
        android:layout_marginTop="5dp"
        android:layout_marginLeft="7dp"
        android:text="@string/leftshi"
        android:id="@+id/leftshi"
        android:textSize="35sp"
        android:layout_marginStart="7dp"
        />
String values:
 <resources>
        <string name="leftshi">"<<"</string> //Error is shown here.
 </resources>
</code>```

答:
You forget to use the escape symbol...try escapse symbol for xml.

What characters do I need to escape in XML documents?

Body:
I tried using this code but it's showing an error "Tag Name Expected".I don't want to use an image to show that in background of button i wan't to use the symbol ">>" itself.

XML code:-
 <Button
        android:layout_width="120dp"
        android:layout_height="50dp"
        android:background="@drawable/shape"
        android:layout_marginTop="5dp"
        android:layout_marginLeft="7dp"
        android:text="@string/leftshi"
        android:id="@+id/leftshi"
        android:textSize="35sp"
        android:layout_marginStart="7dp"
        />
String values:
 <resources>
        <string name="leftshi">"<<"</string> //Error is shown here.
 </resources>


问:
DB2 database restore
When I am restoring the database, by default data is going in C drive, but when I installed the db2 that time I specify the path in D drive only.
Also, sample database files created by db2 is stored in D drive.
Can anyone please tell me what is the issue?

I have run this command:

```<code>SELECT * FROM SYSIBMADM.DBPATHS
</code>```

below is the result i fetched:

```<code>LOGPATH- D:\DB2\NODE000\SQL00001\SQLOGDIR\
DB_STORAGE_PATH- C:\
LOCAL_DB_DIRECTORY -  D:\DB2\NODE000\SQLOGDIR\
DBPATH - D:\DB2\NODE000\SQL00001\
</code>```

I Want to change this DB_STORAGE_PATH C:\ to D:\ for all the database which i will be restoring.

答:
DB2 has a configuration parameter for the default path for databases, dftdbpath. In addition, the command db2sampl to create a sample database has an option dbpath to specify where to place that database.

```<code>db2sample -dbpath D:
</code>```

The above would place the new database on drive D:.

You will find that there are default paths for certain operations. The overview of DB2 database manager configuration parameters has lists most of them.

For your specific issue I would assume that a parameter was changed some time after DB2 was installed and used initially.

For RESTORE be aware that the options TO and DBPATH are ignored if restoring an existing database.

Title: DB2 database restore

Body:
When I am restoring the database, by default data is going in C drive, but when I installed the db2 that time I specify the path in D drive only.
Also, sample database files created by db2 is stored in D drive.
Can anyone please tell me what is the issue?

I have run this command:

SELECT * FROM SYSIBMADM.DBPATHS

below is the result i fetched:

LOGPATH- D:\DB2\NODE000\SQL00001\SQLOGDIR\
DB_STORAGE_PATH- C:\
LOCAL_DB_DIRECTORY -  D:\DB2\NODE000\SQLOGDIR\
DBPATH - D:\DB2\NODE000\SQL00001\

I Want to change this DB_STORAGE_PATH C:\ to D:\ for all the database which i will be restoring.

Body:
DB2 has a configuration parameter for the default path for databases, dftdbpath. In addition, the command db2sampl to create a sample database has an option dbpath to specify where to place that database.

db2sample -dbpath D:

The above would place the new database on drive D:.

You will find that there are default paths for certain operations. The overview of DB2 database manager configuration parameters has lists most of them.

For your specific issue I would assume that a parameter was changed some time after DB2 was installed and used initially.

For RESTORE be aware that the options TO and DBPATH are ignored if restoring an existing database.


问:
Sqlite3, OperationalError: unable to open database file
Question: Why can't I open the database?

Info: I'm working on a project using sqlite3 database. I wrote a test program that runs and passes it the database:

/tmp/cer/could.db

The unit test program can make the db without any problem. But, when I actually use the program passing the same location to it, i got below error:

OperationalError: unable to open database file

I've tried doing it with:

```<code>1) an empty database.
2) the database and the unit test left behind.
3) no database at all.
</code>```

In three cases, I got the above error. The most frustrating part has to be the fact that the unittest can do it just fine, but the actual program can't.

Any clues as to what on earth is going on?

答:
One reason might be running the code in a path that doesn't match with your specified path for the database. For example if in your code you have:

```<code>conn = lite.connect('folder_A/my_database.db')
</code>```

And you run the code inside the folder_A or other places that doesn't have a folder_A it will raise such error. The reason is that SQLite will create the database file if it doesn't exist not the folder.

One other way for getting around this problem might be wrapping your connecting command in a try-except expression and creating the directory if it raises sqlite3.OperationalError.

from os import mkdir
import sqlite3 as lite

```<code>try:
    conn = lite.connect('folder_A/my_database.db')
except lite.OperationalError:
    mkdir('folder_A')
finally:
    conn = lite.connect('folder_A/my_database.db')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Question: Why can't I open the database?

Info: I'm working on a project using sqlite3 database. I wrote a test program that runs and passes it the database:

/tmp/cer/could.db

The unit test program can make the db without any problem. But, when I actually use the program passing the same location to it, i got below error:

OperationalError: unable to open database file

I've tried doing it with:

1) an empty database.
2) the database and the unit test left behind.
3) no database at all.

In three cases, I got the above error. The most frustrating part has to be the fact that the unittest can do it just fine, but the actual program can't.

Any clues as to what on earth is going on?

Body:
One reason might be running the code in a path that doesn't match with your specified path for the database. For example if in your code you have:

conn = lite.connect('folder_A/my_database.db')

And you run the code inside the folder_A or other places that doesn't have a folder_A it will raise such error. The reason is that SQLite will create the database file if it doesn't exist not the folder.

One other way for getting around this problem might be wrapping your connecting command in a try-except expression and creating the directory if it raises sqlite3.OperationalError.

from os import mkdir
import sqlite3 as lite

try:
    conn = lite.connect('folder_A/my_database.db')
except lite.OperationalError:
    mkdir('folder_A')
finally:
    conn = lite.connect('folder_A/my_database.db')


问:
Check that Field Exists with MongoDB
So I'm attempting to find all records who have a field set and isn't null.

I try using $exists, however according to the MongoDB documentation, this query will return fields who equal null.

$exists does match documents that contain the field that stores the null value.

So I'm now assuming I'll have to do something like this:

```<code>db.collection.find({ "fieldToCheck" : { $exists : true, $not : null } })
</code>```

Whenever I try this however, I get the error [invalid use of $not]  Anyone have an idea of how to query for this?

答:
i find that this works for me</p>

```<code>db.getCollection('collectionName').findOne({"fieldName" : {$ne: null}})
</code>```

Title: Check that Field Exists with MongoDB

Body:
So I'm attempting to find all records who have a field set and isn't null.

I try using $exists, however according to the MongoDB documentation, this query will return fields who equal null.

$exists does match documents that contain the field that stores the null value.

So I'm now assuming I'll have to do something like this:

db.collection.find({ "fieldToCheck" : { $exists : true, $not : null } })

Whenever I try this however, I get the error [invalid use of $not]  Anyone have an idea of how to query for this?

Body:
i find that this works for me

db.getCollection('collectionName').findOne({"fieldName" : {$ne: null}})


问:
GNUmake: how to write a true lambda
The following is my take on a so-so emulation of a lambda expression in GNUmake :

```<code>space := $(strip) $(strip)
comma := ,

# convert a space-separated list in $1 into a comma-separated list:
list2param = $(subst $(space),$(comma),$(strip $1))

# param $1 = quoted GUNmake expression
# param $2 = parameters to the expression as space-separated list
lambda = $(eval _lambda=$1)$(eval _lambda:=$$(call _lambda,$(call list2param,$2)))$(_lambda)
</code>```

Example:

```<code>$(info $(call lambda,$$1 .. $$2 .. $$3,foo bar baz))
</code>```

Output:

```<code>foo .. bar .. baz
</code>```

But this is less than satisfying, as I have to use a variable "_lambda" behind the curtain and the mechanism isn't really like lambda as the evaluation isn't separated from the definition. Is there a clean, direct way to implement a lambda? Or is there already some mechanism implemented which my blind procedural programming eyes didn't catch?

答:
As in any primitive substitution language, you defer evaluation by quoting.  The example below looks horrible and doesn't let you nest lambdas, but otherwise works:

```<code>define lambda
$(eval lambda-f=$1)lambda-f
endef

$(foreach n,1 2 3,$(call $(call lambda,$$(info $$(shell seq -s ' ' $$1))),$n))
</code>```

Some readability can be (arguably) regained by amending the syntax like this:

```<code>define lambda
$(eval lambda-f=$(subst ^,$$,$1))lambda-f
endef

$(foreach n,1 2 3,$(call $(call lambda,^(info ^(shell seq -s ' ' ^1))),$n))
</code>```

Title: GNUmake: how to write a true lambda

Body:
The following is my take on a so-so emulation of a lambda expression in GNUmake :

space := $(strip) $(strip)
comma := ,

# convert a space-separated list in $1 into a comma-separated list:
list2param = $(subst $(space),$(comma),$(strip $1))

# param $1 = quoted GUNmake expression
# param $2 = parameters to the expression as space-separated list
lambda = $(eval _lambda=$1)$(eval _lambda:=$$(call _lambda,$(call list2param,$2)))$(_lambda)

Example:

$(info $(call lambda,$$1 .. $$2 .. $$3,foo bar baz))

Output:

foo .. bar .. baz

But this is less than satisfying, as I have to use a variable "_lambda" behind the curtain and the mechanism isn't really like lambda as the evaluation isn't separated from the definition. Is there a clean, direct way to implement a lambda? Or is there already some mechanism implemented which my blind procedural programming eyes didn't catch?

Body:
As in any primitive substitution language, you defer evaluation by quoting.  The example below looks horrible and doesn't let you nest lambdas, but otherwise works:

define lambda
$(eval lambda-f=$1)lambda-f
endef

$(foreach n,1 2 3,$(call $(call lambda,$$(info $$(shell seq -s ' ' $$1))),$n))

Some readability can be (arguably) regained by amending the syntax like this:

define lambda
$(eval lambda-f=$(subst ^,$$,$1))lambda-f
endef

$(foreach n,1 2 3,$(call $(call lambda,^(info ^(shell seq -s ' ' ^1))),$n))


答:
In your code items has an array value, but snippet is a structure not an array. So must use:

```<code>echo $data->items[0]->snippet->title;
</code>```

or if you have second parameter of json_decode as true you can write:

```<code>echo $data['items'][0]['snippet']['title'];
</code>```

Title: Parsing data outside brackets in JSON in PHP

Body:
In your code items has an array value, but snippet is a structure not an array. So must use:

echo $data->items[0]->snippet->title;

or if you have second parameter of json_decode as true you can write:

echo $data['items'][0]['snippet']['title'];


问:
flex 4 - layer a component on top of another?
How can I change the z axis of components and put one in front of the other? The new layout property in Flex 4 has changed significantly & now not sure how to do it.</p>

答: checkout the new depth property introduced in Flex 4 e.g. see http://www.tink.ws/blog/flex-4-uicomponent-depth/</p>


答: In XML you should use < to include a less-than sign in character data.</p>

Title: How can i show left shift operator on my button in android?

Body: In XML you should use &lt; to include a less-than sign in character data.


问:
What's the difference between retail symbols and checked symbols?

Windows XP with Service Pack 3 x86 retail symbols, all languages (File size: 209 MB - Most customers want this package.)

Windows XP with Service Pack 3 x86 checked symbols, all languages (File size: 202 MB)

Quoted from here.

What's the difference between retail symbols and checked symbols?

答:
For practical purposes, desription of both packages was given in microsoft article https://developer.microsoft.com/en-us/windows/hardware/download-symbols . For been precise,

"Almost all customers require the symbols for the retail version. If you are debugging a special version of Windows with extra debugging information, then you should download the symbols for the checked version."

In other words, most likely you need retail version.


问:
Swift: How to offset index on tableView when using more than one TableViewCell class?
I have a tableView that uses two classes: CustomCellOne and CustomCellTwo. CustomCellTwo is displayed at indexPath.row == 1, CustomCellOne is displayed the rest of the time.

CustomCellOne displays data from an array called tableArray. However, the cells after CustomCellTwo are missing one element from the array as the second item in the array is being replaced by CustomCellTwo within the table.

The only solution I can currently think of for this would be to add a redundant element to tableArray as indexPath 1 which would then be skipped but that does not seem elegant.

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

    if indexPath.row == 1 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellTwo", for: indexPath) as! CustomCellTwo

        cell.label.text = ""
        return cell
    } else {
    let cell = tableView.dequeueReusableCell(withIdentifier: cellOne, for: indexPath) as! CustomCellOne

    cell.label.text = tableArray[indexPath.row]
    return cell
}
</code>```

答:
Decrement your index when it is greater than 1.  You can do this by introducing a row value and then adjust it as appropriate:

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

    if indexPath.row == 1 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellTwo", for: indexPath) as! CustomCellTwo

        cell.label.text = ""
        return cell
    } else {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellOne, for: indexPath) as! CustomCellOne
        let row = indexPath.row < 1 ? 0 : indexPath.row - 1
        cell.label.text = tableArray[row]
        return cell
    }
}
</code>```

Note: You will need to return tableArray.count + 1 as the number of rows in section 0 to account for the inserted cell at row 1.

Body:
I have a tableView that uses two classes: CustomCellOne and CustomCellTwo. CustomCellTwo is displayed at indexPath.row == 1, CustomCellOne is displayed the rest of the time.

CustomCellOne displays data from an array called tableArray. However, the cells after CustomCellTwo are missing one element from the array as the second item in the array is being replaced by CustomCellTwo within the table.

The only solution I can currently think of for this would be to add a redundant element to tableArray as indexPath 1 which would then be skipped but that does not seem elegant.

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

    if indexPath.row == 1 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellTwo", for: indexPath) as! CustomCellTwo

        cell.label.text = ""
        return cell
    } else {
    let cell = tableView.dequeueReusableCell(withIdentifier: cellOne, for: indexPath) as! CustomCellOne

    cell.label.text = tableArray[indexPath.row]
    return cell
}

Body:
Decrement your index when it is greater than 1.  You can do this by introducing a row value and then adjust it as appropriate:

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

    if indexPath.row == 1 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellTwo", for: indexPath) as! CustomCellTwo

        cell.label.text = ""
        return cell
    } else {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellOne, for: indexPath) as! CustomCellOne
        let row = indexPath.row < 1 ? 0 : indexPath.row - 1
        cell.label.text = tableArray[row]
        return cell
    }
}

Note: You will need to return tableArray.count + 1 as the number of rows in section 0 to account for the inserted cell at row 1.


问:
How to return an array in Protobuf service rpc
I have the following schema in my .proto file:

```<code>service MyService {
    rpc GetItem (ItemQuery) returns (Item) {
    }
}

message ItemQuery {
    int id = 1;
}
message Item {
    int id = 1;
    string name = 2;
}
</code>```

Now I want to add another rpc method to return multiple Items.
Something like this:

```<code>rpc GetItems (ItemsQuery) returns (repeated Item) {
}
</code>```

Is there a better way to do it than define an Items message?

答:
Option 1 - Use stream:

```<code>rpc GetItems (ItemsQuery) returns (stream Item) {
}
</code>```

Option 2 - Set a response message which will use a repeated object:

```<code>service MyService {
    rpc GetItem (ItemQuery) returns (ItemResponse) {
    }
}

message ItemQuery {
    int id = 1;
}
message ItemResponse {
    repeated Item items = 1;
}
message Item {
    int id = 1;
    string name = 2;
}
</code>```

Body:
I have the following schema in my .proto file:

service MyService {
    rpc GetItem (ItemQuery) returns (Item) {
    }
}

message ItemQuery {
    int id = 1;
}
message Item {
    int id = 1;
    string name = 2;
}

Now I want to add another rpc method to return multiple Items.
Something like this:

rpc GetItems (ItemsQuery) returns (repeated Item) {
}

Is there a better way to do it than define an Items message?

Body:
Option 1 - Use stream:

rpc GetItems (ItemsQuery) returns (stream Item) {
}

Option 2 - Set a response message which will use a repeated object:

service MyService {
    rpc GetItem (ItemQuery) returns (ItemResponse) {
    }
}

message ItemQuery {
    int id = 1;
}
message ItemResponse {
    repeated Item items = 1;
}
message Item {
    int id = 1;
    string name = 2;
}