问:
PHP and SQL -- Select from database
I have a problem with this code. It has syntax error and I don't know what is it.</p>

```<code><?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'id1381007_accounts';
$conn = new mysqli($host,$user,$pass,$db) or die($mysqli->error);

if (!$conn) {
die('Could not connect: ' . mysql_error());

$sql  = 'SELECT id FROM users WHERE email=\"donat12@icloud.com\"';

echo $sql;
?>
</code>```

答:
There are some issue with the code. First you forgot to close the if condition over here

if (!$conn) {

And then you forgot to execute the sql query

the complete code would be like

```<code><?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'id1381007_accounts';
$conn = new mysqli($host,$user,$pass,$db) or die($mysqli->error);

if (!$conn) {
 die('Could not connect: ' . mysql_error());
}
$sql  = 'SELECT id FROM users WHERE email=\"donat12@icloud.com\"';
if ($result = $conn->query($sql)) {
   while ( $row = $result->fetch_assoc()) {
        $data[] = $row;
    }
    echo "```";
    print_r($data);
    echo "```";
}
$conn->close();
?>
</code>```

Title: PHP and SQL -- Select from database

Body:
I have a problem with this code. It has syntax error and I don't know what is it.

<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'id1381007_accounts';
$conn = new mysqli($host,$user,$pass,$db) or die($mysqli->error);

if (!$conn) {
die('Could not connect: ' . mysql_error());

$sql  = 'SELECT id FROM users WHERE email=\"donat12@icloud.com\"';

echo $sql;
?>

Body:
There are some issue with the code. First you forgot to close the if condition over here

if (!$conn) {

And then you forgot to execute the sql query

the complete code would be like

<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'id1381007_accounts';
$conn = new mysqli($host,$user,$pass,$db) or die($mysqli->error);

if (!$conn) {
 die('Could not connect: ' . mysql_error());
}
$sql  = 'SELECT id FROM users WHERE email=\"donat12@icloud.com\"';
if ($result = $conn->query($sql)) {
   while ( $row = $result->fetch_assoc()) {
        $data[] = $row;
    }
    echo "<pre>";
    print_r($data);
    echo "</pre>";
}
$conn->close();
?>


来源: stackexchange

问:
Padding not visible inside div block?
Please check the jsFiddle link and tell why padding is not visible inside div container?

body {
  background-color: #B8C4BB;
}

.container {
  text-align: center;
}

.section_two {
  border: 2px solid red;
  padding: 10 px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="section">
    Change the value of the color property to see how it changes the text color of this element.
  </div>
  <div class="section_two">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sunt, alias, aliquid fugiat dolorem repudiandae quidem. Molestiae illum pariatur officia voluptate cumque. Necessitatibus earum consequuntur explicabo minus ratione mollitia illum nam.
  </div>
</div></code>```

答:
You have only typing mistake.

```<code>use padding property

like: padding: 10px;
insteade of: 10 px;
</code>```

See Fiddle demo

ContentLicense: CC BY-SA 3.0

Title: Padding not visible inside div block?

Body:
Please check the jsFiddle link and tell why padding is not visible inside div container?

body {
  background-color: #B8C4BB;
}

.container {
  text-align: center;
}

.section_two {
  border: 2px solid red;
  padding: 10 px;
}

    Change the value of the color property to see how it changes the text color of this element.

    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sunt, alias, aliquid fugiat dolorem repudiandae quidem. Molestiae illum pariatur officia voluptate cumque. Necessitatibus earum consequuntur explicabo minus ratione mollitia illum nam.

Body:
You have only typing mistake.

use padding property

like: padding: 10px;
insteade of: 10 px;

See Fiddle demo


问:
Is there a website level setting in IIS that would prevent an ASP page from being served?
Trying to copy a website to a new server as the old one is dying.  :(

I tried copying over the files and setting it up manually, but some specific user accounts needed to be used and the guy who set all this up left the company nearly 5 years ago.  And is even worse at documentation than I am.

Anyway, at that point the ASP pages were serving, but getting errors.  Ok, fine... I went back and exported the configuration from the old server (lucky that worked at all) and created a new website from that config on the new server.  On the new website, from the config file, the ASP pages are giving 404 errors.

The Active Server Pages extension is enabled, and I can actually get the asp pages to serve from another website on the server... so I'm thinking it's something at the website level.  No idea what though.

Any ideas?

答:
Back when I was doing classic ASP development we used Parent Paths.  This is at the top of your ASP file you'll see something like;

```<code><!--#include file="../../resource/includes/MSSQLconnection.asp"-->
</code>```

This isn't enabled by default in IIS.  It may not be answer but worth looking at.  But was a long time ago now.

Hope this helps,
Mike

ContentLicense: CC BY-SA 2.5

Body:
Back when I was doing classic ASP development we used Parent Paths.  This is at the top of your ASP file you'll see something like;

<!--#include file="../../resource/includes/MSSQLconnection.asp"-->

This isn't enabled by default in IIS.  It may not be answer but worth looking at.  But was a long time ago now.

Hope this helps,
Mike


问:
Simple ajax function send NULL id
I'm trying to make simple delete ajax function. I'm not very good ad JS at all but when I click on button delete I can see in Chrome Dev Console that id = NULL and when I refresh the page the entry is back. The ajax function is pretty simple

```<code>$("body").on("click",".remove-item",function(){
    var entry_id = $(this).parent("td").data('entry_id');
    var c_obj = $(this).parents("tr");

    $.ajax({
        dataType: 'json',
        type:'POST',
        url: 'delete.php',
        data:{entry_id:entry_id}
    }).done(function(data){
        c_obj.remove();
        toastr.success('Item Deleted Successfully.', 'Success Alert', {timeOut: 5000});

    });
});
</code>```

And the button

```<code><button  class="btn btn-danger remove-item" > Delete</button>
</code>```

And this is the delete.php

```<code>$entry_id  = $_POST["entry_id"];
$stmt = $pdo->prepare("DELETE FROM entries WHERE entry_id = :entry_id");
$stmt->bindParam(':entry_id', $entry_id, PDO::PARAM_INT);
$stmt->execute();

echo json_encode([$entry_id]);
</code>```

Any idea what can be wrong?

update. The table

```<code>    echo '<table class="table">
        <thead>
            <tr>
                <th>#</th>
                <th>Name</th>
                <th>Transaction Quote</th>
                <th>Action</th>
            </tr>
        </thead>';
        foreach($pdo->query("SELECT * FROM entries ORDER BY entry_id DESC LIMIT 20") as $row){
            echo '
                <tbody>
                <tr>
                    <td>'.$row['entry_id'].'</td>
                    <td>'.$row['entry_name'].'</td>
                    <td>'.$row['entry_transaction_quote'].'</td>
                    <td><button  class="btn btn-sm btn-danger remove-item" ><i class="glyphicon glyphicon-trash"></i> Delete</button></td>
                </tr>
                </tbody>  ';
        }
        echo '  </table>
</code>```

答:
Change your td with class name

```<code> <td class="entry_id">'.$row['entry_id'].'</td>
</code>```

jquery

```<code>var entry_id = $(this).parent("td").parent("tr").find('.entry_id').text().trim();
</code>```

Title: Simple ajax function send NULL id

Body:
I'm trying to make simple delete ajax function. I'm not very good ad JS at all but when I click on button delete I can see in Chrome Dev Console that id = NULL and when I refresh the page the entry is back. The ajax function is pretty simple

$("body").on("click",".remove-item",function(){
    var entry_id = $(this).parent("td").data('entry_id');
    var c_obj = $(this).parents("tr");

    $.ajax({
        dataType: 'json',
        type:'POST',
        url: 'delete.php',
        data:{entry_id:entry_id}
    }).done(function(data){
        c_obj.remove();
        toastr.success('Item Deleted Successfully.', 'Success Alert', {timeOut: 5000});

    });
});

And the button

<button  class="btn btn-danger remove-item" > Delete</button>

And this is the delete.php

$entry_id  = $_POST["entry_id"];
$stmt = $pdo->prepare("DELETE FROM entries WHERE entry_id = :entry_id");
$stmt->bindParam(':entry_id', $entry_id, PDO::PARAM_INT);
$stmt->execute();

echo json_encode([$entry_id]);

Any idea what can be wrong?

update. The table

    echo '

                #
                Name
                Transaction Quote
                Action

';
        foreach($pdo->query("SELECT * FROM entries ORDER BY entry_id DESC LIMIT 20") as $row){
            echo '

                    '.$row['entry_id'].'
                    '.$row['entry_name'].'
                    '.$row['entry_transaction_quote'].'
                    <button  class="btn btn-sm btn-danger remove-item" > Delete</button>

  ';
        }
        echo '

Body:
Change your td with class name

 <td class="entry_id">'.$row['entry_id'].'</td>

jquery

var entry_id = $(this).parent("td").parent("tr").find('.entry_id').text().trim();


问:
Dynamically create buttons in c# by user at runtime
How to create buttons dynamically after user input in C# (Visual Studio).
There is a text-box to enter how many buttons user wants?
Then my target is to create buttons below the input field as the user wants
then how can I get id's of that buttons?</p>

```<code>private void button1_Click(object sender, EventArgs e)
{
    List<Button> buttons = new List<Button>();
    for (int i = 0; i < n; i++)
    {
        this.Controls.Add(buttons[i]);
    }
}
</code>```

答:
When you are creating Control(in your case Buttons) you can give them Name property. It will be very good if that name will be unique.

```<code>var btn = new Button();
btn.Name = "MyBtn";
btn.Text = "Our Button";
this.Controls.Add(btn);
</code>```

For creation of N buttons you just need to put this in a Loop with N iterations and set btn.Name to something like "Name"+SomeNumber.
To set the Position of the Buttons to below the input you should set btn.Left and btn.Top to the corresponding coordinates.

Then when you need to work with generated Control/Button you can do search by that Name in the following way:

```<code>var btn = (Button)this.Controls.Find("MyBtn", true).First();
</code>```

and do whatever you want with that Control/Button.

But in this case there is some danger as I am not checking if there was found any control with that name. If you write incorrect Name this will throw exception on .First().

Body:
How to create buttons dynamically after user input in C# (Visual Studio).
There is a text-box to enter how many buttons user wants?
Then my target is to create buttons below the input field as the user wants
then how can I get id's of that buttons?

private void button1_Click(object sender, EventArgs e)
{
    List<Button> buttons = new List<Button>();
    for (int i = 0; i < n; i++)
    {
        this.Controls.Add(buttons[i]);
    }
}

Body:
When you are creating Control(in your case Buttons) you can give them Name property. It will be very good if that name will be unique.

var btn = new Button();
btn.Name = "MyBtn";
btn.Text = "Our Button";
this.Controls.Add(btn);

For creation of N buttons you just need to put this in a Loop with N iterations and set btn.Name to something like "Name"+SomeNumber.
To set the Position of the Buttons to below the input you should set btn.Left and btn.Top to the corresponding coordinates.

Then when you need to work with generated Control/Button you can do search by that Name in the following way:

var btn = (Button)this.Controls.Find("MyBtn", true).First();

and do whatever you want with that Control/Button.

But in this case there is some danger as I am not checking if there was found any control with that name. If you write incorrect Name this will throw exception on .First().


问:
Why does html tag take the background of the body tag only when the html tag has no background-color property set
So I noticed that when I remove the background or background-color property from the html selector when  there is a background or background-color property present for the body selector, the body's background takes up the entire screen.

However, when there is a background or background-color property set for the html tag then the body's background property only affects the portion of the screen the body takes up, AKA the content of the body takes up, and not the entire screen.

What is the reason for this (bug, decision...) and do I now have to set both the backgrounds for html and body now? Thank you.

答:
This is by design.

According to the W3C Colors and backgrounds page,

For HTML documents, however, we recommend that authors specify the background for the BODY element rather than the HTML element. For documents whose root element is an HTML "HTML" element or an XHTML "html" element that has computed values of 'transparent' for 'background-color' and 'none' for 'background-image', user agents must instead use the computed value of the background properties from that element's first HTML "BODY" element or XHTML "body" element child when painting backgrounds for the canvas, and must not paint a background for that child element.

Or, tl;dr: Leaving the 's background alone and only styling the body will cause the background to be assigned to the whole document. This is the recommendation.

The reason is, probably, for compatibility reasons. Long ago, the , element also played the role of the canvas, and the  element did not really have any properties of its own. So you could assign a bgcolor property to the  (but not to the ) and that would become the canvas background.

And the answer to your last question is: only if you want to. In most cases, not styling the  at all will be enough. Except in special cases, e.g. if you want a differently coloured edge around the body, as you noticed.

Example with background on the  only:

body {background:lime}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Hello world</code>```

Example with different backgrounds for the  and the :

html {background:orange}
body {background:lime}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Hello world</code>```

Body:
This is by design.

According to the W3C Colors and backgrounds page,

For HTML documents, however, we recommend that authors specify the background for the BODY element rather than the HTML element. For documents whose root element is an HTML "HTML" element or an XHTML "html" element that has computed values of 'transparent' for 'background-color' and 'none' for 'background-image', user agents must instead use the computed value of the background properties from that element's first HTML "BODY" element or XHTML "body" element child when painting backgrounds for the canvas, and must not paint a background for that child element.

Or, tl;dr: Leaving the <html>'s background alone and only styling the body will cause the background to be assigned to the whole document. This is the recommendation.

The reason is, probably, for compatibility reasons. Long ago, the <body>, element also played the role of the canvas, and the <html> element did not really have any properties of its own. So you could assign a bgcolor property to the <body> (but not to the <html>) and that would become the canvas background.

And the answer to your last question is: only if you want to. In most cases, not styling the <html> at all will be enough. Except in special cases, e.g. if you want a differently coloured edge around the body, as you noticed.

Example with background on the <body> only:

body {background:lime}

Hello world

Example with different backgrounds for the <html> and the <body>:

html {background:orange}
body {background:lime}

Hello world


答:
Your css is like following:

```<code>.section_two {
  border: 2px solid red;
  padding: 10 px;
}
</code>```

Value for padding is invalid. It should be as padding: 10px. Without space between 10 and px

Title: Padding not visible inside div block?

Body:
Your css is like following:

.section_two {
  border: 2px solid red;
  padding: 10 px;
}

Value for padding is invalid. It should be as padding: 10px. Without space between 10 and px


问:
Play Vimeo video in Android , video url containing iframe
Hello i am working on android application in which i want to play vimeo videos , i am getting response from Api in json and playing video using webview and it is playing good , but the webview is displaying very small and the playing video is also small my problems are

I want  playing video width to be according to android device width. I can get it from Displaymetrics but how to set to iframe ?

I want to inflate custom view of media controller for playing videos.
Custom controller like play pause icon

I am getting this kind of url response from api

```<code> <iframe src="https://player.vimeo.com/video/video_id" width="640" height="360" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
</code>```

at video_id i am getting the video id

Below is the code which i used

```<code>webView.setWebChromeClient(new WebChromeClient());
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setPluginState(WebSettings.PluginState.ON);
        webView.getSettings().setPluginState(WebSettings.PluginState.ON_DEMAND);
        webView.setWebViewClient(new WebViewClient());
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setUseWideViewPort(true);

        String data_html=getexplore_list.get(pos).getVideo_url();

        webView.loadDataWithBaseURL("http://vimeo.com", data_html, "text/html", "UTF-8", null);
</code>```

Please Provide any solution or link will be grateful

答:
use style in html,</p>

```<code>String url = "<iframe src=\"" + videoUrl + "\" style=\"border: 0; width: 100%; height: 95%; padding:0px; margin:0px\" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>";
</code>```

Body:
Hello i am working on android application in which i want to play vimeo videos , i am getting response from Api in json and playing video using webview and it is playing good , but the webview is displaying very small and the playing video is also small my problems are

I want  playing video width to be according to android device width. I can get it from Displaymetrics but how to set to iframe ?

I want to inflate custom view of media controller for playing videos.
Custom controller like play pause icon

I am getting this kind of url response from api

at video_id i am getting the video id

Below is the code which i used

webView.setWebChromeClient(new WebChromeClient());
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setPluginState(WebSettings.PluginState.ON);
        webView.getSettings().setPluginState(WebSettings.PluginState.ON_DEMAND);
        webView.setWebViewClient(new WebViewClient());
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setUseWideViewPort(true);

        String data_html=getexplore_list.get(pos).getVideo_url();

        webView.loadDataWithBaseURL("http://vimeo.com", data_html, "text/html", "UTF-8", null);

Please Provide any solution or link will be grateful

Body:
use style in html,

String url = "<iframe src=\"" + videoUrl + "\" style=\"border: 0; width: 100%; height: 95%; padding:0px; margin:0px\" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>";


问:
How to assgin two diffrent url with java script code
Below is a JS code , and i want to redirect user to two different URL - If he enter value in input box 1 so he should redirect to this Default url[https://manage.bagful.com.au/cart.php?a=add&pid=30] else he put more than 1 so this URL [https://manage.bagful.com.au/cart.php?a=add&pid=30&configoption[2]]

Here is the Code:

```<code>$(document).ready(function(){

    document.getElementById("input").addEventListener("keyup", function(event) {
        event.preventDefault();
        if (event.keyCode == 1) {
            var inputvalue = $("#input").val();
            window.location.replace(" https://manage.bagful.com.au/cart.php?a=add&pid=30");
        }
    });

    $('#button').click(function(e) {
        var inputvalue = $("#input").val();
        window.location.replace(" https://manage.bagful.com.au/cart.php?a=add&pid=30&configoption[2]="+inputvalue);
    });
});
</code>```

Please check and suggest the best idea.

答:
If you want to redirect the user after insert value then

Try this

```<code>$('#input').on('change',function(e) {
    var inputvalue = $("this").val();
    if (inputvalue == 1) {
        window.location.replace(" https://manage.bagful.com.au/cart.php?a=add&pid=30");
    }else {
        window.location.replace(" https://manage.bagful.com.au/cart.php?a=add&pid=30&configoption[2]="+inputvalue);
    }
});
</code>```

I thing it will work for you.

Body:
Below is a JS code , and i want to redirect user to two different URL - If he enter value in input box 1 so he should redirect to this Default url[https://manage.bagful.com.au/cart.php?a=add&pid=30] else he put more than 1 so this URL [https://manage.bagful.com.au/cart.php?a=add&pid=30&configoption[2]]

Here is the Code:

$(document).ready(function(){

    document.getElementById("input").addEventListener("keyup", function(event) {
        event.preventDefault();
        if (event.keyCode == 1) {
            var inputvalue = $("#input").val();
            window.location.replace(" https://manage.bagful.com.au/cart.php?a=add&pid=30");
        }
    });

    $('#button').click(function(e) {
        var inputvalue = $("#input").val();
        window.location.replace(" https://manage.bagful.com.au/cart.php?a=add&pid=30&configoption[2]="+inputvalue);
    });
});

Please check and suggest the best idea.

Body:
If you want to redirect the user after insert value then

Try this

$('#input').on('change',function(e) {
    var inputvalue = $("this").val();
    if (inputvalue == 1) {
        window.location.replace(" https://manage.bagful.com.au/cart.php?a=add&pid=30");
    }else {
        window.location.replace(" https://manage.bagful.com.au/cart.php?a=add&pid=30&configoption[2]="+inputvalue);
    }
});

I thing it will work for you.


答:
try if else condition to dynamic the url :

```<code>document.getElementById("input").addEventListener("keyup", function(event) {
event.preventDefault();
var inputvalue = $("#input").val(),
url = (inputvalue == 1) ? 'https://manage.bagful.com.au/cart.php?a=add&pid=30' : 'https://manage.bagful.com.au/cart.php?a=add&pid=30&configoption[2]';
 window.location.replace(url);
});
</code>```

Title: How to assgin two diffrent url with java script code

Body:
try if else condition to dynamic the url :

document.getElementById("input").addEventListener("keyup", function(event) {
event.preventDefault();
var inputvalue = $("#input").val(),
url = (inputvalue == 1) ? 'https://manage.bagful.com.au/cart.php?a=add&pid=30' : 'https://manage.bagful.com.au/cart.php?a=add&pid=30&configoption[2]';
 window.location.replace(url);
});


问:
Authorization is not allowed by Access-Control-Allow-Headers
I'm using create-react-app and trying to figure out what I'm doing wrong here.

I created an integration test in mocha using supertest which works fine:

```<code>  it.only('Can get a list of users', async () => {
      const uri = '/users'

      console.log(uri)

    const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE0OTk0NDM5NDM5MjMsImV4cCI6MTUwMjAzNTk0MzkyMywidXNlclVVSUQiOiI1YjMyMTQ4MC00ZmY1LTExZTctYWMwNi1kNWNmZmY0NmZjOGMiLCJjc3JBZG1pbiI6dHJ1ZSwiY29nbml0b1VzZXJBcm4iOiJ1cy13ZXN0LTI6NGZjMGFlMDgtNjZhNy00ZDUwLTk2ZDAtOWE3ZmQ0ODAzMWUwIiwicHJvZmlsZXMiOlt7InByb2ZpbGVVVUlEIjoiNWIzNDg1ODAtNGZmNS0xMWU3LWFjMDYtZDVjZmZmNDZmYzhjIiwicm9sZSI6Im93bmVyIn1dLCJyb2JvdHMiOltdfQ.WOg2otyaNyU1-mlM0wvkAK4hxOVQtfrQw2202G21al8',
        authorization = `Bearer ${token}`

    let response = await request
        .get(uri)
        .set('Authorization', authorization)
        .accept('application/json')

      expect(response.status).to.equal(200)
      expect(response.body.data[0].uuid.length).to.be.greaterThan(0)
      expect(response.body.data[0].firstName.length).to.be.greaterThan(0)
      expect(response.body.data[0].lastName.length).to.be.greaterThan(0)
      expect(response.body.data[0].email.length).to.be.greaterThan(0)
  })
</code>```

However In the Browser, when the same type of clal is made from my a UserAPI.js, it fails. I even hard coded a token I know works for sure which is the same token that works in the integration test:

```<code>  const FindAllUsers = async (token) => {
    try {
      return await request
        .get(url)
        .set('Content-Type', 'application/x-www-form-urlencoded')
        .set('Authorization', 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE0OTk0NDM5NDM5MjMsImV4cCI6MTUwMjAzNTk0MzkyMywidXNlclVVSUQiOiI1YjMyMTQ4MC00ZmY1LTExZTctYWMwNi1kNWNmZmY0NmZjOGMiLCJjc3JBZG1pbiI6dHJ1ZSwiY29nbml0b1VzZXJBcm4iOiJ1cy13ZXN0LTI6NGZjMGFlMDgtNjZhNy00ZDUwLTk2ZDAtOWE3ZmQ0ODAzMWUwIiwicHJvZmlsZXMiOlt7InByb2ZpbGVVVUlEIjoiNWIzNDg1ODAtNGZmNS0xMWU3LWFjMDYtZDVjZmZmNDZmYzhjIiwicm9sZSI6Im93bmVyIn1dLCJyb2JvdHMiOltdfQ.WOg2otyaNyU1-mlM0wvkAK4hxOVQtfrQw2202G21al8')
        .accept('application/json')
    }
    catch(err) {
      console.log(err)
    }
  }
</code>```

Error I get in the browser:

I know it's not a CORS issue so ignore that, that's a misleading error.  So it's hitting that try/catch and failing at the catch which is what you see logged in the browser

I mean I don't think I malformed my syntax in my UserApi at least I don't see anything wrong, it's the same code I pasted from my integration test that worked!

**Server-side REST API Response to OPTIONS request - are we missing something here? **

the server sends back the following on a successful call (say I make a call via my integration test or say postman) for example:

Access-Control-Allow-Headers →Content-Type, Accept
Access-Control-Allow-Methods →GET, POST, DELETE, PUT, PATCH, OPTIONS
Access-Control-Allow-Origin →*

Is it SuperAgent??

Our backend API dev tested in a browser himself (not using superagent) and said it worked for him so wondering if this might be a
superagent syntax issue?

I'm using create-react-app and as far as I know you don't need to worry about setting up anything for CORS.

Why don't I see a request in Chrome tools | Network tab for this?

When I look at this error in chrome and then try to look for the actual GET request for this, I only see an OPTIONS request by the browser.  I don't see a request to /users.  Why?

答:
The problem is CORS limits headers by default and you do not see "Authorization" header when call CORS requests. So, adjust server to let it send Authorization header in it's settings.

For example in apache httpd:

```<code>Header add Access-Control-Allow-Headers "Content-Type, Accept, Authorization, other_header"
Header add Access-Control-Expose-Headers "Content-Type, Accept, Authorization, other_header"
</code>```

Body:
I'm using create-react-app and trying to figure out what I'm doing wrong here.

I created an integration test in mocha using supertest which works fine:

  it.only('Can get a list of users', async () => {
      const uri = '/users'

      console.log(uri)

    const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE0OTk0NDM5NDM5MjMsImV4cCI6MTUwMjAzNTk0MzkyMywidXNlclVVSUQiOiI1YjMyMTQ4MC00ZmY1LTExZTctYWMwNi1kNWNmZmY0NmZjOGMiLCJjc3JBZG1pbiI6dHJ1ZSwiY29nbml0b1VzZXJBcm4iOiJ1cy13ZXN0LTI6NGZjMGFlMDgtNjZhNy00ZDUwLTk2ZDAtOWE3ZmQ0ODAzMWUwIiwicHJvZmlsZXMiOlt7InByb2ZpbGVVVUlEIjoiNWIzNDg1ODAtNGZmNS0xMWU3LWFjMDYtZDVjZmZmNDZmYzhjIiwicm9sZSI6Im93bmVyIn1dLCJyb2JvdHMiOltdfQ.WOg2otyaNyU1-mlM0wvkAK4hxOVQtfrQw2202G21al8',
        authorization = `Bearer ${token}`

    let response = await request
        .get(uri)
        .set('Authorization', authorization)
        .accept('application/json')

      expect(response.status).to.equal(200)
      expect(response.body.data[0].uuid.length).to.be.greaterThan(0)
      expect(response.body.data[0].firstName.length).to.be.greaterThan(0)
      expect(response.body.data[0].lastName.length).to.be.greaterThan(0)
      expect(response.body.data[0].email.length).to.be.greaterThan(0)
  })

However In the Browser, when the same type of clal is made from my a UserAPI.js, it fails. I even hard coded a token I know works for sure which is the same token that works in the integration test:

  const FindAllUsers = async (token) => {
    try {
      return await request
        .get(url)
        .set('Content-Type', 'application/x-www-form-urlencoded')
        .set('Authorization', 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE0OTk0NDM5NDM5MjMsImV4cCI6MTUwMjAzNTk0MzkyMywidXNlclVVSUQiOiI1YjMyMTQ4MC00ZmY1LTExZTctYWMwNi1kNWNmZmY0NmZjOGMiLCJjc3JBZG1pbiI6dHJ1ZSwiY29nbml0b1VzZXJBcm4iOiJ1cy13ZXN0LTI6NGZjMGFlMDgtNjZhNy00ZDUwLTk2ZDAtOWE3ZmQ0ODAzMWUwIiwicHJvZmlsZXMiOlt7InByb2ZpbGVVVUlEIjoiNWIzNDg1ODAtNGZmNS0xMWU3LWFjMDYtZDVjZmZmNDZmYzhjIiwicm9sZSI6Im93bmVyIn1dLCJyb2JvdHMiOltdfQ.WOg2otyaNyU1-mlM0wvkAK4hxOVQtfrQw2202G21al8')
        .accept('application/json')
    }
    catch(err) {
      console.log(err)
    }
  }

Error I get in the browser:

I know it's not a CORS issue so ignore that, that's a misleading error.  So it's hitting that try/catch and failing at the catch which is what you see logged in the browser

I mean I don't think I malformed my syntax in my UserApi at least I don't see anything wrong, it's the same code I pasted from my integration test that worked!

**Server-side REST API Response to OPTIONS request - are we missing something here? **

the server sends back the following on a successful call (say I make a call via my integration test or say postman) for example:

Access-Control-Allow-Headers →Content-Type, Accept
Access-Control-Allow-Methods →GET, POST, DELETE, PUT, PATCH, OPTIONS
Access-Control-Allow-Origin →*

Is it SuperAgent??

Our backend API dev tested in a browser himself (not using superagent) and said it worked for him so wondering if this might be a
superagent syntax issue?

I'm using create-react-app and as far as I know you don't need to worry about setting up anything for CORS.

Why don't I see a request in Chrome tools | Network tab for this?

When I look at this error in chrome and then try to look for the actual GET request for this, I only see an OPTIONS request by the browser.  I don't see a request to /users.  Why?

Body:
The problem is CORS limits headers by default and you do not see "Authorization" header when call CORS requests. So, adjust server to let it send Authorization header in it's settings.

For example in apache httpd:

Header add Access-Control-Allow-Headers "Content-Type, Accept, Authorization, other_header"
Header add Access-Control-Expose-Headers "Content-Type, Accept, Authorization, other_header"


问:
i make pagination but it cant limit post per page codeigniter
this is my controller , i use $config['per_page'] to limit my post but it not work still all my database show in it,

```<code>function index()

{

    $jumlah_data = $this->m_berita->jumlah_data();

    $config['base_url'] = base_url().'berita/index/';
    $config['total_rows'] = $jumlah_data;
    $config['per_page'] = 2;
    $from = $this->uri->segment(3);

    $this->pagination->initialize($config);

    $halaman['berita'] = $this->m_berita->data($config['per_page'],$from);

    $urutan['berita'] = $this->db->order_by("id", "desc");

    $data['berita'] = $this->m_berita->data_berita()->result();

    $this->load->view('artikel', $data, $urutan, $halaman);

}
</code>```

my model

```<code>class m_berita extends CI_Model{

public function __construct()

    {
        $this->load->database();
    }

    public function data_berita(){
        return $this->db->get('berita');

    }

    public function data($number,$offset){
        return $query = $this->db->get('berita',$number,$offset)->result();
    }

    function jumlah_data(){
        return $this->db->get('berita')->num_rows();
    }
</code>```

and this my view

```<code>    <?php
$no = $this->uri->segment('3') + 1;
foreach ($berita as $u) {
?>

<?php $no++;?>
<div class="container">
<?php $u->id; ?>
    <h4> <?php echo $u->judul; ?> </h4>
    <span style="margin-bottom: 5%;" class="image left 3u"><img class="fit" src="<?php echo base_url('images/').$u->gambar; ?>" alt="" /></span>
    <?php $artikel = $u->isi; $artikel=word_limiter($artikel, 98); ?> <?php echo $artikel;?> <?php echo anchor('berita/tampil_berita/'.$u->id,'Read More'); ?>
</div>

<?php } ?>
<div class="container">
<ul class="pagination">
  <li><?php echo $this->pagination->create_links(); ?></li>
</ul>
</div>
</code>```

答:
Controller Code :

```<code>$this->load->library('pagination');

$config['base_url'] = 'base_url().'berita/index/';

$config['total_rows'] = $this->db->get('berita')->num_rows();

$config['next_link'] = 'Next';

$config['prev_link'] = 'Previous';

$config['uri_segment'] = 4;

$config['per_page'] = 10;

$config['num_links'] = 20;

$config['full_tag_open'] = '<div id="pagination" class="pagination">';

$config['full_tag_close'] = '</div>';

$this->pagination->initialize($config);

$this->data['berita'] = $this->m_berita->data_berita($config['per_page']);
</code>```

Model Code :

```<code>function data_berita($per_page) {

        $query = $this->db->get('berita', $per_page, $this->uri->segment(3));

        return $query->result_array();

    }
</code>```

View Code :

```<code>echo $this->pagination->create_links();
</code>```

and then loop

Body:
this is my controller , i use $config['per_page'] to limit my post but it not work still all my database show in it,

function index()

{

    $jumlah_data = $this->m_berita->jumlah_data();

    $config['base_url'] = base_url().'berita/index/';
    $config['total_rows'] = $jumlah_data;
    $config['per_page'] = 2;
    $from = $this->uri->segment(3);

    $this->pagination->initialize($config);

    $halaman['berita'] = $this->m_berita->data($config['per_page'],$from);

    $urutan['berita'] = $this->db->order_by("id", "desc");

    $data['berita'] = $this->m_berita->data_berita()->result();

    $this->load->view('artikel', $data, $urutan, $halaman);

}

my model

class m_berita extends CI_Model{

public function __construct()

    {
        $this->load->database();
    }

    public function data_berita(){
        return $this->db->get('berita');

    }

    public function data($number,$offset){
        return $query = $this->db->get('berita',$number,$offset)->result();
    }

    function jumlah_data(){
        return $this->db->get('berita')->num_rows();
    }

and this my view

    <?php
$no = $this->uri->segment('3') + 1;
foreach ($berita as $u) {
?>

<?php $no++;?>

<?php $u->id; ?>

 <?php echo $u->judul; ?>

    <img class="fit" src="<?php echo base_url('images/').$u->gambar; ?>" alt="" />
    <?php $artikel = $u->isi; $artikel=word_limiter($artikel, 98); ?> <?php echo $artikel;?> <?php echo anchor('berita/tampil_berita/'.$u->id,'Read More'); ?>

<?php } ?>

<?php echo $this->pagination->create_links(); ?>

Body:
Controller Code :

$this->load->library('pagination');

$config['base_url'] = 'base_url().'berita/index/';

$config['total_rows'] = $this->db->get('berita')->num_rows();

$config['next_link'] = 'Next';

$config['prev_link'] = 'Previous';

$config['uri_segment'] = 4;

$config['per_page'] = 10;

$config['num_links'] = 20;

$config['full_tag_open'] = '<div id="pagination" class="pagination">';

$config['full_tag_close'] = '</div>';

$this->pagination->initialize($config);

$this->data['berita'] = $this->m_berita->data_berita($config['per_page']);

Model Code :

function data_berita($per_page) {

        $query = $this->db->get('berita', $per_page, $this->uri->segment(3));

        return $query->result_array();

    }

View Code :

echo $this->pagination->create_links();

and then loop


问:
Node.js error handling with socket.emit
I have some node.js client side code like this:

```<code>socket.emit('clickAccept', { myrecid: recid });
</code>```

Server side node.js code gets it fine and all is well.

If I take the server down to simulate a server side outage, then click the button that fires this socket.emit on the client side, this happens:

Nothing really, I guess it might eventually time out

When I bring the server back up, the clicks end up being sent to the server and the server acts on them (TCP-like I Guess).

What I want to happen is for those socket.emit calls to die after a short timeout and not send when the server comes back up, it causes all sorts of confusion because if they click 3 times, nothing happens, then when/if the connection or server comes back up they get 3 reactions all at once.

Also, if they click and it times out because the server is down, I would like to show an error to the client user to let them know that basically the click didn't work and to try again.

I know how to act on and show an error if the socket goes down but I don't want to do this if they aren't trying to click something at that time. No sense is firing errors at the user because the socket went down briefly if they have no need to do anything at that moment.

So, to be clear, I only want to show an error if they click on the button and the socket between the client and server is down. AND... If they get an error, I want to kill that emit, not save it all up and fire it and all the other clicks when the server comes back up a few seconds later.

Thanks in advance and I hope that was at least reasonably clear.

答:
The root of your issue is that socket.io attempts to buffer any data that it can't currently send to the server (because the connection to the server is disconnected) and when the server comes back up and the connection is restored, it then sends that data.

You can see the technical details for how this works here: socket.io stop re-emitting event after x seconds/first failed attempt to get a response

You have several implementation options:

If socket.io already knows the client is not connected to the server, then don't buffer the data (perhaps even give you back an error to show to your user).

When socket.io reconnects and there was data buffered while the connection was down, clear that data and throw it away so old data isn't sent on a reconnect.

Implement a timeout to do one of the above after some sort of timeout.

So, to be clear, I only want to show an error if they click on the button and the socket between the client and server is down. AND... If they get an error, I want to kill that emit, not save it all up and fire it and all the other clicks when the server comes back up a few seconds later.

Probably, the simplest way to do that is to implement a version of what is shown in the above referenced answer:

```<code>Socket.prototype.emitWhenConnected = function(msg, data) {
    if (this.connected) {
        this.emit(msg, data);
        return null;
    } else {
        return new Error("not connected");
    }
}
</code>```

Then, switch your code from using .emit() to use .emitWhenConnected() and check the return value when using it.  If the return value is null, then no error was detected.  If the return value is not null, then there was an error.

Title: Node.js error handling with socket.emit

Body:
I have some node.js client side code like this:

socket.emit('clickAccept', { myrecid: recid });

Server side node.js code gets it fine and all is well.

If I take the server down to simulate a server side outage, then click the button that fires this socket.emit on the client side, this happens:

Nothing really, I guess it might eventually time out

When I bring the server back up, the clicks end up being sent to the server and the server acts on them (TCP-like I Guess).

What I want to happen is for those socket.emit calls to die after a short timeout and not send when the server comes back up, it causes all sorts of confusion because if they click 3 times, nothing happens, then when/if the connection or server comes back up they get 3 reactions all at once.

Also, if they click and it times out because the server is down, I would like to show an error to the client user to let them know that basically the click didn't work and to try again.

I know how to act on and show an error if the socket goes down but I don't want to do this if they aren't trying to click something at that time. No sense is firing errors at the user because the socket went down briefly if they have no need to do anything at that moment.

So, to be clear, I only want to show an error if they click on the button and the socket between the client and server is down. AND... If they get an error, I want to kill that emit, not save it all up and fire it and all the other clicks when the server comes back up a few seconds later.

Thanks in advance and I hope that was at least reasonably clear.

Body:
The root of your issue is that socket.io attempts to buffer any data that it can't currently send to the server (because the connection to the server is disconnected) and when the server comes back up and the connection is restored, it then sends that data.

You can see the technical details for how this works here: socket.io stop re-emitting event after x seconds/first failed attempt to get a response

You have several implementation options:

If socket.io already knows the client is not connected to the server, then don't buffer the data (perhaps even give you back an error to show to your user).

When socket.io reconnects and there was data buffered while the connection was down, clear that data and throw it away so old data isn't sent on a reconnect.

Implement a timeout to do one of the above after some sort of timeout.

So, to be clear, I only want to show an error if they click on the button and the socket between the client and server is down. AND... If they get an error, I want to kill that emit, not save it all up and fire it and all the other clicks when the server comes back up a few seconds later.

Probably, the simplest way to do that is to implement a version of what is shown in the above referenced answer:

Socket.prototype.emitWhenConnected = function(msg, data) {
    if (this.connected) {
        this.emit(msg, data);
        return null;
    } else {
        return new Error("not connected");
    }
}

Then, switch your code from using .emit() to use .emitWhenConnected() and check the return value when using it.  If the return value is null, then no error was detected.  If the return value is not null, then there was an error.


问:
Can one git branch bloat another in the same remote?
I have a git repository with a master branch on the origin remote. Other devs on the team are pushing their own dev/feature branches to the same remote. Eventually these branches will either be discarded, or squash-merged into master and later deleted.

Now some devs on the team are unfamiliar with git and are likely to bloat the history of their feature branches by adding binary files, etc. Eventually they will send a pull review request, which must be reviewed, and reviewers will enforce that no binaries are added.

In this scenario, I expect the dev/feature branches to be bloated (e.g. git might become slow, pulling/cloning them might take a while, etc). The question is whether this will cause any performance issues for people just working with other branches in the same remote that are not bloated.

答:
The question is whether this will cause any performance issues for people just working with other branches in the same remote that are not bloated.

If the bloated branches are pushed, yes, it will impact other's performance, but only for git fetch (which includes git pull). It will download the whole history and full content of every branch by default. There are various ways around this, like git clone --single-branch to get only master, but there's a better solution below.

But it should not affect other operations. git diff, git log, etc... should all be largely unaffected.

Rather than preventing people from putting binaries in version control, or cloning only certain branches, use git-lfs. This is the best of both worlds. You can put binary files in version control, but the actual content is stored outside the repository to avoid repository bloat.


问:
multi left join sql - optimize table schema or sql
this is my sql and it is too slow, plz tell me how to optimize my table schema or this sql

SELECT
    activityLog.id, activityLog.business_id, activityLog.business_typedict.label,
    dict.id, callLog.id, callLog.duration, callLog.record_url,
    leads.name AS "leads.name", customer.name AS "customer.name",
    niche.name AS "niche.name", contacts.name AS "contacts.name",
    task.name AS "task.name"
FROM
    biz_business_log activityLog
    LEFT JOIN leads_leads leads
        ON activityLog.business_type=1 AND activityLog.business_id=leads.id
          AND EXISTS (SELECT 1 FROM sys_office
                      WHERE 1 = 1 AND (id = '5' OR parent_ids LIKE '5,%')
                          AND id=leads.office_id)
    LEFT JOIN cust_customer customer
        ON activityLog.business_type=2 AND activityLog.business_id=customer.id
          AND EXISTS (SELECT 1 FROM sys_office
                      WHERE 1 = 1 AND (id = '5' OR parent_ids LIKE '5,%')
                          AND id=customer.office_id)
    LEFT JOIN niche_niche niche
        ON activityLog.business_type=3 AND activityLog.business_id=niche.id
          AND EXISTS (SELECT 1 FROM sys_office
                      WHERE 1 = 1 AND (id = '5' OR parent_ids LIKE '5,%')
                          AND id=niche.office_id)
    LEFT JOIN contacts_contacts contacts
        ON activityLog.business_type=4 AND activityLog.business_id=contacts.id
          AND EXISTS (SELECT 1 FROM sys_office
                      WHERE 1 = 1 AND (id = '5' OR parent_ids LIKE '5,%')
                          AND id=contacts.office_id)
    LEFT JOIN task_task task
        ON activityLog.business_type=5 AND activityLog.business_id=task.id
          AND EXISTS (SELECT 1 FROM sys_office
                      WHERE 1 = 1 AND (id = '5' OR parent_ids LIKE '5,%')
                          AND id=task.office_id)
    LEFT JOIN sys_dict dict
        ON activityLog.activity_log_type = dict.value
    LEFT JOIN biz_call_log callLog
        ON callLog.business_log_id = activityLog.id
WHERE
    1=1
    AND dict.type='activity_log_type'
    AND dict.company_id = 2
    AND activityLog.company_id = 2
    AND dict.delete_flag = 0
ORDER BY
    IFNULL(activityLog.update_time, activityLog.create_time) DESC
LIMIT
    0,20
```

explain:

答: because dict no use index and using temporary</p>

Body:
this is my sql and it is too slow, plz tell me how to optimize my table schema or this sql

SELECT
    activityLog.id, activityLog.business_id, activityLog.business_typedict.label,
    dict.id, callLog.id, callLog.duration, callLog.record_url,
    leads.name AS "leads.name", customer.name AS "customer.name",
    niche.name AS "niche.name", contacts.name AS "contacts.name",
    task.name AS "task.name"
FROM
    biz_business_log activityLog
    LEFT JOIN leads_leads leads
        ON activityLog.business_type=1 AND activityLog.business_id=leads.id
          AND EXISTS (SELECT 1 FROM sys_office
                      WHERE 1 = 1 AND (id = '5' OR parent_ids LIKE '5,%')
                          AND id=leads.office_id)
    LEFT JOIN cust_customer customer
        ON activityLog.business_type=2 AND activityLog.business_id=customer.id
          AND EXISTS (SELECT 1 FROM sys_office
                      WHERE 1 = 1 AND (id = '5' OR parent_ids LIKE '5,%')
                          AND id=customer.office_id)
    LEFT JOIN niche_niche niche
        ON activityLog.business_type=3 AND activityLog.business_id=niche.id
          AND EXISTS (SELECT 1 FROM sys_office
                      WHERE 1 = 1 AND (id = '5' OR parent_ids LIKE '5,%')
                          AND id=niche.office_id)
    LEFT JOIN contacts_contacts contacts
        ON activityLog.business_type=4 AND activityLog.business_id=contacts.id
          AND EXISTS (SELECT 1 FROM sys_office
                      WHERE 1 = 1 AND (id = '5' OR parent_ids LIKE '5,%')
                          AND id=contacts.office_id)
    LEFT JOIN task_task task
        ON activityLog.business_type=5 AND activityLog.business_id=task.id
          AND EXISTS (SELECT 1 FROM sys_office
                      WHERE 1 = 1 AND (id = '5' OR parent_ids LIKE '5,%')
                          AND id=task.office_id)
    LEFT JOIN sys_dict dict
        ON activityLog.activity_log_type = dict.value
    LEFT JOIN biz_call_log callLog
        ON callLog.business_log_id = activityLog.id
WHERE
    1=1
    AND dict.type='activity_log_type'
    AND dict.company_id = 2
    AND activityLog.company_id = 2
    AND dict.delete_flag = 0
ORDER BY
    IFNULL(activityLog.update_time, activityLog.create_time) DESC
LIMIT
    0,20

explain:


问:
Task scheduling for multiple tasks in java?
i have build a java clock with using timer,which works fine for a single task to alarm on next given/setted time, but i am having problem in scheduling multiple tasks(alarms for diff. times) with this timer, as two times can clash each other(same times for two different works) how to synchronize between such conditions, please help....

Thanks and Regards

Alok Sharma

答:
I agree with Lukas that you can use quartz. It is the best, scalable and robust solution.

But if you need something relatively small you can continue using timer based solution. As javadoc of Timer class indicates your tasks should take very few time. In this case you can forget about time clash. If your tasks take more then 0.1 seconds run them in separate thread. I mean use Timer as a trigger that just makes task to start in separate thread.

The thread may be done as following:

Create thread yourself. If you are in J2EE container it is bad practice. If you are in Tomcat it is ... not so bad.

Use thread pool. Comments about container are relevant here too.

Use JMS: Timer just pushes message to JMS. MDB or its equivalent receives message and performs task.

Using Timer itsef in J2EE container is a bad practice too. If you are there and wish to be "clean" use JCA to to run Timer.


问:
Fetch Data from html form to use it in views.py-Django
I am new to django so bear with me.I am trying to build a simple web app to fetch the current weather.Problem is I am not able to fetch the pincode entered in my HTML form and use it in my views.py file.
As I told u I am new to django so please try to explain it the most simple way.
Thanks.

答:
Your form has GET method, but in view you are trying to fetch data from POST.
Change view code to this:

```<code>data=request.GET.get('Location')
</code>```

Also you shoul move

```<code>return HttpResponse('hello')
</code>```

at the end of view. Code after return will never be called.

Body:
Your form has GET method, but in view you are trying to fetch data from POST.
Change view code to this:

data=request.GET.get('Location')

Also you shoul move

return HttpResponse('hello')

at the end of view. Code after return will never be called.


问:
QSystemTrayIcon.setIcon not working to change the tray icon
```<code>import sys
from PyQt5.QtWidgets import QSystemTrayIcon, QApplication, QMenu
from PyQt5.QtGui import QIcon

class autoparse():
    def __init__(self):

       self.main()

    def main(self):
        app = QApplication(sys.argv)

        self.trayIcon = QSystemTrayIcon(QIcon("icons\icon-windowed.ico"), app)
        self.menu = QMenu()
        self.autopconfig = self.menu.addAction('Config')
        self.autopconfig.triggered.connect(self.swapicon)
        self.trayIcon.setContextMenu(self.menu)

        self.trayIcon.show()
        sys.exit(app.exec_())
    def swapicon(self):
        QSystemTrayIcon.setIcon(QIcon("icons\python.ico"))

test1 = autoparse()
</code>```

I can get the initial icon to set just fine and I can work around the issue by creating 2 icons for app and then doing a self.trayIcon.hide() and self.newicon.show() but I don't feel this is the right way to do it.

Pycharm shows a notice saying "Expected QSystemTrayIcon, got QIcon" but if I swap QIcon with QSystemTrayIcon then it says Qicon is missing. SOOOOOO I change it to QSystemTrayIcon(QIcon("icons\python.ico") and it still says QIcon is unfilled. It seems like the problem detection is going in circles.

Running the code as is gives me "setIcon (self, QIcon): first argument of unbound method must have type 'QSystemTrayIcon'" when I run the swapicon function. If I remove QIcon so its just setIcon (file) then I get "setIcon (self, QIcon): not enough arguments"

答:
QSystemTrayIcon is not a static element so to change some property you must use the instance, in your case you must change:

```<code>QSystemTrayIcon.setIcon(QIcon("icons\python.ico"))
</code>```

to:

```<code>self.trayIcon.setIcon(QIcon("icons\python.ico"))
</code>```

You may have been confused with QSystemTrayIcon(QIcon("icons\icon-windowed.ico"), app), this is a constructor and can receive the icon.

ContentLicense: CC BY-SA 4.0

Body:
import sys
from PyQt5.QtWidgets import QSystemTrayIcon, QApplication, QMenu
from PyQt5.QtGui import QIcon

class autoparse():
    def __init__(self):

       self.main()

    def main(self):
        app = QApplication(sys.argv)

        self.trayIcon = QSystemTrayIcon(QIcon("icons\icon-windowed.ico"), app)
        self.menu = QMenu()
        self.autopconfig = self.menu.addAction('Config')
        self.autopconfig.triggered.connect(self.swapicon)
        self.trayIcon.setContextMenu(self.menu)

        self.trayIcon.show()
        sys.exit(app.exec_())
    def swapicon(self):
        QSystemTrayIcon.setIcon(QIcon("icons\python.ico"))

test1 = autoparse()

I can get the initial icon to set just fine and I can work around the issue by creating 2 icons for app and then doing a self.trayIcon.hide() and self.newicon.show() but I don't feel this is the right way to do it.

Pycharm shows a notice saying "Expected QSystemTrayIcon, got QIcon" but if I swap QIcon with QSystemTrayIcon then it says Qicon is missing. SOOOOOO I change it to QSystemTrayIcon(QIcon("icons\python.ico") and it still says QIcon is unfilled. It seems like the problem detection is going in circles.

Running the code as is gives me "setIcon (self, QIcon): first argument of unbound method must have type 'QSystemTrayIcon'" when I run the swapicon function. If I remove QIcon so its just setIcon (file) then I get "setIcon (self, QIcon): not enough arguments"

Body:
QSystemTrayIcon is not a static element so to change some property you must use the instance, in your case you must change:

QSystemTrayIcon.setIcon(QIcon("icons\python.ico"))

to:

self.trayIcon.setIcon(QIcon("icons\python.ico"))

You may have been confused with QSystemTrayIcon(QIcon("icons\icon-windowed.ico"), app), this is a constructor and can receive the icon.


问:
Xpath selector not working for (presumably) Ajax control
I am trying to select flights between 2 places on this travel website.

I am able to select the source (LEAVING FROM field), but having issues with destination (GOING TO field) input field.

Here is the code:

```<code>public class CathaypacificFlightSearch {
    static WebDriver driver=null;
    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.gecko.driver", "D:\\bala back up\\personel\\selenium\\Jars\\Drivers\\geckodriver.exe");
        driver=new FirefoxDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://www.cathaypacific.com/cx/en_IN.html");

        WebElement leavingFrom=driver.findElement(By.xpath("//*[@id='depart-label']"));
        leavingFrom.click();
        leavingFrom.sendKeys("Bengaluru"); // Entering the starting point

        WebElement cityList=driver.findElement(By.xpath("//*[contains(@id,'ui-id')]//a"));
        System.out.println(cityList.getText());
        cityList.click();  // Selecting the required option

        WebElement goingTo=driver.findElement(By.xpath("//*[@id='destination-label']"));
        goingTo.click();
        goingTo.sendKeys("Singapore");  //Entering the Destination point

        WebElement gCityList=driver.findElement(By.xpath("//*[contains(@id,'ui-id')]//a")); //THIS IS WHERE XPATH IS NOT WORKING
        System.out.println(gCityList.getText());
        gCityList.click();
}}
</code>```

I also tried using the below xpath and cssSelector, but no luck.

```<code> //WebElement gCityList=driver.findElement(By.cssSelector("li[id*='ui-id'] a"));
 //WebElement gCityList=driver.findElement(By.xpath("//ul[contains(@id,'ui-id')]//li//a"));
</code>```

FYI, a similar kind of XPath worked for source field. Only having issues with selecting the destination city.

答:
Well, I've loaded your test-case into my automation harness and I've seen your problem. You're logic was good, but your selectors strategy was your undoing.

You are using the "//*[contains(@id,'ui-id')]//a" XPath selector to target the suggested city options for each of your <input> field values (Leaving from/Going to).

It's working for cityList, but failing for gCityList. This is due to the fact you're selector will match both suggestions (even though your cityList one is now hidden). As you probably already know, in Selenium, if your selector matches multiple WebElements, it will click on the first one, in your case, on the
  of the departure (Going from) suggested options.

Possible fixes:

1.) Make your city suggestion selectors more specific (I used CSS selectors):

```<code>// for 'Departure'
WebElement cityList=driver.findElement(By.cssSelector("div.flight-depart li[id*='ui-id'] a"));
System.out.println(cityList.getText());
cityList.click();  // Selecting the required option

// for 'Destiation'
WebElement gCityList=driver.findElement(By.cssSelector("div.flight-destination li[id*='ui-id'] a"));
System.out.println(gCityList.getText());
gCityList.click();
</code>```

2.) Make use of the .sendKeys() method:

```<code>WebElement leavingFrom=driver.findElement(By.xpath("//*[@id='depart-label']"));
leavingFrom.click();
leavingFrom.sendKeys("Bengaluru"); // Entering the starting point

// Now we are performing a TAB, or Enter to auto-complete the departure
leavingFrom.sendKeys(Keys.TAB) //, or leavingFrom.sendKeys(Keys.ENTER)

WebElement goingTo=driver.findElement(By.xpath("//*[@id='destination-label']"));
goingTo.click();
goingTo.sendKeys("Singapore");  //Entering the Destination point

// Now we are performing a 'Tab', or 'Enter' to auto-complete the destination
goingTo.sendKeys(Keys.TAB) //, or goingTo.sendKeys(Keys.ENTER)
</code>```

Note: This method (2.) is only going to be relevant if the value you're inserting into the Departure/Destination fields is unique (only one city returned), else it will auto-complete the first city in the list.

Note2: On a personal note, I would always go with the .sendKeys() method as it's way safer than clicking on dynamical ID WebElements populated in containers such as that drop-down list. Yet, if you want to stick with method 1., then you should add some Explicit Waits to your .click()s.

Let me know if this helps you. Cheers!

Body:
I am trying to select flights between 2 places on this travel website.

I am able to select the source (LEAVING FROM field), but having issues with destination (GOING TO field) input field.

Here is the code:

public class CathaypacificFlightSearch {
    static WebDriver driver=null;
    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.gecko.driver", "D:\\bala back up\\personel\\selenium\\Jars\\Drivers\\geckodriver.exe");
        driver=new FirefoxDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://www.cathaypacific.com/cx/en_IN.html");

        WebElement leavingFrom=driver.findElement(By.xpath("//*[@id='depart-label']"));
        leavingFrom.click();
        leavingFrom.sendKeys("Bengaluru"); // Entering the starting point

        WebElement cityList=driver.findElement(By.xpath("//*[contains(@id,'ui-id')]//a"));
        System.out.println(cityList.getText());
        cityList.click();  // Selecting the required option

        WebElement goingTo=driver.findElement(By.xpath("//*[@id='destination-label']"));
        goingTo.click();
        goingTo.sendKeys("Singapore");  //Entering the Destination point

        WebElement gCityList=driver.findElement(By.xpath("//*[contains(@id,'ui-id')]//a")); //THIS IS WHERE XPATH IS NOT WORKING
        System.out.println(gCityList.getText());
        gCityList.click();
}}

I also tried using the below xpath and cssSelector, but no luck.

 //WebElement gCityList=driver.findElement(By.cssSelector("li[id*='ui-id'] a"));
 //WebElement gCityList=driver.findElement(By.xpath("//ul[contains(@id,'ui-id')]//li//a"));

FYI, a similar kind of XPath worked for source field. Only having issues with selecting the destination city.

Body:
Well, I've loaded your test-case into my automation harness and I've seen your problem. You're logic was good, but your selectors strategy was your undoing.

You are using the "//*[contains(@id,'ui-id')]//a" XPath selector to target the suggested city options for each of your <input> field values (Leaving from/Going to).

It's working for cityList, but failing for gCityList. This is due to the fact you're selector will match both suggestions (even though your cityList one is now hidden). As you probably already know, in Selenium, if your selector matches multiple WebElements, it will click on the first one, in your case, on the <li> <a> of the departure (Going from) suggested options.

Possible fixes:

1.) Make your city suggestion selectors more specific (I used CSS selectors):

// for 'Departure'
WebElement cityList=driver.findElement(By.cssSelector("div.flight-depart li[id*='ui-id'] a"));
System.out.println(cityList.getText());
cityList.click();  // Selecting the required option

// for 'Destiation'
WebElement gCityList=driver.findElement(By.cssSelector("div.flight-destination li[id*='ui-id'] a"));
System.out.println(gCityList.getText());
gCityList.click();

2.) Make use of the .sendKeys() method:

WebElement leavingFrom=driver.findElement(By.xpath("//*[@id='depart-label']"));
leavingFrom.click();
leavingFrom.sendKeys("Bengaluru"); // Entering the starting point

// Now we are performing a TAB, or Enter to auto-complete the departure
leavingFrom.sendKeys(Keys.TAB) //, or leavingFrom.sendKeys(Keys.ENTER)

WebElement goingTo=driver.findElement(By.xpath("//*[@id='destination-label']"));
goingTo.click();
goingTo.sendKeys("Singapore");  //Entering the Destination point

// Now we are performing a 'Tab', or 'Enter' to auto-complete the destination
goingTo.sendKeys(Keys.TAB) //, or goingTo.sendKeys(Keys.ENTER)

Note: This method (2.) is only going to be relevant if the value you're inserting into the Departure/Destination fields is unique (only one city returned), else it will auto-complete the first city in the list.

Note2: On a personal note, I would always go with the .sendKeys() method as it's way safer than clicking on dynamical ID WebElements populated in containers such as that drop-down list. Yet, if you want to stick with method 1., then you should add some Explicit Waits to your .click()s.

Let me know if this helps you. Cheers!


问:
PHP script on mySQL table : FROM_UNIXTIME and INTO OUTFILE issues
This is my first php script for a mysql table.

mySQL table looks as below :

From that table i would like to generate a dynamic HTML table with the following requirements :

HTML table sorted ASC by NEXT_EVENT

HTML table gets a new column showing NEXT_EVENT value as human readable datetime.

Once the table is sorted i need to output ID and NEXT_EVENT values from the very first row to a TXT file, the 2 values will be comma separared.

I tryed to write a PHP script, but it get errors.

Sorting ASC looks working properly, but conversion with FROM UNIXTIME does not and file output won't work either.

mysql table's name is : 'webpilot'

```<code>$result = mysqli_query($conn, "SELECT * FROM webpilot ORDER BY NEXT_EVENT ASC");

$table = '<table>
            <tr>
                <th>ID</th>
                <th>NAME</th>
                <th>NEXT_EVENT</th>
            </tr>';

if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {
        mysqli_query($conn, "SELECT FROM_UNIXTIME(".$row['NEXT_EVENT'].") as $datetime");

        $table .= '<tr>
                    <td>'.$row['ID'].'</td>
                    <td>'.$row['NAME'].'</td>
                    <td>'.$row['NEXT_EVENT'].'</td>
                    <td>'.$datetime.'</td>
                   </tr>';
    }
} else {
    $table .= '<tr><td colspan="3">No date found</td></tr>';
}
$table .= '</table>';
echo $table;

$fileoutput = mysql_query($conn, "SELECT ID,NAME,NEXT_EVENT FROM webpilot INTO OUTFILE '/next_event.txt' LINES TERMINATED BY '\n'");
</code>```

The live result can be seen here : http://s529471052.onlinehome.fr/bs3/gpio/dyntable.php

but i had to comment out the following line, as it reports an error avoiding the rest of script to be run and php webpage to be displayed.

```<code>mysqli_query($conn,"SELECT FROM_UNIXTIME(.$row['NEXT_EVENT']) as $datetime");
</code>```

Line 203 is related to that line :

```<code>$fileoutput = mysql_query($conn,"SELECT ID,NAME,NEXT_EVENT FROM webpilot INTO OUTFILE '/next_event.txt' LINES TERMINATED BY '\n'");
</code>```

Would you please show me how to get expected result.

答:
HTML table sorted ASC by NEXT_EVENT (You are correct)

```<code>SELECT * FROM webpilot ORDER BY NEXT_EVENT ASC
</code>```

HTML table gets a new column showing NEXT_EVENT value as human readable datetime. (You can try to more easy way, do inside php)

```<code>$getDateTime = mysqli_query($conn,"SELECT NEXT_EVENT FROM webpilot where NEXT_EVENT=".$row['NEXT_EVENT'].");

$rowDateTime = mysqli_fetch_array($getDateTime );

$datetime = date("Y-m-d H:i:s", $rowDateTime('NEXT_EVENT'));
</code>```

MYSQL ways:

```<code>SELECT ID, FAVORITE, NAME, ORDERTYPE, STATE, LAST_EVENT RECCURENCY, FROM_UNIXTIME(timestamp) as datetime FROM webpilot ORDER BY timestamp ASC
</code>```

so your this codemysqli_query($conn, "SELECT FROM_UNIXTIME(".$row['NEXT_EVENT'].") as $datetime"); can be remove.

Body:
This is my first php script for a mysql table.

mySQL table looks as below :

From that table i would like to generate a dynamic HTML table with the following requirements :

HTML table sorted ASC by NEXT_EVENT

HTML table gets a new column showing NEXT_EVENT value as human readable datetime.

Once the table is sorted i need to output ID and NEXT_EVENT values from the very first row to a TXT file, the 2 values will be comma separared.

I tryed to write a PHP script, but it get errors.

Sorting ASC looks working properly, but conversion with FROM UNIXTIME does not and file output won't work either.

mysql table's name is : 'webpilot'

$result = mysqli_query($conn, "SELECT * FROM webpilot ORDER BY NEXT_EVENT ASC");

$table = '

                ID
                NAME
                NEXT_EVENT

';

if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {
        mysqli_query($conn, "SELECT FROM_UNIXTIME(".$row['NEXT_EVENT'].") as $datetime");

        $table .= '

                    '.$row['ID'].'
                    '.$row['NAME'].'
                    '.$row['NEXT_EVENT'].'
                    '.$datetime.'

';
    }
} else {
    $table .= '
No date found
';
}
$table .= '
';
echo $table;

$fileoutput = mysql_query($conn, "SELECT ID,NAME,NEXT_EVENT FROM webpilot INTO OUTFILE '/next_event.txt' LINES TERMINATED BY '\n'");

The live result can be seen here : http://s529471052.onlinehome.fr/bs3/gpio/dyntable.php

but i had to comment out the following line, as it reports an error avoiding the rest of script to be run and php webpage to be displayed.

mysqli_query($conn,"SELECT FROM_UNIXTIME(.$row['NEXT_EVENT']) as $datetime");

Line 203 is related to that line :

$fileoutput = mysql_query($conn,"SELECT ID,NAME,NEXT_EVENT FROM webpilot INTO OUTFILE '/next_event.txt' LINES TERMINATED BY '\n'");

Would you please show me how to get expected result.

Body:
HTML table sorted ASC by NEXT_EVENT (You are correct)

SELECT * FROM webpilot ORDER BY NEXT_EVENT ASC

HTML table gets a new column showing NEXT_EVENT value as human readable datetime. (You can try to more easy way, do inside php)

$getDateTime = mysqli_query($conn,"SELECT NEXT_EVENT FROM webpilot where NEXT_EVENT=".$row['NEXT_EVENT'].");

$rowDateTime = mysqli_fetch_array($getDateTime );

$datetime = date("Y-m-d H:i:s", $rowDateTime('NEXT_EVENT'));

MYSQL ways:

SELECT ID, FAVORITE, NAME, ORDERTYPE, STATE, LAST_EVENT RECCURENCY, FROM_UNIXTIME(timestamp) as datetime FROM webpilot ORDER BY timestamp ASC

so your this codemysqli_query($conn, "SELECT FROM_UNIXTIME(".$row['NEXT_EVENT'].") as $datetime"); can be remove.


问:
Angular 4 Refresh section of page only
Hi community I have a Plunker where I have implemented this flow:

Updated Plunker: I solved but header component gets called each time and I have to put my header component in each html is there a better way to do it?

Login

Show list of countries (User info on top)

Click on one of the  countries and show details about it (Problem is here)

Go back to list

I need to refresh only the section of the countries list, but in my plunker you can see the whole page is refreshing I want to keep the user info on top (static).

I have little experience.
Thanks a lot!

```<code>@Component({
selector : 'login',
template: `
<input type="text" value="james">
<input type="password" value="123">
<button (click)="logIn()">Login</button>
`
})
class LoginComponent {
constructor(private route: ActivatedRoute,
            private router: Router) { }

    logIn () {
        //LOGIN LOGIC
        this.router.navigate(['/base']);
    }
}
</code>```

答:
The router-outlet shows the content of the route.
That means you have to place your user template code above the router-outlet so it wone be affected by your route navigation...

```<code><label>User: Mr. James</label>
  <label>Role: Administrator</label>
  <hr>
<router-outlet>
</code>```

Title: Angular 4 Refresh section of page only

Body:
Hi community I have a Plunker where I have implemented this flow:

Updated Plunker: I solved but header component gets called each time and I have to put my header component in each html is there a better way to do it?

Login

Show list of countries (User info on top)

Click on one of the  countries and show details about it (Problem is here)

Go back to list

I need to refresh only the section of the countries list, but in my plunker you can see the whole page is refreshing I want to keep the user info on top (static).

I have little experience.
Thanks a lot!

@Component({
selector : 'login',
template: `
<input type="text" value="james">
<input type="password" value="123">
<button (click)="logIn()">Login</button>
`
})
class LoginComponent {
constructor(private route: ActivatedRoute,
            private router: Router) { }

    logIn () {
        //LOGIN LOGIC
        this.router.navigate(['/base']);
    }
}

Body:
The router-outlet shows the content of the route.
That means you have to place your user template code above the router-outlet so it wone be affected by your route navigation...

<label>User: Mr. James</label>
  <label>Role: Administrator</label>
  <hr>
<router-outlet>


问:
2 var arrays change mysteriously after i change arrayToDataTable input (google chart line)
I'm displaying a line chart of currency rates via google charts.

Basically i have 2 type of values:

Date (format iso8601)

Rate (decimal number)

i'm trying to impelement a function that changes the input of arrayToDataTable:

```<code>    dataChart = google.visualization.arrayToDataTable(arrayForChart);
</code>```

basically im changing the role of base currency between the 2 currencies.
the line chart should reverse everytime i do that.

when i'm pressing on the change display button once ('currencyRates_changeDisplay'), its changes the graph. he graph is reversed and everything is ok.
but after that the graph is stuck with the values of the last change. and the google chart line will not change any more.

i did some debugging.

it seems that the "var arrayForChart" and "var arrayTest" change to the value of "var arrayChanegeDisplaySettingForChart" after i press the button "#currencyRates_changeDisplay" once. and they do not change anymore after that.
i think it is because of this line:

```<code>    dataChart = google.visualization.arrayToDataTable(arrayForChart);
</code>```

but i'm not sure. here is my full code:

```<code>    <script>

    var arrayForChart;
    var arrayTest;
    var checkkk=0;

    var arrayChanegeDisplaySettingForChart;

    var dataChart;

    var baseCurrencyDisplaySetting=1;
    var baseCurrency="USD";

    var dayResults;
    var yesterdayResults;

    var fromCurrency;
    var toCurrency;
    var currencyAmount;

    var direction;
    var percent;
    var gainLoss;

    loadRates();

    $(document).ajaxStop(function () {

        if (baseCurrencyDisplaySetting==2){
            arrayChanegeDisplaySettingForChart=arrayForChart;
            arrayChanegeDisplaySettingForChart=changeArrayForChart(arrayChanegeDisplaySettingForChart);
        }
        whenAjaxReallyStops();

    });
    function whenAjaxReallyStops() {

            //alert("AJAX REALLY ENDED");
            displayCurrencyConverterResult();
            dipsplayChart();
            displayAllRates();

    }

    function loadRates(){
        baseCurrency   = $("#baseCurrency").val();
        fromCurrency   = $("#currency_from").val();
        toCurrency   = $("#currency_to").val();
        currencyAmount = $("#currency_amount").val();

    $.ajax({
    type: "POST",
    url: "just a url here...",
    data: {
    baseCurrency: baseCurrency,
    toCurrency: toCurrency
            },
    cache: false
        }).done(function(data) {

            resultArray=data;
            dayResults=resultArray["0"];
            yesterdayResults=resultArray["1"];
            console.log(dayResults);
            console.log(yesterdayResults);
            arrayTest=resultArray["arrayForCharts"];
            arrayForChart=resultArray["arrayForCharts"];
            alert ("arrayForChart changed");
            console.log(resultArray);

        });
    }

    function changeArrayForChart(changedArrayForChart){

        console.log(changedArrayForChart);
        for (var key in changedArrayForChart) {
            if (key != 0){
                let newRateForChart=1*(1 / changedArrayForChart[key][1]);
                changedArrayForChart[key][1]=newRateForChart;
            }
        }
        return changedArrayForChart;
    }
    function dipsplayChart(){
        //from here google chart stuff
        google.charts.load("current", {packages: ["corechart", "line"]});
        google.charts.setOnLoadCallback(drawLineColors);

        //until here google chart stuff
    }

    function drawLineColors() {
        dataChart=null;
        if (baseCurrencyDisplaySetting==1){
            if (checkkk==0){
                    console.log (JSON.stringify(arrayForChart));
                dataChart = google.visualization.arrayToDataTable(arrayForChart);
            }else{
                    console.log (JSON.stringify(arrayTest));
                dataChart = google.visualization.arrayToDataTable(arrayTest);
            }
            checkkk=checkkk+1;
            var titleChartString = baseCurrency + " vs " + toCurrency + " Last 90 days";
        }else{
                console.log(JSON.stringify(arrayChanegeDisplaySettingForChart));
dataChart = google.visualization.arrayToDataTable(arrayChanegeDisplaySettingForChart);
            var titleChartString = toCurrency + " vs " + baseCurrency + " Last 90 days";
        }
        var options = {
    title: titleChartString ,
    explorer: {
    actions: ["dragToZoom", "rightClickToReset"],
    axis: "horizontal",
    keepInBounds: true
            },
    hAxis: {
    title: "Date",
    format: "d MMM",

            },
    vAxis: {
    title: "Rate",
            },
    colors: ["#a52714", "#097138"]
        };
        var chart = new google.visualization.LineChart(document.getElementById("chart_div"));
        chart.draw(dataChart, options);
    }

    $("body").on( "click", "#currencyRates_changeDisplay", function(){
        if (baseCurrencyDisplaySetting==1){
            baseCurrencyDisplaySetting=2;
            if (typeof arrayChanegeDisplaySettingForChart == "undefined"){
                arrayChanegeDisplaySettingForChart=arrayForChart;
                arrayChanegeDisplaySettingForChart=changeArrayForChart(arrayChanegeDisplaySettingForChart);
            }
        }else{
            baseCurrencyDisplaySetting=1;
        }
        displayAllRates();
        dipsplayChart();
    });

    </script>
</code>```

here are sample data:

arrayForChart:

```<code>[[{"label":"Date","id":"Date","type":"date"},{"label":"Rate","id":"Rate","type":"number"}],["Date(2017, 3, 10)",3.6618],["Date(2017, 3, 11)",3.6565]]
</code>```

then i press the button 'currencyRates_changeDisplay'.

i get this notice in console log:

```<code>[Violation] Added non-passive event listener to a scroll-blocking 'mousewheel' event. Consider marking event handler as 'passive' to make the page more responsive.
</code>```

arrayChanegeDisplaySettingForChart:

```<code>[[{"label":"Date","id":"Date","type":"date"},{"label":"Rate","id":"Rate","type":"number"}],["Date(2017, 3, 10)",0.2730897372876727],["Date(2017, 3, 11)",0.2734855736359907]]
</code>```

then i press the button 'currencyRates_changeDisplay' again.

arrayTest:

```<code>[[{"label":"Date","id":"Date","type":"date"},{"label":"Rate","id":"Rate","type":"number"}],["Date(2017, 3, 10)",0.2730897372876727],["Date(2017, 3, 11)",0.2734855736359907]
</code>```

from here, evrytime i press the butoon 'currencyRates_changeDisplay': 'arrayTest' and 'arrayForChart' are stuck with the values of 'arrayChanegeDisplaySettingForChart' and the chart never change.

Anybody might know what is the problem?

many thanks!!

答:
Your code is instructing to only call changeArrayForChart when arrayChanegeDisplaySettingForChart is undefined. Therefore this only happens once, as after the first time, that latter variable is no longer undefined.

So change this:

```<code>if (baseCurrencyDisplaySetting==1){
    baseCurrencyDisplaySetting=2;
    if (typeof arrayChanegeDisplaySettingForChart == "undefined"){
        arrayChanegeDisplaySettingForChart=arrayForChart;
        arrayChanegeDisplaySettingForChart=changeArrayForChart(arrayChanegeDisplaySettingForChart);
    }
}else{
    baseCurrencyDisplaySetting=1;
}
</code>```

To:

```<code>// For arrays you can just use `!` to test for not being defined:
if (!arrayChanegeDisplaySettingForChart) {
    // This happens only once:
    arrayChanegeDisplaySettingForChart = arrayForChart;
}
// Now toggle. Note that changeArrayForChart mutates the given array
// so you don't need the return value
changeArrayForChart(arrayChanegeDisplaySettingForChart);
// A way to toggle between 1 and 2:
baseCurrencyDisplaySetting = 3 - baseCurrencyDisplaySetting;
</code>```

Body:
I'm displaying a line chart of currency rates via google charts.

Basically i have 2 type of values:

Date (format iso8601)

Rate (decimal number)

i'm trying to impelement a function that changes the input of arrayToDataTable:

    dataChart = google.visualization.arrayToDataTable(arrayForChart);

basically im changing the role of base currency between the 2 currencies.
the line chart should reverse everytime i do that.

when i'm pressing on the change display button once ('currencyRates_changeDisplay'), its changes the graph. he graph is reversed and everything is ok.
but after that the graph is stuck with the values of the last change. and the google chart line will not change any more.

i did some debugging.

it seems that the "var arrayForChart" and "var arrayTest" change to the value of "var arrayChanegeDisplaySettingForChart" after i press the button "#currencyRates_changeDisplay" once. and they do not change anymore after that.
i think it is because of this line:

    dataChart = google.visualization.arrayToDataTable(arrayForChart);

but i'm not sure. here is my full code:

here are sample data:

arrayForChart:

[[{"label":"Date","id":"Date","type":"date"},{"label":"Rate","id":"Rate","type":"number"}],["Date(2017, 3, 10)",3.6618],["Date(2017, 3, 11)",3.6565]]

then i press the button 'currencyRates_changeDisplay'.

i get this notice in console log:

[Violation] Added non-passive event listener to a scroll-blocking 'mousewheel' event. Consider marking event handler as 'passive' to make the page more responsive.

arrayChanegeDisplaySettingForChart:

[[{"label":"Date","id":"Date","type":"date"},{"label":"Rate","id":"Rate","type":"number"}],["Date(2017, 3, 10)",0.2730897372876727],["Date(2017, 3, 11)",0.2734855736359907]]

then i press the button 'currencyRates_changeDisplay' again.

arrayTest:

[[{"label":"Date","id":"Date","type":"date"},{"label":"Rate","id":"Rate","type":"number"}],["Date(2017, 3, 10)",0.2730897372876727],["Date(2017, 3, 11)",0.2734855736359907]

from here, evrytime i press the butoon 'currencyRates_changeDisplay': 'arrayTest' and 'arrayForChart' are stuck with the values of 'arrayChanegeDisplaySettingForChart' and the chart never change.

Anybody might know what is the problem?

many thanks!!

Body:
Your code is instructing to only call changeArrayForChart when arrayChanegeDisplaySettingForChart is undefined. Therefore this only happens once, as after the first time, that latter variable is no longer undefined.

So change this:

if (baseCurrencyDisplaySetting==1){
    baseCurrencyDisplaySetting=2;
    if (typeof arrayChanegeDisplaySettingForChart == "undefined"){
        arrayChanegeDisplaySettingForChart=arrayForChart;
        arrayChanegeDisplaySettingForChart=changeArrayForChart(arrayChanegeDisplaySettingForChart);
    }
}else{
    baseCurrencyDisplaySetting=1;
}

To:

// For arrays you can just use `!` to test for not being defined:
if (!arrayChanegeDisplaySettingForChart) {
    // This happens only once:
    arrayChanegeDisplaySettingForChart = arrayForChart;
}
// Now toggle. Note that changeArrayForChart mutates the given array
// so you don't need the return value
changeArrayForChart(arrayChanegeDisplaySettingForChart);
// A way to toggle between 1 and 2:
baseCurrencyDisplaySetting = 3 - baseCurrencyDisplaySetting;


问:
Exception thrown when attempting to delete object from listview
I'm working in javafx. I have a Listview which is updated by an ObservableList.
Here is my code.

```<code>//Dummy list for testing listview
    final ObservableList<String> names = FXCollections.observableArrayList(
            "Julia", "Ian", "Sue", "Matthew", "Hannah", "Stephan", "Denise");

    final ListView<String> listView = new ListView(names.sorted());

    //Try to remove the first element for testing purposes
    listView.getItems().remove(0);
</code>```

When I try to delete I get this exception.

```<code>Exception in Application start method
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
    at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.UnsupportedOperationException
    at java.util.AbstractList.remove(AbstractList.java:161)
    at sample.Main.start(Main.java:39)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
    ... 1 more
Exception running application sample.Main
</code>```

Is there some step that I'm missing in this case? Or am I trying to use ObservableList and ListView in the wrong way?

答:
You are using javafx.collections.transformation.SortedList<E> in an incorrect way.

It's only a wrapper, a view.

To remove an element, you have to use the source collection: names.

javafx.collections.transformation.SortedList<E> doesn't implements remove() but:

Wraps an ObservableList and sorts it's content. All changes in the
  ObservableList are propagated immediately to the SortedList. Note:
  invalid SortedList (as a result of broken comparison) doesn't send any
  notification to listeners on becoming valid again.

JavaDoc of javafx.collections.transformation.SortedList

This tutorial may help.

Body:
I'm working in javafx. I have a Listview which is updated by an ObservableList.
Here is my code.

//Dummy list for testing listview
    final ObservableList<String> names = FXCollections.observableArrayList(
            "Julia", "Ian", "Sue", "Matthew", "Hannah", "Stephan", "Denise");

    final ListView<String> listView = new ListView(names.sorted());

    //Try to remove the first element for testing purposes
    listView.getItems().remove(0);

When I try to delete I get this exception.

Exception in Application start method
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
    at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.UnsupportedOperationException
    at java.util.AbstractList.remove(AbstractList.java:161)
    at sample.Main.start(Main.java:39)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
    ... 1 more
Exception running application sample.Main

Is there some step that I'm missing in this case? Or am I trying to use ObservableList and ListView in the wrong way?


答:
if you are using GET in form

in views

```<code>location = request.GET.get('Location')
print(location)
return HttpResponse('whatever')
</code>```

Title: Fetch Data from html form to use it in views.py-Django

Body:
I am new to django so bear with me.I am trying to build a simple web app to fetch the current weather.Problem is I am not able to fetch the pincode entered in my HTML form and use it in my views.py file.
As I told u I am new to django so please try to explain it the most simple way.
Thanks.

Body:
if you are using GET in form

in views

location = request.GET.get('Location')
print(location)
return HttpResponse('whatever')


问:
Unable to open file in exported jar
So i have wrote an application that uses 'config.properties' & 'profile.properties' Files.

Anything works fine in Eclipse (Debug), but after exporting Runnable JAR
, this JAR does not include the Properties Files.
so i dragged this two files inside the jar and now i got this exception / error:

```<code>java.io.FileNotFoundException: config.properties (Nie można odnaleźć
określonego pliku)
   at java.io.FileInputStream.open0(Native Method)
   at java.io.FileInputStream.open(Unknown Source)
   at java.io.FileInputStream.<init>(Unknown Source)
   at com.profilemaker.Profiler.<init>(Profiler.java:32)
   at com.main.Main.main(Main.java:7) Exception in thread "main" java.lang.NullPointerException
   at com.profilemaker.Profiler.<init>(Profiler.java:43)
   at com.main.Main.main(Main.java:7)
</code>```

答:
If the properties are in the jar, you shouldn't be using a FileInputStream to read them. Entries of a jar file are not files. A file lives on your file system. Not in a jar.

Use

```<code>Profiler.class.getResourceAsStream("/path/in/the/jar/of/the.properties")
</code>```

to read the properties resources.

Title: Unable to open file in exported jar

Body:
So i have wrote an application that uses 'config.properties' & 'profile.properties' Files.

Anything works fine in Eclipse (Debug), but after exporting Runnable JAR
, this JAR does not include the Properties Files.
so i dragged this two files inside the jar and now i got this exception / error:

java.io.FileNotFoundException: config.properties (Nie można odnaleźć
określonego pliku)
   at java.io.FileInputStream.open0(Native Method)
   at java.io.FileInputStream.open(Unknown Source)
   at java.io.FileInputStream.<init>(Unknown Source)
   at com.profilemaker.Profiler.<init>(Profiler.java:32)
   at com.main.Main.main(Main.java:7) Exception in thread "main" java.lang.NullPointerException
   at com.profilemaker.Profiler.<init>(Profiler.java:43)
   at com.main.Main.main(Main.java:7)

Body:
If the properties are in the jar, you shouldn't be using a FileInputStream to read them. Entries of a jar file are not files. A file lives on your file system. Not in a jar.

Use

Profiler.class.getResourceAsStream("/path/in/the/jar/of/the.properties")

to read the properties resources.


问:
How do I bundle a JRE in my JAR, so that it can run on systems without Java?
I want to bundle a JRE inside my executable JAR, so that the exe can run on any system.

I have tried Launch4j, but that approach requires me to ship both the JRE and the exe. As per my requirements, I should not use an installer to ship, nor extract/install the JRE on the client machine.

How do I put a JRE inside a JAR and make use of it?

答:
You cannot put a JRE inside a JAR file.  (Well you can ... but it won't help.)

What you need to do is build and distribute an installer.  Prior to Java 9, the recommended way to create an installer is to use a commercial or open-source installer generator.  (Google will help you find one.)

It is also possible to do embed a JRE in a ZIP file, as described here:

How to bundle a JRE with Launch4j? (see the accepted answer)

The ZIP file contains the JRE and the application JAR, and other files that it needs.  The user has to unzip the ZIP file to install the application.

.. but it's copying total JRE in client system of almost 100 MB.  Is it possible to make JRE light weight?

Not really.  The most (legal) light-weight way to distribute a JRE is to distribute an Oracle Java installer.  Beware that the Java Binary License forbids the distribution of a cut-down JRE.  If you want to go down that path talk to a lawyer first!!

Distributing Java apps with an embedded JRE is arguably a bad thing:

It fills up the user's disk with multiple JREs.

The JREs tend to be hidden away / not visible to normal security updates / patching / audits.  Hence they tend to become a security liability.

You need to regularly update your distributables ... to avoid foisting out-of-date / insecure JREs on the unsuspecting user.

From Java 9 onwards there is a better solution than inluding a standard JRE in your installer.  Use the new jlink utility to create a tailored JRE for your application; see https://www.baeldung.com/jlink for a tutorial, and the Oracle Jlink manual entry.

Note that jlink addresses the concerns with embedded JREs that we mentioned above.  But it clearly makes it your responsibility1 to provide JVM security patches to your users in the form of new jlink'd distributables.

1 - In reality, it has always been an application supplier / vendor's responsibility to advise and assist customers in upgrading embedded JREs.  Unfortunately, many vendors neglected this, leading to customers running applications with known Java vulnerabilities, and Sun/Oracle getting the blame ... unfairly ... for the vendor's failings.


问:
body-parser parse by index
Using DataTables for front end and nodejs+express+mongoose+body-parser on back end

When I tried to delete a row in the table, this is what is passed to backend (HTTP DELETE)

```<code>action:remove
data[5957c1368225f446c84dde9b][_id]:5957c1368225f446c84dde9b
data[5957c1368225f446c84dde9b][updatedAt]:2017-07-01T15:35:18.407Z
data[5957c1368225f446c84dde9b][createdAt]:2017-07-01T15:35:18.407Z
data[5957c1368225f446c84dde9b][account]:test@gmail.com
data[5957c1368225f446c84dde9b][name]:Beryl Welch
data[5957c1368225f446c84dde9b][number]:074-882-4899 x241
data[5957c1368225f446c84dde9b][email]:Naomi.Lemke@yahoo.com
data[5957c1368225f446c84dde9b][__v]:0
</code>```

I am trying to get the value _id out of the DELETE request 5957c1368225f446c84dde9b

I am trying to figure out how to access this value without knowing it in the first place as this value is actually the ID of the document to delete from mongo

If I stringify req.query, this is what I get

```<code>{"action":"remove","data":{"5957c3e07c5c3c150c10f5cb":{"_id":"5957c3e0
7c5c3c150c10f5cb","updatedAt":"2017-07-01T15:46:40.635Z","createdAt":"2017-
07-01T15:46:40.635Z","account":"test@gmail.com","name":"Breanna
Ratke","number":
"(055) 304-7364 x20329","email":"Mathilde.Moore51@hotmail.com","__v":"0"}}}
</code>```

Any ideas?

Thanks
/T

答:
Thank a lot Andy.
This also worked for me:</p>

```<code>Object.getOwnPropertyNames(req.body["data"]).toString();
</code>```

Title: body-parser parse by index

Body:
Using DataTables for front end and nodejs+express+mongoose+body-parser on back end

When I tried to delete a row in the table, this is what is passed to backend (HTTP DELETE)

action:remove
data[5957c1368225f446c84dde9b][_id]:5957c1368225f446c84dde9b
data[5957c1368225f446c84dde9b][updatedAt]:2017-07-01T15:35:18.407Z
data[5957c1368225f446c84dde9b][createdAt]:2017-07-01T15:35:18.407Z
data[5957c1368225f446c84dde9b][account]:test@gmail.com
data[5957c1368225f446c84dde9b][name]:Beryl Welch
data[5957c1368225f446c84dde9b][number]:074-882-4899 x241
data[5957c1368225f446c84dde9b][email]:Naomi.Lemke@yahoo.com
data[5957c1368225f446c84dde9b][__v]:0

I am trying to get the value _id out of the DELETE request 5957c1368225f446c84dde9b

I am trying to figure out how to access this value without knowing it in the first place as this value is actually the ID of the document to delete from mongo

If I stringify req.query, this is what I get

{"action":"remove","data":{"5957c3e07c5c3c150c10f5cb":{"_id":"5957c3e0
7c5c3c150c10f5cb","updatedAt":"2017-07-01T15:46:40.635Z","createdAt":"2017-
07-01T15:46:40.635Z","account":"test@gmail.com","name":"Breanna
Ratke","number":
"(055) 304-7364 x20329","email":"Mathilde.Moore51@hotmail.com","__v":"0"}}}

Any ideas?

Thanks
/T

Body:
Thank a lot Andy.
This also worked for me:

Object.getOwnPropertyNames(req.body["data"]).toString();


问:
"Fallthrough" in Django URLConf?
I've got a situation where I'm basically allowing any URL, with no prefix; one way that I had been thinking of designing it involved basically having two '' matches - the first would see if it could serve the request and if not it would fall through to the second.

If I raise Http404 from the first view, I get a 404 page.

If I return, I get a ValueError complaining I "didn't return an HttpResponse object."

Looking briefly at the code in django.core.urlresolvers, I'm fairly convinced that the architecture simply isn't in place to do this - it resolves to a single match, the URL resolution phase is entirely separate from the view phase and once you've gone to the view there's no returning to the URL resolution phase. Is this correct? Personally I would see this as a slight deficiency; I can see how it could be quite useful to have two types of 404 - one saying "no, it doesn't exist" as it currently does, and one saying "I don't know about it", which would make it look through further the URLConf. At the moment it seems to me like anyone wanting this style of system basically has to replace the URL resolution part of Django.

I've worked around this (basically getting a trivial view to palm it off to one and then the other), so I don't think I really have any need for this particular thing any more, but still I'm curious if there is a way of doing this which I just didn't spot, or whether there might be a neater workaround.

答: I think the workaround you mention at the end is the right way to do this in Django. It's part of the contract of a view that it must return an HttpResponse, so there's no way of avoiding that.

Title: "Fallthrough" in Django URLConf?