问:
Generating and using RSA keys with Python
I'm working on a Python project which is supposed to encrypt, send and then decrypt messages with RSA. (I precise it's not a professional project)
I've written a small program to create these keys, and I thought it would work however I think there's a problem in my keys.

The keys are created this way :

```<code>def generate_integer ():

    i = 0
    number = ""
    number += str(randrange(1,10))
    while i < 1:
        number += str(randrange(0,10))
        i += 1

    return int (number)

def generate_prime_integers ():

    p = generate_integer ()
    q = 0
    premiers = False

    while not prime:
        q = generate_integer ()
        prime = extended_euclide (p, q, False)
        if p == q:
            prime = False

    return p, q

def generate_prime_with_Euler (i_Euler):

    prime_with_Euler = False
    while not prime_with_Euler:
        e = randrange(2,100)
        prime_with_Euler = extended_euclide (e, i_Euler, False)

    return e

def extended_euclide (a,b,calculate_bezout):

    r = a
    u = 1
    v = 0
    r2 = b
    u2 = 0
    v2 = 1
    quotient = 0

    while r2 != 0:
        q = r // r2
        (r, u, v, r2, u2, v2) = (r2, u2, v2, r - q * r2, u - q * u2, v - q * v2)

    prime = False
    if r == 1:
        prime = True

    if calculate_bezout:
        return u
    else:
        return prime

def calculate_d (e, i_Euler):

    u = extended_euclide (e, i_Euler, True)
    return u

def create_keys():
    d = -1
    while d < 0:
        p, q = generate_prime_integers()
        n = p*q
        i_Euler = (p-1) * (q-1)
        e = generate_prime_with_ Euler (i_Euler)
        d = calculate_d (e, i_Euler)

    return n, e, d
</code>```

A few explanations : e is the encrypting exponent, d is the decrypting exponent, i_Euler is the Phi(n) function.
The function called is create_keys (), it uses all the functions above to create the 2 keys, public and private. I took the function 'extended_euclide' from Wikipedia, because I had no idea how to code the algorithm of Euclide, and modified it a bit so that it either gives me d (when I give True as third parameter) or tells if the two integers are relatively prime (when giving False).

So, the problem is : when I create my keys and try to encrypt/decrypt any value, it's not working

```<code>>>> n,e,d = create_keys()
n : 1634
e :  47
d :  293
>>> message = 64
>>> encrypted_message = pow (message, e, n)
>>> encrypted_message
1208
>>> decrypted_message = pow (encrypted_message, d, n)
>>> decrypted_message
140
</code>```

Here, decrypted_message should be equal to message, that is to say, 64. Why is it not working ? Is there a problem in the creation of my keys, or is this another issue ?

Edit:
Thanks @BurningKarl I had indeed forgoten to check if p and q were prime numbers. Here's the new function which replaces generate_integer ()

```<code>def generate_prime_integer ():

    prime= False
    while not prime:
        number= randrange (10,100)
        square_root= int (sqrt (nombre))
        if square_root< sqrt (nombre):
            square_root+= 1
        square_root+= 1

        prime= True
        for i in range (2, square_root):
            if number % i == 0:
                prime = False

    return number
</code>```

With that code it seems to be working properly.

答:
Here is my comment as an answer:

When looking at the RSA Wikipedia page it states:

A user of RSA creates and then publishes a public key based on two large prime numbers, along with an auxiliary value.

So for the encryption to work prime numbers are needed while extended_euclide (p, q, False) only checks whether p and q are comprime, i.e. whether their greatest common divisor is 1.

Body:
I'm working on a Python project which is supposed to encrypt, send and then decrypt messages with RSA. (I precise it's not a professional project)
I've written a small program to create these keys, and I thought it would work however I think there's a problem in my keys.

The keys are created this way :

def generate_integer ():

    i = 0
    number = ""
    number += str(randrange(1,10))
    while i < 1:
        number += str(randrange(0,10))
        i += 1

    return int (number)

def generate_prime_integers ():

    p = generate_integer ()
    q = 0
    premiers = False

    while not prime:
        q = generate_integer ()
        prime = extended_euclide (p, q, False)
        if p == q:
            prime = False

    return p, q

def generate_prime_with_Euler (i_Euler):

    prime_with_Euler = False
    while not prime_with_Euler:
        e = randrange(2,100)
        prime_with_Euler = extended_euclide (e, i_Euler, False)

    return e

def extended_euclide (a,b,calculate_bezout):

    r = a
    u = 1
    v = 0
    r2 = b
    u2 = 0
    v2 = 1
    quotient = 0

    while r2 != 0:
        q = r // r2
        (r, u, v, r2, u2, v2) = (r2, u2, v2, r - q * r2, u - q * u2, v - q * v2)

    prime = False
    if r == 1:
        prime = True

    if calculate_bezout:
        return u
    else:
        return prime

def calculate_d (e, i_Euler):

    u = extended_euclide (e, i_Euler, True)
    return u

def create_keys():
    d = -1
    while d < 0:
        p, q = generate_prime_integers()
        n = p*q
        i_Euler = (p-1) * (q-1)
        e = generate_prime_with_ Euler (i_Euler)
        d = calculate_d (e, i_Euler)

    return n, e, d

A few explanations : e is the encrypting exponent, d is the decrypting exponent, i_Euler is the Phi(n) function.
The function called is create_keys (), it uses all the functions above to create the 2 keys, public and private. I took the function 'extended_euclide' from Wikipedia, because I had no idea how to code the algorithm of Euclide, and modified it a bit so that it either gives me d (when I give True as third parameter) or tells if the two integers are relatively prime (when giving False).

So, the problem is : when I create my keys and try to encrypt/decrypt any value, it's not working

>>> n,e,d = create_keys()
n : 1634
e :  47
d :  293
>>> message = 64
>>> encrypted_message = pow (message, e, n)
>>> encrypted_message
1208
>>> decrypted_message = pow (encrypted_message, d, n)
>>> decrypted_message
140

Here, decrypted_message should be equal to message, that is to say, 64. Why is it not working ? Is there a problem in the creation of my keys, or is this another issue ?

Edit:
Thanks @BurningKarl I had indeed forgoten to check if p and q were prime numbers. Here's the new function which replaces generate_integer ()

def generate_prime_integer ():

    prime= False
    while not prime:
        number= randrange (10,100)
        square_root= int (sqrt (nombre))
        if square_root< sqrt (nombre):
            square_root+= 1
        square_root+= 1

        prime= True
        for i in range (2, square_root):
            if number % i == 0:
                prime = False

    return number

With that code it seems to be working properly.


来源: stackexchange

问:
Make status bar transparent without affecting navigation bar
I have this code that makes the status bar transparent:

```<code>private void setTransparentStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        }
}
</code>```

But this also makes the navigation bar transparent making my views occupy the space under it
like this. Is there any way to make ONLY the status bar transparent?

答:
From styles.xml you can do the following:

```<code><style name="transparent" parent="Theme.AppCompat.Light">//AppCompat is the key; You can choose any other theme than the light-theme, but stick to AppCompat

    <item name="colorPrimaryDark">#00000000</item>//THIS is the important part.
    //Other styling(optional)
</style>
</code>```

What I did was I set colorPrimaryDark to transparent(that is why there are 8 digits instead of 6: transparency is set in the first 2). This sets the color of the statusbar to transparent.

Then to apply it to your layout, simply add the following line in the root layout(view):

```<code>android:theme="@style/transparent"
</code>```

that sets the theme of the layout to the style I showed you above, setting the colorPrimaryDark(the color of the statusbar) to transparent. It still shows things such as the time, notifications, etc, but it has no color.

Now, if you meant hiding the statusbar, you can do it like this:

```<code>    if (Build.VERSION.SDK_INT < 16) {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }
</code>```

Note that setting it to fullscreen in this manner does NOT hide the navbar. To hide the navbar, you have to look into immersive fullscreen mode.

FINAL NOTE

This final note is to make sure I am in the clear:

If you by navigation bar mean the action bar(the bar with app name/other text at the top of the screen, under the status bar), it is not affected by this. To affect the action bar, change colorPrimary.

IMPORTANT NOTE

Even though you set the bar to transparent, if there is nothing to render underneath, it will show the color of the theme(background color) or black(as there is nothing there, it shows black)

ContentLicense: CC BY-SA 3.0

Body:
I have this code that makes the status bar transparent:

private void setTransparentStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        }
}

But this also makes the navigation bar transparent making my views occupy the space under it
like this. Is there any way to make ONLY the status bar transparent?

Body:
From styles.xml you can do the following:

<style name="transparent" parent="Theme.AppCompat.Light">//AppCompat is the key; You can choose any other theme than the light-theme, but stick to AppCompat

    <item name="colorPrimaryDark">#00000000</item>//THIS is the important part.
    //Other styling(optional)
</style>

What I did was I set colorPrimaryDark to transparent(that is why there are 8 digits instead of 6: transparency is set in the first 2). This sets the color of the statusbar to transparent.

Then to apply it to your layout, simply add the following line in the root layout(view):

android:theme="@style/transparent"

that sets the theme of the layout to the style I showed you above, setting the colorPrimaryDark(the color of the statusbar) to transparent. It still shows things such as the time, notifications, etc, but it has no color.

Now, if you meant hiding the statusbar, you can do it like this:

    if (Build.VERSION.SDK_INT < 16) {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

Note that setting it to fullscreen in this manner does NOT hide the navbar. To hide the navbar, you have to look into immersive fullscreen mode.

FINAL NOTE

This final note is to make sure I am in the clear:

If you by navigation bar mean the action bar(the bar with app name/other text at the top of the screen, under the status bar), it is not affected by this. To affect the action bar, change colorPrimary.

IMPORTANT NOTE

Even though you set the bar to transparent, if there is nothing to render underneath, it will show the color of the theme(background color) or black(as there is nothing there, it shows black)


问:
Making Form at Wordpress Template
I'm a self learner so I didnt had anyone to get a clue, I wan't to make a form with POST method and I take w3 tutorial to make one.

PHP Form Validation Example

I successfully make it, and I want to make it included at wordpress theme, so I put those codes at page templates, just like this

```<code><?php
/*
Template Name: Urut Embed
*/
 get_header();
// define variables and set to empty values
$nameErr = $videocodeErr =  $embedurlErr = "";
$name = $videocode = $embed = $embedurl = $embedurut[] = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["name"])) {
        $nameErr = "Name is required";
    } else {
        $name = test_input($_POST["name"]);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
            $nameErr = "Only letters and white space allowed";
        }
    }
    if (empty($_POST["embedurl"])) {
        $embedurl = "";
    } else {
        $embedurl = test_input($_POST["embedurl"]);
        // check if URL address syntax is valid (this regular     expression also allows dashes in the URL)
        if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$embedurl)) {
            $embedurlErr = "Invalid URL";
        }
    }
    if (empty($_POST["videocode"])) {
        $videocode = "";
    } else {
        $videocode = test_input($_POST["videocode"]);
        // check if URL address syntax is valid (this regular expression also allows dashes in the URL)
        if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$videocode)) {
            $videocodeErr = "Invalid URL";
        }
    }
    if (empty($_POST["embed"])) {
        $embed = "";
    } else {
        $embed = test_input($_POST["embed"]);
        if($videocode == "sf"){
            $embedurut = str_replace("http://www.savefile.co/","sf;", $embed);
            $embedurut = str_replace(" savefile.co.",".", $embed);
        } else if($videocode == "mp4"){
            $embedurut = str_replace("https://www.mp4upload.com/"," mp4;", $embed);
        } else if($videocode == "yu"){
            $embedurut = str_replace("https://www.yourupload.com/embed/","yu;", $embed);
        } else if($videocode == "gk"){
            $embedurut = str_replace("|"," - gk;", $embed);
        } else {
            $embedurut = $embed;
        }
        $embedurut = str_replace($name,"", $embedurut);
        $embedurut = explode(PHP_EOL, $embedurut);
        sort($embedurut);
    }
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>
<nav class="navbar navbar-default">
    <div class="container">
        <div class="navbar-header">
            <a href="#" class="navbar-brand">Urut Embed Videocode</a>
        </div>
    </div>
</nav>

<div class="container">
    <form method="post" action="<?php echo htmlspecialchars($_SERVER['REQUEST_URI']);?>">
        <div class="input-group input-group-lg">
            <span class="input-group-addon">Remove Strings</span>
            <input type="text" name="name"  class="form-control" placeholder="Masukkan bagian videocode yang ingin dihilangkan" value="<?php echo $name;?>">
        </div>
        <br>
        <div class="alert alert-dismissable alert-success">
            Check sesuai dengan embed video untuk mengubah link menjadi videocode, none jika tidak ingin mengubah.
        </div>

        <label class="radio-inline"><input type="radio" name="videocode" <?php if (isset($videocode) && $videocode=="none"){ echo "checked"; } else if ($videocode==""){ echo "checked"; } ?> value="none">None</label>
        <label class="radio-inline"><input type="radio" name="videocode" <?php if (isset($videocode) && $videocode=="sf") echo "checked";?> value="sf">SaveFile</label>
        <label class="radio-inline"><input type="radio" name="videocode" <?php if (isset($videocode) && $videocode=="mp4") echo "checked";?> value="mp4">MP4Upload</label>
        <label class="radio-inline"><input type="radio" name="videocode" <?php if (isset($videocode) && $videocode=="yu") echo "checked";?> value="yu">YourUpload</label>
        <label class="radio-inline"><input type="radio" name="videocode" <?php if (isset($videocode) && $videocode=="gk") echo "checked";?> value="gk">gk</label>
        <br><br>

        <span class="label label-primary">
            Embeds
        </span>
        <textarea class="form-control" name="embed" rows="5" cols="150"><?php echo $embed;?></textarea>
        <br>

        <input class="btn btn-success" type="submit" name="submit" value="Submit">
    </form>
    <br>

    <span class="label label-primary">
        Embed Terurut
    </span>
    <textarea class="form-control" name="embed" rows="12" cols="150"><?php
    $alength = count($embedurut);
    for($x = 0; $x < $alength; $x++) {
    echo $embedurut[$x];
    }
    ?></textarea>
</div>
</code>```

But when I ran it, it comes back with 404 page, but with the page url, not 404 url. I dont have any clue at all how to make it work.
Can you guys help me? Sorry for bad English.

Regards

答: Make page from wordpress admin dashboard and call this template and then run the page.</p>

Title: Making Form at Wordpress Template

Body:
I'm a self learner so I didnt had anyone to get a clue, I wan't to make a form with POST method and I take w3 tutorial to make one.

PHP Form Validation Example

I successfully make it, and I want to make it included at wordpress theme, so I put those codes at page templates, just like this

<?php
/*
Template Name: Urut Embed
*/
 get_header();
// define variables and set to empty values
$nameErr = $videocodeErr =  $embedurlErr = "";
$name = $videocode = $embed = $embedurl = $embedurut[] = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["name"])) {
        $nameErr = "Name is required";
    } else {
        $name = test_input($_POST["name"]);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
            $nameErr = "Only letters and white space allowed";
        }
    }
    if (empty($_POST["embedurl"])) {
        $embedurl = "";
    } else {
        $embedurl = test_input($_POST["embedurl"]);
        // check if URL address syntax is valid (this regular     expression also allows dashes in the URL)
        if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$embedurl)) {
            $embedurlErr = "Invalid URL";
        }
    }
    if (empty($_POST["videocode"])) {
        $videocode = "";
    } else {
        $videocode = test_input($_POST["videocode"]);
        // check if URL address syntax is valid (this regular expression also allows dashes in the URL)
        if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$videocode)) {
            $videocodeErr = "Invalid URL";
        }
    }
    if (empty($_POST["embed"])) {
        $embed = "";
    } else {
        $embed = test_input($_POST["embed"]);
        if($videocode == "sf"){
            $embedurut = str_replace("http://www.savefile.co/","sf;", $embed);
            $embedurut = str_replace(" savefile.co.",".", $embed);
        } else if($videocode == "mp4"){
            $embedurut = str_replace("https://www.mp4upload.com/"," mp4;", $embed);
        } else if($videocode == "yu"){
            $embedurut = str_replace("https://www.yourupload.com/embed/","yu;", $embed);
        } else if($videocode == "gk"){
            $embedurut = str_replace("|"," - gk;", $embed);
        } else {
            $embedurut = $embed;
        }
        $embedurut = str_replace($name,"", $embedurut);
        $embedurut = explode(PHP_EOL, $embedurut);
        sort($embedurut);
    }
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>

            Urut Embed Videocode

    <form method="post" action="<?php echo htmlspecialchars($_SERVER['REQUEST_URI']);?>">

            Remove Strings
            <input type="text" name="name"  class="form-control" placeholder="Masukkan bagian videocode yang ingin dihilangkan" value="<?php echo $name;?>">

            Check sesuai dengan embed video untuk mengubah link menjadi videocode, none jika tidak ingin mengubah.

        <input type="radio" name="videocode" <?php if (isset($videocode) && $videocode=="none"){ echo "checked"; } else if ($videocode==""){ echo "checked"; } ?> value="none">None
        <input type="radio" name="videocode" <?php if (isset($videocode) && $videocode=="sf") echo "checked";?> value="sf">SaveFile
        <input type="radio" name="videocode" <?php if (isset($videocode) && $videocode=="mp4") echo "checked";?> value="mp4">MP4Upload
        <input type="radio" name="videocode" <?php if (isset($videocode) && $videocode=="yu") echo "checked";?> value="yu">YourUpload
        <input type="radio" name="videocode" <?php if (isset($videocode) && $videocode=="gk") echo "checked";?> value="gk">gk

            Embeds

        <textarea class="form-control" name="embed" rows="5" cols="150"><?php echo $embed;?></textarea>

        <input class="btn btn-success" type="submit" name="submit" value="Submit">
    </form>

        Embed Terurut

    <textarea class="form-control" name="embed" rows="12" cols="150"><?php
    $alength = count($embedurut);
    for($x = 0; $x < $alength; $x++) {
    echo $embedurut[$x];
    }
    ?></textarea>

But when I ran it, it comes back with 404 page, but with the page url, not 404 url. I dont have any clue at all how to make it work.
Can you guys help me? Sorry for bad English.

Regards


问:
Styling a wordpress widget title
I've been struggling with this problem for a while now. How do I style my widget title to have this horizontal line besides my widget title and not under it. Like so:enter image description here</p>

答:
If you have access to the CSS Editor in WordPress, then just use the pseudo class :after to add that underline beside the widget title.

You can see the working demo here: https://jsfiddle.net/j835Lbg2/3/

/* just an example widget */
.widget {
  height: 300px;
  width: 500px;
  background: #ffffff;
  border: 1px solid #cccccc;
  margin-bottom: 30px;
}

.widget-title {
  position: relative;
  font-family: sans-serif;
  font-weight: bold;
  font-size: 16px;
  color: rgba(0,0,0,0.7);
  padding: 12px 12px;
}

/* widget title text */
.widget-title > .widget_name {
  position: relative;
  background: #ffffff;
  padding: 5px 15px 5px 0px;
  z-index: 1;
}

/* widget underline beside the title */
.widget_dash:after {
  content: "";
  position: absolute;
  display: block;
  left: 20px;
  right: 20px;
  top: 25px;
  border-bottom: 1px solid #cccccc;
  z-index: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="widget">
  <div class="widget-title">
    <span class="widget_name">WIDGET TITLE</span>
    <span class="widget_dash"></span>
  </div>
</div>

<div class="widget">
  <div class="widget-title">
    <span class="widget_name">ANOTHER WIDGET</span>
    <span class="widget_dash"></span>
  </div>
</div></code>```

Let me know if this helps :)

Title: Styling a wordpress widget title

Body:
If you have access to the CSS Editor in WordPress, then just use the pseudo class :after to add that underline beside the widget title.

You can see the working demo here: https://jsfiddle.net/j835Lbg2/3/

/* just an example widget */
.widget {
  height: 300px;
  width: 500px;
  background: #ffffff;
  border: 1px solid #cccccc;
  margin-bottom: 30px;
}

.widget-title {
  position: relative;
  font-family: sans-serif;
  font-weight: bold;
  font-size: 16px;
  color: rgba(0,0,0,0.7);
  padding: 12px 12px;
}

/* widget title text */
.widget-title > .widget_name {
  position: relative;
  background: #ffffff;
  padding: 5px 15px 5px 0px;
  z-index: 1;
}

/* widget underline beside the title */
.widget_dash:after {
  content: "";
  position: absolute;
  display: block;
  left: 20px;
  right: 20px;
  top: 25px;
  border-bottom: 1px solid #cccccc;
  z-index: 0;
}

<div class="widget">
  <div class="widget-title">
    <span class="widget_name">WIDGET TITLE</span>
    <span class="widget_dash"></span>
  </div>
</div>

<div class="widget">
  <div class="widget-title">
    <span class="widget_name">ANOTHER WIDGET</span>
    <span class="widget_dash"></span>
  </div>
</div>

Let me know if this helps :)


问:
How would browser cookies look from TCP server point of view?
So imagine we have TCP server recieving all browser requests. How a cookie generated by some JavaScript function like:

```<code>function writeCookie()
{

var the_cookie = "users_resolution="+ screen.width +"x"+ screen.height;

document.cookie=the_cookie

location = location.href;
}
</code>```

Will loock  if some browser like chrome will come to such server? what will full page requesl look like?

答:
There will be a

```<code>Cookie: users_resolution=1024x768
</code>```

header in the request.

ContentLicense: CC BY-SA 2.5

Body:
So imagine we have TCP server recieving all browser requests. How a cookie generated by some JavaScript function like:

function writeCookie()
{

var the_cookie = "users_resolution="+ screen.width +"x"+ screen.height;

document.cookie=the_cookie

location = location.href;
}

Will loock  if some browser like chrome will come to such server? what will full page requesl look like?

Body:
There will be a

Cookie: users_resolution=1024x768

header in the request.


问:
Javascript + Browser - How to detect when dev tools / firebug is open?
Before anyone of you starts saying it's impossible, please navigate to facebook.com open the devtools, even in non attached mode, and it will tell you that dev tools is opened, right?

So how is facebook able to pull that off?

I am able to do it for attached windows

```<code>window.outerHeight - window.innerHeight > 200 || window.outerWidth - window.innerWidth > 200
</code>```

But when the window is popped up, this doesn't work.

How is facebook able to pull this off?

答:
As @elpddev speculated in the comments, they are just using console.log to log it when the page loads, they are not detecting that you have opened the console.

If you examine the JS code on the page you should find this:

```<code>var j = i.stop || h._("Stop!")
  , k = i.text || h._("This is a browser feature intended for developers. If someone told you to copy-paste something here to enable a Facebook feature or \"hack\" someone's account, it is a scam and will give them access to your Facebook account.")
  , l = i.more || h._("See {url} for more information.", [h.param('url', 'https://www.facebook.com/selfxss')]);
if ((window.chrome || window.safari) && !i.textonly) {
    var m = 'font-family:helvetica; font-size:20px; ';
    [[j, i.c1 || m + 'font-size:50px; font-weight:bold; ' + 'color:red; -webkit-text-stroke:1px black;'], [k, i.c2 || m], [l, i.c3 || m], ['', '']].map(function(s) {
        setTimeout(console.log.bind(console, '\n%c' + s[0], s[1]));
    });
} else {
    var n = ['', ' .d8888b.  888                       888', 'd88P  Y88b 888                       888', 'Y88b.      888                       888', ' "Y888b.   888888  .d88b.  88888b.   888', '    "Y88b. 888    d88""88b 888 "88b  888', '      "888 888    888  888 888  888  Y8P', 'Y88b  d88P Y88b.  Y88..88P 888 d88P', ' "Y8888P"   "Y888  "Y88P"  88888P"   888', '                           888', '                           888', '                           888']
      , o = ('' + k).match(/.{35}.+?\s+|.+$/g)
      , p = Math.floor(Math.max(0, (n.length - o.length) / 2));
    for (var q = 0; q < n.length || q < o.length; q++) {
        var r = n[q];
        n[q] = r + new Array(45 - r.length).join(' ') + (o[q - p] || '');
    }
    console.log('\n\n\n' + n.join('\n') + '\n\n' + l + '\n');
    return;
}
</code>```

It's a little hard to read since it is minified, even with pretty printing. The j = i.stop || h._("Stop!") type stuff appears to be trying to load localized text, falling back to English. It then test to see if they have detected the browser as Chrome or Safari and i.textonly is not set, if so it appears to be displaying it with the fancy styling you get when viewing it in Chrome/Safari. The else clause is harder to follow but it appears to create the ASCII art banner you get in text mode or non-Chrome/Safari browsers:

```<code> .d8888b.  888                       888
d88P  Y88b 888                       888
Y88b.      888                       888    This is a browser feature intended for
 "Y888b.   888888  .d88b.  88888b.   888    developers. If someone told you to copy-paste
    "Y88b. 888    d88""88b 888 "88b  888    something here to enable a Facebook feature
      "888 888    888  888 888  888  Y8P    or "hack" someone's account, it is a
Y88b  d88P Y88b.  Y88..88P 888 d88P         scam and will give them access to your
 "Y8888P"   "Y888  "Y88P"  88888P"   888    Facebook account.
                           888
                           888
                           888

See https://www.facebook.com/selfxss for more information.
</code>```

Body:
Before anyone of you starts saying it's impossible, please navigate to facebook.com open the devtools, even in non attached mode, and it will tell you that dev tools is opened, right?

So how is facebook able to pull that off?

I am able to do it for attached windows

window.outerHeight - window.innerHeight > 200 || window.outerWidth - window.innerWidth > 200

But when the window is popped up, this doesn't work.

How is facebook able to pull this off?

Body:
As @elpddev speculated in the comments, they are just using console.log to log it when the page loads, they are not detecting that you have opened the console.

If you examine the JS code on the page you should find this:

var j = i.stop || h._("Stop!")
  , k = i.text || h._("This is a browser feature intended for developers. If someone told you to copy-paste something here to enable a Facebook feature or \"hack\" someone's account, it is a scam and will give them access to your Facebook account.")
  , l = i.more || h._("See {url} for more information.", [h.param('url', 'https://www.facebook.com/selfxss')]);
if ((window.chrome || window.safari) && !i.textonly) {
    var m = 'font-family:helvetica; font-size:20px; ';
    [[j, i.c1 || m + 'font-size:50px; font-weight:bold; ' + 'color:red; -webkit-text-stroke:1px black;'], [k, i.c2 || m], [l, i.c3 || m], ['', '']].map(function(s) {
        setTimeout(console.log.bind(console, '\n%c' + s[0], s[1]));
    });
} else {
    var n = ['', ' .d8888b.  888                       888', 'd88P  Y88b 888                       888', 'Y88b.      888                       888', ' "Y888b.   888888  .d88b.  88888b.   888', '    "Y88b. 888    d88""88b 888 "88b  888', '      "888 888    888  888 888  888  Y8P', 'Y88b  d88P Y88b.  Y88..88P 888 d88P', ' "Y8888P"   "Y888  "Y88P"  88888P"   888', '                           888', '                           888', '                           888']
      , o = ('' + k).match(/.{35}.+?\s+|.+$/g)
      , p = Math.floor(Math.max(0, (n.length - o.length) / 2));
    for (var q = 0; q < n.length || q < o.length; q++) {
        var r = n[q];
        n[q] = r + new Array(45 - r.length).join(' ') + (o[q - p] || '');
    }
    console.log('\n\n\n' + n.join('\n') + '\n\n' + l + '\n');
    return;
}

It's a little hard to read since it is minified, even with pretty printing. The j = i.stop || h._("Stop!") type stuff appears to be trying to load localized text, falling back to English. It then test to see if they have detected the browser as Chrome or Safari and i.textonly is not set, if so it appears to be displaying it with the fancy styling you get when viewing it in Chrome/Safari. The else clause is harder to follow but it appears to create the ASCII art banner you get in text mode or non-Chrome/Safari browsers:

 .d8888b.  888                       888
d88P  Y88b 888                       888
Y88b.      888                       888    This is a browser feature intended for
 "Y888b.   888888  .d88b.  88888b.   888    developers. If someone told you to copy-paste
    "Y88b. 888    d88""88b 888 "88b  888    something here to enable a Facebook feature
      "888 888    888  888 888  888  Y8P    or "hack" someone's account, it is a
Y88b  d88P Y88b.  Y88..88P 888 d88P         scam and will give them access to your
 "Y8888P"   "Y888  "Y88P"  88888P"   888    Facebook account.
                           888
                           888
                           888

See https://www.facebook.com/selfxss for more information.


问:
Facebook PHP SDK: Cannot get Access Token from JavascriptHelper Class
I have am using FB's Javascript SDK on the client and PHP SDK on the server.
I can see when I use getSignedRequest() I get the signed request containing the code property and  the correct userId. However for the life in me I can't figure out how to go on to use this signedRequest to obtain a valid access token which I can use to create further calls for things like user information. I have tried querying for the access code by attempting to instantiate a signed request or calling the ->getAccessToken() method on the $facebook object as well as the jsHelper object but nothing is returned to me. Here's my code:

```<code>require_once 'src/autoload.php';
 $facebook = new Facebook\Facebook([
    'app_id' => $AppId,
   'app_secret' => $AppSecret,
   'default_graph_version' => 'v2.8',
 ]);

$jsHelper = $facebook->getJavaScriptHelper();
$signedRequest = $jsHelper->getSignedRequest();

if ($signedRequest) {

try {
  $codeField = $signedRequest->get('code');

  $g = $facebook->getAccessToken();
  //I would hope this would be the access token, but sadly it's an empty
     value.
  error_log($g);

 } catch(Facebook\Exceptions\FacebookResponseException $e) {
 error_log("fbResp Ex: ". $e->getMessage());
 exit;
 } catch(Facebook\Exceptions\FacebookSDKException $e) {
  error_log("SDK Ex: ". $e->getMessage());

  exit;
</code>```

}

答:
I never used JavaScriptHelper but AccessToken comes from helper not Facebook object itself. Try

```<code> $g = $jsHelper->getAccessToken();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have am using FB's Javascript SDK on the client and PHP SDK on the server.
I can see when I use getSignedRequest() I get the signed request containing the code property and  the correct userId. However for the life in me I can't figure out how to go on to use this signedRequest to obtain a valid access token which I can use to create further calls for things like user information. I have tried querying for the access code by attempting to instantiate a signed request or calling the ->getAccessToken() method on the $facebook object as well as the jsHelper object but nothing is returned to me. Here's my code:

require_once 'src/autoload.php';
 $facebook = new Facebook\Facebook([
    'app_id' => $AppId,
   'app_secret' => $AppSecret,
   'default_graph_version' => 'v2.8',
 ]);

$jsHelper = $facebook->getJavaScriptHelper();
$signedRequest = $jsHelper->getSignedRequest();

if ($signedRequest) {

try {
  $codeField = $signedRequest->get('code');

  $g = $facebook->getAccessToken();
  //I would hope this would be the access token, but sadly it's an empty
     value.
  error_log($g);

 } catch(Facebook\Exceptions\FacebookResponseException $e) {
 error_log("fbResp Ex: ". $e->getMessage());
 exit;
 } catch(Facebook\Exceptions\FacebookSDKException $e) {
  error_log("SDK Ex: ". $e->getMessage());

  exit;

}

Body:
I never used JavaScriptHelper but AccessToken comes from helper not Facebook object itself. Try

 $g = $jsHelper->getAccessToken();


问:
cannot export to csv using pdo
I am retrieving data from the database and downloading the data into a csv file. the functionality is working as expected, however the csv file that is being downloaded also contains the page source code, I do not know why this is happening and have been trying for a long time. I hope someone can help me with this. below is the source code:

```<code>public function exportSalesCsv()
{

$conn = new PDO('mysql:host=' . config::get('mysql/host') . ';dbname=' . config::get('mysql/db'), config::get('mysql/username'), config::get('mysql/password'));
$sql = "SELECT
            CONCAT(u.name, ' ', u.surname) AS salesPerson,
            t.initiation_timestamp AS saleDate,
            t.customer_account_id AS customerAccount,
            tt.transaction_type AS transactionType,
            r.resource_unique_value AS soldResource,
            CONCAT(rb.resource_brand,
                    ' ',
                    rm.resource_model,
                    ' ',
                    rt.resource_type) AS resourceModel,
            r.voucher_value_id as value
        FROM
            ims.transactions t
                INNER JOIN
            ims.resources r ON t.resource_id = r.resource_id
                INNER JOIN
            ims.resource_models rm ON r.resource_model_id = rm.resource_model_id
                INNER JOIN
            ims.resource_brands rb ON rm.resource_brand_id = rb.resource_brand_id
                INNER JOIN
            ims.resource_types rt ON rm.resource_type_id = rt.resource_type_id
                INNER JOIN
            ims.users u ON t.uid = u.uid
                INNER JOIN
            ims.transaction_types tt ON t.transaction_type_id = tt.transaction_type_id
        WHERE
            t.transaction_type_id = 3
                AND YEAR(t.initiation_timestamp) = YEAR(CURDATE())
        UNION SELECT
            CONCAT(u.name, ' ', u.surname) AS salesPerson,
            o.closing_timestamp AS saleDate,
            o.customer_id AS customerAccount,
            tt.transaction_type AS transactionType,
            r.resource_unique_value AS soldResource,
            CONCAT(rb.resource_brand,
                    ' ',
                    rm.resource_model,
                    ' ',
                    rt.resource_type) AS resourceModel,
            r.voucher_value_id as value
        FROM
            orders o
                INNER JOIN
            ims.users u ON o.initiation_uid = u.uid
                INNER JOIN
            ims.transaction_types tt ON o.order_type_id = tt.transaction_type_id
                INNER JOIN
            ims.resources r ON o.resource_id = r.resource_id
                INNER JOIN
            ims.resource_models rm ON r.resource_model_id = rm.resource_model_id
                INNER JOIN
            ims.resource_brands rb ON rm.resource_brand_id = rb.resource_brand_id
                INNER JOIN
            ims.resource_types rt ON rm.resource_type_id = rt.resource_type_id
        WHERE
            o.order_type_id = 4
                AND order_status_id = 1
                AND YEAR(o.closing_timestamp) = YEAR(CURDATE())";
$results = $conn->query($sql);

$response = implode(",", array('salesPerson','saleDate','customerAccount','transactionType','soldResource','resourceModel','value'));
$response .= "\n";

foreach($results as $row)
{
    $response .= implode(",",array($row['salesPerson'], $row['saleDate'], $row['customerAccount'], $row['transactionType'], $row['soldResource'], $row['resourceModel'], $row[escape('value')]));
    $response .= "\n";
}

header('Content-type: text/csv');
header('Content-disposition: attachment;filename=salesExport.csv');

echo $response;

return;
</code>```

}

The following screenshot explains what I mean: Click Here

And here is how I am invoking the method:

```<code><?php
require_once 'core/init.php';
include_once ("header.php");

if ($user->isLoggedIn()){

//check if user has permission
if ($user->hasPermission('reports') || $user->hasPermission('allAccess')){

    $inventory = new inventory();

    if(isset($_POST['exportSalesCsv'])){

        $inventory->exportSalesCsv();

    }...
</code>```

答:
Your script only saves the file to disk and is populated with data, but it is not return in the response of call

One solution if the created file is accessible by apache/nginx server you could redirect to it. Add this to the end of your function.

```<code>header('Location: ' . $url_to_file);
return;
</code>```

Another solution is not to print to file but write to a variable and return it with the headers for returning a CSV file, so that the browser interprets it as a csv file:

```<code>$results = $conn->query($sql);

$response = implode(",", array('salesPerson','saleDate','customerAccount','transactionType','soldResource'));
$response .= "\n";

foreach($results as $row)
{
    $response .= implode(",",array($row['salesPerson'], $row['saleDate'], $row['customerAccount'], $row['transactionType'], $row['soldResource']));
    $response .= "\n";
}

header('Content-type: text/csv');
header('Content-disposition: attachment;filename=' . strtotime("now") . '.csv');

echo $response;

return;
</code>```

Title: cannot export to csv using pdo

Body:
I am retrieving data from the database and downloading the data into a csv file. the functionality is working as expected, however the csv file that is being downloaded also contains the page source code, I do not know why this is happening and have been trying for a long time. I hope someone can help me with this. below is the source code:

public function exportSalesCsv()
{

$conn = new PDO('mysql:host=' . config::get('mysql/host') . ';dbname=' . config::get('mysql/db'), config::get('mysql/username'), config::get('mysql/password'));
$sql = "SELECT
            CONCAT(u.name, ' ', u.surname) AS salesPerson,
            t.initiation_timestamp AS saleDate,
            t.customer_account_id AS customerAccount,
            tt.transaction_type AS transactionType,
            r.resource_unique_value AS soldResource,
            CONCAT(rb.resource_brand,
                    ' ',
                    rm.resource_model,
                    ' ',
                    rt.resource_type) AS resourceModel,
            r.voucher_value_id as value
        FROM
            ims.transactions t
                INNER JOIN
            ims.resources r ON t.resource_id = r.resource_id
                INNER JOIN
            ims.resource_models rm ON r.resource_model_id = rm.resource_model_id
                INNER JOIN
            ims.resource_brands rb ON rm.resource_brand_id = rb.resource_brand_id
                INNER JOIN
            ims.resource_types rt ON rm.resource_type_id = rt.resource_type_id
                INNER JOIN
            ims.users u ON t.uid = u.uid
                INNER JOIN
            ims.transaction_types tt ON t.transaction_type_id = tt.transaction_type_id
        WHERE
            t.transaction_type_id = 3
                AND YEAR(t.initiation_timestamp) = YEAR(CURDATE())
        UNION SELECT
            CONCAT(u.name, ' ', u.surname) AS salesPerson,
            o.closing_timestamp AS saleDate,
            o.customer_id AS customerAccount,
            tt.transaction_type AS transactionType,
            r.resource_unique_value AS soldResource,
            CONCAT(rb.resource_brand,
                    ' ',
                    rm.resource_model,
                    ' ',
                    rt.resource_type) AS resourceModel,
            r.voucher_value_id as value
        FROM
            orders o
                INNER JOIN
            ims.users u ON o.initiation_uid = u.uid
                INNER JOIN
            ims.transaction_types tt ON o.order_type_id = tt.transaction_type_id
                INNER JOIN
            ims.resources r ON o.resource_id = r.resource_id
                INNER JOIN
            ims.resource_models rm ON r.resource_model_id = rm.resource_model_id
                INNER JOIN
            ims.resource_brands rb ON rm.resource_brand_id = rb.resource_brand_id
                INNER JOIN
            ims.resource_types rt ON rm.resource_type_id = rt.resource_type_id
        WHERE
            o.order_type_id = 4
                AND order_status_id = 1
                AND YEAR(o.closing_timestamp) = YEAR(CURDATE())";
$results = $conn->query($sql);

$response = implode(",", array('salesPerson','saleDate','customerAccount','transactionType','soldResource','resourceModel','value'));
$response .= "\n";

foreach($results as $row)
{
    $response .= implode(",",array($row['salesPerson'], $row['saleDate'], $row['customerAccount'], $row['transactionType'], $row['soldResource'], $row['resourceModel'], $row[escape('value')]));
    $response .= "\n";
}

header('Content-type: text/csv');
header('Content-disposition: attachment;filename=salesExport.csv');

echo $response;

return;

}

The following screenshot explains what I mean: Click Here

And here is how I am invoking the method:

<?php
require_once 'core/init.php';
include_once ("header.php");

if ($user->isLoggedIn()){

//check if user has permission
if ($user->hasPermission('reports') || $user->hasPermission('allAccess')){

    $inventory = new inventory();

    if(isset($_POST['exportSalesCsv'])){

        $inventory->exportSalesCsv();

    }...

Body:
Your script only saves the file to disk and is populated with data, but it is not return in the response of call

One solution if the created file is accessible by apache/nginx server you could redirect to it. Add this to the end of your function.

header('Location: ' . $url_to_file);
return;

Another solution is not to print to file but write to a variable and return it with the headers for returning a CSV file, so that the browser interprets it as a csv file:

$results = $conn->query($sql);

$response = implode(",", array('salesPerson','saleDate','customerAccount','transactionType','soldResource'));
$response .= "\n";

foreach($results as $row)
{
    $response .= implode(",",array($row['salesPerson'], $row['saleDate'], $row['customerAccount'], $row['transactionType'], $row['soldResource']));
    $response .= "\n";
}

header('Content-type: text/csv');
header('Content-disposition: attachment;filename=' . strtotime("now") . '.csv');

echo $response;

return;


问:
c++ condition variable notification not working as expected
I'm trying to launch new threads as soon as work in previous worker_thread has started, but maybe ended or not. I've replaced started and ended work with time delays. My code is:

```<code>#include <iostream>
#include <string>
#include <mutex>
#include <condition_variable>
#include <future>
#include <atomic>
#include <chrono>
#include <thread>

std::mutex m;
std::condition_variable cv;
bool started = false;

void worker_thread()
{
    std::unique_lock<std::mutex> lk(m);

    static std::atomic<int> count(1);
    std::this_thread::sleep_for(std::chrono::milliseconds{(count % 5) * 100});
    std::cerr << "Start Worker thread: " << count << "\n";

    started = true;
    lk.unlock();
    cv.notify_one();

    std::this_thread::sleep_for(std::chrono::milliseconds{3000});
    std::cerr << "Exit Worker thread: " << count << "\n";
    ++count;
}

int main()
{
    while(1) {
        std::async(std::launch::async, worker_thread);
        std::unique_lock<std::mutex> lk(m);
        cv.wait(lk, []{return started;});
        started = false;
    }
}
</code>```

The output looks like that:

```<code>Start Worker thread: 1
Exit Worker thread: 1
Start Worker thread: 2
Exit Worker thread: 2
Start Worker thread: 3
Exit Worker thread: 3
Start Worker thread: 4
Exit Worker thread: 4
Start Worker thread: 5
Exit Worker thread: 5
</code>```

which isn't the behavior I wanted. What I wanted was something like (not exactly) this:

```<code>Start Worker thread: 1
Start Worker thread: 2
Start Worker thread: 3
Start Worker thread: 4
Exit Worker thread: 1
Exit Worker thread: 3
Exit Worker thread: 4
Exit Worker thread: 2
Start Worker thread: 5
Exit Worker thread: 5
</code>```

Currently the next thread is only started when work is finished in previous thread. But I want to start next thread as soon as work is started in previous thread and not wait for it's end, only wait for start.

答:
std::async returns a std::future holding result of function execution. In your case, it is a temporary object which is immideatly destroyed. The documentation for std::future says:

these actions will not block for the shared state to become ready, except that it may block if all of the following are true:

✔ the shared state was created by a call to std::async

✔ the shared state is not yet ready

✔ this was the last reference to the shared state

All of those are true, so destruction of that future will block until worker function will finish executing.

You can create detached thread to avoid this problem:

```<code>std::thread(worker_thread).detach();
</code>```

Body:
I'm trying to launch new threads as soon as work in previous worker_thread has started, but maybe ended or not. I've replaced started and ended work with time delays. My code is:

#include <iostream>
#include <string>
#include <mutex>
#include <condition_variable>
#include <future>
#include <atomic>
#include <chrono>
#include <thread>

std::mutex m;
std::condition_variable cv;
bool started = false;

void worker_thread()
{
    std::unique_lock<std::mutex> lk(m);

    static std::atomic<int> count(1);
    std::this_thread::sleep_for(std::chrono::milliseconds{(count % 5) * 100});
    std::cerr << "Start Worker thread: " << count << "\n";

    started = true;
    lk.unlock();
    cv.notify_one();

    std::this_thread::sleep_for(std::chrono::milliseconds{3000});
    std::cerr << "Exit Worker thread: " << count << "\n";
    ++count;
}

int main()
{
    while(1) {
        std::async(std::launch::async, worker_thread);
        std::unique_lock<std::mutex> lk(m);
        cv.wait(lk, []{return started;});
        started = false;
    }
}

The output looks like that:

Start Worker thread: 1
Exit Worker thread: 1
Start Worker thread: 2
Exit Worker thread: 2
Start Worker thread: 3
Exit Worker thread: 3
Start Worker thread: 4
Exit Worker thread: 4
Start Worker thread: 5
Exit Worker thread: 5

which isn't the behavior I wanted. What I wanted was something like (not exactly) this:

Start Worker thread: 1
Start Worker thread: 2
Start Worker thread: 3
Start Worker thread: 4
Exit Worker thread: 1
Exit Worker thread: 3
Exit Worker thread: 4
Exit Worker thread: 2
Start Worker thread: 5
Exit Worker thread: 5

Currently the next thread is only started when work is finished in previous thread. But I want to start next thread as soon as work is started in previous thread and not wait for it's end, only wait for start.

Body:
std::async returns a std::future holding result of function execution. In your case, it is a temporary object which is immideatly destroyed. The documentation for std::future says:

these actions will not block for the shared state to become ready, except that it may block if all of the following are true:

✔ the shared state was created by a call to std::async

✔ the shared state is not yet ready

✔ this was the last reference to the shared state

All of those are true, so destruction of that future will block until worker function will finish executing.

You can create detached thread to avoid this problem:

std::thread(worker_thread).detach();


问:
Crash in tableView with CABasicAnimation, textColor when the TableViewCell is not visible
The application is a satisfaction survey that all the fields must be filled by people. I used a tableView and I would like, when a field is not filled, that it scrolls automatically to the field, that it put the tableviewcell in red, and that it shake the tableviewcell. I found all that but the problem is that it seems that it crash when the cell is not on the screen (may be because of the fact that the cell is not visible on the screen).

May be I have to do something to wait for the cell is visible first. How can I do that ?

```<code>    let cellPb = self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))

    self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Top, animated: false)
    //color
    cellPb!.textLabel!.textColor = UIColor.redColor()

    //shake the cell
    let shake = CABasicAnimation(keyPath: "position")
    shake.duration = 0.1
    shake.repeatCount = 3
    shake.autoreverses = true
    shake.fromValue = NSValue(CGPoint: CGPointMake(cellPb!.center.x - 5, cellPb!.center.y))
    shake.toValue = NSValue(CGPoint: CGPointMake(cellPb!.center.x + 5, cellPb!.center.y))
    cellPb!.layer.addAnimation(shake, forKey: "position")

 UIAlertView(title: "Please, fill the blank field.", message: nil, delegate: nil, cancelButtonTitle: "Ok").show()
</code>```

答:
```<code>cellPb!.textLabel!.textColor = UIColor.redColor()
</code>```

Above line forcefully unwrap the value. that's why it will crash. so use
if let this is safe way to unwrap any value

Try this code

```<code>       if let cellPb = self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 1, inSection: 0)) {
            //color
            cellPb.textLabel!.textColor = UIColor.redColor()

            //shake the cell
            let shake = CABasicAnimation(keyPath: "position")
            shake.duration = 0.1
            shake.repeatCount = 3
            shake.autoreverses = true
            shake.fromValue = NSValue(CGPoint: CGPointMake(cellPb!.center.x - 5, cellPb!.center.y))
            shake.toValue = NSValue(CGPoint: CGPointMake(cellPb!.center.x + 5, cellPb!.center.y))
            cellPb.layer.addAnimation(shake, forKey: "position")

            UIAlertView(title: "Please, fill the blank field.", message: nil, delegate: nil, cancelButtonTitle: "Ok").show()
        } else {
             self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 1, inSection: 0), atScrollPosition: .Top, animated: false)
        }
</code>```

Body:
The application is a satisfaction survey that all the fields must be filled by people. I used a tableView and I would like, when a field is not filled, that it scrolls automatically to the field, that it put the tableviewcell in red, and that it shake the tableviewcell. I found all that but the problem is that it seems that it crash when the cell is not on the screen (may be because of the fact that the cell is not visible on the screen).

May be I have to do something to wait for the cell is visible first. How can I do that ?

    let cellPb = self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))

    self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Top, animated: false)
    //color
    cellPb!.textLabel!.textColor = UIColor.redColor()

    //shake the cell
    let shake = CABasicAnimation(keyPath: "position")
    shake.duration = 0.1
    shake.repeatCount = 3
    shake.autoreverses = true
    shake.fromValue = NSValue(CGPoint: CGPointMake(cellPb!.center.x - 5, cellPb!.center.y))
    shake.toValue = NSValue(CGPoint: CGPointMake(cellPb!.center.x + 5, cellPb!.center.y))
    cellPb!.layer.addAnimation(shake, forKey: "position")

 UIAlertView(title: "Please, fill the blank field.", message: nil, delegate: nil, cancelButtonTitle: "Ok").show()

Body:
cellPb!.textLabel!.textColor = UIColor.redColor()

Above line forcefully unwrap the value. that's why it will crash. so use
if let this is safe way to unwrap any value

Try this code

       if let cellPb = self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 1, inSection: 0)) {
            //color
            cellPb.textLabel!.textColor = UIColor.redColor()

            //shake the cell
            let shake = CABasicAnimation(keyPath: "position")
            shake.duration = 0.1
            shake.repeatCount = 3
            shake.autoreverses = true
            shake.fromValue = NSValue(CGPoint: CGPointMake(cellPb!.center.x - 5, cellPb!.center.y))
            shake.toValue = NSValue(CGPoint: CGPointMake(cellPb!.center.x + 5, cellPb!.center.y))
            cellPb.layer.addAnimation(shake, forKey: "position")

            UIAlertView(title: "Please, fill the blank field.", message: nil, delegate: nil, cancelButtonTitle: "Ok").show()
        } else {
             self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 1, inSection: 0), atScrollPosition: .Top, animated: false)
        }


问:
csv to json with column data that needs to be grouped
I have a CSV file in a format similar to this

```<code>order_id, customer_name, item_1_id, item_1_quantity, Item_2_id, Item_2_quantity, Item_3_id, Item_3_quantity
1,        John,          4,         1,               24,        4,               16,        1
2,        Paul,          8,         3,               41,        1,               33,        1
3,        Andrew,        1,         1,               34,        4,               8,          2
</code>```

I want to export to json, currently I am doing this.

```<code>df = pd.read_csv('simple.csv')
print ( df.to_json(orient = 'records') )
</code>```

And the output is

```<code>[
    {
        "Item_2_id": 24,
        "Item_2_quantity": 4,
        "Item_3_id": 16,
        "Item_3_quantity": 1,
        "customer_name": "John",
        "item_1_id": 4,
        "item_1_quantity": 1,
        "order_id": 1
    },
......
</code>```

However, I would like the output to be

```<code>[
    {
        "customer_name": "John",
        "order_id": 1,
        "items": [
            { "id": 4, "quantity": 1 },
            { "id": 24, "quantity": 4 },
            { "id": 16, "quantity": 1 },
         ]
    },
......
</code>```

Any suggestions on a good way to do this?

In this particular project, there will not be more than 5 times per order

答:
Source DF:

```<code>In [168]: df
Out[168]:
   order_id customer_name  item_1_id  item_1_quantity  Item_2_id  Item_2_quantity  Item_3_id  Item_3_quantity
0         1          John          4                1         24                4         16                1
1         2          Paul          8                3         41                1         33                1
2         3        Andrew          1                1         34                4          8                2
</code>```

Solution:

```<code>In [169]: %paste
import re

x = df[['order_id','customer_name']].copy()
x['id'] = \
    pd.Series(df.loc[:, df.columns.str.contains(r'item_.*?_id',
                                                flags=re.I)].values.tolist(),
              index=df.index)
x['quantity'] = \
    pd.Series(df.loc[:, df.columns.str.contains(r'item_.*?_quantity',
                                                flags=re.I)].values.tolist(),
              index=df.index)
x.to_json(orient='records')
## -- End pasted text --
Out[169]: '[{"order_id":1,"customer_name":"John","id":[4,24,16],"quantity":[1,4,1]},{"order_id":2,"customer_name":"Paul","id":[8,41,33],"qua
ntity":[3,1,1]},{"order_id":3,"customer_name":"Andrew","id":[1,34,8],"quantity":[1,4,2]}]'
</code>```

Intermediate helper DF:

```<code>In [82]: x
Out[82]:
   order_id customer_name           id   quantity
0         1          John  [4, 24, 16]  [1, 4, 1]
1         2          Paul  [8, 41, 33]  [3, 1, 1]
2         3        Andrew   [1, 34, 8]  [1, 4, 2]
</code>```

Body:
I have a CSV file in a format similar to this

order_id, customer_name, item_1_id, item_1_quantity, Item_2_id, Item_2_quantity, Item_3_id, Item_3_quantity
1,        John,          4,         1,               24,        4,               16,        1
2,        Paul,          8,         3,               41,        1,               33,        1
3,        Andrew,        1,         1,               34,        4,               8,          2

I want to export to json, currently I am doing this.

df = pd.read_csv('simple.csv')
print ( df.to_json(orient = 'records') )

And the output is

[
    {
        "Item_2_id": 24,
        "Item_2_quantity": 4,
        "Item_3_id": 16,
        "Item_3_quantity": 1,
        "customer_name": "John",
        "item_1_id": 4,
        "item_1_quantity": 1,
        "order_id": 1
    },
......

However, I would like the output to be

[
    {
        "customer_name": "John",
        "order_id": 1,
        "items": [
            { "id": 4, "quantity": 1 },
            { "id": 24, "quantity": 4 },
            { "id": 16, "quantity": 1 },
         ]
    },
......

Any suggestions on a good way to do this?

In this particular project, there will not be more than 5 times per order

Body:
Source DF:

In [168]: df
Out[168]:
   order_id customer_name  item_1_id  item_1_quantity  Item_2_id  Item_2_quantity  Item_3_id  Item_3_quantity
0         1          John          4                1         24                4         16                1
1         2          Paul          8                3         41                1         33                1
2         3        Andrew          1                1         34                4          8                2

Solution:

In [169]: %paste
import re

x = df[['order_id','customer_name']].copy()
x['id'] = \
    pd.Series(df.loc[:, df.columns.str.contains(r'item_.*?_id',
                                                flags=re.I)].values.tolist(),
              index=df.index)
x['quantity'] = \
    pd.Series(df.loc[:, df.columns.str.contains(r'item_.*?_quantity',
                                                flags=re.I)].values.tolist(),
              index=df.index)
x.to_json(orient='records')
## -- End pasted text --
Out[169]: '[{"order_id":1,"customer_name":"John","id":[4,24,16],"quantity":[1,4,1]},{"order_id":2,"customer_name":"Paul","id":[8,41,33],"qua
ntity":[3,1,1]},{"order_id":3,"customer_name":"Andrew","id":[1,34,8],"quantity":[1,4,2]}]'

Intermediate helper DF:

In [82]: x
Out[82]:
   order_id customer_name           id   quantity
0         1          John  [4, 24, 16]  [1, 4, 1]
1         2          Paul  [8, 41, 33]  [3, 1, 1]
2         3        Andrew   [1, 34, 8]  [1, 4, 2]


问:
Capitalizing words in a string using C#
I need to take a string, and capitalize words in it. Certain words ("in", "at", etc.), are not capitalized and are changed to lower case if encountered. The first word should always be capitalized. Last names like "McFly" are not in the current scope, so the same rule will apply to them - only first letter capitalized.

For example: "of mice and men By CNN" should be changed to "Of Mice and Men by CNN". (Therefore ToTitleString won't work here.)

What would be the best way to do that?

I thought of splitting the string by spaces, and go over each word, changing it if necessary, and concatenating it to the previous word, and so on.
It seems pretty naive and I was wondering if there's a better way to do it. I am using .NET 3.5.

答:
Try something like this:

```<code>public static string TitleCase(string input, params string[] dontCapitalize) {
   var split = input.Split(' ');
   for(int i = 0; i < split.Length; i++)
        split[i] = i == 0
          ? CapitalizeWord(split[i])
          : dontCapitalize.Contains(split[i])
             ? split[i]
             : CapitalizeWord(split[i]);
   return string.Join(" ", split);
}
public static string CapitalizeWord(string word)
{
    return char.ToUpper(word[0]) + word.Substring(1);
}
</code>```

You can then later update the CapitalizeWord method if you need to handle complex surnames.
Add those methods to a class and use it like this:

```<code>SomeClass.TitleCase("a test is a sentence", "is", "a"); // returns "A Test is a Sentence"
</code>```

Title: Capitalizing words in a string using C#

Body:
Try something like this:

public static string TitleCase(string input, params string[] dontCapitalize) {
   var split = input.Split(' ');
   for(int i = 0; i < split.Length; i++)
        split[i] = i == 0
          ? CapitalizeWord(split[i])
          : dontCapitalize.Contains(split[i])
             ? split[i]
             : CapitalizeWord(split[i]);
   return string.Join(" ", split);
}
public static string CapitalizeWord(string word)
{
    return char.ToUpper(word[0]) + word.Substring(1);
}

You can then later update the CapitalizeWord method if you need to handle complex surnames.
Add those methods to a class and use it like this:

SomeClass.TitleCase("a test is a sentence", "is", "a"); // returns "A Test is a Sentence"


问:
Regular expression to find large numbers in word form
I'm trying to extract numbers in word form from a string. For example, an input string might be something like:

```<code>"What is 3 million 6 hundred 5 divided by 5 hundred?"
</code>```

From this input, I'd like to figure out how to get the two numbers as groups.

```<code>["3 million 6 hundred 5", "5 hundred"]
</code>```

Note: It is possible that there could be more numbers found in other input strings.

I believe regex is the correct route to solve this problem. Ideally I could pass in a list of the scales such as:

```<code>["hundred", "thousand", "million", "billion", ...]
</code>```

So far this is what I have:

```<code>scales= ["hundred", "thousand", "million", "billion"]
scale_pattern = '|'.join(scales)
regex = re.compile('\b(d+' + scale_pattern + 'd+)+\b')
</code>```

I know my pattern isn't quite right, the psudeocode for what I'm going for is:

```<code>for any number of the following occurrences:
    find the pattern [int word_from_list optional_int]
</code>```

答:
Well, below is an inferior parser.</p>

```<code># you should expand these lists later...
units = ["hundred", "thousand", "million", "billion"]
operations = ['divided', 'multiplied']
delims = ['by', 'with']
discards = ['?', '!', '.']

sentence = 'What is 3 million 6 hundred 5 divided by 5 hundred?'

filterd_sentence = sentence
for t in discards:
    filterd_sentence = filterd_sentence.replace(t, '')

filterd_t = []
buffer = ''
for t in filterd_sentence.split(' '):
    if t.isnumeric() or t in units:
        buffer += t + ' '
    elif t in operations or t in delims:
        if buffer != '':
            filterd_t.append(buffer[:len(buffer)-1])
            buffer = ''

if buffer != '':
    filterd_t.append(buffer[:len(buffer)-1])

print(filterd_t)
# ['3 million 6 hundred 5', '5 hundred']
</code>```

Body:
I'm trying to extract numbers in word form from a string. For example, an input string might be something like:

"What is 3 million 6 hundred 5 divided by 5 hundred?"

From this input, I'd like to figure out how to get the two numbers as groups.

["3 million 6 hundred 5", "5 hundred"]

Note: It is possible that there could be more numbers found in other input strings.

I believe regex is the correct route to solve this problem. Ideally I could pass in a list of the scales such as:

["hundred", "thousand", "million", "billion", ...]

So far this is what I have:

scales= ["hundred", "thousand", "million", "billion"]
scale_pattern = '|'.join(scales)
regex = re.compile('\b(d+' + scale_pattern + 'd+)+\b')

I know my pattern isn't quite right, the psudeocode for what I'm going for is:

for any number of the following occurrences:
    find the pattern [int word_from_list optional_int]

Body:
Well, below is an inferior parser.

# you should expand these lists later...
units = ["hundred", "thousand", "million", "billion"]
operations = ['divided', 'multiplied']
delims = ['by', 'with']
discards = ['?', '!', '.']

sentence = 'What is 3 million 6 hundred 5 divided by 5 hundred?'

filterd_sentence = sentence
for t in discards:
    filterd_sentence = filterd_sentence.replace(t, '')

filterd_t = []
buffer = ''
for t in filterd_sentence.split(' '):
    if t.isnumeric() or t in units:
        buffer += t + ' '
    elif t in operations or t in delims:
        if buffer != '':
            filterd_t.append(buffer[:len(buffer)-1])
            buffer = ''

if buffer != '':
    filterd_t.append(buffer[:len(buffer)-1])

print(filterd_t)
# ['3 million 6 hundred 5', '5 hundred']


问:
Toolbar haven't the full size
Hey Guys I want to make a Custom Toolbar. I tried so many things but nothing works.... So I have this in my manifest.xml:

```<code><application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true">
    <activity android:name=".HomeActivity"
        android:theme="@style/Theme.AppCompat.Light.NoActionBar">
        <!--android:theme="@style/HomeActionBar">-->
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
</code>```

And here my activity_home.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_home"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.iiiii.iiiii.HomeActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/my_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="enterAlways|scroll" />

</android.support.design.widget.CoordinatorLayout>```

But look! I didn't get the full size of the ActionBar:

答:
Remove CoordinatorLayout's padding attributes.

Replace your XML with this:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_home"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.iiiii.iiiii.HomeActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/my_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="enterAlways|scroll" />

</android.support.design.widget.CoordinatorLayout>
</code>```

Title: Toolbar haven't the full size

Body:
Hey Guys I want to make a Custom Toolbar. I tried so many things but nothing works.... So I have this in my manifest.xml:

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true">
    <activity android:name=".HomeActivity"
        android:theme="@style/Theme.AppCompat.Light.NoActionBar">

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

And here my activity_home.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_home"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.iiiii.iiiii.HomeActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/my_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="enterAlways|scroll" />

</android.support.design.widget.CoordinatorLayout>

But look! I didn't get the full size of the ActionBar:

Body:
Remove CoordinatorLayout's padding attributes.

Replace your XML with this:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_home"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.iiiii.iiiii.HomeActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/my_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="enterAlways|scroll" />

</android.support.design.widget.CoordinatorLayout>


问:
How to switch class for div using js?
I've done this using jquery, but can't do it with js.

Look at my code:

https:// jsfiddle. net/88pd6zj0/

It's working only with first class = "html", but not working with another.
I've tried change "querySelector" on "querySelectorAll" - and it's working no one class.

How to fix this problem?
Thank you.

答:
Here is the sample to switch class

```<code>var icon = document.querySelectorAll(".buttons div");
for (var i = 0; i < icon.length; i++) {
  icon[i].addEventListener("click", function(event) {
    event.preventDefault();
    if(this.className.includes("active")){
      this.classList.remove("active");
    } else {
      this.classList.add("active");
    }
  });
}
</code>```

Here is the working jsfiddle :
https://jsfiddle.net/88pd6zj0/3/

Title: How to switch class for div using js?

Body:
Here is the sample to switch class

var icon = document.querySelectorAll(".buttons div");
for (var i = 0; i < icon.length; i++) {
  icon[i].addEventListener("click", function(event) {
    event.preventDefault();
    if(this.className.includes("active")){
      this.classList.remove("active");
    } else {
      this.classList.add("active");
    }
  });
}

Here is the working jsfiddle :
https://jsfiddle.net/88pd6zj0/3/


问:
QMediaPlayer duration() returns 0 always
I use Qt 5.7
I'm writing Music Player, and have one problem. Method duration() of QMediaPlayer always returns 0. How can I fix it?

Example of code:

```<code>QMediaPlayer *player = new QMediaPlayer;
player->setMedia(QMediaContent(QUrl(path)));
qDebug() << player->duration(); // returns 0
player->play(); // it works
</code>```

答:
You cannot do a player->duration() right after the player->setMedia(QMediaContent(QUrl(path)));.

Indeed, the QMediaPlayer::setMedia is asynchronous so if you call the duration right after it, the media won't be set yet and then the duration will be wrong.

From Qt documentation on setMedia:

Note: This function returns immediately after recording the specified source of the media. It does not wait for the media to finish loading and does not check for errors.

When the duration is updated, QMediaPlayer send a signal named durationChanged(qint64 duration). So that you need to do is to connect this signal with a lambda or a slot.

For example,

```<code>QMediaPlayer *player = new QMediaPlayer(this);
connect(player, &QMediaPlayer::durationChanged, this, [&](qint64 dur) {
    qDebug() << "duration = " << dur;
});
QUrl file = QUrl::fromLocalFile(QFileDialog::getOpenFileName(this, tr("Open Music"), "", tr("")));
if (file.url() == "")
    return ;
player->setMedia(file);
qDebug() << player->duration();
player->setVolume(50);
player->play();
</code>```

the first qDebug will write 0 as your but the second in the lambda will write the new duration of the QMediaPlayer.

Body:
I use Qt 5.7
I'm writing Music Player, and have one problem. Method duration() of QMediaPlayer always returns 0. How can I fix it?

Example of code:

QMediaPlayer *player = new QMediaPlayer;
player->setMedia(QMediaContent(QUrl(path)));
qDebug() << player->duration(); // returns 0
player->play(); // it works

Body:
You cannot do a player->duration() right after the player->setMedia(QMediaContent(QUrl(path)));.

Indeed, the QMediaPlayer::setMedia is asynchronous so if you call the duration right after it, the media won't be set yet and then the duration will be wrong.

From Qt documentation on setMedia:

Note: This function returns immediately after recording the specified source of the media. It does not wait for the media to finish loading and does not check for errors.

When the duration is updated, QMediaPlayer send a signal named durationChanged(qint64 duration). So that you need to do is to connect this signal with a lambda or a slot.

For example,

QMediaPlayer *player = new QMediaPlayer(this);
connect(player, &QMediaPlayer::durationChanged, this, [&](qint64 dur) {
    qDebug() << "duration = " << dur;
});
QUrl file = QUrl::fromLocalFile(QFileDialog::getOpenFileName(this, tr("Open Music"), "", tr("")));
if (file.url() == "")
    return ;
player->setMedia(file);
qDebug() << player->duration();
player->setVolume(50);
player->play();

the first qDebug will write 0 as your but the second in the lambda will write the new duration of the QMediaPlayer.


问:
Using FFMPEG for online video hosting
I've been looking around for using FFMPEG and PHP. I've noticed you can use FFMPEG with HTML5. I've read the documentation of the FFMPEG's website and it's far beyond my knowledge.  I have an open source document of a 'premade' .php file that stores the information to the database and tells it to execute to the ffmpeg function.  However, they use mp4box and FLVtool2.

The array's of video size, frame rates, etc. are quite easy to understand.  When designing this from scratch I really have not idea where to start.

I've defined the variables that will be recorded once the file is uploaded, thereafter, checking to see if the file exists and recording it the database.

The real question is using mp4box and flvtool2 to convert all videos right to .flv so you can use flowplayer or jwplayer then telling to convert.

EDIT: Sorry to edit, I've seen many posts about the same question but they all relate to old versions of the software, will the php carry over to newer versions (probably could find out on their website if they had a more in depth HOWTO for website streaming)

答:
I'm not sure I completely understand your question but I'll do my best to give you useful information.

I've noticed you can use FFMPEG with HTML5. I've read the documentation of the FFMPEG's website and it's far beyond my knowledge

HTML5 enabled browsers have a <video> tag that you can use to play a video on your site, the encoding depends on the browser, until now it was mainly H.264 but recently Google, Mozilla and others joined efforts on the WebM Project with the new VP8 codec.

The real question is using mp4box and flvtool2 to convert all videos right to .flv so you can use flowplayer or jwplayer then telling to convert.

flowplayer and other flash based video streaming players use the FLV format, which has (at least on latest flash players) as underlying encoding the same H.264.

FFMPEG can convert videos to FLV so you can use it along side with flowplayer.

flvtool2 is for reading and writing FLV metadata (duration and others) from and to the file.

So, you can use this tools to create your videos an stream them through flowplayer.

More info on FFMPEG and x264 and on Converting to FLV with FFMPEG

Title: Using FFMPEG for online video hosting


问:
How can I use custom variable for product impression instead of enhanced ecommerce datalayer?
I got a request where we need to create custom javascript variable to send product impression instead of enhanced ecommerce datalayer. Can someone please help me understand how that can be achieved by pointing me in correct direction?

TIA

答: Your question is certainly unclear but I will try to give you some options. First if it is the kind of use-case you are looking for because the product impression data are not in the dataLayer and you just want to fetch them from somewhere else, the solution is described in this Simo Ahava blog post. If the reason is that you cannot use the GTM tags to send your product impressions, I would advise you use either the custom Javascript or custom HTML tag to implement your script. That script would get in any way the product data for your page and then use the manual ga() command as described here.  But here is the catch. If you try to send this in a page where GTM is implemented you will get an error: 'Command ignored. Unknown target: undefined'. That is because GTM uses it's own tracker names to send data to GA. To implement your own tracking along with GTM on the same page you should make some changes or additions to your code to be able to get the correct tracker name. How to do that imo is not easy but one way is described in this article</p>


问:
Remove vertical padding from horizontal ProgressBar
By default the ProgressBar has a certain padding above and below the bar itself. Is there a way to remove this padding so as to only have the bar in the end?</p>

答:
I'm using style="@style/Widget.AppCompat.ProgressBar.Horizontal" and it was fairly easy to get rid of the margins.  That style is:

```<code>    <item name="progressDrawable">@drawable/progress_horizontal_material</item>
    <item name="indeterminateDrawable">@drawable/progress_indeterminate_horizontal_material</item>
    <item name="minHeight">16dip</item>
    <item name="maxHeight">16dip</item>
</code>```

I just overrode the min/max height:

```<code>    <ProgressBar
        style="@style/Widget.AppCompat.ProgressBar.Horizontal"
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:indeterminate="true"
        android:minHeight="2dp"
        android:maxHeight="2dp" />
</code>```

Body:
I'm using style="@style/Widget.AppCompat.ProgressBar.Horizontal" and it was fairly easy to get rid of the margins.  That style is:

    <item name="progressDrawable">@drawable/progress_horizontal_material</item>
    <item name="indeterminateDrawable">@drawable/progress_indeterminate_horizontal_material</item>
    <item name="minHeight">16dip</item>
    <item name="maxHeight">16dip</item>

I just overrode the min/max height:

    <ProgressBar
        style="@style/Widget.AppCompat.ProgressBar.Horizontal"
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:indeterminate="true"
        android:minHeight="2dp"
        android:maxHeight="2dp" />


问:
Thymeleaf- Create dynamic id for table row
I am new to Thymeleaf and I am trying to create id for tr and getting dynamic rows.

Successfully getting table rows but I don't know hot to create id for each row in Thymeleaf.

```<code><table class="table table-hover" id="table">
  <thead style="background-color:#CCE5FF">
  <tr>
    <th>ID</th>
    <th>Code</th>
    <th>Created Date</th>
    <th></th>
  </tr>
  </thead>
  <tbody>
  <tr th:each="emp,iterStat : ${empList}">
    <td th:text="${emp.id}">ID</td>
    <td th:text="${emp.mdrcode}">Code</td>
    <td th:text="${emp.createDate}">Created Date</td>
    <td>
      <a id="editview" class="btn btn-sm btn-default" th:href="@{/}"><i class="fa fa-edit"></i> View</a>
    </td>
  </tr>
  </tbody>
</table>
</code>```

答:
You can use th:id for that.

```<code><!-- this would assign the emp.id to the id attribute of the tr.
<tr th:id="${emp.id}" th:each="emp,iterStat : ${empList}">
    <td th:text="${emp.id}">ID</td>
    <td th:text="${emp.mdrcode}">Code</td>
    <td th:text="${emp.createDate}">Created Date</td>
    <td><a  id="editview" class="btn btn-sm btn-default" th:href="@{/}"><i class="fa fa-edit"></i> View</a></td>
</tr>
</code>```

We can also add some text to the id:

```<code><!-- this would assign someText + emp.id to the id attribute of the tr.
<tr th:id="'someText' + ${emp.id}" th:each="emp,iterStat : ${empList}">
    <td th:text="${emp.id}">ID</td>
    <td th:text="${emp.mdrcode}">Code</td>
    <td th:text="${emp.createDate}">Created Date</td>
    <td><a  id="editview" class="btn btn-sm btn-default" th:href="@{/}"><i class="fa fa-edit"></i> View</a></td>
</tr>
</code>```

Body:
I am new to Thymeleaf and I am trying to create id for tr and getting dynamic rows.

Successfully getting table rows but I don't know hot to create id for each row in Thymeleaf.

    ID
    Code
    Created Date

    ID
    Code
    Created Date

       View

Body:
You can use th:id for that.

<!-- this would assign the emp.id to the id attribute of the tr.
<tr th:id="${emp.id}" th:each="emp,iterStat : ${empList}">
    <td th:text="${emp.id}">ID</td>
    <td th:text="${emp.mdrcode}">Code</td>
    <td th:text="${emp.createDate}">Created Date</td>
    <td><a  id="editview" class="btn btn-sm btn-default" th:href="@{/}"><i class="fa fa-edit"></i> View</a></td>
</tr>

We can also add some text to the id:

<!-- this would assign someText + emp.id to the id attribute of the tr.
<tr th:id="'someText' + ${emp.id}" th:each="emp,iterStat : ${empList}">
    <td th:text="${emp.id}">ID</td>
    <td th:text="${emp.mdrcode}">Code</td>
    <td th:text="${emp.createDate}">Created Date</td>
    <td><a  id="editview" class="btn btn-sm btn-default" th:href="@{/}"><i class="fa fa-edit"></i> View</a></td>
</tr>


问:
Wordpress - Disable "Are you sure you want to navigate away from this page?" when saving custom post
I have a Wordpress site very customized where there are a lot of contributors and lots of posts are published. When you try to publish/update a custom post it displays a popup saying "The changes you made will be lost if you navigate away from this page. Are you sure you want to leave this page?".

This only happens when the modified/new content of the post is in custom fields corresponding to "Advanced Custom Fields" plugin. This popup is very annoying for the contributors. So I would like to know if is possible to disable this popup or any way to fix that.

Thanks.

答:
```<code>jQuery(document).ready(function()
{
    jQuery(window).off("beforeunload", null);
});
</code>```


问:
Displaying HTML with Blade shows the HTML code
I have a string returned to one of my views, like this:

```<code>$text = '<p><strong>Lorem</strong> ipsum dolor <img src="images/test.jpg"></p>'
</code>```

I'm trying to display it with Blade:

```<code>{{$text}}
</code>```

However, the output is a raw string instead of rendered HTML. How do I display HTML with Blade in Laravel?

PS. PHP echo() displays the HTML correctly.

答:
There is another way. If object purpose is to render html you can implement \Illuminate\Contracts\Support\Htmlable contract that has toHtml() method.

Then you can render that object from blade like this: {{ $someObject }} (note, no need for {!! !!} syntax).

Also if you want to return html property and you know it will be html, use \Illuminate\Support\HtmlString class like this:

```<code>public function getProductDescription()
{
    return new HtmlString($this->description);
}
</code>```

and then use it like {{ $product->getProductDescription() }}.

Of course be responsible when directly rendering raw html on page.

Body:
I have a string returned to one of my views, like this:

$text = '
Lorem ipsum dolor
'

I'm trying to display it with Blade:

{{$text}}

However, the output is a raw string instead of rendered HTML. How do I display HTML with Blade in Laravel?

PS. PHP echo() displays the HTML correctly.

Body:
There is another way. If object purpose is to render html you can implement \Illuminate\Contracts\Support\Htmlable contract that has toHtml() method.

Then you can render that object from blade like this: {{ $someObject }} (note, no need for {!! !!} syntax).

Also if you want to return html property and you know it will be html, use \Illuminate\Support\HtmlString class like this:

public function getProductDescription()
{
    return new HtmlString($this->description);
}

and then use it like {{ $product->getProductDescription() }}.

Of course be responsible when directly rendering raw html on page.


问:
Avoiding repetitive javascript
I have a HTML form with about 30 similar lines in it. Each line is something like this:

```<code><tr>
  <td>Car Park</td>
  <td><input type="checkbox" id="local_parking" name="amenity[]" value="local_parking"></td>
  <td><input type="text" id="local_parking_t" name="amenity_text[]" value="Car park"></td>
</tr>
</code>```

If the checkbox is not checked, the text box needs to be disabled to avoid it passing its value to the mySQL query that follows. I can do that for one line with this javascript:

```<code>document.getElementById('local_parking').onchange = function() {
  document.getElementById('local_parking_t').disabled = !this.checked;
};
</code>```

However it seems unreasonably messy to repeat the javascript 30 times over with different IDs. Is there a better way?

答:
You can use a common class to target the CHECKBOX element then DOM traversal method to target the INPUT element.

var elements = document.querySelectorAll('.local_parking');
elements.forEach(function(element) {
  element.addEventListener('change', function() {
    this.parentNode.nextElementSibling.childNodes[0].disabled = !this.checked;
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <td>Car Park</td>
    <td><input type="checkbox" class="local_parking" name="amenity[]" value="local_parking"></td>
    <td><input type="text" class="local_parking_t" name="amenity_text[]" value="Car park" disabled></td>
  </tr>
  <tr>
    <td>Car Park</td>
    <td><input type="checkbox" class="local_parking" name="amenity[]" value="local_parking"></td>
    <td><input type="text" class="local_parking_t" name="amenity_text[]" value="Car park" disabled></td>
  </tr>
</table></code>```

Title: Avoiding repetitive javascript

Body:
I have a HTML form with about 30 similar lines in it. Each line is something like this:

  Car Park
  <input type="checkbox" id="local_parking" name="amenity[]" value="local_parking">
  <input type="text" id="local_parking_t" name="amenity_text[]" value="Car park">

If the checkbox is not checked, the text box needs to be disabled to avoid it passing its value to the mySQL query that follows. I can do that for one line with this javascript:

document.getElementById('local_parking').onchange = function() {
  document.getElementById('local_parking_t').disabled = !this.checked;
};

However it seems unreasonably messy to repeat the javascript 30 times over with different IDs. Is there a better way?

Body:
You can use a common class to target the CHECKBOX element then DOM traversal method to target the INPUT element.

var elements = document.querySelectorAll('.local_parking');
elements.forEach(function(element) {
  element.addEventListener('change', function() {
    this.parentNode.nextElementSibling.childNodes[0].disabled = !this.checked;
  });
});

<table>
  <tr>
    <td>Car Park</td>
    <td><input type="checkbox" class="local_parking" name="amenity[]" value="local_parking"></td>
    <td><input type="text" class="local_parking_t" name="amenity_text[]" value="Car park" disabled></td>
  </tr>
  <tr>
    <td>Car Park</td>
    <td><input type="checkbox" class="local_parking" name="amenity[]" value="local_parking"></td>
    <td><input type="text" class="local_parking_t" name="amenity_text[]" value="Car park" disabled></td>
  </tr>
</table>


答:
Catch every checkbox and bind change event listener. If user checks specified checkbox - enable corresponding text input.

var checkboxes = document.querySelectorAll('input[type=checkbox]'),
    inputs = document.querySelectorAll('input[type=text]');

    [...checkboxes].forEach((v,i) => v.addEventListener('change', function(){
      inputs[i].disabled = !this.checked;
    }));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><tr>
  <td>Car Park</td>
  <td><input type="checkbox" id="local_parking" name="amenity[]" value="local_parking"></td>
  <td><input type="text" id="local_parking_t" disabled name="amenity_text[]" value="Car park"></td>
</tr>
<br>
<tr>
  <td>Some txt</td>
  <td><input type="checkbox" id="local_parking" name="amenity[]" value="local_parking"></td>
  <td><input type="text" id="local_parking_t" disabled name="amenity_text[]" value="Car "></td>
</tr></code>```

Title: Avoiding repetitive javascript

Body:
Catch every checkbox and bind change event listener. If user checks specified checkbox - enable corresponding text input.

var checkboxes = document.querySelectorAll('input[type=checkbox]'),
    inputs = document.querySelectorAll('input[type=text]');

    [...checkboxes].forEach((v,i) => v.addEventListener('change', function(){
      inputs[i].disabled = !this.checked;
    }));

<tr>
  <td>Car Park</td>
  <td><input type="checkbox" id="local_parking" name="amenity[]" value="local_parking"></td>
  <td><input type="text" id="local_parking_t" disabled name="amenity_text[]" value="Car park"></td>
</tr>
<br>
<tr>
  <td>Some txt</td>
  <td><input type="checkbox" id="local_parking" name="amenity[]" value="local_parking"></td>
  <td><input type="text" id="local_parking_t" disabled name="amenity_text[]" value="Car "></td>
</tr>


问:
RC special variable in REXX?
how to assign a value to RC special variable in REXX?</p>

答:
```<code>/* REXX */
"LISTDS ?"         /* Command that sets RC to 12 */
SAY 'RC IS' RC     /* RC is 12 */
RC = X             /* RC set to X */
SAY 'RC IS' RC     /* RC is X */
</code>```

The above works, there is nothing special about the RC variable except it will be over written by the return code from the last command.
So you can set it to whatever you want at least on a mainframe running Zos.

Maybe you need to provide more detail in your question like what type of Rexx it is (Classic or OO) and what environment you are using.

Title: RC special variable in REXX?

Body:
/* REXX */
"LISTDS ?"         /* Command that sets RC to 12 */
SAY 'RC IS' RC     /* RC is 12 */
RC = X             /* RC set to X */
SAY 'RC IS' RC     /* RC is X */

The above works, there is nothing special about the RC variable except it will be over written by the return code from the last command.
So you can set it to whatever you want at least on a mainframe running Zos.

Maybe you need to provide more detail in your question like what type of Rexx it is (Classic or OO) and what environment you are using.


问:
onClick is not working in chrome?
I have a slider menu which I want by clicking on that another page loaded. in firefox its works but I want to works my HTML in any browsers? could you please help me? thanks.

index.html:

```<code><!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body>
<div >
    <a href="#" id="link1" >Vertical link 1</a>
</div>
<div id="content"></div>
<script>
    $("#link1").on("click", function () {
    $("#content").load("test.html");
    });
</script>
</body>
</html>
</code>```

test.html:

```<code><!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<div>
    <table>
        <thead>
            <tr>
                <th scope="col">A</th>
                <th scope="col">B</th>
                <th scope="col">C</th>
                <th scope="col">D</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>1</td>
                <td>2</td>
                <td>3</td>
                <td>4</td>
            </tr>
        </tbody>
    </table>
</div>
</body>
</html>
</code>```

答:
If the content is dynamic then it needs to be delegated :    </p>

```<code>$(document).on("click", "#link1" , function () {
    console.log('click')
    $("#content").load("./resources/link1.html");
});
</code>```

Title: onClick is not working in chrome?

Body:
I have a slider menu which I want by clicking on that another page loaded. in firefox its works but I want to works my HTML in any browsers? could you please help me? thanks.

index.html:

<!DOCTYPE html>

    <title></title>

    Vertical link 1

test.html:

<!DOCTYPE html>

    <title></title>

                A
                B
                C
                D

                1
                2
                3
                4

Body:
If the content is dynamic then it needs to be delegated :

$(document).on("click", "#link1" , function () {
    console.log('click')
    $("#content").load("./resources/link1.html");
});