问:
while I'm retrieving the tabular format data using JSON data into PHP
I'm trying to get data into the tabular format by invoking JSON data into PHP code.

JSON code written to use for converting into tabular format.

```<code>[

  {
   "#":"3586 "
   "Project" :"SSMT",
   "Tracker" :"Maintenance",
   "Status" : "To Do"
   "Subject" : "Test the following scenario and provide the relevant scripts in centos7"
   "Author" : "Anil K"
   "Assignee" : "SSMT Group"
  },
  {
   "#" :"3517"
   "Project" : "SSMT"
   "Tracker" : "Improvement"
   "Status" : "In Progress"
   "Subject" : "Image server daily backup"
   "Author" : "Lakshmi G"
   "Assignee" : "Pooja S"
  },
  {
   "Project" : "SSMT"
   "Tracker" : "Improvement"
   "Status" : "In Progress"
   "Subject" : "setup openstack all-in-one in centos7 instance on ORAVM1 box."
   "Author" : "Anil K"
   "Assignee" : "Bhanuprakash P"
  }
]
</code>```

The below php code is written to fetch the above JSON data.

```<code><!DOCTYPE html>
<html lang = "en-US">

<?php

$url = 'data.json';
$data = file_get_contents($url);
$characters = json_decode($data);

echo $characters[0]->name;

foreach ($characters as $character) {
         echo $character->name . '<br>';

}
?>

 <table>
        <tbody>
                <tr>
                        <th>#</th>
                        <th>Project</th>
                        <th>Tracker</th>
                        <th>Status</th>
                        <th>Subject</th>
                        <th>Author</th>
                        <th>Assignee</th>

                </tr>
                        <?php
                        foreach ($characters as $character) {
                                echo '<tr>'
                                echo '<td>' . $character-># . '</td>';
                                echo '<td>' . $character->project . '</td>';
                                echo '<td>' . $character->tracker . '</td>';
                                echo '<td>' . $character->status . '</td>';
                                echo '<td>' . $character->subject . '</td>';
                                echo '<td>' . $character->author . '</td>';
                                echo '<td>' . $character->assignee . '</td>';
                                echo '</tr>';
                        }
                        ?>
        </tbody>

 </table>

</html>
</code>```

I received following error
PHP Parse error:  syntax error, unexpected 'echo' (T_ECHO), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in /var/www/html/tabularformat.php on line 34

can anyone suggest othis? ?

after adding ; at the end of each 'echo' statement. also getting the same error. please find it.

答:
I recommend using true as the second parameter to form array elements.

Your json is invalid (I fixed it in my code)

You need to access the keys case-sensitively.

Check that an element exists before trying to access it.

Code: (Demo)

```<code>$json='[
  {
   "#":"3586 ",
   "Project" :"SSMT",
   "Tracker" :"Maintenance",
   "Status" : "To Do",
   "Subject" : "Test the following scenario and provide the relevant scripts in centos7",
   "Author" : "Anil K",
   "Assignee" : "SSMT Group"
  },
  {
   "#" :"3517",
   "Project" : "SSMT",
   "Tracker" : "Improvement",
   "Status" : "In Progress",
   "Subject" : "Image server daily backup",
   "Author" : "Lakshmi G",
   "Assignee" : "Pooja S"
  },
  {
   "Project" : "SSMT",
   "Tracker" : "Improvement",
   "Status" : "In Progress",
   "Subject" : "setup openstack all-in-one in centos7 instance on ORAVM1 box.",
   "Author" : "Anil K",
   "Assignee" : "Bhanuprakash P"
  }
]';

$characters = json_decode($json,true);
foreach ($characters as $character) {
    echo '<tr>';
        echo '<td>',(isset($character['#'])?$character['#']:''),'</td>';
        echo '<td>',(isset($character['Project'])?$character['Project']:''),'</td>';
        echo '<td>',(isset($character['Tracker'])?$character['Tracker']:''),'</td>';
        echo '<td>',(isset($character['Status'])?$character['Status']:''),'</td>';
        echo '<td>',(isset($character['Subject'])?$character['Subject']:''),'</td>';
        echo '<td>',(isset($character['Author'])?$character['Author']:''),'</td>';
        echo '<td>',(isset($character['Assignee'])?$character['Assignee']:''),'</td>';
    echo '</tr>';
}
</code>```

Output:

```<code><tr>
    <td>3586 </td>
    <td>SSMT</td>
    <td>Maintenance</td>
    <td>To Do</td>
    <td>Test the following scenario and provide the relevant scripts in centos7</td>
    <td>Anil K</td>
    <td>SSMT Group</td>
</tr>
<tr>
    <td>3517</td>
    <td>SSMT</td>
    <td>Improvement</td>
    <td>In Progress</td>
    <td>Image server daily backup</td>
    <td>Lakshmi G</td>
    <td>Pooja S</td>
</tr>
<tr>
    <td></td>
    <td>SSMT</td>
    <td>Improvement</td>
    <td>In Progress</td>
    <td>setup openstack all-in-one in centos7 instance on ORAVM1 box.</td>
    <td>Anil K</td>
    <td>Bhanuprakash P</td>
</tr>
</code>```

Otherwise, you can use "encapsulation" to access the # object.

```<code>$characters = json_decode($json);
foreach ($characters as $character) {
    echo '<tr>';
        echo '<td>',(isset($character->{'#'})?$character->{'#'}:''),'</td>';
        // ...
</code>```

From the manual:

Example #2 Accessing invalid object properties

Accessing elements within an object that contain characters not permitted under PHP's naming convention (e.g. the hyphen) can be accomplished by encapsulating the element name within braces and the apostrophe.

```<code>$json = '{"foo-bar": 12345}';

$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345
</code>```

Body:
I'm trying to get data into the tabular format by invoking JSON data into PHP code.

JSON code written to use for converting into tabular format.

[

  {
   "#":"3586 "
   "Project" :"SSMT",
   "Tracker" :"Maintenance",
   "Status" : "To Do"
   "Subject" : "Test the following scenario and provide the relevant scripts in centos7"
   "Author" : "Anil K"
   "Assignee" : "SSMT Group"
  },
  {
   "#" :"3517"
   "Project" : "SSMT"
   "Tracker" : "Improvement"
   "Status" : "In Progress"
   "Subject" : "Image server daily backup"
   "Author" : "Lakshmi G"
   "Assignee" : "Pooja S"
  },
  {
   "Project" : "SSMT"
   "Tracker" : "Improvement"
   "Status" : "In Progress"
   "Subject" : "setup openstack all-in-one in centos7 instance on ORAVM1 box."
   "Author" : "Anil K"
   "Assignee" : "Bhanuprakash P"
  }
]

The below php code is written to fetch the above JSON data.

<!DOCTYPE html>

<?php

$url = 'data.json';
$data = file_get_contents($url);
$characters = json_decode($data);

echo $characters[0]->name;

foreach ($characters as $character) {
         echo $character->name . '
';

}
?>

                        #
                        Project
                        Tracker
                        Status
                        Subject
                        Author
                        Assignee

                        <?php
                        foreach ($characters as $character) {
                                echo '
'
                                echo '' . $character-># . '	';
                                echo '' . $character->project . '	';
                                echo '' . $character->tracker . '	';
                                echo '' . $character->status . '	';
                                echo '' . $character->subject . '	';
                                echo '' . $character->author . '	';
                                echo '' . $character->assignee . '	';
                                echo '
';
                        }
                        ?>

I received following error
PHP Parse error:  syntax error, unexpected 'echo' (T_ECHO), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in /var/www/html/tabularformat.php on line 34

can anyone suggest othis? ?

after adding ; at the end of each 'echo' statement. also getting the same error. please find it.

Body:
I recommend using true as the second parameter to form array elements.

Your json is invalid (I fixed it in my code)

You need to access the keys case-sensitively.

Check that an element exists before trying to access it.

Code: (Demo)

$json='[
  {
   "#":"3586 ",
   "Project" :"SSMT",
   "Tracker" :"Maintenance",
   "Status" : "To Do",
   "Subject" : "Test the following scenario and provide the relevant scripts in centos7",
   "Author" : "Anil K",
   "Assignee" : "SSMT Group"
  },
  {
   "#" :"3517",
   "Project" : "SSMT",
   "Tracker" : "Improvement",
   "Status" : "In Progress",
   "Subject" : "Image server daily backup",
   "Author" : "Lakshmi G",
   "Assignee" : "Pooja S"
  },
  {
   "Project" : "SSMT",
   "Tracker" : "Improvement",
   "Status" : "In Progress",
   "Subject" : "setup openstack all-in-one in centos7 instance on ORAVM1 box.",
   "Author" : "Anil K",
   "Assignee" : "Bhanuprakash P"
  }
]';

$characters = json_decode($json,true);
foreach ($characters as $character) {
    echo '<tr>';
        echo '<td>',(isset($character['#'])?$character['#']:''),'</td>';
        echo '<td>',(isset($character['Project'])?$character['Project']:''),'</td>';
        echo '<td>',(isset($character['Tracker'])?$character['Tracker']:''),'</td>';
        echo '<td>',(isset($character['Status'])?$character['Status']:''),'</td>';
        echo '<td>',(isset($character['Subject'])?$character['Subject']:''),'</td>';
        echo '<td>',(isset($character['Author'])?$character['Author']:''),'</td>';
        echo '<td>',(isset($character['Assignee'])?$character['Assignee']:''),'</td>';
    echo '</tr>';
}

Output:

<tr>
    <td>3586 </td>
    <td>SSMT</td>
    <td>Maintenance</td>
    <td>To Do</td>
    <td>Test the following scenario and provide the relevant scripts in centos7</td>
    <td>Anil K</td>
    <td>SSMT Group</td>
</tr>
<tr>
    <td>3517</td>
    <td>SSMT</td>
    <td>Improvement</td>
    <td>In Progress</td>
    <td>Image server daily backup</td>
    <td>Lakshmi G</td>
    <td>Pooja S</td>
</tr>
<tr>
    <td></td>
    <td>SSMT</td>
    <td>Improvement</td>
    <td>In Progress</td>
    <td>setup openstack all-in-one in centos7 instance on ORAVM1 box.</td>
    <td>Anil K</td>
    <td>Bhanuprakash P</td>
</tr>

Otherwise, you can use "encapsulation" to access the # object.

$characters = json_decode($json);
foreach ($characters as $character) {
    echo '<tr>';
        echo '<td>',(isset($character->{'#'})?$character->{'#'}:''),'</td>';
        // ...

From the manual:

Example #2 Accessing invalid object properties

Accessing elements within an object that contain characters not permitted under PHP's naming convention (e.g. the hyphen) can be accomplished by encapsulating the element name within braces and the apostrophe.

$json = '{"foo-bar": 12345}';

$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345


来源: stackexchange

问:
Stanza.io Could not create WebRTC answer
Im using ejabberd + stanza.io to make a realtime messaging website,
everything is working perfectly.
now im willing to implement Webrtc audio/video using the jingle protocole.
this is my JS code that i use to connect:

```<code>var client = XMPP.createClient({
  jid: xmpp_user+'@'+XMPP_DOMAIN,
  password: cu.auth.user_password,
  transport: 'websocket',
  wsURL: "ws://"+xms+":5280/websocket/"
});

client.jingle.config.debug = true;

client.on('session:started', function () {
  client.enableCarbons();
  client.getRoster(function (err, resp) {
    client.updateCaps();
    client.sendPresence({
      caps: client.disco.caps
    });
  });
});

client.connect();
</code>```

the problem is when i call the user from an other app (AstraChat: iOS app that support Jingle) i get this in browser log:

```<code>Jingle: 67bzrsog243: session-initiate undefined undefined
Jingle: 67bzrsog243: Could not create WebRTC answer undefined undefined
</code>```

this is the xml that astrachat is sending:

```<code><iq xmlns='jabber:client' xml:lang='en' to='c4ca4238a0b923820dcc509a6f75849b@h2745110.stratoserver.net/352555070032013318140962' from='med@h2745110.stratoserver.net/AstraChat-iOS-21820150' type='get' id='3e8kjajc22'><query xmlns='http://jabber.org/protocol/disco#info'/></iq>
<r xmlns='urn:xmpp:sm:3'/>
<a h='1' xmlns='urn:xmpp:sm:3'/>
<a h='2' xmlns='urn:xmpp:sm:3'/>
jingle:created
iq:set:jingle
<iq xmlns='jabber:client' xml:lang='en' to='c4ca4238a0b923820dcc509a6f75849b@h2745110.stratoserver.net/352555070032013318140962' from='med@h2745110.stratoserver.net/AstraChat-iOS-21820150' type='set' id='3e8kjajc23'><jingle xmlns='urn:xmpp:jingle:1' action='session-initiate' initiator='med@h2745110.stratoserver.net/AstraChat-iOS-21820150' responder='c4ca4238a0b923820dcc509a6f75849b@h2745110.stratoserver.net/352555070032013318140962' sid='3e8kjajc24'><content creator='initiator' name='voice'><description xmlns='urn:xmpp:jingle:apps:rtp:1' media='audio'><payload-type id='101' name='speex' clockrate='8000'/></description><transport xmlns='urn:xmpp:jingle:transports:ice-udp:1' pwd='TC5NsD6IEQGXeDO8d5/3OU' ufrag='yA0z'/></content></jingle></iq>
<r xmlns='urn:xmpp:sm:3'/>
Jingle: 3e8kjajc24: session-initiate undefined undefined
Could not create WebRTC answer undefined undefined
</code>```

i really have no clue on how to fix that, any help will be appreciated.

答:
the session-initiate from Astra chat is this according to your logs:

<iq xmlns="jabber:client" xml:lang="en" to="c4ca4238a0b923820dcc509a6f75849b@h2745110.stratoserver.net/352555070032013318140962" from="med@h2745110.stratoserver.net/AstraChat-iOS-21820150" type="set" id="3e8kjajc23">
    <jingle xmlns="urn:xmpp:jingle:1" action="session-initiate" initiator="med@h2745110.stratoserver.net/AstraChat-iOS-21820150" responder="c4ca4238a0b923820dcc509a6f75849b@h2745110.stratoserver.net/352555070032013318140962" sid="3e8kjajc24">
        <content creator="initiator" name="voice">
            <description xmlns="urn:xmpp:jingle:apps:rtp:1" media="audio">
                <payload-type id="101" name="speex" clockrate="8000" />
            </description>
            <transport xmlns="urn:xmpp:jingle:transports:ice-udp:1" pwd="TC5NsD6IEQGXeDO8d5/3OU" ufrag="yA0z" />
        </content>
    </jingle>
</iq>

which only offers the speex audio codec that WebRTC does not support (opus or G.711 are mandatory). Also there is no encryption which is mandatory in WebRTC.

ContentLicense: CC BY-SA 3.0

Body:
Im using ejabberd + stanza.io to make a realtime messaging website,
everything is working perfectly.
now im willing to implement Webrtc audio/video using the jingle protocole.
this is my JS code that i use to connect:

var client = XMPP.createClient({
  jid: xmpp_user+'@'+XMPP_DOMAIN,
  password: cu.auth.user_password,
  transport: 'websocket',
  wsURL: "ws://"+xms+":5280/websocket/"
});

client.jingle.config.debug = true;

client.on('session:started', function () {
  client.enableCarbons();
  client.getRoster(function (err, resp) {
    client.updateCaps();
    client.sendPresence({
      caps: client.disco.caps
    });
  });
});

client.connect();

the problem is when i call the user from an other app (AstraChat: iOS app that support Jingle) i get this in browser log:

Jingle: 67bzrsog243: session-initiate undefined undefined
Jingle: 67bzrsog243: Could not create WebRTC answer undefined undefined

this is the xml that astrachat is sending:

<iq xmlns='jabber:client' xml:lang='en' to='c4ca4238a0b923820dcc509a6f75849b@h2745110.stratoserver.net/352555070032013318140962' from='med@h2745110.stratoserver.net/AstraChat-iOS-21820150' type='get' id='3e8kjajc22'><query xmlns='http://jabber.org/protocol/disco#info'/></iq>
<r xmlns='urn:xmpp:sm:3'/>

jingle:created
iq:set:jingle
<iq xmlns='jabber:client' xml:lang='en' to='c4ca4238a0b923820dcc509a6f75849b@h2745110.stratoserver.net/352555070032013318140962' from='med@h2745110.stratoserver.net/AstraChat-iOS-21820150' type='set' id='3e8kjajc23'><jingle xmlns='urn:xmpp:jingle:1' action='session-initiate' initiator='med@h2745110.stratoserver.net/AstraChat-iOS-21820150' responder='c4ca4238a0b923820dcc509a6f75849b@h2745110.stratoserver.net/352555070032013318140962' sid='3e8kjajc24'><content creator='initiator' name='voice'><description xmlns='urn:xmpp:jingle:apps:rtp:1' media='audio'><payload-type id='101' name='speex' clockrate='8000'/></description><transport xmlns='urn:xmpp:jingle:transports:ice-udp:1' pwd='TC5NsD6IEQGXeDO8d5/3OU' ufrag='yA0z'/></content></jingle></iq>
<r xmlns='urn:xmpp:sm:3'/>
Jingle: 3e8kjajc24: session-initiate undefined undefined
Could not create WebRTC answer undefined undefined

i really have no clue on how to fix that, any help will be appreciated.


问:
What will happen if var a = function b(){}
So I was reading about javascript functions in which I found out that there are two ways of writing a function first is

```<code>function b(){console.log("name")}
</code>```

in which if I write b.name it gives b

and second way is to use

```<code>var a = function() {console.log("name")}
</code>```

in which if I write a.name it gives a

so my question is what happens when we write a function like this

```<code>var a =function b(){console.log("name")}
</code>```

in this case if I call a();
it will work fine
and if I call b(); it shows me an error
but if I write a.name it shows me b. Please can someone help me understand?

答:
In

```<code>var a =function b(){console.log("name")}
</code>```

...because you specified a name in the function expression, that becomes the function's name (e.g., a.name will return "b" [as will b.name*, of course, since a and b refer to the same function]). The name is only inferred (when possible) from the assignment expression when the function expression doesn't assign one.

(Note that inferring function names for functions created with anonymous function expressions is relatively new, a feature added in ES2015. Also note that the name property of functions wasn't officially added until then either.)

Here are all those demonstrated:

function b1() {
  console.log("[inside] b1.name = " + b1.name);
}
console.log("b1.name = " + b1.name);
b1();

var a1 = function() {
  console.log("[inside] a1.name = " + a1.name);
};
console.log("a1.name = " + a1.name);
a1();

var a2 = function b2() {
  console.log("[inside] b2.name = " + b2.name);
};
console.log("a2.name = " + a2.name);
a2();```

* If you use it where b is in scope. It isn't in scope outside the function, but it is inside the function. That's because when you use a named function expression (instead of a function declaration), the name of the function isn't added to the scope where the expression is defined (whereas with a function declaration, it is). But the name is still in scope within the function.

Body:
So I was reading about javascript functions in which I found out that there are two ways of writing a function first is

function b(){console.log("name")}

in which if I write b.name it gives b

and second way is to use

var a = function() {console.log("name")}

in which if I write a.name it gives a

so my question is what happens when we write a function like this

var a =function b(){console.log("name")}

in this case if I call a();
it will work fine
and if I call b(); it shows me an error
but if I write a.name it shows me b. Please can someone help me understand?

Body:
In

var a =function b(){console.log("name")}

...because you specified a name in the function expression, that becomes the function's name (e.g., a.name will return "b" [as will b.name*, of course, since a and b refer to the same function]). The name is only inferred (when possible) from the assignment expression when the function expression doesn't assign one.

(Note that inferring function names for functions created with anonymous function expressions is relatively new, a feature added in ES2015. Also note that the name property of functions wasn't officially added until then either.)

Here are all those demonstrated:

function b1() {
  console.log("[inside] b1.name = " + b1.name);
}
console.log("b1.name = " + b1.name);
b1();

var a1 = function() {
  console.log("[inside] a1.name = " + a1.name);
};
console.log("a1.name = " + a1.name);
a1();

var a2 = function b2() {
  console.log("[inside] b2.name = " + b2.name);
};
console.log("a2.name = " + a2.name);
a2();

* If you use it where b is in scope. It isn't in scope outside the function, but it is inside the function. That's because when you use a named function expression (instead of a function declaration), the name of the function isn't added to the scope where the expression is defined (whereas with a function declaration, it is). But the name is still in scope within the function.


问:
Left joins, i need an explanation about a code
i am watching a tutorial. There is a code which i don't understand what is supposed to do.

```<code>$sql = 'SELECT p.*,
      a.screen_name AS author_name,
      c.name AS category_name
    FROM
      posts p
      LEFT JOIN
        admin_users a ON p.author_id = a.id
      LEFT JOIN
        categories c ON p.category_id = c.id
    WHERE
      p.id = ?';
</code>```

I read about the left joins but i didn't understand them. Can somebody please explain me the code i shared.
Thanks in advance!

答:
Imagine you have two tables.  One that stores the information about the programmers on your website, and the other table that keeps track of their online purchases.

PROGRAMMERS Table

```<code>+--------------------------------------------+
| ID | NAME     | AGE | ADDRESS   | SALARY   |
+----+----------+-----+-----------+----------+
|  1 | Desire   |  32 | 123 fake s|  3000.00 |
|  2 | Jamin    |  25 | 234 fake s|  2500.00 |
|  3 | Jon      |  23 | 567 fake s|  2000.00 |
|  4 | Bob      |  30 | 789 fake s|  1500.00 |
|  5 | OtherGuy |  31 | 890 fake s|  1000.00 |
|  6 | DudeMan  |  32 | 901 fake s|   500.00 |
+--------------------------------------------+
</code>```

PURCHASES Table

```<code>+---------------------------------------------+
| ORDER_ID    | PROG_ID |    DATE    | PRICE  |
+-------------+---------+---------------------|
|  1          | 1       |  1-1-2017  | 100    |
|  2          | 2       |  1-2-2017  | 200    |
|  3          | 6       |  1-3-2017  | 300    |
+---------------------------------------------|
</code>```

You decide you need to make a new table to consolidate this information to a table that contains
certain columns you want.

For example, you figure it would be nice for shipping purposes to have a table
that has the ID, the NAME, the PRICE, and the DATE columns.

Currently, the tables we have don't display all of that in a single table.

If we were to LEFT JOIN these tables, we would end up filling the desired columns
with NULL values where there is no information to join.

```<code>SELECT ID, NAME, PRICE, DATE
    FROM PROGRAMMERS
    LEFT JOIN PURCHASES
    ON PROGRAMMERS.ID = PURCHASES.PROG_ID;
</code>```

Notice that I'm selecting the columns I want from the starting table, then joining the right table
even though there might be missing information.

RESULTING TABLE

```<code>+-------------------------------------+
| ID | NAME     | PRICE   |   DATE    |
+----+----------+-----------------+---+
|  1 | Desire   | 100     | 1-1-2017  |
|  2 | Jamin    | 200     | 1-2-2017  |
|  3 | Jon      | NULL    |   NULL    |
|  4 | Bob      | NULL    |   NULL    |
|  5 | OtherGuy | NULL    |   NULL    |
|  6 | DudeMan  | 300     | 1-3-2017  |
+-------------------------------------+
</code>```

For a visual representation of the difference between SQL JOINs check out
https://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins .

Body:
i am watching a tutorial. There is a code which i don't understand what is supposed to do.

$sql = 'SELECT p.*,
      a.screen_name AS author_name,
      c.name AS category_name
    FROM
      posts p
      LEFT JOIN
        admin_users a ON p.author_id = a.id
      LEFT JOIN
        categories c ON p.category_id = c.id
    WHERE
      p.id = ?';

I read about the left joins but i didn't understand them. Can somebody please explain me the code i shared.
Thanks in advance!

Body:
Imagine you have two tables.  One that stores the information about the programmers on your website, and the other table that keeps track of their online purchases.

PROGRAMMERS Table

+--------------------------------------------+
| ID | NAME     | AGE | ADDRESS   | SALARY   |
+----+----------+-----+-----------+----------+
|  1 | Desire   |  32 | 123 fake s|  3000.00 |
|  2 | Jamin    |  25 | 234 fake s|  2500.00 |
|  3 | Jon      |  23 | 567 fake s|  2000.00 |
|  4 | Bob      |  30 | 789 fake s|  1500.00 |
|  5 | OtherGuy |  31 | 890 fake s|  1000.00 |
|  6 | DudeMan  |  32 | 901 fake s|   500.00 |
+--------------------------------------------+

PURCHASES Table

+---------------------------------------------+
| ORDER_ID    | PROG_ID |    DATE    | PRICE  |
+-------------+---------+---------------------|
|  1          | 1       |  1-1-2017  | 100    |
|  2          | 2       |  1-2-2017  | 200    |
|  3          | 6       |  1-3-2017  | 300    |
+---------------------------------------------|

You decide you need to make a new table to consolidate this information to a table that contains
certain columns you want.

For example, you figure it would be nice for shipping purposes to have a table
that has the ID, the NAME, the PRICE, and the DATE columns.

Currently, the tables we have don't display all of that in a single table.

If we were to LEFT JOIN these tables, we would end up filling the desired columns
with NULL values where there is no information to join.

SELECT ID, NAME, PRICE, DATE
    FROM PROGRAMMERS
    LEFT JOIN PURCHASES
    ON PROGRAMMERS.ID = PURCHASES.PROG_ID;

Notice that I'm selecting the columns I want from the starting table, then joining the right table
even though there might be missing information.

RESULTING TABLE

+-------------------------------------+
| ID | NAME     | PRICE   |   DATE    |
+----+----------+-----------------+---+
|  1 | Desire   | 100     | 1-1-2017  |
|  2 | Jamin    | 200     | 1-2-2017  |
|  3 | Jon      | NULL    |   NULL    |
|  4 | Bob      | NULL    |   NULL    |
|  5 | OtherGuy | NULL    |   NULL    |
|  6 | DudeMan  | 300     | 1-3-2017  |
+-------------------------------------+

For a visual representation of the difference between SQL JOINs check out
https://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins .


问:
Cannot add multi series to Highstock but same thing works for Highcharts
I am trying to create a highstock chart with 2 series as you can see in this fiddle and below, none of the series are displayed.

  Highcharts.stockChart('container', {
  "exporting": {
    "enabled": false
  },
  "rangeSelector": {
    "inputEnabled": true
  },
  "chart": {
    "type": "line",
    "renderTo": "container",
    "backgroundColor": "#fff",

  },
  "title": {
    "text": "30 DAY GOLD PRICE CHART"
  },
  "scrollbar": {
    "liveRedraw": false
  },
  "subtitle": {
    "text": "www.gold-feed.com"
  },
  "series": [{
    "name": "Open",
    "data": [{
      "x": new Date(2013, 11, 18),
      "y": 1233.7
    }, {
      "x": new Date(2013, 11, 19),
      "y": 1224.77
    }, {
      "x": new Date(2013, 11, 20),
      "y": 1193.18
    }],
    "index": 0
  }, {
    "name": "High",
    "data": [{
      "x": new Date(2013, 11, 18),
      "y": 1244.46
    }, {
      "x": new Date(2013, 11, 19),
      "y": 1226.38
    }, {
      "x": new Date(2013, 11, 20),
      "y": 1207.37
    }],
    "index": 1
  }, {
    "name": "Low",
    "data": [{
      "x": new Date(2013, 11, 18),
      "y": 1216.24
    }, {
      "x": new Date(2013, 11, 19),
      "y": 1187.18
    }, {
      "x": new Date(2013, 11, 20),
      "y": 1191.35
    }],
    "index": 2
  }, {
    "name": "Close",
    "data": [{
      "x": new Date(2013, 11, 18),
      "y": 1218.23
    }, {
      "x": new Date(2013, 11, 19),
      "y": 1187.76
    }, {
      "x": new Date(2013, 11, 20),
      "y": 1202.09
    }],
    "index": 3
  }],
  "credits": {
    "text": "Gold Feed Inc.",
    "href": "http://www.gold-feed.com"
  },
  "xAxis": {
    "title": {
      "text": null
    },
    "labels": {
      "rotation": null
    },
    "type": "datetime"
  },
  "yAxis": [{
    "title": {
      "text": "Price Per Troy Ounce"
    }
  }],
  "navigator": {
    "adaptToUpdatedData": false
  },
  "legend": {
    "x": 10
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>

<div id="container" style="height: 400px; min-width: 310px"></div></code>```

If I replace Highcharts.stockChart with Highcharts.chart it works perfectly, as seen in this fiddle and below.

  Highcharts.chart('container', {
  "exporting": {
    "enabled": false
  },
  "rangeSelector": {
    "inputEnabled": true
  },
  "chart": {
    "type": "line",
    "renderTo": "container",
    "backgroundColor": "#fff",

  },
  "title": {
    "text": "30 DAY GOLD PRICE CHART"
  },
  "scrollbar": {
    "liveRedraw": false
  },
  "subtitle": {
    "text": "www.gold-feed.com"
  },
  "series": [{
    "name": "Open",
    "data": [{
      "x": new Date(2013, 11, 18),
      "y": 1233.7
    }, {
      "x": new Date(2013, 11, 19),
      "y": 1224.77
    }, {
      "x": new Date(2013, 11, 20),
      "y": 1193.18
    }],
    "index": 0
  }, {
    "name": "High",
    "data": [{
      "x": new Date(2013, 11, 18),
      "y": 1244.46
    }, {
      "x": new Date(2013, 11, 19),
      "y": 1226.38
    }, {
      "x": new Date(2013, 11, 20),
      "y": 1207.37
    }],
    "index": 1
  }, {
    "name": "Low",
    "data": [{
      "x": new Date(2013, 11, 18),
      "y": 1216.24
    }, {
      "x": new Date(2013, 11, 19),
      "y": 1187.18
    }, {
      "x": new Date(2013, 11, 20),
      "y": 1191.35
    }],
    "index": 2
  }, {
    "name": "Close",
    "data": [{
      "x": new Date(2013, 11, 18),
      "y": 1218.23
    }, {
      "x": new Date(2013, 11, 19),
      "y": 1187.76
    }, {
      "x": new Date(2013, 11, 20),
      "y": 1202.09
    }],
    "index": 3
  }],
  "credits": {
    "text": "Gold Feed Inc.",
    "href": "http://www.gold-feed.com"
  },
  "xAxis": {
    "title": {
      "text": null
    },
    "labels": {
      "rotation": null
    },
    "type": "datetime"
  },
  "yAxis": [{
    "title": {
      "text": "Price Per Troy Ounce"
    }
  }],
  "navigator": {
    "adaptToUpdatedData": false
  },
  "legend": {
    "x": 10
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>

<div id="container" style="height: 400px; min-width: 310px"></div></code>```

So... why this basic example does not work for Highstock but does work for Highcharts?

Thanks in advance,

答:
For highstock time should be in milliseconds

```<code>new Date(2013, 11, 18).getTime()
</code>```

  Highcharts.stockChart('container', {
  "exporting": {
    "enabled": false
  },
  "rangeSelector": {
    "inputEnabled": true
  },
  "chart": {
    "type": "line",
    "renderTo": "container",
    "backgroundColor": "#fff",

  },
  "title": {
    "text": "30 DAY GOLD PRICE CHART"
  },
  "scrollbar": {
    "liveRedraw": false
  },
  "subtitle": {
    "text": "www.gold-feed.com"
  },
  "series": [{
    "name": "Open",
    "data": [{
      "x": new Date(2013, 11, 18).getTime(),
      "y": 1233.7
    }, {
      "x": new Date(2013, 11, 19).getTime(),
      "y": 1224.77
    }, {
      "x": new Date(2013, 11, 20).getTime(),
      "y": 1193.18
    }],
    "index": 0
  }, {
    "name": "High",
    "data": [{
      "x": new Date(2013, 11, 18).getTime(),
      "y": 1244.46
    }, {
      "x": new Date(2013, 11, 19).getTime(),
      "y": 1226.38
    }, {
      "x": new Date(2013, 11, 20).getTime(),
      "y": 1207.37
    }],
    "index": 1
  }, {
    "name": "Low",
    "data": [{
      "x": new Date(2013, 11, 18).getTime(),
      "y": 1216.24
    }, {
      "x": new Date(2013, 11, 19).getTime(),
      "y": 1187.18
    }, {
      "x": new Date(2013, 11, 20).getTime(),
      "y": 1191.35
    }],
    "index": 2
  }, {
    "name": "Close",
    "data": [{
      "x": new Date(2013, 11, 18).getTime(),
      "y": 1218.23
    }, {
      "x": new Date(2013, 11, 19).getTime(),
      "y": 1187.76
    }, {
      "x": new Date(2013, 11, 20).getTime(),
      "y": 1202.09
    }],
    "index": 3
  }],
  "credits": {
    "text": "Gold Feed Inc.",
    "href": "http://www.gold-feed.com"
  },
  "xAxis": {
    "title": {
      "text": null
    },
    "labels": {
      "rotation": null
    },
    "type": "datetime"
  },
  "yAxis": [{
    "title": {
      "text": "Price Per Troy Ounce"
    }
  }],
  "navigator": {
    "adaptToUpdatedData": false
  },
  "legend": {
    "x": 10
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>

<div id="container" style="height: 400px; min-width: 310px"></div></code>```

Body:
I am trying to create a highstock chart with 2 series as you can see in this fiddle and below, none of the series are displayed.

  Highcharts.stockChart('container', {
  "exporting": {
    "enabled": false
  },
  "rangeSelector": {
    "inputEnabled": true
  },
  "chart": {
    "type": "line",
    "renderTo": "container",
    "backgroundColor": "#fff",

  },
  "title": {
    "text": "30 DAY GOLD PRICE CHART"
  },
  "scrollbar": {
    "liveRedraw": false
  },
  "subtitle": {
    "text": "www.gold-feed.com"
  },
  "series": [{
    "name": "Open",
    "data": [{
      "x": new Date(2013, 11, 18),
      "y": 1233.7
    }, {
      "x": new Date(2013, 11, 19),
      "y": 1224.77
    }, {
      "x": new Date(2013, 11, 20),
      "y": 1193.18
    }],
    "index": 0
  }, {
    "name": "High",
    "data": [{
      "x": new Date(2013, 11, 18),
      "y": 1244.46
    }, {
      "x": new Date(2013, 11, 19),
      "y": 1226.38
    }, {
      "x": new Date(2013, 11, 20),
      "y": 1207.37
    }],
    "index": 1
  }, {
    "name": "Low",
    "data": [{
      "x": new Date(2013, 11, 18),
      "y": 1216.24
    }, {
      "x": new Date(2013, 11, 19),
      "y": 1187.18
    }, {
      "x": new Date(2013, 11, 20),
      "y": 1191.35
    }],
    "index": 2
  }, {
    "name": "Close",
    "data": [{
      "x": new Date(2013, 11, 18),
      "y": 1218.23
    }, {
      "x": new Date(2013, 11, 19),
      "y": 1187.76
    }, {
      "x": new Date(2013, 11, 20),
      "y": 1202.09
    }],
    "index": 3
  }],
  "credits": {
    "text": "Gold Feed Inc.",
    "href": "http://www.gold-feed.com"
  },
  "xAxis": {
    "title": {
      "text": null
    },
    "labels": {
      "rotation": null
    },
    "type": "datetime"
  },
  "yAxis": [{
    "title": {
      "text": "Price Per Troy Ounce"
    }
  }],
  "navigator": {
    "adaptToUpdatedData": false
  },
  "legend": {
    "x": 10
  }
})

If I replace Highcharts.stockChart with Highcharts.chart it works perfectly, as seen in this fiddle and below.

  Highcharts.chart('container', {
  "exporting": {
    "enabled": false
  },
  "rangeSelector": {
    "inputEnabled": true
  },
  "chart": {
    "type": "line",
    "renderTo": "container",
    "backgroundColor": "#fff",

  },
  "title": {
    "text": "30 DAY GOLD PRICE CHART"
  },
  "scrollbar": {
    "liveRedraw": false
  },
  "subtitle": {
    "text": "www.gold-feed.com"
  },
  "series": [{
    "name": "Open",
    "data": [{
      "x": new Date(2013, 11, 18),
      "y": 1233.7
    }, {
      "x": new Date(2013, 11, 19),
      "y": 1224.77
    }, {
      "x": new Date(2013, 11, 20),
      "y": 1193.18
    }],
    "index": 0
  }, {
    "name": "High",
    "data": [{
      "x": new Date(2013, 11, 18),
      "y": 1244.46
    }, {
      "x": new Date(2013, 11, 19),
      "y": 1226.38
    }, {
      "x": new Date(2013, 11, 20),
      "y": 1207.37
    }],
    "index": 1
  }, {
    "name": "Low",
    "data": [{
      "x": new Date(2013, 11, 18),
      "y": 1216.24
    }, {
      "x": new Date(2013, 11, 19),
      "y": 1187.18
    }, {
      "x": new Date(2013, 11, 20),
      "y": 1191.35
    }],
    "index": 2
  }, {
    "name": "Close",
    "data": [{
      "x": new Date(2013, 11, 18),
      "y": 1218.23
    }, {
      "x": new Date(2013, 11, 19),
      "y": 1187.76
    }, {
      "x": new Date(2013, 11, 20),
      "y": 1202.09
    }],
    "index": 3
  }],
  "credits": {
    "text": "Gold Feed Inc.",
    "href": "http://www.gold-feed.com"
  },
  "xAxis": {
    "title": {
      "text": null
    },
    "labels": {
      "rotation": null
    },
    "type": "datetime"
  },
  "yAxis": [{
    "title": {
      "text": "Price Per Troy Ounce"
    }
  }],
  "navigator": {
    "adaptToUpdatedData": false
  },
  "legend": {
    "x": 10
  }
})

So... why this basic example does not work for Highstock but does work for Highcharts?

Thanks in advance,

Body:
For highstock time should be in milliseconds

new Date(2013, 11, 18).getTime()

  Highcharts.stockChart('container', {
  "exporting": {
    "enabled": false
  },
  "rangeSelector": {
    "inputEnabled": true
  },
  "chart": {
    "type": "line",
    "renderTo": "container",
    "backgroundColor": "#fff",

  },
  "title": {
    "text": "30 DAY GOLD PRICE CHART"
  },
  "scrollbar": {
    "liveRedraw": false
  },
  "subtitle": {
    "text": "www.gold-feed.com"
  },
  "series": [{
    "name": "Open",
    "data": [{
      "x": new Date(2013, 11, 18).getTime(),
      "y": 1233.7
    }, {
      "x": new Date(2013, 11, 19).getTime(),
      "y": 1224.77
    }, {
      "x": new Date(2013, 11, 20).getTime(),
      "y": 1193.18
    }],
    "index": 0
  }, {
    "name": "High",
    "data": [{
      "x": new Date(2013, 11, 18).getTime(),
      "y": 1244.46
    }, {
      "x": new Date(2013, 11, 19).getTime(),
      "y": 1226.38
    }, {
      "x": new Date(2013, 11, 20).getTime(),
      "y": 1207.37
    }],
    "index": 1
  }, {
    "name": "Low",
    "data": [{
      "x": new Date(2013, 11, 18).getTime(),
      "y": 1216.24
    }, {
      "x": new Date(2013, 11, 19).getTime(),
      "y": 1187.18
    }, {
      "x": new Date(2013, 11, 20).getTime(),
      "y": 1191.35
    }],
    "index": 2
  }, {
    "name": "Close",
    "data": [{
      "x": new Date(2013, 11, 18).getTime(),
      "y": 1218.23
    }, {
      "x": new Date(2013, 11, 19).getTime(),
      "y": 1187.76
    }, {
      "x": new Date(2013, 11, 20).getTime(),
      "y": 1202.09
    }],
    "index": 3
  }],
  "credits": {
    "text": "Gold Feed Inc.",
    "href": "http://www.gold-feed.com"
  },
  "xAxis": {
    "title": {
      "text": null
    },
    "labels": {
      "rotation": null
    },
    "type": "datetime"
  },
  "yAxis": [{
    "title": {
      "text": "Price Per Troy Ounce"
    }
  }],
  "navigator": {
    "adaptToUpdatedData": false
  },
  "legend": {
    "x": 10
  }
})

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>

<div id="container" style="height: 400px; min-width: 310px"></div>


问:
Selenium webdriver doesn't open website - [fresh] [error] probe_ppp_module, can't find libpepflashplayer.so
When i am trying to use selenium at pycharm it couldn't open websites.

I am using Debian, Pycharm 2017.1.5, selenium 3.0.1, geckodriver 0.19.1, Firefox 52.5.0 64bit.
I have tried solution with installing geckodriver for firefox and all the other fixes, but when i am trying to launch my app it holds when browser is launched and no website is load (empty, clean firefox).

```<code>from selenium import webdriver

driver = webdriver.Firefox()
driver.get("http://www.python.org")
</code>```

My geckodriver.log:

```<code>1512819033857   geckodriver INFO    geckodriver 0.19.1
1512819033861   geckodriver INFO    Listening on 127.0.0.1:60859
1512819034970   mozrunner::runner   INFO    Running command: "/usr/bin/firefox" "-marionette" "-profile" "/tmp/rust_mozprofile.6erCM69GHVqK"
1512819036141   Marionette  INFO    Listening on port 2828
[fresh] [error] probe_ppp_module, can't find libpepflashplayer.so
[fresh] [error] probe_ppp_module, can't find libpepflashplayer.so
[fresh] [error] probe_ppp_module, can't find libpepflashplayer.so
[fresh] [error] probe_ppp_module, can't find libpepflashplayer.so
[fresh] [error] probe_ppp_module, can't find libpepflashplayer.so
[fresh] [error] probe_ppp_module, can't find libpepflashplayer.so
</code>```

I have installed browser-plugin-freshplayer-pepperflash and couldn't find what else is going wrong.

答:
I think the problem is on firefox flash player plugin.
 To get rid of this first Just do the following:

```<code>sudo add-apt-repository ppa:skunk/pepper-flash
sudo apt-get update
sudo apt-get install pepflashplugin-installer
sudo mkdir -p /opt/google/chrome/PepperFlash
sudo ln -s /usr/lib/pepflashplugin-installer/libpepflashplayer.so /opt/google/chrome/PepperFlash
</code>```

Then do this:

```<code>sudo add-apt-repository ppa:nilarimogard/webupd8
sudo apt-get update
sudo apt-get install freshplayerplugin
</code>```

Above will install pepper flash  to firefox.

Also Dont forget to set capabilities for mac geckodriver

```<code> from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
 from selenium.webdriver.common.keys import Keys

 firefox_profile = webdriver.FirefoxProfile()
 firefox_profile.set_preference("webdriver.gecko.driver", "YourPathTo/geckodriver"")

 driver = webdriver.Firefox(firefox_profile=firefox_profile, capabilities=firefox_capabilities)
</code>```

Body:
When i am trying to use selenium at pycharm it couldn't open websites.

I am using Debian, Pycharm 2017.1.5, selenium 3.0.1, geckodriver 0.19.1, Firefox 52.5.0 64bit.
I have tried solution with installing geckodriver for firefox and all the other fixes, but when i am trying to launch my app it holds when browser is launched and no website is load (empty, clean firefox).

from selenium import webdriver

driver = webdriver.Firefox()
driver.get("http://www.python.org")

My geckodriver.log:

1512819033857   geckodriver INFO    geckodriver 0.19.1
1512819033861   geckodriver INFO    Listening on 127.0.0.1:60859
1512819034970   mozrunner::runner   INFO    Running command: "/usr/bin/firefox" "-marionette" "-profile" "/tmp/rust_mozprofile.6erCM69GHVqK"
1512819036141   Marionette  INFO    Listening on port 2828
[fresh] [error] probe_ppp_module, can't find libpepflashplayer.so
[fresh] [error] probe_ppp_module, can't find libpepflashplayer.so
[fresh] [error] probe_ppp_module, can't find libpepflashplayer.so
[fresh] [error] probe_ppp_module, can't find libpepflashplayer.so
[fresh] [error] probe_ppp_module, can't find libpepflashplayer.so
[fresh] [error] probe_ppp_module, can't find libpepflashplayer.so

I have installed browser-plugin-freshplayer-pepperflash and couldn't find what else is going wrong.

Body:
I think the problem is on firefox flash player plugin.
 To get rid of this first Just do the following:

sudo add-apt-repository ppa:skunk/pepper-flash
sudo apt-get update
sudo apt-get install pepflashplugin-installer
sudo mkdir -p /opt/google/chrome/PepperFlash
sudo ln -s /usr/lib/pepflashplugin-installer/libpepflashplayer.so /opt/google/chrome/PepperFlash

Then do this:

sudo add-apt-repository ppa:nilarimogard/webupd8
sudo apt-get update
sudo apt-get install freshplayerplugin

Above will install pepper flash  to firefox.

Also Dont forget to set capabilities for mac geckodriver

 from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
 from selenium.webdriver.common.keys import Keys

 firefox_profile = webdriver.FirefoxProfile()
 firefox_profile.set_preference("webdriver.gecko.driver", "YourPathTo/geckodriver"")

 driver = webdriver.Firefox(firefox_profile=firefox_profile, capabilities=firefox_capabilities)


问:
Using AppleScript and JavaScript to click a button that has no id
I'm trying to use AppleScript to click a button that has no id:

```<code><div class="form-group">
    <button type="submit" class="btn btn-lg btn-success btn-block">Sign in</button>
</div>
</code>```

The Sign in button on this site: https://intakeq.com/signin

Using this AppleScript code:

```<code>do JavaScript "document.getElementsByClassName('form-group')[0].firstElementChild.click()"
</code>```

答:
You can click the button using its class name.

The following example AppleScript code assumes the target is in the current tab of the frontmost Safari window. Otherwise add appropriate code as necessary/required.

```<code>tell application "Safari"
    do JavaScript "document.getElementsByClassName('btn btn-lg btn-success btn-block')[0].click();" in document 1
end tell
</code>```

Body:
I'm trying to use AppleScript to click a button that has no id:

    <button type="submit" class="btn btn-lg btn-success btn-block">Sign in</button>

The Sign in button on this site: https://intakeq.com/signin

Using this AppleScript code:

do JavaScript "document.getElementsByClassName('form-group')[0].firstElementChild.click()"

Body:
You can click the button using its class name.

The following example AppleScript code assumes the target is in the current tab of the frontmost Safari window. Otherwise add appropriate code as necessary/required.

tell application "Safari"
    do JavaScript "document.getElementsByClassName('btn btn-lg btn-success btn-block')[0].click();" in document 1
end tell


问:
Changing colour of picker view on Swift
I have 5 picker views on my viewController. I want to change my all picker view's color. I did everything but I could not succeed. It gives me black as default. I want to make it white. How can I fix this. Can anyone help me over my code? Also after entering some datas from pickerview by user, if he or she first go o back page and next come to this screen again, datas will remain whatever he or she enter to pickerview, datas will not clean after this process. How can I do these?</p>

```<code>class LoggedInVC: UIViewController, UIPickerViewDataSource,UIPickerViewDelegate{

    @IBOutlet weak var cinsiyetButton: UIButton!
    @IBOutlet weak var türButton: UIButton!
    @IBOutlet weak var ageButton: UIButton!
    @IBOutlet weak var colorBotton: UIButton!
    @IBOutlet weak var healthButton: UIButton!
    @IBOutlet weak var cinsiyetPicker: UIPickerView!
    @IBOutlet weak var turPicher: UIPickerView!
    @IBOutlet weak var agePicker: UIPickerView!
    @IBOutlet weak var colorPicker: UIPickerView!
    @IBOutlet weak var healthPicker: UIPickerView!

    let cinsiyet = ["Erkek","Dişi"]
    let tur = ["pug","terrier","dogo","doberman"]
    let color = ["siyah","beyaz","kahverangi","karışık"]
    let age = ["1","2","3","4","5"]
    let health = ["kısır","Kısır Değil"]

    override func viewDidLoad() {
        super.viewDidLoad()

        cinsiyetPicker.dataSource = self
        cinsiyetPicker.delegate = self
        turPicher.dataSource = self
        turPicher.delegate = self
        agePicker.dataSource = self
        agePicker.delegate = self
        colorPicker.dataSource = self
        colorPicker.delegate = self
        healthPicker.dataSource = self
        healthPicker.delegate = self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @IBAction func cinsiyetPressed(_ sender: Any) {
        cinsiyetPicker.isHidden = false
    }

    @IBAction func turPressed(_ sender: Any) {
        turPicher.isHidden = false

    }

    @IBAction func agePressed(_ sender: Any) {

        agePicker.isHidden = false
    }

    @IBAction func colorPressed(_ sender: Any) {

        colorPicker.isHidden = false

    }

    @IBAction func healthPressed(_ sender: Any) {
        healthPicker.isHidden = false
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if pickerView.tag==1{
            return cinsiyet.count
        }
        else if pickerView.tag==2{
            return tur.count
        }
        else if pickerView.tag==3{
            return age.count
        }
        else if pickerView.tag==4{
            return color.count
        }
        else if pickerView.tag==5 {
            return health.count
        }
        return health.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

        if pickerView.tag==1{
            return cinsiyet[row]
        }
        else if pickerView.tag==2{
            return tur[row]
        }
        else if pickerView.tag==3{
            return age[row]
        }
        else if pickerView.tag==4{
            return color[row]
        }
        else if pickerView.tag==5 {
            return health[row]
        }
        return health[row]
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        if pickerView.tag==1{
            cinsiyetButton.setTitle(cinsiyet[row], for: UIControlState())
            cinsiyetPicker.isHidden = true
        }
        if pickerView.tag==2{
            türButton.setTitle(tur[row], for: UIControlState())
            turPicher.isHidden = true
        }
        if pickerView.tag==3{
            ageButton.setTitle(age[row], for: UIControlState())
            agePicker.isHidden = true
        }
        if pickerView.tag==4{
            colorBotton.setTitle(color[row], for: UIControlState())
            colorPicker.isHidden = true
        }
        if pickerView.tag==5{
            healthButton.setTitle(health[row], for: UIControlState())
            healthPicker.isHidden = true
        }
    }
}
</code>```

答:
I think your requirement could be achieved by simply using this delegate method</p>

```<code>func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString?
</code>```

Title: Changing colour of picker view on Swift

Body:
I have 5 picker views on my viewController. I want to change my all picker view's color. I did everything but I could not succeed. It gives me black as default. I want to make it white. How can I fix this. Can anyone help me over my code? Also after entering some datas from pickerview by user, if he or she first go o back page and next come to this screen again, datas will remain whatever he or she enter to pickerview, datas will not clean after this process. How can I do these?

class LoggedInVC: UIViewController, UIPickerViewDataSource,UIPickerViewDelegate{

    @IBOutlet weak var cinsiyetButton: UIButton!
    @IBOutlet weak var türButton: UIButton!
    @IBOutlet weak var ageButton: UIButton!
    @IBOutlet weak var colorBotton: UIButton!
    @IBOutlet weak var healthButton: UIButton!
    @IBOutlet weak var cinsiyetPicker: UIPickerView!
    @IBOutlet weak var turPicher: UIPickerView!
    @IBOutlet weak var agePicker: UIPickerView!
    @IBOutlet weak var colorPicker: UIPickerView!
    @IBOutlet weak var healthPicker: UIPickerView!

    let cinsiyet = ["Erkek","Dişi"]
    let tur = ["pug","terrier","dogo","doberman"]
    let color = ["siyah","beyaz","kahverangi","karışık"]
    let age = ["1","2","3","4","5"]
    let health = ["kısır","Kısır Değil"]

    override func viewDidLoad() {
        super.viewDidLoad()

        cinsiyetPicker.dataSource = self
        cinsiyetPicker.delegate = self
        turPicher.dataSource = self
        turPicher.delegate = self
        agePicker.dataSource = self
        agePicker.delegate = self
        colorPicker.dataSource = self
        colorPicker.delegate = self
        healthPicker.dataSource = self
        healthPicker.delegate = self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @IBAction func cinsiyetPressed(_ sender: Any) {
        cinsiyetPicker.isHidden = false
    }

    @IBAction func turPressed(_ sender: Any) {
        turPicher.isHidden = false

    }

    @IBAction func agePressed(_ sender: Any) {

        agePicker.isHidden = false
    }

    @IBAction func colorPressed(_ sender: Any) {

        colorPicker.isHidden = false

    }

    @IBAction func healthPressed(_ sender: Any) {
        healthPicker.isHidden = false
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if pickerView.tag==1{
            return cinsiyet.count
        }
        else if pickerView.tag==2{
            return tur.count
        }
        else if pickerView.tag==3{
            return age.count
        }
        else if pickerView.tag==4{
            return color.count
        }
        else if pickerView.tag==5 {
            return health.count
        }
        return health.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

        if pickerView.tag==1{
            return cinsiyet[row]
        }
        else if pickerView.tag==2{
            return tur[row]
        }
        else if pickerView.tag==3{
            return age[row]
        }
        else if pickerView.tag==4{
            return color[row]
        }
        else if pickerView.tag==5 {
            return health[row]
        }
        return health[row]
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        if pickerView.tag==1{
            cinsiyetButton.setTitle(cinsiyet[row], for: UIControlState())
            cinsiyetPicker.isHidden = true
        }
        if pickerView.tag==2{
            türButton.setTitle(tur[row], for: UIControlState())
            turPicher.isHidden = true
        }
        if pickerView.tag==3{
            ageButton.setTitle(age[row], for: UIControlState())
            agePicker.isHidden = true
        }
        if pickerView.tag==4{
            colorBotton.setTitle(color[row], for: UIControlState())
            colorPicker.isHidden = true
        }
        if pickerView.tag==5{
            healthButton.setTitle(health[row], for: UIControlState())
            healthPicker.isHidden = true
        }
    }
}

Body:
I think your requirement could be achieved by simply using this delegate method

func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString?


答:
If you check the function's name (type a.name) you'll receive "b".

So apparently the identifier after the function keyword is the function's name, and the identifier before the assignment is the reference to the function.

If no assignment is specified, (i.e. your first example - function b() {} without the var a =), the name itself will be the reference (the object b will have the reference to the function).

Title: What will happen if var a = function b(){}


问:
How to push struct type variable in standard stack in c++
Code Should i use &g on calling or *s in stack declaration?:</p>

```<code>#include<iostream>
#include<stack>
using namespace std;

struct node{
    int data;
    struct node *link;
};

main(){
    stack<node> s;
    struct node *g;
    g = new node;
    s.push(g);
}
</code>```

答:
Stack push() either copy the object, either move it. If you do not need share access to node objects, put them (not pointers) to stack via move semantic:

```<code>std::stack<node> st;
st.push(node());
</code>```

http://en.cppreference.com/w/cpp/container/stack/push

Body:
Code Should i use &g on calling or *s in stack declaration?:

#include<iostream>
#include<stack>
using namespace std;

struct node{
    int data;
    struct node *link;
};

main(){
    stack<node> s;
    struct node *g;
    g = new node;
    s.push(g);
}

Body:
Stack push() either copy the object, either move it. If you do not need share access to node objects, put them (not pointers) to stack via move semantic:

std::stack<node> st;
st.push(node());

http://en.cppreference.com/w/cpp/container/stack/push


问:
bring pagecontroll on front
I'm using scrollview and pagecontroll to scroll something. I used the code below  but I want the pagecontroller's dots be shown on views.I tried to bring it to front of all views and scrollview but it dosnt work.

```<code>    class DummyVC: UIViewController, UIScrollViewDelegate {

let scrollView = UIScrollView(frame: CGRect(x:0, y:0, width:320,height: 300))
var colors:[UIColor] = [UIColor.red, UIColor.blue, UIColor.green, UIColor.yellow]
var frame: CGRect = CGRect(x:0, y:0, width:0, height:0)
var pageControl : UIPageControl = UIPageControl(frame: CGRect(x:50,y: 300, width:200, height:50))

override func viewDidLoad() {
    super.viewDidLoad()

    configurePageControl()

    scrollView.delegate = self
    scrollView.isPagingEnabled = true

    self.view.addSubview(scrollView)
    for index in 0..<4 {

        frame.origin.x = self.scrollView.frame.size.width * CGFloat(index)
        frame.size = self.scrollView.frame.size

        let subView = UIView(frame: frame)
        subView.backgroundColor = colors[index]
        self.scrollView .addSubview(subView)
    }

    self.scrollView.contentSize = CGSize(width:self.scrollView.frame.size.width * 4,height: self.scrollView.frame.size.height)
    pageControl.addTarget(self, action: #selector(self.changePage(sender:)), for: UIControlEvents.valueChanged)

}

func configurePageControl() {
    // The total number of pages that are available is based on how many available colors we have.
    self.pageControl.numberOfPages = colors.count
    self.pageControl.currentPage = 0
    self.pageControl.tintColor = UIColor.red
    self.pageControl.pageIndicatorTintColor = UIColor.black
    self.pageControl.currentPageIndicatorTintColor = UIColor.green
    self.view.addSubview(pageControl)

}

// MARK : TO CHANGE WHILE CLICKING ON PAGE CONTROL
func changePage(sender: AnyObject) -> () {
    let x = CGFloat(pageControl.currentPage) * scrollView.frame.size.width
    scrollView.setContentOffset(CGPoint(x:x, y:0), animated: true)
}

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {

    let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
    pageControl.currentPage = Int(pageNumber)
}
</code>```

I want to add images to scrollviews subviwes and I want the dots shown on images

答: Move that line of code in viewDidLoad: configurePageControl() to the bottom of the scope.

Title: bring pagecontroll on front

Body:
I'm using scrollview and pagecontroll to scroll something. I used the code below  but I want the pagecontroller's dots be shown on views.I tried to bring it to front of all views and scrollview but it dosnt work.

    class DummyVC: UIViewController, UIScrollViewDelegate {

let scrollView = UIScrollView(frame: CGRect(x:0, y:0, width:320,height: 300))
var colors:[UIColor] = [UIColor.red, UIColor.blue, UIColor.green, UIColor.yellow]
var frame: CGRect = CGRect(x:0, y:0, width:0, height:0)
var pageControl : UIPageControl = UIPageControl(frame: CGRect(x:50,y: 300, width:200, height:50))

override func viewDidLoad() {
    super.viewDidLoad()

    configurePageControl()

    scrollView.delegate = self
    scrollView.isPagingEnabled = true

    self.view.addSubview(scrollView)
    for index in 0..<4 {

        frame.origin.x = self.scrollView.frame.size.width * CGFloat(index)
        frame.size = self.scrollView.frame.size

        let subView = UIView(frame: frame)
        subView.backgroundColor = colors[index]
        self.scrollView .addSubview(subView)
    }

    self.scrollView.contentSize = CGSize(width:self.scrollView.frame.size.width * 4,height: self.scrollView.frame.size.height)
    pageControl.addTarget(self, action: #selector(self.changePage(sender:)), for: UIControlEvents.valueChanged)

}

func configurePageControl() {
    // The total number of pages that are available is based on how many available colors we have.
    self.pageControl.numberOfPages = colors.count
    self.pageControl.currentPage = 0
    self.pageControl.tintColor = UIColor.red
    self.pageControl.pageIndicatorTintColor = UIColor.black
    self.pageControl.currentPageIndicatorTintColor = UIColor.green
    self.view.addSubview(pageControl)

}

// MARK : TO CHANGE WHILE CLICKING ON PAGE CONTROL
func changePage(sender: AnyObject) -> () {
    let x = CGFloat(pageControl.currentPage) * scrollView.frame.size.width
    scrollView.setContentOffset(CGPoint(x:x, y:0), animated: true)
}

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {

    let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
    pageControl.currentPage = Int(pageNumber)
}

I want to add images to scrollviews subviwes and I want the dots shown on images


问:
ASP.NET - Is it possible for clients to disable/disregard a 301 redirect?
I have 2 domains that resolve to my web site www.mysite.com and www.mysitecommonmisspelling.com, plus the IP address. I have some code in my Global.asax file that was intended to force all users and crawlers to only use the main domain, like so:

```<code>    Protected Sub Application_BeginRequest(ByVal sender As Object, ByVal e As System.EventArgs)

    'If the domain isn't the correct top level domain for this environment,
    'we want to do a 301 redirect to tell the search engines that this is not the right domain to
    'index.
    Dim Host As String = Me.EnvironmentHost
    Dim CurrentHost As String = Request.Url.DnsSafeHost

    If CurrentHost.ToLower <> Host.ToLower Then
        Dim Url As String = Request.Url.AbsoluteUri

        'The AbsolutUri property returns the Default.aspx whether it was actually specified
        'in the URL or not. Since our server is set up to respond to this as the default page,
        'we can safely remove it from the URL if it actually exists. We don't want Default.aspx
        'indexed anyway if possible.
        Url = Url.Replace("Default.aspx", "")
        Url = Url.Replace("default.aspx", "")

        'Replace the current host with the environment host
        Url = Url.Replace(CurrentHost, Host)

        Response.Clear()
        Response.StatusCode = 301
        Response.Status = "301 Moved Permanently"
        Response.AddHeader("Location", Url)
        Response.End()

    End If

End Sub
</code>```

I checked and Google has not indexed any pages on www.mysitecommonmisspelling.com, so they are apparently respecting the 301. However, a few days ago we had a customer on our site who got free shipping because the licensing code that is only registered for www.mysite.com failed (in other words, the browser was able to access www.mysitecommonmisspelling.com). In the past, we have had issues with the 3rd party shipping component because users were able to access the site using the IP address.

In any case, we don't want users to be able to access the site without the correct domain so the SSL certificate doesn't complain.

I have searched for a way to disable 301 redirects in IE7, but there doesn't appear to be a way. So, what I am wondering is if there are any browsers that can disable 301, and if so what kind of workarounds can I put in place to ensure all browsers on my site are going to the main domain, www.mysite.com?

答:
This type of redirect really belongs in the Web Server, not the Application. For IIS7, there is the URL Rewrite Module.

You may want to setup the IIS to host two websites, MySite and Misspelling, so that Misspelling never ever actually hits your real site. Just setup a redirect on that site.

You may want to check Server Fault on how to properly do it as I'm not an IIS7 Expert.

As for the part of your question about Browsers ignoring it: Sure, Browsers can decide not to follow the 301 Redirect, but then they would just display a blank page. If someone can bypass it, then it means that this line:

```<code> If CurrentHost.ToLower <> Host.ToLower Then
</code>```

is not working correctly. I don't know if Browsers can actually send a wrong Hostname while accessing a different one (although when in doubt I blame Proxies since they are often very weird).

ContentLicense: CC BY-SA 2.5

Body:
I have 2 domains that resolve to my web site www.mysite.com and www.mysitecommonmisspelling.com, plus the IP address. I have some code in my Global.asax file that was intended to force all users and crawlers to only use the main domain, like so:

    Protected Sub Application_BeginRequest(ByVal sender As Object, ByVal e As System.EventArgs)

    'If the domain isn't the correct top level domain for this environment,
    'we want to do a 301 redirect to tell the search engines that this is not the right domain to
    'index.
    Dim Host As String = Me.EnvironmentHost
    Dim CurrentHost As String = Request.Url.DnsSafeHost

    If CurrentHost.ToLower <> Host.ToLower Then
        Dim Url As String = Request.Url.AbsoluteUri

        'The AbsolutUri property returns the Default.aspx whether it was actually specified
        'in the URL or not. Since our server is set up to respond to this as the default page,
        'we can safely remove it from the URL if it actually exists. We don't want Default.aspx
        'indexed anyway if possible.
        Url = Url.Replace("Default.aspx", "")
        Url = Url.Replace("default.aspx", "")

        'Replace the current host with the environment host
        Url = Url.Replace(CurrentHost, Host)

        Response.Clear()
        Response.StatusCode = 301
        Response.Status = "301 Moved Permanently"
        Response.AddHeader("Location", Url)
        Response.End()

    End If

End Sub

I checked and Google has not indexed any pages on www.mysitecommonmisspelling.com, so they are apparently respecting the 301. However, a few days ago we had a customer on our site who got free shipping because the licensing code that is only registered for www.mysite.com failed (in other words, the browser was able to access www.mysitecommonmisspelling.com). In the past, we have had issues with the 3rd party shipping component because users were able to access the site using the IP address.

In any case, we don't want users to be able to access the site without the correct domain so the SSL certificate doesn't complain.

I have searched for a way to disable 301 redirects in IE7, but there doesn't appear to be a way. So, what I am wondering is if there are any browsers that can disable 301, and if so what kind of workarounds can I put in place to ensure all browsers on my site are going to the main domain, www.mysite.com?

Body:
This type of redirect really belongs in the Web Server, not the Application. For IIS7, there is the URL Rewrite Module.

You may want to setup the IIS to host two websites, MySite and Misspelling, so that Misspelling never ever actually hits your real site. Just setup a redirect on that site.

You may want to check Server Fault on how to properly do it as I'm not an IIS7 Expert.

As for the part of your question about Browsers ignoring it: Sure, Browsers can decide not to follow the 301 Redirect, but then they would just display a blank page. If someone can bypass it, then it means that this line:

 If CurrentHost.ToLower <> Host.ToLower Then

is not working correctly. I don't know if Browsers can actually send a wrong Hostname while accessing a different one (although when in doubt I blame Proxies since they are often very weird).


问:
Symfony query with Doctrine
I'm working on a little exercise to improve myself with Symfony 3. I have got a mistake in building a query to get adverts not linked to applications and on which the date is older than 30 days.

I have created a new method in my controller, a new query in my advertRepository and a service named "Purger" in which I have to delete these old adverts.

I paste you the code just below (controller, service class, AdvertRepository, services.yml) :

```<code>public function purgeAction($days)
{
  // Appel du service
  $testPurge = $this->get('oc_platform.purger.advert');
  $testPurge->purge($days);

  return new Response("Purge done !");
}

namespace OC\PlatformBundle\Purger\Advert;

use OC\PlatformBundle\Entity\Advert;
use Doctrine\ORM\EntityManager;

class OCAdvertsPurger
 {
  private $em;

  public function __construct(EntityManager $em)
  {
    $this->em = $em;
  }

  //Ce service va récupérer et supprimer toutes les annonces dont la date de
  modification
  // est plus vieille que X jours. Ce "X" est le paramètre de la méthode.
  public function purge($days)
   {
     $listAdverts = $this->em->getRepository('OCPlatformBundle:Advert')-
     >getOldAdvertsOnly($days);
   }
 }

public function getOldAdvertsOnly($days)
{
  // Liste de toutes les annonces
  $qb = $this->createQueryBuilder('a')
    ->leftJoin('a.applications', "app")
    ->addSelect('app')
  ;

  // On retire celles attachées à des candidatures
  $qb->where($qb->expr()->isNull('app.advert_id'));

  return $qb
    ->getQuery()
    ->getResult()
  ;
}

public function deleteOldAdvertsOnly($adverts)
{
  $qb = $this->createQuery('DELETE $adverts FROM
  OC\PlatformBundle\Entity\Advert  WHERE DATE_DIFF(CURRENT_DATE(),
  updated_at) > $days');

  return $qb
    ->getQuery()
    ->getResut()
  ;
}
    services:
        oc_platform.purger.advert:
        class: OC\PlatformBundle\Purger\Advert\OCAdvertsPurger
        arguments:
            - "@doctrine.orm.entity_manager"
</code>```

I tried to do something with the DATE_DIFF function() in the same query with queryBuilder but there was a mistake because queryBuilder() doesn't know this function as CURRENT_DATE() I think so I was trying to make it work with two different queries (one with queryBuilder and one with the DQL langage).

Really thanks for going to help me !

答:
Thank you guys ! I just modified my query and it worked !
I have to bear in mind your trick about adding SQL functions to Doctrine :)</p>

Title: Symfony query with Doctrine

Body:
I'm working on a little exercise to improve myself with Symfony 3. I have got a mistake in building a query to get adverts not linked to applications and on which the date is older than 30 days.

I have created a new method in my controller, a new query in my advertRepository and a service named "Purger" in which I have to delete these old adverts.

I paste you the code just below (controller, service class, AdvertRepository, services.yml) :

public function purgeAction($days)
{
  // Appel du service
  $testPurge = $this->get('oc_platform.purger.advert');
  $testPurge->purge($days);

  return new Response("Purge done !");
}

namespace OC\PlatformBundle\Purger\Advert;

use OC\PlatformBundle\Entity\Advert;
use Doctrine\ORM\EntityManager;

class OCAdvertsPurger
 {
  private $em;

  public function __construct(EntityManager $em)
  {
    $this->em = $em;
  }

  //Ce service va récupérer et supprimer toutes les annonces dont la date de
  modification
  // est plus vieille que X jours. Ce "X" est le paramètre de la méthode.
  public function purge($days)
   {
     $listAdverts = $this->em->getRepository('OCPlatformBundle:Advert')-
     >getOldAdvertsOnly($days);
   }
 }

public function getOldAdvertsOnly($days)
{
  // Liste de toutes les annonces
  $qb = $this->createQueryBuilder('a')
    ->leftJoin('a.applications', "app")
    ->addSelect('app')
  ;

  // On retire celles attachées à des candidatures
  $qb->where($qb->expr()->isNull('app.advert_id'));

  return $qb
    ->getQuery()
    ->getResult()
  ;
}

public function deleteOldAdvertsOnly($adverts)
{
  $qb = $this->createQuery('DELETE $adverts FROM
  OC\PlatformBundle\Entity\Advert  WHERE DATE_DIFF(CURRENT_DATE(),
  updated_at) > $days');

  return $qb
    ->getQuery()
    ->getResut()
  ;
}
    services:
        oc_platform.purger.advert:
        class: OC\PlatformBundle\Purger\Advert\OCAdvertsPurger
        arguments:
            - "@doctrine.orm.entity_manager"

I tried to do something with the DATE_DIFF function() in the same query with queryBuilder but there was a mistake because queryBuilder() doesn't know this function as CURRENT_DATE() I think so I was trying to make it work with two different queries (one with queryBuilder and one with the DQL langage).

Really thanks for going to help me !


问:
pthread segmentation fault (core dumped) error
Can somebody point out why my code is throwing segmentation fault? Most likely I am making a mistake when calling pthread_create() but I am failing to understand the mistake. Can somebody point out where am I going wrong?

```<code>#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

int x = 0;
int counter =
    0;  // This is the global variable that all the threads will increment.
pthread_mutex_t lock;

void* addcounter(void* threadid) {
  pthread_mutex_lock(&lock);
  int* id = (int*)threadid + 1;
  int* y = (int*)x;
  int total = (*id) * (*y);
  int i = 0;
  for (i = 0; i < total; i++) {
    counter += 1;
  }
  pthread_mutex_unlock(&lock);
}

int main(int argc, char* argv[]) {
  int thread_count = 0;
  int loop_count = 0;
  int expected_value = -1;

  if (argc != 3) {
    printf("Usage: threads <no_of_threads> <no_of_loops>\n");
    exit(1);
  }

  thread_count = atoi(argv[1]);
  loop_count = atoi(argv[2]);
  x = loop_count;

  // Start your implementation after this comment.
  pthread_t* threads;
  threads = malloc(sizeof(pthread_t) * thread_count);
  int t;
  int flag = 0;
  for (t = 0; t < thread_count; t++) {
    int* z = malloc(sizeof(int));
    *z = t;
    flag = pthread_create(&threads[t], NULL, addcounter, (void*)z);
  }
  if (flag != 0) {
    printf("error in creating threads");
    exit(0);
  }

  for (t = 0; t < thread_count; t++) pthread_join(threads[t], NULL);
  // Do not change the code below this comment
  return 0;
}
</code>```

The output of this code is:

Segmentation fault (core dumped)

How should I resolve this error?

答:
Multiple pointer issues in

```<code>void* addcounter(void* threadid) {
  pthread_mutex_lock(&lock);
  int* id = (int*)threadid + 1;    // <== A
  int* y = (int*)x;                // <== B
  int total = (*id) * (*y);        // <== C
  int i = 0;
  for (i = 0; i < total; i++) {
    counter += 1;
  }
  pthread_mutex_unlock(&lock);
}
</code>```

Explanations

A: probably int id = *(int *)threadid + 1;

B: int *y = (int *)x will have y pointer set to x... an int dangerous! Was probably int y = x; (?)

C: Then fix the total int total = id + y; (the following loop is not necessary, counter += total; is enough

Body:
Can somebody point out why my code is throwing segmentation fault? Most likely I am making a mistake when calling pthread_create() but I am failing to understand the mistake. Can somebody point out where am I going wrong?

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

int x = 0;
int counter =
    0;  // This is the global variable that all the threads will increment.
pthread_mutex_t lock;

void* addcounter(void* threadid) {
  pthread_mutex_lock(&lock);
  int* id = (int*)threadid + 1;
  int* y = (int*)x;
  int total = (*id) * (*y);
  int i = 0;
  for (i = 0; i < total; i++) {
    counter += 1;
  }
  pthread_mutex_unlock(&lock);
}

int main(int argc, char* argv[]) {
  int thread_count = 0;
  int loop_count = 0;
  int expected_value = -1;

  if (argc != 3) {
    printf("Usage: threads <no_of_threads> <no_of_loops>\n");
    exit(1);
  }

  thread_count = atoi(argv[1]);
  loop_count = atoi(argv[2]);
  x = loop_count;

  // Start your implementation after this comment.
  pthread_t* threads;
  threads = malloc(sizeof(pthread_t) * thread_count);
  int t;
  int flag = 0;
  for (t = 0; t < thread_count; t++) {
    int* z = malloc(sizeof(int));
    *z = t;
    flag = pthread_create(&threads[t], NULL, addcounter, (void*)z);
  }
  if (flag != 0) {
    printf("error in creating threads");
    exit(0);
  }

  for (t = 0; t < thread_count; t++) pthread_join(threads[t], NULL);
  // Do not change the code below this comment
  return 0;
}

The output of this code is:

Segmentation fault (core dumped)

How should I resolve this error?

Body:
Multiple pointer issues in

void* addcounter(void* threadid) {
  pthread_mutex_lock(&lock);
  int* id = (int*)threadid + 1;    // <== A
  int* y = (int*)x;                // <== B
  int total = (*id) * (*y);        // <== C
  int i = 0;
  for (i = 0; i < total; i++) {
    counter += 1;
  }
  pthread_mutex_unlock(&lock);
}

Explanations

A: probably int id = *(int *)threadid + 1;

B: int *y = (int *)x will have y pointer set to x... an int dangerous! Was probably int y = x; (?)

C: Then fix the total int total = id + y; (the following loop is not necessary, counter += total; is enough


问:
Clicking a button within a form causes page refresh
I have a form in Angular that has two buttons tags in it. One button submits the form on ng-click. The other button is purely for navigation using ng-click. However, when this second button is clicked, AngularJS is causing a page refresh which triggers a 404. I’ve dropped a breakpoint in the function and it is triggering my function. If I do any of the following, it stops:

If I remove the ng-click, the button doesn’t cause a page refresh.

If I comment out the code in the function, it doesn’t cause a page refresh.

If I change the button tag to an anchor tag () with href="", then it doesn’t cause a refresh.

The latter seems like the simplest workaround, but why is AngularJS even running any code after my function that causes the page to reload? Seems like a bug.

Here is the form:

```<code><form class="form-horizontal" name="myProfile" ng-switch-when="profile">
  <fieldset>
    <div class="control-group">
      <label class="control-label" for="passwordButton">Password</label>
      <div class="controls">
        <button id="passwordButton" class="secondaryButton" ng-click="showChangePassword()">Change</button>
      </div>
    </div>

    <div class="buttonBar">
      <button id="saveProfileButton" class="primaryButton" ng-click="saveUser()">Save</button>
    </div>
  </fieldset>
</form>
</code>```

Here is the controller method:

```<code>$scope.showChangePassword = function() {
  $scope.selectedLink = "changePassword";
};
</code>```

答:
This answer may not be directly related to the question. It's just for the case when you submit the form using scripts.

According to ng-submit code

 var handleFormSubmission = function(event) {
  scope.$apply(function() {
    controller.$commitViewValue();
    controller.$setSubmitted();
  });

  event.preventDefault();
};

formElement[0].addEventListener('submit', handleFormSubmission);```

It adds submit event listener on the form.
But submit event handler wouldn't be called when submit is initiated by calling form.submit(). In this case, ng-submit will not prevent the default action, you have to call preventDefault yourself in ng-submit handler;

To provide a reasonably definitive answer, the HTML Form Submission Algorithm item 5 states that a form only dispatches a submit event if it was not submitted by calling the submit method (which means it only dispatches a submit event if submitted by a button or other implicit method, e.g. pressing enter while focus is on an input type text element).

See Form submitted using submit() from a link cannot be caught by onsubmit handler

Body:
I have a form in Angular that has two buttons tags in it. One button submits the form on ng-click. The other button is purely for navigation using ng-click. However, when this second button is clicked, AngularJS is causing a page refresh which triggers a 404. I’ve dropped a breakpoint in the function and it is triggering my function. If I do any of the following, it stops:

If I remove the ng-click, the button doesn’t cause a page refresh.

If I comment out the code in the function, it doesn’t cause a page refresh.

If I change the button tag to an anchor tag () with href="", then it doesn’t cause a refresh.

The latter seems like the simplest workaround, but why is AngularJS even running any code after my function that causes the page to reload? Seems like a bug.

Here is the form:

<form class="form-horizontal" name="myProfile" ng-switch-when="profile">
  <fieldset>

      Password

        <button id="passwordButton" class="secondaryButton" ng-click="showChangePassword()">Change</button>

      <button id="saveProfileButton" class="primaryButton" ng-click="saveUser()">Save</button>

  </fieldset>
</form>

Here is the controller method:

$scope.showChangePassword = function() {
  $scope.selectedLink = "changePassword";
};

Body:
This answer may not be directly related to the question. It's just for the case when you submit the form using scripts.

According to ng-submit code

 var handleFormSubmission = function(event) {
  scope.$apply(function() {
    controller.$commitViewValue();
    controller.$setSubmitted();
  });

  event.preventDefault();
};

formElement[0].addEventListener('submit', handleFormSubmission);

It adds submit event listener on the form.
But submit event handler wouldn't be called when submit is initiated by calling form.submit(). In this case, ng-submit will not prevent the default action, you have to call preventDefault yourself in ng-submit handler;

To provide a reasonably definitive answer, the HTML Form Submission Algorithm item 5 states that a form only dispatches a submit event if it was not submitted by calling the submit method (which means it only dispatches a submit event if submitted by a button or other implicit method, e.g. pressing enter while focus is on an input type text element).

See Form submitted using submit() from a link cannot be caught by onsubmit handler


问:
Android: How to add FCM in a library project
I have a library project in android. It is currently using GCM. The app that uses the project registers their gcm sender id and the project will generate a token from it and send it to the server and then listen to the GCM messages.

I want to upgrade my project to FCM. I was following the steps given here.

I am a little confused with the steps. My questions are:

Its asking me to get google-services.json file, which you can get by registering the app SHA value. I do not have an app in this case.

I need to implement the Service which will just listen to the FCM and do the relevant action but that is not clear from the document

Please help in how can I integrate FCM in a library project.

Thanks in advance.

Downvoting should be accompanied with the reason.

答:
You need not add the google-services.json file in your SDK. The client app which integrates the SDK will need to do it.

Refer to this example repo, this should clear out your confusion regarding implementing services


问:
Iterate through xml file and store content inside Textfield c#
I have an Xml file where I want to loop through each module node which increments by 1. Here is a sample of my xml file:

```<code><PersonDetails>
  <PersonTitle>Teacher</PersonTitle>
  <Keystage3>
    <Subject>
      <subjectName>maths</subjectName>
      <subjectId>qq1</subjectId>
      <subjectvalue>20</subjectvalue>
      <subjectscore />
    </Subject>
    <Subject>
      <subjectName>science</subjectName>
      <subjectId>sla1s</subjectId>
      <subjectvalue>25</subjectvalue>
      <subjectscore />
    </Subject>
  </Keystage3>
</PersonDetails>
</code>```

I want to loop through the xml file and get all data of Subject for both
<Subject> node and store each value inside a variable.

I have a piece of code which gets the value from a specific node and outputs
it on a textfield.

here is the code I have so far:

```<code>public partial class Form1 : Form
{
    private string subName, subId, subvalue;

    public XmlDocument Doc;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {

        XmlTextReader reader = new XmlTextReader("data.xml");
        XmlNodeType type;

        while (reader.Read()) {

            type = reader.NodeType;

            if(type == XmlNodeType.Element)
            {

                    if (reader.Name == "subjectName")
                    {
                        reader.Read();
                        textBox1.Text = reader.Value;
                    }
                    if (reader.Name == "subjectId")
                    {
                        reader.Read();
                        textBox2.Text = reader.Value;
                    }
                    if (reader.Name == "subjectvalue")
                    {
                        reader.Read();
                        textBox3.Text = reader.Value;
                   }

            }
        }
        reader.Close();

    }
</code>```

How can I make it so that the output recieved is something like:

```<code>{maths,qq1,20}
{science,sla1s,25}
</code>```

答:
You can perform it by using XDocument. If you want to store the nodes values as a collection you can create a class for SubjectNode like this;

```<code>        public class SubjectNode
        {
            public string SubjectName { get; set; }
            public string SubjectId { get; set; }
            public string SubjectValue { get; set; }
        }
</code>```

Then you can retrieve the data like this;

```<code>        var xdoc = XDocument.Load("data.xml");
        var keystageNode = xdoc.Descendants("Keystage3").FirstOrDefault();
        var iterateNode = keystageNode.FirstNode;
        var subjectNodes = new List<SubjectNode>();
        while (iterateNode != null)
        {
            var node = (XElement)iterateNode.NextNode;
            subjectNodes.Add(new SubjectNode
            {
                SubjectName = node.Element("subjectName").Value,
                SubjectId = node.Element("subjectId").Value,
                SubjectValue = node.Element("subjectvalue").Value
            });
            iterateNode = iterateNode.NextNode;
        }
</code>```

Body:
I have an Xml file where I want to loop through each module node which increments by 1. Here is a sample of my xml file:

<PersonDetails>
  <PersonTitle>Teacher</PersonTitle>
  <Keystage3>
    <Subject>
      <subjectName>maths</subjectName>
      <subjectId>qq1</subjectId>
      <subjectvalue>20</subjectvalue>
      <subjectscore />
    </Subject>
    <Subject>
      <subjectName>science</subjectName>
      <subjectId>sla1s</subjectId>
      <subjectvalue>25</subjectvalue>
      <subjectscore />
    </Subject>
  </Keystage3>
</PersonDetails>

I want to loop through the xml file and get all data of Subject for both
<Subject> node and store each value inside a variable.

I have a piece of code which gets the value from a specific node and outputs
it on a textfield.

here is the code I have so far:

public partial class Form1 : Form
{
    private string subName, subId, subvalue;

    public XmlDocument Doc;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {

        XmlTextReader reader = new XmlTextReader("data.xml");
        XmlNodeType type;

        while (reader.Read()) {

            type = reader.NodeType;

            if(type == XmlNodeType.Element)
            {

                    if (reader.Name == "subjectName")
                    {
                        reader.Read();
                        textBox1.Text = reader.Value;
                    }
                    if (reader.Name == "subjectId")
                    {
                        reader.Read();
                        textBox2.Text = reader.Value;
                    }
                    if (reader.Name == "subjectvalue")
                    {
                        reader.Read();
                        textBox3.Text = reader.Value;
                   }

            }
        }
        reader.Close();

    }

How can I make it so that the output recieved is something like:

{maths,qq1,20}
{science,sla1s,25}

Body:
You can perform it by using XDocument. If you want to store the nodes values as a collection you can create a class for SubjectNode like this;

        public class SubjectNode
        {
            public string SubjectName { get; set; }
            public string SubjectId { get; set; }
            public string SubjectValue { get; set; }
        }

Then you can retrieve the data like this;

        var xdoc = XDocument.Load("data.xml");
        var keystageNode = xdoc.Descendants("Keystage3").FirstOrDefault();
        var iterateNode = keystageNode.FirstNode;
        var subjectNodes = new List<SubjectNode>();
        while (iterateNode != null)
        {
            var node = (XElement)iterateNode.NextNode;
            subjectNodes.Add(new SubjectNode
            {
                SubjectName = node.Element("subjectName").Value,
                SubjectId = node.Element("subjectId").Value,
                SubjectValue = node.Element("subjectvalue").Value
            });
            iterateNode = iterateNode.NextNode;
        }


问:
Fetch data with single and fast SQL query
I have the following data:

```<code>ExamEntry   Student_ID     Grade
  11           1             80
  12           2             70
  13           3             20
  14           3             68
  15           4             75
</code>```

I want to find all the students that passed an exam. In this case, if there are few exams
that one student attended to, I need to find the last result.

So, in this case I'd get that all students passed.

Can I find it with one fast query? I do it this way:

Find the list of entries by
select max(ExamEntry) from data group by Student_ID

Find the results:

select ExamEntry from data where ExamEntry in ( ).

But this is VERY slow - I get around 1000 entries, and this 2 step process takes 10 seconds.

Is there a better way?

Thanks.

答:
I've used the hints given here, and here the query I found that runs almost 3 orders faster than my first one (.03 sec instead of 10 sec):

```<code>SELECT ExamEntry, Student_ID, Grade from data,
       ( SELECT max(ExamEntry) as ExId GROUP BY Student_ID) as newdata
WHERE `data`.`ExamEntry`=`newdata`.`ExId` AND Grade > 60;
</code>```

Thanks All!

OwnerDisplayName: Alex

Body:
I have the following data:

ExamEntry   Student_ID     Grade
  11           1             80
  12           2             70
  13           3             20
  14           3             68
  15           4             75

I want to find all the students that passed an exam. In this case, if there are few exams
that one student attended to, I need to find the last result.

So, in this case I'd get that all students passed.

Can I find it with one fast query? I do it this way:

Find the list of entries by
select max(ExamEntry) from data group by Student_ID

Find the results:

select ExamEntry from data where ExamEntry in ( ).

But this is VERY slow - I get around 1000 entries, and this 2 step process takes 10 seconds.

Is there a better way?

Thanks.

LastEditorDisplayName: Yaakov Ellis

Body:
I've used the hints given here, and here the query I found that runs almost 3 orders faster than my first one (.03 sec instead of 10 sec):

SELECT ExamEntry, Student_ID, Grade from data,
       ( SELECT max(ExamEntry) as ExId GROUP BY Student_ID) as newdata
WHERE `data`.`ExamEntry`=`newdata`.`ExId` AND Grade > 60;

Thanks All!

LastEditorDisplayName: Alex


问:
How do I create a link using JavaScript?
I have a string for a title and a string for a link.  I'm not sure how to put the two together to create a link on a page using JavaScript.  Any help is appreciated.

The reason I'm trying to figure this out is because I have an RSS feed and have a list of titles ands URLs.  I would like to link the titles to the URL to make the page useful.

I am using jQuery but am completely new to it and wasn't aware it could help in this situation.

答:
There are a couple of ways:

If you want to use raw Javascript (without a helper like JQuery), then you could do something like:

```<code>var link = "http://google.com";
var element = document.createElement("a");
element.setAttribute("href", link);
element.innerHTML = "your text";

// and append it to where you'd like it to go:
document.body.appendChild(element);
</code>```

The other method is to write the link directly into the document:

```<code>document.write("<a href='" + link + "'>" + text + "</a>");
</code>```

ContentLicense: CC BY-SA 4.0

Body:
There are a couple of ways:

If you want to use raw Javascript (without a helper like JQuery), then you could do something like:

var link = "http://google.com";
var element = document.createElement("a");
element.setAttribute("href", link);
element.innerHTML = "your text";

// and append it to where you'd like it to go:
document.body.appendChild(element);

The other method is to write the link directly into the document:

document.write("<a href='" + link + "'>" + text + "</a>");


问:
I cannot center my header in the middle
I'm trying to get my header with ul in the center. Another page suggested having overflow:hidden  but when I shrink the window, a second scroll bar still appears.

Every time I try something, the li isn't in line with my logo.
Also tried to have the class 'container' margin: auto but nothing happens.

body {
  font: 15px/1.5 Arial, Helvetica, sans-serif;
  padding: 0;
  margin: 0;
  background-color: #f4f4f4;
}

/*Global styling */

.container {
  width: 100%;
  overflow: visible;
}

ul {
  margin: 0;
  padding: 0;
}

/*Header*/

header {
  background: #100806;
  color: #f2f2f2;
  min-height: 75px;
  border-bottom: #ffffff 3px solid;
  text-align: center;
}

header a {
  color: #ffffff;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 15px;
}

header li {
  display: inline-block;
  padding: 0 30px 10px 0;
  float: left;
}

header .center-logo img {
  width: 100px;
  padding-left: 30px;
  padding-right: 30px;
}

header nav span {
  float: left;
}

header nav span:first-child {
  padding-right: 50px;
  /* half the logo width */
  padding-top: 20px;
}

header nav span:last-child {
  padding-left: 50px;
  padding-top: 20px;
  /* half the logo width */
}

header .highlight,
header .current a {
  color: #e8491d;
  font-weight: bold;
}

header a:hover {
  color: #666666;
  font-weight: bold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <div class="container">
    <nav>
      <ul>
        <span>
          <li class="current"> Home</li>
          <li> Photography</li>
        </span>
        <div class="center-logo">
          <li><img src="https://placehold.it/100x50"></li>
        </div>
        <span>
          <li> Biography</li>
          <li> Contact Us</li>
        </span>
      </ul>
    </nav>
  </div>
</header></code>```

答:
You could use Flexbox.

```<code>header ul {
   display:flex
}

header li {
   flex: 1
}
</code>```

Powerful tool flex.

See fiddle: https://jsfiddle.net/fo7v1253/1/

Title: I cannot center my header in the middle

Body:
I'm trying to get my header with ul in the center. Another page suggested having overflow:hidden  but when I shrink the window, a second scroll bar still appears.

Every time I try something, the li isn't in line with my logo.
Also tried to have the class 'container' margin: auto but nothing happens.

body {
  font: 15px/1.5 Arial, Helvetica, sans-serif;
  padding: 0;
  margin: 0;
  background-color: #f4f4f4;
}

/*Global styling */

.container {
  width: 100%;
  overflow: visible;
}

ul {
  margin: 0;
  padding: 0;
}

/*Header*/

header {
  background: #100806;
  color: #f2f2f2;
  min-height: 75px;
  border-bottom: #ffffff 3px solid;
  text-align: center;
}

header a {
  color: #ffffff;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 15px;
}

header li {
  display: inline-block;
  padding: 0 30px 10px 0;
  float: left;
}

header .center-logo img {
  width: 100px;
  padding-left: 30px;
  padding-right: 30px;
}

header nav span {
  float: left;
}

header nav span:first-child {
  padding-right: 50px;
  /* half the logo width */
  padding-top: 20px;
}

header nav span:last-child {
  padding-left: 50px;
  padding-top: 20px;
  /* half the logo width */
}

header .highlight,
header .current a {
  color: #e8491d;
  font-weight: bold;
}

header a:hover {
  color: #666666;
  font-weight: bold;
}

 Home

 Photography

 Biography

 Contact Us

Body:
You could use Flexbox.

header ul {
   display:flex
}

header li {
   flex: 1
}

Powerful tool flex.

See fiddle: https://jsfiddle.net/fo7v1253/1/


问:
AppCompatRadioButton not shown
Since I want to use buttonTint on versions < 21, I need to switch from RadioButton to AppCompatRadioButton. Unfortunately the button is not shown on the device (Android 5.1). It's strange because the android:text of the AppCompatRadioButton works, so that means that the button basically works. Only the circle is not shown. Any ideas why? I also tried to set other color attributes which come with AppCompatRadioButton. It didn't work either. I also updated to the latest compatibility package, I moved the button inside the xml to another position, but nothing works.

This is the xml definition:

```<code><android.support.v7.widget.AppCompatRadioButton
    android:id="@+id/radio_bronze_monthly"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:onClick="onBillingRadioButtonClicked"
    android:text="@string/bronze_monthly"
    android:textColor="@color/black"
    android:textSize="@dimen/default_text_size"
    app:buttonTint="@color/black"
    app:colorAccent="@color/black"
    app:colorPrimary="@color/black"
    app:colorPrimaryDark="@color/black"/>
</code>```

答: Build design library in build.gradle(App) module</p>

Title: AppCompatRadioButton not shown

Body:
Since I want to use buttonTint on versions < 21, I need to switch from RadioButton to AppCompatRadioButton. Unfortunately the button is not shown on the device (Android 5.1). It's strange because the android:text of the AppCompatRadioButton works, so that means that the button basically works. Only the circle is not shown. Any ideas why? I also tried to set other color attributes which come with AppCompatRadioButton. It didn't work either. I also updated to the latest compatibility package, I moved the button inside the xml to another position, but nothing works.

This is the xml definition:

<android.support.v7.widget.AppCompatRadioButton
    android:id="@+id/radio_bronze_monthly"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:onClick="onBillingRadioButtonClicked"
    android:text="@string/bronze_monthly"
    android:textColor="@color/black"
    android:textSize="@dimen/default_text_size"
    app:buttonTint="@color/black"
    app:colorAccent="@color/black"
    app:colorPrimary="@color/black"
    app:colorPrimaryDark="@color/black"/>