问:
Swing draws only after resizing
Program should draw the line twice longer after clicking the button, but it only does that after clicking AND THEN resizing the window. I don't know what is happening, i thought this is gonna be easy.

Could you tell me how can I fix it?

```<code>import javax.swing.*;
import java.awt.*;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.util.Random;
import java.util.Stack;

class MyButtonPanel extends JPanel {

public static final int HEIGHT = 800;
public static final int WIDTH = 800;
private JButton greenButton;
private JPanel buttonPanel;
Stack<Point> points;
int X = 25;
int Y = 25;

public MyButtonPanel() {
    greenButton = new GreenButton();
    points = new Stack<Point>();

    buttonPanel = this;

    setLayout(new FlowLayout());
    setPreferredSize(new Dimension(WIDTH, HEIGHT));
    add(greenButton);

}

class GreenButton extends JButton implements ActionListener
{
    GreenButton() {
        super("LongerLine");
        addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        //points.push(new Point(0,0));
        X = 2 * X;
        Y = 2 * Y;
        validate();
    }

}

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;
    //g2d.setColor(Color.WHITE);
    //g2d.fillRect(0, 0, WIDTH, HEIGHT);
    g2d.setColor(Color.BLACK);
    //drawLines(g2d);
    Line2D lin = new Line2D.Double(0,0, X, Y);
    g2d.draw(lin);
}

private void drawLines(Graphics2D g2d) {
    //Line2D lin = new Line2D.Float(100, 100, 250, 260);
    //g2d.draw(lin);
    double x1, y1, x2, y2;
    /*
    for(Point point: points) {
        x1 = (double) point.getX();
        y1 = (double) point.getY();
        Line2D line = new Line2D.Double(x1,y1,200,200);
        g2d.draw(line);
    }
    */
}

}

public class MyActionFrame extends JFrame {

public MyActionFrame() {
    super("Test akcji");

    JPanel buttonPanel = new MyButtonPanel();
    add(buttonPanel);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    pack();
    setVisible(true);
    //setResizable(false);
}

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            new MyActionFrame();
        }
    });
}
}
</code>```

答: This validate();, or better revalidate(); is called when a container's layout needs to be re-done, often when components are added or removed, and is not what you're doing or desiring. Instead you want to call repaint() which suggests that the component be painted.

Title: Swing draws only after resizing

Body:
Program should draw the line twice longer after clicking the button, but it only does that after clicking AND THEN resizing the window. I don't know what is happening, i thought this is gonna be easy.

Could you tell me how can I fix it?

import javax.swing.*;
import java.awt.*;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.util.Random;
import java.util.Stack;

class MyButtonPanel extends JPanel {

public static final int HEIGHT = 800;
public static final int WIDTH = 800;
private JButton greenButton;
private JPanel buttonPanel;
Stack<Point> points;
int X = 25;
int Y = 25;

public MyButtonPanel() {
    greenButton = new GreenButton();
    points = new Stack<Point>();

    buttonPanel = this;

    setLayout(new FlowLayout());
    setPreferredSize(new Dimension(WIDTH, HEIGHT));
    add(greenButton);

}

class GreenButton extends JButton implements ActionListener
{
    GreenButton() {
        super("LongerLine");
        addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        //points.push(new Point(0,0));
        X = 2 * X;
        Y = 2 * Y;
        validate();
    }

}

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;
    //g2d.setColor(Color.WHITE);
    //g2d.fillRect(0, 0, WIDTH, HEIGHT);
    g2d.setColor(Color.BLACK);
    //drawLines(g2d);
    Line2D lin = new Line2D.Double(0,0, X, Y);
    g2d.draw(lin);
}

private void drawLines(Graphics2D g2d) {
    //Line2D lin = new Line2D.Float(100, 100, 250, 260);
    //g2d.draw(lin);
    double x1, y1, x2, y2;
    /*
    for(Point point: points) {
        x1 = (double) point.getX();
        y1 = (double) point.getY();
        Line2D line = new Line2D.Double(x1,y1,200,200);
        g2d.draw(line);
    }
    */
}

}

public class MyActionFrame extends JFrame {

public MyActionFrame() {
    super("Test akcji");

    JPanel buttonPanel = new MyButtonPanel();
    add(buttonPanel);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    pack();
    setVisible(true);
    //setResizable(false);
}

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            new MyActionFrame();
        }
    });
}
}


来源: stackexchange

问:
How to get a of most recent posts/messages with the Facebook Graph API
The Graph API lets you obtain the "top news" for a given user, via the "/home" connection type. But how do you obtain the "Most recent"?

I also asked this on the facebook forum

答: /home is the most recent from the looks of it. I just tested /me/home and it's the same as my "most recent" feed on the front end. You never know with Facebook though. Data is never reliable.</p>

ContentLicense: CC BY-SA 2.5


问:
Can't get date modified From Json
i can get section name , url  web title and headline but i can't get lastmodified date  from parse json this code for Json

{
   "response":{
      "status":"ok",
      "userTier":"developer",
      "total":368,
      "startIndex":1,
      "pageSize":10,
      "currentPage":1,
      "pages":37,
      "orderBy":"relevance",
      "results":[
         {
            "id":"technology/2017/may/24/fitness-trackers-out-of-step-when-measuring-calories-research-shows",
            "type":"article",
            "sectionId":"technology",
            "sectionName":"Technology",
            "webPublicationDate":"2017-05-24T15:00:24Z",
            "webTitle":"Fitness trackers out of step when measuring calories, research shows",
            "webUrl":"https://www.theguardian.com/technology/2017/may/24/fitness-trackers-out-of-step-when-measuring-calories-research-shows",
            "apiUrl":"https://content.guardianapis.com/technology/2017/may/24/fitness-trackers-out-of-step-when-measuring-calories-research-shows",
            "fields":{
               "headline":"Fitness trackers out of step when measuring calories, research shows",
               "lastModified":"2017-05-24T15:02:19Z",
               "thumbnail":"https://media.guim.co.uk/8d3e17604195078ec89e20329e2ddc5027eca8ea/0_213_6362_3817/500.jpg"
            },
            "isHosted":false
         },```
</div>
</div>
</p>

<p>and this my code to parse it.</p>

<p>JSONObject response = root.getJSONObject("response");</p>

```        if(response.has("results")){

            JSONArray results = response.getJSONArray("results");
            for(int i=0;i<results.length();i++){
                long lastModified=0;
                String headline=null;
                JSONObject details=results.getJSONObject(i);
                String sectionName=details.getString("sectionName");
                Log.i(LOG_TAG,sectionName);
                String webUrl=details.getString("webUrl");
                Log.i(LOG_TAG,webUrl);
                if(details.has("fields")){
                JSONObject fields=details.getJSONObject("fields");
                    if(fields.has("headline")){

                 headline =fields.getString("headline");
                Log.i(LOG_TAG,headline);}
                if(fields.has("lastModified")){
                 lastModified =fields.getLong("lastModified");
                Log.i(LOG_TAG, String.valueOf(lastModified));}}
```

i do not know why not get lastmodified date?

答:
this java class</p>

```<code>public class News {
private  String mTitle;
private String mSectionName;
private String mUrl;
private String mDate;
// constructor  of news`

 public News(String title,String sectionName,String date,String url){
    mTitle =title;
    mSectionName=sectionName;
    mDate=date;
    mUrl=url;}
public  News(String title,String sectionName){ mTitle =title;
    mSectionName=sectionName;}
// get methods.
public String getmTitle(){return mTitle;}
public String getmSectionName(){return mSectionName;}
public String getmUrl(){return mUrl;}

public String getmDate() {
    return mDate;}}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Can't get date modified From Json

Body:
i can get section name , url  web title and headline but i can't get lastmodified date  from parse json this code for Json

{
   "response":{
      "status":"ok",
      "userTier":"developer",
      "total":368,
      "startIndex":1,
      "pageSize":10,
      "currentPage":1,
      "pages":37,
      "orderBy":"relevance",
      "results":[
         {
            "id":"technology/2017/may/24/fitness-trackers-out-of-step-when-measuring-calories-research-shows",
            "type":"article",
            "sectionId":"technology",
            "sectionName":"Technology",
            "webPublicationDate":"2017-05-24T15:00:24Z",
            "webTitle":"Fitness trackers out of step when measuring calories, research shows",
            "webUrl":"https://www.theguardian.com/technology/2017/may/24/fitness-trackers-out-of-step-when-measuring-calories-research-shows",
            "apiUrl":"https://content.guardianapis.com/technology/2017/may/24/fitness-trackers-out-of-step-when-measuring-calories-research-shows",
            "fields":{
               "headline":"Fitness trackers out of step when measuring calories, research shows",
               "lastModified":"2017-05-24T15:02:19Z",
               "thumbnail":"https://media.guim.co.uk/8d3e17604195078ec89e20329e2ddc5027eca8ea/0_213_6362_3817/500.jpg"
            },
            "isHosted":false
         },

and this my code to parse it.

JSONObject response = root.getJSONObject("response");

        if(response.has("results")){

            JSONArray results = response.getJSONArray("results");
            for(int i=0;i<results.length();i++){
                long lastModified=0;
                String headline=null;
                JSONObject details=results.getJSONObject(i);
                String sectionName=details.getString("sectionName");
                Log.i(LOG_TAG,sectionName);
                String webUrl=details.getString("webUrl");
                Log.i(LOG_TAG,webUrl);
                if(details.has("fields")){
                JSONObject fields=details.getJSONObject("fields");
                    if(fields.has("headline")){

                 headline =fields.getString("headline");
                Log.i(LOG_TAG,headline);}
                if(fields.has("lastModified")){
                 lastModified =fields.getLong("lastModified");
                Log.i(LOG_TAG, String.valueOf(lastModified));}}

i do not know why not get lastmodified date?

Body:
this java class

public class News {
private  String mTitle;
private String mSectionName;
private String mUrl;
private String mDate;
// constructor  of news`

 public News(String title,String sectionName,String date,String url){
    mTitle =title;
    mSectionName=sectionName;
    mDate=date;
    mUrl=url;}
public  News(String title,String sectionName){ mTitle =title;
    mSectionName=sectionName;}
// get methods.
public String getmTitle(){return mTitle;}
public String getmSectionName(){return mSectionName;}
public String getmUrl(){return mUrl;}

public String getmDate() {
    return mDate;}}


问:
Populate table in ascending order
I use the code below to populate a very large table and the table populates in descending order. Sometimes, the full table does not show and the new contents down will not appear. I want this table to populate in ascending order since what i require is the most recent contents.
Thanks for your help.</p>

```<code><?php
echo "<table style='border: solid 1px black;'>";
echo "<tr><th>mydate</th><th>mball14</th><th>mball14a</th><th>mball15</th>
<th>mball15a</th><th>mball16</th><th>mball16a</th><th>mball17</th>
<th>mball17a</th><th>mball18</th><th>mball18a</th><th>mball19</th>
<th>mball19a</th><th>mball20</th><th>mball20a</th></tr>";

class TableRows extends RecursiveIteratorIterator {
 function __construct($it) {
     parent::__construct($it, self::LEAVES_ONLY);
 }

 function current() {
     return "<td style='width: 150px; border: 1px solid black;'>" . parent::current(). "</td>";
 }

 function beginChildren() {
     echo "<tr>";
 }

 function endChildren() {
     echo "</tr>" . "\n";
 }
}

$servername = "localhost";
$username = "***";
$password = "***";
$dbname = "***";

try {
 $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
 $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 $stmt = $conn->prepare("SELECT mydate, mball14, mball14a, mball15, mball15a, mball16, mball16a, mball17, mball17a, mball18, mball18a, mball19, mball19a, mball20, mball20a FROM manager");
 $stmt->execute();

 // set the resulting array to associative
 $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);

 foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
     echo $v;
 }
}
catch(PDOException $e) {
 echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>
</code>```

答:
Change

```<code> $stmt = $conn->prepare("SELECT mydate, mball14, mball14a, mball15, mball15a, mball16, mball16a, mball17, mball17a, mball18, mball18a, mball19, mball19a, mball20, mball20a FROM manager");
</code>```

To

```<code> $stmt = $conn->prepare("SELECT mydate, mball14, mball14a, mball15, mball15a, mball16, mball16a, mball17, mball17a, mball18, mball18a, mball19, mball19a, mball20, mball20a FROM manager ORDER BY mydate DESC");
</code>```

This will take the dates, and put the newest on the top

Title: Populate table in ascending order

Body:
I use the code below to populate a very large table and the table populates in descending order. Sometimes, the full table does not show and the new contents down will not appear. I want this table to populate in ascending order since what i require is the most recent contents.
Thanks for your help.

<?php
echo "
";
echo "
mydate	mball14	mball14a	mball15
mball15a	mball16	mball16a	mball17
mball17a	mball18	mball18a	mball19
mball19a	mball20	mball20a
";

class TableRows extends RecursiveIteratorIterator {
 function __construct($it) {
     parent::__construct($it, self::LEAVES_ONLY);
 }

 function current() {
     return "" . parent::current(). "	";
 }

 function beginChildren() {
     echo "
";
 }

 function endChildren() {
     echo "
" . "\n";
 }
}

$servername = "localhost";
$username = "***";
$password = "***";
$dbname = "***";

try {
 $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
 $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 $stmt = $conn->prepare("SELECT mydate, mball14, mball14a, mball15, mball15a, mball16, mball16a, mball17, mball17a, mball18, mball18a, mball19, mball19a, mball20, mball20a FROM manager");
 $stmt->execute();

 // set the resulting array to associative
 $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);

 foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
     echo $v;
 }
}
catch(PDOException $e) {
 echo "Error: " . $e->getMessage();
}
$conn = null;
echo "
";
?>

Body:
Change

 $stmt = $conn->prepare("SELECT mydate, mball14, mball14a, mball15, mball15a, mball16, mball16a, mball17, mball17a, mball18, mball18a, mball19, mball19a, mball20, mball20a FROM manager");

To

 $stmt = $conn->prepare("SELECT mydate, mball14, mball14a, mball15, mball15a, mball16, mball16a, mball17, mball17a, mball18, mball18a, mball19, mball19a, mball20, mball20a FROM manager ORDER BY mydate DESC");

This will take the dates, and put the newest on the top


问:
An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll Additional information: Input string was not in a correct format
```<code>        //Declaring of "Total Statements"
        double   NetSalary, PensionFundPercentage, grossSalary, TaxableAmount, MonthlySalary, Allowance, Paye, Uif, MedicalAid, totalDeduction;
        double PensionFund;

        double Other = 0;
        double.TryParse(txtOtherDeductions.Text, out Other);

        //Convert Statements
        Allowance = Convert.ToDouble(txtDeductions.Text);
        PensionFund = Convert.ToDouble(txtPenFund.Text);
        Paye = Convert.ToDouble(txtPayasUEarn.Text);
</code>```

 IM UNABLE TO CALCULTE THE SALARY AMOUNT TO AGAINST THE THE AMOUNT QUOTED

答:
Try localize the where it fails.

Taken from msdn.

Remarks

Using the ToDouble(String) method is equivalent to passing value to the Double.Parse(String) method. value is interpreted by using the formatting conventions of the current thread culture.

If you prefer not to handle an exception if the conversion fails, you can call the Double.TryParse method instead. It returns a Boolean value that indicates whether the conversion succeeded or failed.

Read more here: https://msdn.microsoft.com/en-us/library/zh1hkw6k(v=vs.110).aspx

Body:
        //Declaring of "Total Statements"
        double   NetSalary, PensionFundPercentage, grossSalary, TaxableAmount, MonthlySalary, Allowance, Paye, Uif, MedicalAid, totalDeduction;
        double PensionFund;

        double Other = 0;
        double.TryParse(txtOtherDeductions.Text, out Other);

        //Convert Statements
        Allowance = Convert.ToDouble(txtDeductions.Text);
        PensionFund = Convert.ToDouble(txtPenFund.Text);
        Paye = Convert.ToDouble(txtPayasUEarn.Text);

 IM UNABLE TO CALCULTE THE SALARY AMOUNT TO AGAINST THE THE AMOUNT QUOTED


问:
How to do timestamp regex given start time and end time?
I was working on extracting the log lines of interest from a huge log file.
Note that I'm not familiar with python at all.

The log line all starts from a timestamp, like

09:00:00.648711172 [Info  ] [....]
```

<p>And I want to match it with a specific period of time, say from 09:00 to 09:30, I came up with the following solution:</p>

```r'^(09:[012][0-9]|30)
```

The problem is this cannot apply to a generic case, say we're given a start_time and an end_time, how can I do the match?

答:
Regex that matches any one entry of date from 09:00:00 to 09:30:00 and doesn't match anything else:

```<code>log_regex = re.compile(r'09:(([0-2]/d{1}):([0-5]/d{1}|60))|30:00')
</code>```

You want to match all occurrence for this regex:

```<code>log_regex.findAll(your_string_variable)
</code>```

Body:
I was working on extracting the log lines of interest from a huge log file.
Note that I'm not familiar with python at all.

The log line all starts from a timestamp, like

09:00:00.648711172 [Info  ] [....]

And I want to match it with a specific period of time, say from 09:00 to 09:30, I came up with the following solution:

r'^(09:[012][0-9]|30)

The problem is this cannot apply to a generic case, say we're given a start_time and an end_time, how can I do the match?

Body:
Regex that matches any one entry of date from 09:00:00 to 09:30:00 and doesn't match anything else:

log_regex = re.compile(r'09:(([0-2]/d{1}):([0-5]/d{1}|60))|30:00')

You want to match all occurrence for this regex:

log_regex.findAll(your_string_variable)


问:
ÅÄÖ: what is considered more SEO friendly URL
As far as I can tell I shouldn't be using ÅÄÖ (somthing like they have no visual representation in ASCII??).

So what is considered more SEO friendly? Replacing i.e. all "ä" with "a" or "ae"? (The CMS Umbraco replaces with ae and I'm leaning towards this).

EDIT:  Summary of how some Swedish sites does it:

aftonbladet.se/ ä => a (http://www.aftonbladet.se/kropphalsa/)

uppsatser.se/ ä => ä (http://www.uppsatser.se/om/v%C3%A5rd+av/)

lindqvist.com/ ä => a (http://www.lindqvist.com/b/google-maps-placering-ar-gratis)

umbraco CMS sites (like vaxab.se) ä => ae (http://vaxab.se/tjaenster.aspx)

dn.se/ ä => a (http://www.dn.se/sthlm/brak-utanfor-aspuddsbadet-1.1008899)

答:
For what it's worth, Wikipedia, one of the biggest and most prominent sites on the Internet, preserves all sorts of weird diacritics in its URLs. Conventions for changing diacritics to plain letters will vary between languages: Acute and grave accents in French can be safely removed. (The French themselves tend to remove them when writing in block capitals.) Fadas in Irish should be retained if possible, or cleanly removed. Diaereses may be simply stripped, or replaced with a double vowel, or replaced with vowel+e, depending on the language. And for languages written in the Greek or Cyrillic alphabets, there's no obvious system unless you want to go for full transcription.

And there's no need: ru.wikipedia.org/wiki/Заглавная_страница


问:
How to add a div that does not damage the view?
My case is like this

My view is like this :

```<code><div class="form-group">
    <div class="col-sm-10">
        <ul class="list-inline list-photo">
            @foreach($product->photos as $i => $photo)
            <li id="thumbnail-view-{{$i}}" >
                  ...
            </li>
            @endforeach

            @for($i = count($product->photos); $i < 5; $i++)
                <li id="thumbnail-upload-li-{{$i}}">
                    <a href="javascript:" class="thumbnail thumbnail-upload" id="thumbnail-view-{{$i}}">
                        <span class="fa fa-plus fa-2x"></span>
                    </a>
                </li>
                ...
            @endfor
            </div>
        </ul>
    </div>
</div>
</code>```

I want to add div before @for like this :

```<code><div id="test">
    @for($i = count($product->photos); $i < 5; $i++)
        <li id="thumbnail-upload-li-{{$i}}">
            ...
        </li>
        ...
    @endfor
</div>
</code>```

When I add div, the view becomes not tidy

I need to add div. So I want to call it from javascript

How can I solve the problem?

答: try to use span because div has a line break compare to span or another option is to use css to suite your needs</p>

Body:
My case is like this

My view is like this :

            @foreach($product->photos as $i => $photo)

                  ...

            @endforeach

            @for($i = count($product->photos); $i < 5; $i++)

                ...
            @endfor

I want to add div before @for like this :

    @for($i = count($product->photos); $i < 5; $i++)

            ...

        ...
    @endfor

When I add div, the view becomes not tidy

I need to add div. So I want to call it from javascript

How can I solve the problem?


问:
Jquery function for retrieving input values of the active checkbox when the page loads. JFIDDLE
I need to display the values of the selected checkbox when the page loads. Currently, the values are displayed when I click on a checkbox, but I need the values from the default checkbox when page loads.

Here if the link to my code: JFIDDLE

Here is a link to my page: My Website

Here is my code copy & paste:

```<code><!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>TEST LIST</title>
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script src="simpleCart.js"></script>
</head>
<body>
<fieldset id="" class="" style="margin-top: 0px;font-variant: small-caps;letter-spacing: 2px;" data-role="controlgroup">

    <input class="weight1" type="hidden" value="2.0" >
    <input class="price1" type="radio" name="radio-choice-v-2" id="radio-choice-v-2a" value="20.00" checked="checked">
    <label class="price_weight_lable1" style="display: flex;" for="radio-choice-v-2a">
        <div style="flex:2;">2.0 grams</div>
        <div style="flex:1;text-align: center;">$22.00</div>
    </label>

    <input class="weight2" type="hidden" value="3.5" >
    <input class="price2" type="radio" name="radio-choice-v-2" id="radio-choice-v-2b" value="45.00">
    <label class="price_weight_lable2" style="display: flex;" for="radio-choice-v-2b">
        <div style="flex:2;">3.5 grams</div>
        <div style="flex:1;text-align: center;">$45.00</div>
    </label>

   <input class="weight3" type="hidden" value="7.0" >
    <input class="price3" type="radio" name="radio-choice-v-2" id="radio-choice-v-2c" value="90.00">
    <label class="price_weight_lable3" style="display: flex;" for="radio-choice-v-2c">
        <div style="flex:2;">7.0 grams</div>
        <div style="flex:1;text-align: center;">$90.00</div>
  </label>
</fieldset>

    <script>

$('input[type=radio]').on( 'change', function(el){
  $( '.weight_results' ).text( $(this).parent().prev().val() );
  $( '.price_results' ).text( $(this).val() );
});
    </script>

<div class="simpleCart_shelfItem">

    <div class="item_price"> <!-- simplecart div -->
        <div class="price_results"></div> <!-- price function result? -->
    </div>

     <div class="item_weight"> <!-- simplecart div -->
        <div class="weight_results"></div>   <!-- weight function result? -->
    </div>

</div>

</body>
</html>
</code>```

答:
Simply Add .change() at the last of your code to make the change event run on page load

$(document).ready(function(){
  $('input[type=radio]').on( 'change', function(el){
    $( '.weight_results' ).text( $(this).parent().prev().val() );
    $( '.price_results' ).text( $(this).val() );
  }).change(); // add .change to run the code on load
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.js"></script>

<fieldset id="" class="" style="margin-top: 0px;font-variant: small-caps;letter-spacing: 2px;" data-role="controlgroup">

    <input class="weight1" type="hidden" value="2.0" >
    <input class="price1" type="radio" name="radio-choice-v-2" id="radio-choice-v-2a" value="20.00" checked="checked">
    <label class="price_weight_lable1" style="display: flex;" for="radio-choice-v-2a">
     <div style="flex:2;">2.0 grams</div>
     <div style="flex:1;text-align: center;">$20.00</div>
    </label>

    <input class="weight2" type="hidden" value="3.5" >
    <input class="price2" type="radio" name="radio-choice-v-2" id="radio-choice-v-2b" value="45.00">
 <label class="price_weight_lable2" style="display: flex;" for="radio-choice-v-2b">
  <div style="flex:2;">3.5 grams</div>
     <div style="flex:1;text-align: center;">$45.00</div>
 </label>

   <input class="weight3" type="hidden" value="7.0" >
    <input class="price3" type="radio" name="radio-choice-v-2" id="radio-choice-v-2c" value="90.00">
    <label class="price_weight_lable3" style="display: flex;" for="radio-choice-v-2c">
  <div style="flex:2;">7.0 grams</div>
     <div style="flex:1;text-align: center;">$90.00</div>
  </label>
</fieldset>

 <div class="item_price"> <!-- simplecart div -->
  <div class="price_results"></div> <!-- price function result? -->
 </div>

  <div class="item_weight"> <!-- simplecart div -->
  <div class="weight_results"></div>   <!-- weight function result? -->
 </div></code>```

Note: wrap code on $(document).ready() as
  Icewine said

Body:
I need to display the values of the selected checkbox when the page loads. Currently, the values are displayed when I click on a checkbox, but I need the values from the default checkbox when page loads.

Here if the link to my code: JFIDDLE

Here is a link to my page: My Website

Here is my code copy & paste:

<!doctype html>

<meta charset="utf-8">
<title>TEST LIST</title>
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">

<fieldset id="" class="" style="margin-top: 0px;font-variant: small-caps;letter-spacing: 2px;" data-role="controlgroup">

    <input class="weight1" type="hidden" value="2.0" >
    <input class="price1" type="radio" name="radio-choice-v-2" id="radio-choice-v-2a" value="20.00" checked="checked">

2.0 grams

$22.00

    <input class="weight2" type="hidden" value="3.5" >
    <input class="price2" type="radio" name="radio-choice-v-2" id="radio-choice-v-2b" value="45.00">

3.5 grams

$45.00

   <input class="weight3" type="hidden" value="7.0" >
    <input class="price3" type="radio" name="radio-choice-v-2" id="radio-choice-v-2c" value="90.00">

7.0 grams

$90.00

</fieldset>

Body:
Simply Add .change() at the last of your code to make the change event run on page load

$(document).ready(function(){
  $('input[type=radio]').on( 'change', function(el){
    $( '.weight_results' ).text( $(this).parent().prev().val() );
    $( '.price_results' ).text( $(this).val() );
  }).change(); // add .change to run the code on load
});

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.js"></script>

<fieldset id="" class="" style="margin-top: 0px;font-variant: small-caps;letter-spacing: 2px;" data-role="controlgroup">

    <input class="weight1" type="hidden" value="2.0" >
    <input class="price1" type="radio" name="radio-choice-v-2" id="radio-choice-v-2a" value="20.00" checked="checked">
    <label class="price_weight_lable1" style="display: flex;" for="radio-choice-v-2a">
     <div style="flex:2;">2.0 grams</div>
     <div style="flex:1;text-align: center;">$20.00</div>
    </label>

    <input class="weight2" type="hidden" value="3.5" >
    <input class="price2" type="radio" name="radio-choice-v-2" id="radio-choice-v-2b" value="45.00">
 <label class="price_weight_lable2" style="display: flex;" for="radio-choice-v-2b">
  <div style="flex:2;">3.5 grams</div>
     <div style="flex:1;text-align: center;">$45.00</div>
 </label>

   <input class="weight3" type="hidden" value="7.0" >
    <input class="price3" type="radio" name="radio-choice-v-2" id="radio-choice-v-2c" value="90.00">
    <label class="price_weight_lable3" style="display: flex;" for="radio-choice-v-2c">
  <div style="flex:2;">7.0 grams</div>
     <div style="flex:1;text-align: center;">$90.00</div>
  </label>
</fieldset>

 <div class="item_price"> <!-- simplecart div -->
  <div class="price_results"></div> <!-- price function result? -->
 </div>

  <div class="item_weight"> <!-- simplecart div -->
  <div class="weight_results"></div>   <!-- weight function result? -->
 </div>

Note: wrap code on $(document).ready() as
  Icewine said


问:
Xcode 9 only for members of the Apple Developer Program
Did they change it so you need to be in the Apple Developer Program to access the latest Xcode beta version or GM Seed? Because I remember downloading Xcode Beta not too long ago. It says on https://developer.apple.com/library/content/documentation/DeveloperTools/Conceptual/WhatsNewXcode/xcode_9/xcode_9.html :

Prerelease versions of Xcode are made available from developer.apple.com to authorized seed developers, packaged in a compressed XIP file.

Does seed developer equals being a member in the Apple Developer Program?

答:
You may need a developer account to access the betas. However, you will not need a paid account. It is fairly easy and free to create a developer account and download the betas.

Creating a Developer Account

Create an AppleID normally at:

https://appleid.apple.com/account#!&page=create

Alternatively, if you already have an AppleID that you would like to create a developer account with, you can use that.

Go to http://developer.apple.com/account.

Log in with your AppleID. Follow the steps provided to create your Developer Account.

Downloading Betas

After you have created a developer account, you can download the betas from https://developer.apple.com/download/.

Make sure that you do not go to https://beta.apple.com. This is the public beta program and is coming in July, it also doesn't have the Xcode beta.


问:
exception in release mode and not in debug mode
When i run this code in debug mode no exceptions appear but in release mode i get this exception :

Unhandled exception at 0x768b4b32 in RealTimeSLT.exe: Microsoft C++
  exception: cv::Exception at memory location 0x003de734..

why this problem appear only when release ?and how can i fix it ??

```<code>FileStorage fs2(fileName, FileStorage::READ);
fs2.open(fileName, FileStorage::READ);
fs2["Mat"] >> Mat;
fs2["dMat"]>> dMat;
fs2.release();
</code>```

答:
In my case, it was because the OpenCV libraries were built with VS2010, and I was using VS2015.

To resolve issue, I changed my Project Properties > General > Platform Toolset to match the toolset used to build the opencv libraries I was linking with.

Body:
When i run this code in debug mode no exceptions appear but in release mode i get this exception :

Unhandled exception at 0x768b4b32 in RealTimeSLT.exe: Microsoft C++
  exception: cv::Exception at memory location 0x003de734..

why this problem appear only when release ?and how can i fix it ??

FileStorage fs2(fileName, FileStorage::READ);
fs2.open(fileName, FileStorage::READ);
fs2["Mat"] >> Mat;
fs2["dMat"]>> dMat;
fs2.release();


问:
Does if with ifelse ,ifelse needs to have at least one else statement
```<code>if ()
{}else if (){}
else if (){}
else if (){}
else{}
</code>```

Do we need to have at least one  else {}?

答: No it is not. Neither is it required when only using an if statement. Your also asking if it needs at least one else statement. The maximum is 1 else statement. You can not have if(){}else{}else{} (Wouldn't make sense either :P)

Body:
if ()
{}else if (){}
else if (){}
else if (){}
else{}

Do we need to have at least one  else {}?


问:
WebHostBuilder.Build() MissingMethodException in .NET Core migrated solution
I'm migrating a solution built with .NET Core SDK 1.0.0-preview2-1-003177 because  I want to use it in Visual Studio 2017. I use the dotnet migrate command from .NET Core SDK 1.0.1, it goes well, it compiles. When I run the web part with IIS Express the classic Program.cs containing

```<code>var host = new WebHostBuilder()
    .UseKestrel()
    .UseContentRoot(Directory.GetCurrentDirectory())
    .UseIISIntegration()
    .UseStartup<Startup>()
    .Build();

host.Run();
</code>```

crashes at Build() with this exception

System.MissingMethodException: 'Method not found:
  'System.IServiceProvider
  Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(Microsoft.Extensions.DependencyInjection.IServiceCollection)'.'

I can't find the reason at all.

答:
This happened for me because I was over eager and installed too many EntityFrameworkCore packages.

I had

```<code>Microsoft.EntityFrameworkCore 2.0.0-preview1-final
Microsoft.EntityFrameworkCore.SqlServer 1.1.2
</code>```

I removed the first one so I was left with

```<code>Microsoft.EntityFrameworkCore.SqlServer 1.1.2
</code>```

And then the error disappeared.

Body:
I'm migrating a solution built with .NET Core SDK 1.0.0-preview2-1-003177 because  I want to use it in Visual Studio 2017. I use the dotnet migrate command from .NET Core SDK 1.0.1, it goes well, it compiles. When I run the web part with IIS Express the classic Program.cs containing

var host = new WebHostBuilder()
    .UseKestrel()
    .UseContentRoot(Directory.GetCurrentDirectory())
    .UseIISIntegration()
    .UseStartup<Startup>()
    .Build();

host.Run();

crashes at Build() with this exception

System.MissingMethodException: 'Method not found:
  'System.IServiceProvider
  Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(Microsoft.Extensions.DependencyInjection.IServiceCollection)'.'

I can't find the reason at all.

Body:
This happened for me because I was over eager and installed too many EntityFrameworkCore packages.

I had

Microsoft.EntityFrameworkCore 2.0.0-preview1-final
Microsoft.EntityFrameworkCore.SqlServer 1.1.2

I removed the first one so I was left with

Microsoft.EntityFrameworkCore.SqlServer 1.1.2

And then the error disappeared.


问:
file_exists() not working in php5 inside while loop
file_exists isn't working. I've looked at a few examples and still no go. Program does not detect the file. The path of my file is /var/www/osbs/PHPAPI/recording.mp3 and the website root is inside osbs. The location of this file is inside PHPAPI that is why I do not put full path in file_put_contents. The program is able to make the original recording.mp3 but not any appended versions of it.</p>

```<code><?php
$actual_name = pathinfo("PHPAPI/recording.mp3",PATHINFO_FILENAME);
$original_name = $actual_name;
$extension = pathinfo("PHPAPI/recording.mp3",PATHINFO_EXTENSION);

if ($_GET["RecordingUrl"]) {
     if (file_exists("/var/www/osbs/PHPAPI/".$actual_name.".".$extension)) {
        $actual_name = find_new_name($original_name, $extension);
     }
     else {
        $actual_name = $original_name;
     }
     $name = $actual_name.".".$extension;
     file_put_contents($name, file_get_contents($_GET["RecordingUrl"]));
}

function find_new_name ( $file, $extension ) {
    $name = $file.".".$extension;
    $i = 0;
    while(file_exists("/var/www/osbs/PHPAPI/".$name)){
        $new_name = $file.$i;
        $name = $new_name.".".$extension;
        $i++;
    }
    return $new_name;
}
 ?>
</code>```

答:
The problem seems to be in the first line of your script:

```<code>$actual_name = pathinfo("PHPAPI/recording.mp3", PATHINFO_FILENAME);
</code>```

This will assign recording.mp3 to $actual_filename. You are then checking for recording.mp3.mp3 by concatenating the extension to the filename. I think you want to use PATHINFO_BASENAME which will return the filename sans extension.

Body:
file_exists isn't working. I've looked at a few examples and still no go. Program does not detect the file. The path of my file is /var/www/osbs/PHPAPI/recording.mp3 and the website root is inside osbs. The location of this file is inside PHPAPI that is why I do not put full path in file_put_contents. The program is able to make the original recording.mp3 but not any appended versions of it.

<?php
$actual_name = pathinfo("PHPAPI/recording.mp3",PATHINFO_FILENAME);
$original_name = $actual_name;
$extension = pathinfo("PHPAPI/recording.mp3",PATHINFO_EXTENSION);

if ($_GET["RecordingUrl"]) {
     if (file_exists("/var/www/osbs/PHPAPI/".$actual_name.".".$extension)) {
        $actual_name = find_new_name($original_name, $extension);
     }
     else {
        $actual_name = $original_name;
     }
     $name = $actual_name.".".$extension;
     file_put_contents($name, file_get_contents($_GET["RecordingUrl"]));
}

function find_new_name ( $file, $extension ) {
    $name = $file.".".$extension;
    $i = 0;
    while(file_exists("/var/www/osbs/PHPAPI/".$name)){
        $new_name = $file.$i;
        $name = $new_name.".".$extension;
        $i++;
    }
    return $new_name;
}
 ?>

Body:
The problem seems to be in the first line of your script:

$actual_name = pathinfo("PHPAPI/recording.mp3", PATHINFO_FILENAME);

This will assign recording.mp3 to $actual_filename. You are then checking for recording.mp3.mp3 by concatenating the extension to the filename. I think you want to use PATHINFO_BASENAME which will return the filename sans extension.


问:
Connect to Amazon web services SQS (Simple Queue service) using Python?
I was wondering if somebody here knows how I can connect to AWS SQS using Python? Do I need a public Url?

Could someone provide a simple code example on how to do this?

Thank you.

答:
Here's some sample code for pushing messages into SQS (sorry, using boto rather than the recommended boto3):

```<code>import boto, boto.sqs
from boto.sqs.message import Message
from optparse import OptionParser

# Parse command line
parser = OptionParser()
(options, args) = parser.parse_args()

# Send to SQS
q_conn = boto.sqs.connect_to_region("ap-southeast-2")

q = q_conn.get_queue('cheese-queue')
if q==None:
  print "No queue!"
else:
  m = Message()
  m.set_body(args[0])
  q.write(m)
  print args[0] + ' pushed to Queue'
</code>```

Here's some sample code to read from SQS:

```<code>import boto, boto.sqs
from boto.sqs.message import Message

# Connect to Queue
q_conn = boto.sqs.connect_to_region("ap-southeast-2")
q = q_conn.get_queue('cheese-queue')

# Get a message
m = q.read(visibility_timeout=15)
if m == None:
  print "No message!"
else:
  print m.get_body()
  q.delete_message(m)
</code>```

Body:
Here's some sample code for pushing messages into SQS (sorry, using boto rather than the recommended boto3):

import boto, boto.sqs
from boto.sqs.message import Message
from optparse import OptionParser

# Parse command line
parser = OptionParser()
(options, args) = parser.parse_args()

# Send to SQS
q_conn = boto.sqs.connect_to_region("ap-southeast-2")

q = q_conn.get_queue('cheese-queue')
if q==None:
  print "No queue!"
else:
  m = Message()
  m.set_body(args[0])
  q.write(m)
  print args[0] + ' pushed to Queue'

Here's some sample code to read from SQS:

import boto, boto.sqs
from boto.sqs.message import Message

# Connect to Queue
q_conn = boto.sqs.connect_to_region("ap-southeast-2")
q = q_conn.get_queue('cheese-queue')

# Get a message
m = q.read(visibility_timeout=15)
if m == None:
  print "No message!"
else:
  print m.get_body()
  q.delete_message(m)


问:
java.lang.SecurityException-Not allowed to start activity Intent { flg=0x4000000 cmp=[MY_ACTIVITY] (has extras) }
I am getting the following exception when starting my activity.

```<code>java.lang.SecurityException-Not allowed to start activity Intent { flg=0x4000000 cmp=[MY_ACTIVITY] (has extras)}-
[android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1696),
android.app.Instrumentation.execStartActivity(Instrumentation.java:1488),
android.app.Activity.startActivityForResult(Activity.java:3401),
android.app.Activity.startActivityForResult(Activity.java:3357),
android.app.Activity.startActivity(Activity.java:3597),
android.app.Activity.startActivity(Activity.java:3565), ...]
</code>```

The code is pretty strait forward.
Creating Intent, making sure with getPackageManager().queryIntentActivities that there is activity that filtered by this intent and performing startActivity(intent)
Any ideas?

答:
See the source code. We can find that the root cause of exception is ActivityManager.START_PERMISSION_DENIED:

```<code>            case ActivityManager.START_PERMISSION_DENIED:
            throw new SecurityException("Not allowed to start activity "
                    + intent);
</code>```

So, when another process wants to execute some component in your app which can only be accessed internally, that will cause this exception. In other words, caller process doesn't have the permission declared in the android:permission attribute of your component, or the android:exported attribute set to false.

Body:
I am getting the following exception when starting my activity.

java.lang.SecurityException-Not allowed to start activity Intent { flg=0x4000000 cmp=[MY_ACTIVITY] (has extras)}-
[android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1696),
android.app.Instrumentation.execStartActivity(Instrumentation.java:1488),
android.app.Activity.startActivityForResult(Activity.java:3401),
android.app.Activity.startActivityForResult(Activity.java:3357),
android.app.Activity.startActivity(Activity.java:3597),
android.app.Activity.startActivity(Activity.java:3565), ...]

The code is pretty strait forward.
Creating Intent, making sure with getPackageManager().queryIntentActivities that there is activity that filtered by this intent and performing startActivity(intent)
Any ideas?

Body:
See the source code. We can find that the root cause of exception is ActivityManager.START_PERMISSION_DENIED:

            case ActivityManager.START_PERMISSION_DENIED:
            throw new SecurityException("Not allowed to start activity "
                    + intent);

So, when another process wants to execute some component in your app which can only be accessed internally, that will cause this exception. In other words, caller process doesn't have the permission declared in the android:permission attribute of your component, or the android:exported attribute set to false.


问:
Force DocView mode to show updated file without confirmation?
I use DocView Mode to display .pdf compilations via "latex-preview-pane-mode." Recently, Emacs will ask me "file ____.pdf changed on disk. Reread from disk? (yes or no)".

Typing "yes" each time disrupts my workflow. I have tried setting auto-revert-mode for the DocView buffer, but this did not help. Is there any way to fix this, or any idea why it changed suddenly (no changes to my .emacs.d in the recent past).

答:
Take a look at the variable revert-without-query. From the Emacs Lisp documentation:

This variable holds a list of files that should be reverted without
       query.  The value is a list of regular expressions.  If the visited
       file name matches one of these regular expressions, and the file
       has changed on disk but the buffer is not modified, then
       ‘revert-buffer’ reverts the file without asking the user for
       confirmation.

Adding .+\.pdf to the list should make buffers visiting pdf files revert when you change the file on disk.


问:
How do I expose a docker container port to another container
I have a docker container that relies on selenium as a linked service (also a docker container). This docker container just uses selenium service as host to run nightwatchJS tests headlessly. The selenium service starts up fine but when the nightwatch tests attempt to run within the docker container, i receive a refused connection error on the selenium service port (4444). I can access the selenium host at this port using curl and can also run the nightwatch tests on it if i do not run the tests through docker. Here is my docker compose yaml file:

```<code>services:
  selenium:
    image: selenium/standalone-chrome
    ports:
      - "4444:4444"
  nightwatch:
    build: .
    volumes:
      - .:/home/client_test
    links:
      - selenium
    environment:
      selenium: 4444
    expose:
      - "4444"
</code>```

and my docker file:

```<code>#
#Nightwatch.js Dockerfile
#

FROM alpine:3.4

WORKDIR /home/client-tests
ADD . /home/client-tests/
ENV NODE_PATH=/home/client-app/node_modules
#RUN apk add 'firefox-esr<45.6.0-r0'

#install firefox

#RUN wget -c http://ftp.mozilla.org/pub/firefox/releases/45.8.0esr/firefox-45.8.0esr.linux-x86_64.sdk.tar.bz2 -P /usr/local
#RUN tar xvjf /usr/local/firefox-45.8.0esr.linux-x86_64.sdk.tar.bz2
#RUN ln -s /usr/local/firefox/firefox /usr/local/bin/

RUN apk --no-cache --update add  bash \
    # Install tini, a tiny but valid init for containers
    tini \
    # Install nodejs
    nodejs-lts \
    #Install java
    openjdk8-jre-base \
    #Install chrome
    chromium \
    chromium-chromedriver \
    #Install firefox
    #firefox \
    unzip \
    wget \
    xvfb \

    dbus \
    tar \
    # Install other dependencies
    && npm install -g nightwatch  \
#   -g request \
#   chai \
#   superagent \
    # Clean up obsolete files:
    && rm -rf \
        /tmp/* \
        /root/.npm

#RUN apk update -q && apk add --no-cache xvfb firefox-esr dbus
#ADD https://gist.github.com/elbaschid/5a91271c07bb0de7bfa6/raw/d07b4eecf02fd3341ef72753e4c5875cf137bda8/xvfb-run.sh /usr/bin/xvfb-run
#RUN chmod u+x /usr/bin/xvfb-run
#
RUN npm install request
RUN npm install chai
RUN npm install superagent
EXPOSE 4444
#
##Fetch the chrome drive for linux
#RUN rm -rf /home/client-app/bin/chromedriver
#RUN rm -rf /home/client-app/bin/geckodriver
#
#RUN wget -c http://chromedriver.storage.googleapis.com/2.28/chromedriver_linux64.zip -P /tmp
#RUN unzip /tmp/chromedriver_linux64.zip -d /tmp
#RUN chmod +x /tmp/chromedriver
#RUN mv -f /tmp/chromedriver /home/client-app/bin/chromedriver
#
##get the gecko driver for linux
#RUN wget https://github.com/mozilla/geckodriver/releases/download/v0.16.1/geckodriver-v0.16.1-linux64.tar.gz -P /tmp
#RUN tar xvzf /tmp/geckodriver-v0.16.1-linux64.tar.gz -C /tmp
#RUN chmod 755 /tmp/geckodriver
#RUN mv -f /tmp/geckodriver /home/client-app/bin/geckodriver

#CMD xvfb-run -e java -Dwebdriver.chrome.driver=./bin/chromedriver -jar ./bin/selenium-server-standalone-3.4.0.jar &; nightwatch -e chrome -t tests/*'
CMD nightwatch -e chrome -t tests/loginTest.js
</code>```

and this is my nightwatchJS json file that specifies the host (url is changed for privacy)

```<code>{
  "src_folders" : ["./tests"],
  "output_folder" : "./reports",
  "custom_commands_path" : "./custom-commands",
  "page_objects_path" : "",
  "custom_assertions_path" : "",
  "globals_path" : "./globals.js",
  "live_output" : false,
  "parallel_process_delay" : 10,
  "disable_colors": false,
  "test_workers" : true,

  "selenium" : {
    "start_process" : false,
    "server_path" : "./bin/selenium-server-standalone-3.4.0.jar",
    "log_path" : "",
    "host" : "127.0.0.1",
    "port" : 4444,
    "cli_args" : {
      "webdriver.gecko.driver" : "./bin/geckodriver",
      "webdriver.chrome.driver" : "./bin/chromedriver",
      "webdriver.ie.driver" : "./bin/IEDriverServer.exe"
    }
  },

  "test_settings" : {
    "default" : {
      "launch_url" : "https://google.com",
      "selenium_host" : "hub",
      "selenium_port" : 4444,
      "silent" : true,
      "disable_colors": false,
      "screenshots" : {
        "enabled" : true,
        "path" : "./screenshots"
      },
      "desiredCapabilities" : {
        "browserName" : "firefox",
        "javascriptEnabled" : true,
        "acceptSslCerts" : true,
        "acceptInsecureCerts" : true,
        "applicationCacheEnabled" : true
      }
    },

    "chrome" : {
      "launch_url" : "https://google.com/",
      "selenium_host" : "0.0.0.0",
      "selenium_post" : 4444,
      "disable_colors" : false,
      "screenshots" : {
        "enabled" : false,
        "path" : ""
      },
      "desiredCapabilities" : {
        "browserName" : "chrome",
        "javascriptEnabled" : true,
        "acceptSslCerts" : true,
        "acceptInsecureCerts" : true,
        "chromeOptions": {
          "args": [ "--no-sandbox"]
        }
      }
    },

    "IE" : {
      "launch_url" : "https://google.com/",
      "selenium_host" : "fakeURLFORSTACK.com",
      "selenium_post" : 4444,
      "disable_colors" : false,
      "screenshots" : {
        "enabled" : false,
        "path" : ""
      },
      "desiredCapabilities" : {
        "browserName" : "internet explorer",
        "javascriptEnabled" : true,
        "acceptSslCerts" : true,
        "acceptInsecureCerts" : true
      }
    },

    "saucelabs" : {
      "selenium_host" : "ondemand.saucelabs.com",
      "selenium_port" : 80,
      "username" : "${SAUCE_USERNAME}",
      "access_key" : "${SAUCE_ACCESS_KEY}",
      "use_ssl" : false,
      "silent" : true,
      "output" : true,
      "screenshots" : {
        "enabled" : false,
        "on_failure" : true,
        "path" : ""
      },
      "desiredCapabilities": {
        "name" : "test-example",
        "browserName": "firefox"
      },
      "globals" : {
        "myGlobal" : "some_sauce_global"
      },
      "selenium" : {
        "start_process" : false
      }
    },

    "phantomjs" : {
      "desiredCapabilities" : {
        "browserName" : "phantomjs",
        "javascriptEnabled" : true,
        "acceptSslCerts" : true,
        "acceptInsecureCerts" : true,
        "phantomjs.binary.path" : "phantomjs"
      }
    },

    "browserstack" : {
      "selenium" : {
        "start_process" : false
      },
      "selenium_host" : "hub.browserstack.com",
      "selenium_port" : 80,
      "silent" : true,
      "desiredCapabilities": {
        "name" : "test-example",
        "browserName": "firefox",
        "browserstack.user" : "...",
        "browserstack.key" : "..."
      }
    },

    "testingbot" : {
      "selenium_host" : "hub.testingbot.com",
      "selenium_port" : 80,
      "apiKey" : "${TB_KEY}",
      "apiSecret" : "${TB_SECRET}",
      "silent" : true,
      "output" : true,
      "screenshots" : {
        "enabled" : false,
        "on_failure" : true,
        "path" : ""
      },
      "desiredCapabilities": {
        "name" : "test-example",
        "browserName": "firefox"
      },
      "selenium" : {
        "start_process" : false
      }
    }
  }
}
</code>```

How can i allow my nightwatch tests running in one docker container to utilize the selenium host running in another on port 4444?

答:
Each container has its own networking. Each one has eth0 and lo (localhost) interfaces, that live in the docker's network.

So, your selenium is not in the localhost of the Nighwatch app. It is available as this:

```<code>selenium:4444
</code>```

That hostname is translated to the correct IP that correspond to the selenium container. So adapt your scripts and config to that information.

You can find and inspect the docker network using this:

```<code>docker network ls
docker network inspect <network-id>
</code>```

Body:
I have a docker container that relies on selenium as a linked service (also a docker container). This docker container just uses selenium service as host to run nightwatchJS tests headlessly. The selenium service starts up fine but when the nightwatch tests attempt to run within the docker container, i receive a refused connection error on the selenium service port (4444). I can access the selenium host at this port using curl and can also run the nightwatch tests on it if i do not run the tests through docker. Here is my docker compose yaml file:

services:
  selenium:
    image: selenium/standalone-chrome
    ports:
      - "4444:4444"
  nightwatch:
    build: .
    volumes:
      - .:/home/client_test
    links:
      - selenium
    environment:
      selenium: 4444
    expose:
      - "4444"

and my docker file:

#
#Nightwatch.js Dockerfile
#

FROM alpine:3.4

WORKDIR /home/client-tests
ADD . /home/client-tests/
ENV NODE_PATH=/home/client-app/node_modules
#RUN apk add 'firefox-esr<45.6.0-r0'

#install firefox

#RUN wget -c http://ftp.mozilla.org/pub/firefox/releases/45.8.0esr/firefox-45.8.0esr.linux-x86_64.sdk.tar.bz2 -P /usr/local
#RUN tar xvjf /usr/local/firefox-45.8.0esr.linux-x86_64.sdk.tar.bz2
#RUN ln -s /usr/local/firefox/firefox /usr/local/bin/

RUN apk --no-cache --update add  bash \
    # Install tini, a tiny but valid init for containers
    tini \
    # Install nodejs
    nodejs-lts \
    #Install java
    openjdk8-jre-base \
    #Install chrome
    chromium \
    chromium-chromedriver \
    #Install firefox
    #firefox \
    unzip \
    wget \
    xvfb \

    dbus \
    tar \
    # Install other dependencies
    && npm install -g nightwatch  \
#   -g request \
#   chai \
#   superagent \
    # Clean up obsolete files:
    && rm -rf \
        /tmp/* \
        /root/.npm

#RUN apk update -q && apk add --no-cache xvfb firefox-esr dbus
#ADD https://gist.github.com/elbaschid/5a91271c07bb0de7bfa6/raw/d07b4eecf02fd3341ef72753e4c5875cf137bda8/xvfb-run.sh /usr/bin/xvfb-run
#RUN chmod u+x /usr/bin/xvfb-run
#
RUN npm install request
RUN npm install chai
RUN npm install superagent
EXPOSE 4444
#
##Fetch the chrome drive for linux
#RUN rm -rf /home/client-app/bin/chromedriver
#RUN rm -rf /home/client-app/bin/geckodriver
#
#RUN wget -c http://chromedriver.storage.googleapis.com/2.28/chromedriver_linux64.zip -P /tmp
#RUN unzip /tmp/chromedriver_linux64.zip -d /tmp
#RUN chmod +x /tmp/chromedriver
#RUN mv -f /tmp/chromedriver /home/client-app/bin/chromedriver
#
##get the gecko driver for linux
#RUN wget https://github.com/mozilla/geckodriver/releases/download/v0.16.1/geckodriver-v0.16.1-linux64.tar.gz -P /tmp
#RUN tar xvzf /tmp/geckodriver-v0.16.1-linux64.tar.gz -C /tmp
#RUN chmod 755 /tmp/geckodriver
#RUN mv -f /tmp/geckodriver /home/client-app/bin/geckodriver

#CMD xvfb-run -e java -Dwebdriver.chrome.driver=./bin/chromedriver -jar ./bin/selenium-server-standalone-3.4.0.jar &; nightwatch -e chrome -t tests/*'
CMD nightwatch -e chrome -t tests/loginTest.js

and this is my nightwatchJS json file that specifies the host (url is changed for privacy)

{
  "src_folders" : ["./tests"],
  "output_folder" : "./reports",
  "custom_commands_path" : "./custom-commands",
  "page_objects_path" : "",
  "custom_assertions_path" : "",
  "globals_path" : "./globals.js",
  "live_output" : false,
  "parallel_process_delay" : 10,
  "disable_colors": false,
  "test_workers" : true,

  "selenium" : {
    "start_process" : false,
    "server_path" : "./bin/selenium-server-standalone-3.4.0.jar",
    "log_path" : "",
    "host" : "127.0.0.1",
    "port" : 4444,
    "cli_args" : {
      "webdriver.gecko.driver" : "./bin/geckodriver",
      "webdriver.chrome.driver" : "./bin/chromedriver",
      "webdriver.ie.driver" : "./bin/IEDriverServer.exe"
    }
  },

  "test_settings" : {
    "default" : {
      "launch_url" : "https://google.com",
      "selenium_host" : "hub",
      "selenium_port" : 4444,
      "silent" : true,
      "disable_colors": false,
      "screenshots" : {
        "enabled" : true,
        "path" : "./screenshots"
      },
      "desiredCapabilities" : {
        "browserName" : "firefox",
        "javascriptEnabled" : true,
        "acceptSslCerts" : true,
        "acceptInsecureCerts" : true,
        "applicationCacheEnabled" : true
      }
    },

    "chrome" : {
      "launch_url" : "https://google.com/",
      "selenium_host" : "0.0.0.0",
      "selenium_post" : 4444,
      "disable_colors" : false,
      "screenshots" : {
        "enabled" : false,
        "path" : ""
      },
      "desiredCapabilities" : {
        "browserName" : "chrome",
        "javascriptEnabled" : true,
        "acceptSslCerts" : true,
        "acceptInsecureCerts" : true,
        "chromeOptions": {
          "args": [ "--no-sandbox"]
        }
      }
    },

    "IE" : {
      "launch_url" : "https://google.com/",
      "selenium_host" : "fakeURLFORSTACK.com",
      "selenium_post" : 4444,
      "disable_colors" : false,
      "screenshots" : {
        "enabled" : false,
        "path" : ""
      },
      "desiredCapabilities" : {
        "browserName" : "internet explorer",
        "javascriptEnabled" : true,
        "acceptSslCerts" : true,
        "acceptInsecureCerts" : true
      }
    },

    "saucelabs" : {
      "selenium_host" : "ondemand.saucelabs.com",
      "selenium_port" : 80,
      "username" : "${SAUCE_USERNAME}",
      "access_key" : "${SAUCE_ACCESS_KEY}",
      "use_ssl" : false,
      "silent" : true,
      "output" : true,
      "screenshots" : {
        "enabled" : false,
        "on_failure" : true,
        "path" : ""
      },
      "desiredCapabilities": {
        "name" : "test-example",
        "browserName": "firefox"
      },
      "globals" : {
        "myGlobal" : "some_sauce_global"
      },
      "selenium" : {
        "start_process" : false
      }
    },

    "phantomjs" : {
      "desiredCapabilities" : {
        "browserName" : "phantomjs",
        "javascriptEnabled" : true,
        "acceptSslCerts" : true,
        "acceptInsecureCerts" : true,
        "phantomjs.binary.path" : "phantomjs"
      }
    },

    "browserstack" : {
      "selenium" : {
        "start_process" : false
      },
      "selenium_host" : "hub.browserstack.com",
      "selenium_port" : 80,
      "silent" : true,
      "desiredCapabilities": {
        "name" : "test-example",
        "browserName": "firefox",
        "browserstack.user" : "...",
        "browserstack.key" : "..."
      }
    },

    "testingbot" : {
      "selenium_host" : "hub.testingbot.com",
      "selenium_port" : 80,
      "apiKey" : "${TB_KEY}",
      "apiSecret" : "${TB_SECRET}",
      "silent" : true,
      "output" : true,
      "screenshots" : {
        "enabled" : false,
        "on_failure" : true,
        "path" : ""
      },
      "desiredCapabilities": {
        "name" : "test-example",
        "browserName": "firefox"
      },
      "selenium" : {
        "start_process" : false
      }
    }
  }
}

How can i allow my nightwatch tests running in one docker container to utilize the selenium host running in another on port 4444?

Body:
Each container has its own networking. Each one has eth0 and lo (localhost) interfaces, that live in the docker's network.

So, your selenium is not in the localhost of the Nighwatch app. It is available as this:

selenium:4444

That hostname is translated to the correct IP that correspond to the selenium container. So adapt your scripts and config to that information.

You can find and inspect the docker network using this:

docker network ls
docker network inspect <network-id>


问:
Why an instance of Typescript execute first the get and after the code in the get?
This is my call

```<code>let sqlLocalSelect = new SqlLocalSelect();
var variable = sqlLocalSelect;
console.log("variable " + JSON.stringify(variable));
</code>```

this is the class i call

```<code>import { SQLite } from 'ionic-native';

export class SqlLocalSelect {

database: SQLite;
private li_sitios: Array<Object> = [];

constructor() {}

get get_li_sitios(): Array<Object> {
this.database = new SQLite();
this.database.openDatabase({name: "data.db", location: "default"}).then(() => {
  this.database.executeSql('SELECT * FROM Markers;', [])
  .then((data) => {
    if(data.rows.length > 0){
      this.li_sitios = [];
      for(var i = 0; i < data.rows.length; i++) {
        var value:string = "no";
        if (data.rows.item(i).synchronised) {
          value = "si";
        } else {
          value = "no";
        }
        this.li_sitios.unshift({
          id: data.rows.item(i).id,
          id_externa: data.rows.item(i).id_externa,
          id_owner: data.rows.item(i).id_owner,
          name: data.rows.item(i).name,
          lat: data.rows.item(i).lat,
          lng: data.rows.item(i).lng,
          draggable: false,
          synchronised: value,
          fecha: data.rows.item(i).fecha,
          hora: data.rows.item(i).hora
        });
      }
    } else {
      console.log("No se encontraron datos");
    }
    console.log("Consulta realizada correctamente");
    console.log("li_sitios "+ JSON.stringify(this.li_sitios));

  }, (error) => {
    console.log("Error ejecutando la consulta: " + JSON.stringify(error));
  });
  }, (error) => {
    console.log("Error al conectar con la base de datos local: " + JSON.stringify(error));
  });
  return this.li_sitios;
  }
}
</code>```

Basically it is a query to an sqlite database, but the data output does not run in console in the correct order

This is my output

06-07 18:23:51.030 21450-21450/io.ionic.starter I/chromium: [INFO:CONSOLE(60258)] "variable []", source: file:///android_asset/www/build/main.js (60258)
06-07 18:23:51.120 21450-21450/io.ionic.starter I/chromium: [INFO:CONSOLE(179)] "OPEN database: data.db - OK", source: file:///android_asset/www/plugins/cordova-sqlite-storage/www/SQLitePlugin.js (179)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err: java.sql.SQLException: sqlite3_step failure: cannot rollback - no transaction is active
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at io.liteglue.SQLiteGlueConnection$SQLGStatement.step(SQLiteGlueConnection.java:135)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at io.sqlc.SQLiteConnectorDatabase.executeSQLiteStatement(SQLiteConnectorDatabase.java:214)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at io.sqlc.SQLiteConnectorDatabase.executeSqlBatch(SQLiteConnectorDatabase.java:114)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at io.sqlc.SQLitePlugin$DBRunner.run(SQLitePlugin.java:340)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at java.lang.Thread.run(Thread.java:831)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err: java.sql.SQLException: sqlite3_step failure: cannot rollback - no transaction is active
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at io.liteglue.SQLiteGlueConnection$SQLGStatement.step(SQLiteGlueConnection.java:135)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at io.sqlc.SQLiteConnectorDatabase.executeSQLiteStatement(SQLiteConnectorDatabase.java:214)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at io.sqlc.SQLiteConnectorDatabase.executeSqlBatch(SQLiteConnectorDatabase.java:114)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at io.sqlc.SQLitePlugin$DBRunner.run(SQLitePlugin.java:340)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at java.lang.Thread.run(Thread.java:831)
06-07 18:23:51.290 21450-21450/io.ionic.starter I/chromium: [INFO:CONSOLE(60834)] "Consulta realizada correctamente", source: file:///android_asset/www/build/main.js (60834)
06-07 18:23:51.290 21450-21450/io.ionic.starter I/chromium: [INFO:CONSOLE(60835)] "li_sitios [{"id":4,"id_externa":0,"id_owner":1,"name":"Nombre 4","lat":22.834722222222,"lng":-103.91194444444,"draggable":false,"synchronised":"si","fecha":"2017-6-5","hora":"15:36"},{"id":3,"id_externa":0,"id_owner":1,"name":"Nombre 2","lat":22.534722222222,"lng":-103.91194444444,"draggable":false,"synchronised":"si","fecha":"2017-6-5","hora":"15:29"},{"id":2,"id_externa":15,"id_owner":1,"name":"Nombre 2","lat":22.534722222222,"lng":-103.91194444444,"draggable":false,"synchronised":"no","fecha":"2017-6-5","hora":"15:24"},{"id":1,"id_externa":16,"id_owner":1,"name":"Nombre 1","lat":22.034722222222,"lng":-103.91194444444,"draggable":false,"synchronised":"no","fecha":"2017-6-5","hora":"15:22"}]", source: file:///android_asset/www/build/main.js (60835)

As I mention it first it appears the result of the get empty and then the results of the query is throwing to console.

答:
Thank you very much, I resolved it with your help</p>

```<code>  this.sqlLocalSelect = new SqlLocalSelect();
  setTimeout(()=>{
    var variable = this.sqlLocalSelect.get_li_sitios;
    console.log("variable " + JSON.stringify(variable));
  }, 1000);
</code>```

Body:
This is my call

let sqlLocalSelect = new SqlLocalSelect();
var variable = sqlLocalSelect;
console.log("variable " + JSON.stringify(variable));

this is the class i call

import { SQLite } from 'ionic-native';

export class SqlLocalSelect {

database: SQLite;
private li_sitios: Array<Object> = [];

constructor() {}

get get_li_sitios(): Array<Object> {
this.database = new SQLite();
this.database.openDatabase({name: "data.db", location: "default"}).then(() => {
  this.database.executeSql('SELECT * FROM Markers;', [])
  .then((data) => {
    if(data.rows.length > 0){
      this.li_sitios = [];
      for(var i = 0; i < data.rows.length; i++) {
        var value:string = "no";
        if (data.rows.item(i).synchronised) {
          value = "si";
        } else {
          value = "no";
        }
        this.li_sitios.unshift({
          id: data.rows.item(i).id,
          id_externa: data.rows.item(i).id_externa,
          id_owner: data.rows.item(i).id_owner,
          name: data.rows.item(i).name,
          lat: data.rows.item(i).lat,
          lng: data.rows.item(i).lng,
          draggable: false,
          synchronised: value,
          fecha: data.rows.item(i).fecha,
          hora: data.rows.item(i).hora
        });
      }
    } else {
      console.log("No se encontraron datos");
    }
    console.log("Consulta realizada correctamente");
    console.log("li_sitios "+ JSON.stringify(this.li_sitios));

  }, (error) => {
    console.log("Error ejecutando la consulta: " + JSON.stringify(error));
  });
  }, (error) => {
    console.log("Error al conectar con la base de datos local: " + JSON.stringify(error));
  });
  return this.li_sitios;
  }
}

Basically it is a query to an sqlite database, but the data output does not run in console in the correct order

This is my output

06-07 18:23:51.030 21450-21450/io.ionic.starter I/chromium: [INFO:CONSOLE(60258)] "variable []", source: file:///android_asset/www/build/main.js (60258)
06-07 18:23:51.120 21450-21450/io.ionic.starter I/chromium: [INFO:CONSOLE(179)] "OPEN database: data.db - OK", source: file:///android_asset/www/plugins/cordova-sqlite-storage/www/SQLitePlugin.js (179)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err: java.sql.SQLException: sqlite3_step failure: cannot rollback - no transaction is active
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at io.liteglue.SQLiteGlueConnection$SQLGStatement.step(SQLiteGlueConnection.java:135)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at io.sqlc.SQLiteConnectorDatabase.executeSQLiteStatement(SQLiteConnectorDatabase.java:214)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at io.sqlc.SQLiteConnectorDatabase.executeSqlBatch(SQLiteConnectorDatabase.java:114)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at io.sqlc.SQLitePlugin$DBRunner.run(SQLitePlugin.java:340)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at java.lang.Thread.run(Thread.java:831)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err: java.sql.SQLException: sqlite3_step failure: cannot rollback - no transaction is active
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at io.liteglue.SQLiteGlueConnection$SQLGStatement.step(SQLiteGlueConnection.java:135)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at io.sqlc.SQLiteConnectorDatabase.executeSQLiteStatement(SQLiteConnectorDatabase.java:214)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at io.sqlc.SQLiteConnectorDatabase.executeSqlBatch(SQLiteConnectorDatabase.java:114)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at io.sqlc.SQLitePlugin$DBRunner.run(SQLitePlugin.java:340)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
06-07 18:23:51.240 21450-21555/io.ionic.starter W/System.err:     at java.lang.Thread.run(Thread.java:831)
06-07 18:23:51.290 21450-21450/io.ionic.starter I/chromium: [INFO:CONSOLE(60834)] "Consulta realizada correctamente", source: file:///android_asset/www/build/main.js (60834)
06-07 18:23:51.290 21450-21450/io.ionic.starter I/chromium: [INFO:CONSOLE(60835)] "li_sitios [{"id":4,"id_externa":0,"id_owner":1,"name":"Nombre 4","lat":22.834722222222,"lng":-103.91194444444,"draggable":false,"synchronised":"si","fecha":"2017-6-5","hora":"15:36"},{"id":3,"id_externa":0,"id_owner":1,"name":"Nombre 2","lat":22.534722222222,"lng":-103.91194444444,"draggable":false,"synchronised":"si","fecha":"2017-6-5","hora":"15:29"},{"id":2,"id_externa":15,"id_owner":1,"name":"Nombre 2","lat":22.534722222222,"lng":-103.91194444444,"draggable":false,"synchronised":"no","fecha":"2017-6-5","hora":"15:24"},{"id":1,"id_externa":16,"id_owner":1,"name":"Nombre 1","lat":22.034722222222,"lng":-103.91194444444,"draggable":false,"synchronised":"no","fecha":"2017-6-5","hora":"15:22"}]", source: file:///android_asset/www/build/main.js (60835)

As I mention it first it appears the result of the get empty and then the results of the query is throwing to console.

Body:
Thank you very much, I resolved it with your help

  this.sqlLocalSelect = new SqlLocalSelect();
  setTimeout(()=>{
    var variable = this.sqlLocalSelect.get_li_sitios;
    console.log("variable " + JSON.stringify(variable));
  }, 1000);


问:
What's the point of throwing an exception?
I'm writing a login class in c#, and I'm trying to be diligent about throwing exceptions for null passwords, insufficiant password characters, etc. The thing that suddenly occured to me was - What do I do with these exception? What/who are they for? Whether I handle the exception or not, the app will still fail at that point. Is the exception for other developers, the customer!? </p>

答:
Exceptions are used to provide detailed information about the cause of a particular failure. If you simply let the code fail on its own you miss the opportunity to provide richer details about the actual cause of the failure.

Your users should not be seeing the information you add to your exceptions. Instead, consider adding a global exception handler that catches your detailed exceptions, logs the information, and then displays a friendly error message to your user.

Exceptions provide not only a detailed message in your logs about why the failure occurred (i.e. password was null in your example) but also call stack information that indicates the call chain that led to the exception. In a login form this is less important. However, in a multi-threaded asynchronous client/server application this can be critical.

This article contains many good guidelines: http://msdn.microsoft.com/en-us/library/ms229005.aspx


问:
SaltStack: Downloading archive based on changes to SHASUM file
I upload my builds to S3 and have a latest folder which always contains the newest build. Alongside of the build I have a SHASUM file SHASUM256.txt.asc which looks like this:

```<code>-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256

c05c2e459aab92a490bbbb498c20a86433be23a1  server.tar.gz
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1

iF4EAREIAAYFAlja1qkACgkQb6kayJ97kRKmHgEArOhI8kWEBwddkSY0rmPvFjGh
WgYTK2BuPf3M0mL1n50BAJCj5cl6ZbOIfp5j+499xk/LLxDu1PcWDA+u8XhZ88Sf
=czUN
-----END PGP SIGNATURE-----
</code>```

I'm trying to get Salt to download and extract the archive anytime that the SHASUM changes, but it never thinks that the archive has changed. The only solution I've found is to force it to always download and extract the file, but that kind of defeats the whole purpose.

Here's what I'm currently using:

```<code>server-build:
  archive.extracted:
    - name: /opt/server
    - makedirs: True
    - source: {{ branch }}/latest/build/server.tar.gz
    - archive_format: tar
    - source_hash: {{ branch }}/latest/build/SHASUMS256.txt.asc
    - overwrite: True
</code>```

What's the right way to tell Salt to only download an archive based on changes to the SHASUM file? I'm currently using salt 2016.11.3 (Carbon).

答:
So, there is no way to make it only download the file if the source hash has changed, but you can set source_hash_update: True and the new file will be extracted if the hash changes.

This should make it so that the file only downloads if the hash is updated, but it might still be downloaded some other times, that I am not certain about.

Body:
I upload my builds to S3 and have a latest folder which always contains the newest build. Alongside of the build I have a SHASUM file SHASUM256.txt.asc which looks like this:

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256

c05c2e459aab92a490bbbb498c20a86433be23a1  server.tar.gz
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1

iF4EAREIAAYFAlja1qkACgkQb6kayJ97kRKmHgEArOhI8kWEBwddkSY0rmPvFjGh
WgYTK2BuPf3M0mL1n50BAJCj5cl6ZbOIfp5j+499xk/LLxDu1PcWDA+u8XhZ88Sf
=czUN
-----END PGP SIGNATURE-----

I'm trying to get Salt to download and extract the archive anytime that the SHASUM changes, but it never thinks that the archive has changed. The only solution I've found is to force it to always download and extract the file, but that kind of defeats the whole purpose.

Here's what I'm currently using:

server-build:
  archive.extracted:
    - name: /opt/server
    - makedirs: True
    - source: {{ branch }}/latest/build/server.tar.gz
    - archive_format: tar
    - source_hash: {{ branch }}/latest/build/SHASUMS256.txt.asc
    - overwrite: True

What's the right way to tell Salt to only download an archive based on changes to the SHASUM file? I'm currently using salt 2016.11.3 (Carbon).


问:
Generic method and JSON
I wrote generic method which returns list of some objects, for example Orders. My question is why in second, non-generic method it returns correct list of Orders and the first method (generic) returns list of linkedHashMaps instead of Orders?

Generic:

```<code> private <T> List<T> mapObjectsToList(String objectsListInJson) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    TypeReference<List<T>> mapType = new TypeReference<List<T>>() {
    };
    return objectMapper.readValue(objectsListInJson, mapType);
}
</code>```

Non-generic:

```<code>private List<Order> mapObjectsToList(String objectsListInJson) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    TypeReference<List<Order>> mapType = new TypeReference<List<Order>>() {
    };
    return objectMapper.readValue(objectsListInJson, mapType);
}
</code>```

Generic method returns that:
LinkedHashMap

答:
The problem is that you can't pass a type parameter by simply declaring it.

Type parameters are erased so within your generic function <T> just not exist so even the type reference can't convey such info.

You should build the type reference with the actual reference of the class and pass a type reference to the method like this:

```<code>List<Composite> out = mapObjectsToList(in, new TypeReference<List<Composite>>() {});
</code>```

or ...

Knowing in advance that you are deserializing exactly List of T you can play with TypeFactory

```<code>private static <T> List<T> mapObjectsToList(Reader objectsListInJson, Class<T> clazz) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    CollectionLikeType typeref = TypeFactory.defaultInstance().constructCollectionType(ArrayList.class, clazz);
    return objectMapper.readValue(objectsListInJson, typeref);
}
</code>```

And call it like this:

```<code>List<Composite> out = mapObjectsToList(in, Composite.class);
</code>```

Title: Generic method and JSON

Body:
I wrote generic method which returns list of some objects, for example Orders. My question is why in second, non-generic method it returns correct list of Orders and the first method (generic) returns list of linkedHashMaps instead of Orders?

Generic:

 private <T> List<T> mapObjectsToList(String objectsListInJson) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    TypeReference<List<T>> mapType = new TypeReference<List<T>>() {
    };
    return objectMapper.readValue(objectsListInJson, mapType);
}

Non-generic:

private List<Order> mapObjectsToList(String objectsListInJson) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    TypeReference<List<Order>> mapType = new TypeReference<List<Order>>() {
    };
    return objectMapper.readValue(objectsListInJson, mapType);
}

Generic method returns that:
LinkedHashMap

Body:
The problem is that you can't pass a type parameter by simply declaring it.

Type parameters are erased so within your generic function <T> just not exist so even the type reference can't convey such info.

You should build the type reference with the actual reference of the class and pass a type reference to the method like this:

List<Composite> out = mapObjectsToList(in, new TypeReference<List<Composite>>() {});

or ...

Knowing in advance that you are deserializing exactly List of T you can play with TypeFactory

private static <T> List<T> mapObjectsToList(Reader objectsListInJson, Class<T> clazz) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    CollectionLikeType typeref = TypeFactory.defaultInstance().constructCollectionType(ArrayList.class, clazz);
    return objectMapper.readValue(objectsListInJson, typeref);
}

And call it like this:

List<Composite> out = mapObjectsToList(in, Composite.class);


问:
Angular Reactive Forms
I have two Angular components.  One is called web-services and another is called web-service.  I am hosting a web-service on the template page of web-services and attempting to bind to its service property via the @Input() decorator that I am importing from @angular/core.  However, whenever a web service is selected, I'm getting an error message of 'Cannot read property controls of undefined' which seems to be a problem with my web-service.component.html when it accesses inputParameters.controls.  I've printed inputParameters.controls to the console after it's been set and both name and type are definitely there as form controls.  Am I accessing them incorrectly some how in the HTML?

web-services.component.ts

```<code>export class WebServicesComponent implements OnInit {
  services: Observable<WebService[]>;
  isLoading = false;
  selectedService: WebService;

  constructor(private webServicesService: WebServicesService) { }

  ngOnInit() {
    this.getServices();
  }

  getServices() {
    this.isLoading = true;
    this.services = this.webServicesService.getWebServices()
      .finally(() => this.isLoading = false);
    this.selectedService = undefined;
  }

  selected(service: WebService) {
    this.selectedService = service;
  }

}
</code>```

web-services.component.html

```<code><h3 *ngIf="isLoading"><i>Loading services ... </i></h3>
<h3 *ngIf="!isLoading && !selectedService">Select a service:</h3>

<ul class="ms-List" *ngIf="!selectedService">
    <li class="ms-ListItem" tabindex="0" *ngFor="let service of services | async">
        <span class="ms-ListItem-primaryText">{{service.name}}</span>
        <span class="ms-ListItem-secondaryText">{{service.description}}</span>
        <span class="ms-ListItem-tertiaryText">{{service.version}}</span>
        <span class="ms-ListItem-metaText">{{service.creationTime}}</span>
        <a class="ms-Link" (click)="selected(service)">Select</a>
    </li>
</ul>

<div *ngIf="selectedService">
    <app-web-service [service]="selectedService"></app-web-service>
</div>
</code>```

web-service.component.ts

```<code>export class WebServiceComponent implements OnInit {
  @Input() service: WebService;

  serviceForm: FormGroup;

  constructor(private fb: FormBuilder, private excelService: ExcelService) {
    this.createForm();
  }

  ngOnInit() {

  }

  createForm() {
    this.serviceForm = this.fb.group({
      inputParameters: this.fb.array([]),
      outputParameters: this.fb.array([])
    });
  }

  ngOnChanges() {
    this.setParameters()
  }

  setParameters() {
    console.log(this.service.inputParameterDefinitions);
    const inputParameters = this.service.inputParameterDefinitions.map(input => this.fb.group(input));
    const inputParametersFormArray = this.fb.array(inputParameters);
    this.serviceForm.setControl('inputParameters', inputParametersFormArray);

    console.log(this.serviceForm.controls);

    const outputParameters = this.service.outputParameterDefinitions.map(output => this.fb.group(output));
    const outputParametersFormArray = this.fb.array(outputParameters);
    this.serviceForm.setControl('outputParameters', outputParametersFormArray);
  }
</code>```

web-service.component.html

```<code><form [formGroup]="serviceForm" (ngSubmit)="onSubmit()" novalidate>
    <!-- Service Controls -->
    <div formArrayName="inputParameters">
        <div *ngFor="let parameter of inputParameters.controls; let i=index" [formGroupName]="i">
            <!--The repeated parameter template-->
            <div>
                <label>Name:
                    <input formControlName="name">
                </label>
            </div>
            <div>
                <label>Type:
                    <input formControlName="type">
                </label>
            </div>
        </div>
    </div>
</form>
</code>```

答:
try to test if your service is not null before setting parameters :

```<code>ngOnChanges(changes: {[ propName: string]: SimpleChange}) {
        if(changes[service].currentValue)
              this.setParameters();
}
</code>```

hope it helps you :)

Title: Angular Reactive Forms

Body:
I have two Angular components.  One is called web-services and another is called web-service.  I am hosting a web-service on the template page of web-services and attempting to bind to its service property via the @Input() decorator that I am importing from @angular/core.  However, whenever a web service is selected, I'm getting an error message of 'Cannot read property controls of undefined' which seems to be a problem with my web-service.component.html when it accesses inputParameters.controls.  I've printed inputParameters.controls to the console after it's been set and both name and type are definitely there as form controls.  Am I accessing them incorrectly some how in the HTML?

web-services.component.ts

export class WebServicesComponent implements OnInit {
  services: Observable<WebService[]>;
  isLoading = false;
  selectedService: WebService;

  constructor(private webServicesService: WebServicesService) { }

  ngOnInit() {
    this.getServices();
  }

  getServices() {
    this.isLoading = true;
    this.services = this.webServicesService.getWebServices()
      .finally(() => this.isLoading = false);
    this.selectedService = undefined;
  }

  selected(service: WebService) {
    this.selectedService = service;
  }

}

web-services.component.html

Loading services ...

Select a service:

        {{service.name}}
        {{service.description}}
        {{service.version}}
        {{service.creationTime}}
        Select

    <app-web-service [service]="selectedService"></app-web-service>

web-service.component.ts

export class WebServiceComponent implements OnInit {
  @Input() service: WebService;

  serviceForm: FormGroup;

  constructor(private fb: FormBuilder, private excelService: ExcelService) {
    this.createForm();
  }

  ngOnInit() {

  }

  createForm() {
    this.serviceForm = this.fb.group({
      inputParameters: this.fb.array([]),
      outputParameters: this.fb.array([])
    });
  }

  ngOnChanges() {
    this.setParameters()
  }

  setParameters() {
    console.log(this.service.inputParameterDefinitions);
    const inputParameters = this.service.inputParameterDefinitions.map(input => this.fb.group(input));
    const inputParametersFormArray = this.fb.array(inputParameters);
    this.serviceForm.setControl('inputParameters', inputParametersFormArray);

    console.log(this.serviceForm.controls);

    const outputParameters = this.service.outputParameterDefinitions.map(output => this.fb.group(output));
    const outputParametersFormArray = this.fb.array(outputParameters);
    this.serviceForm.setControl('outputParameters', outputParametersFormArray);
  }

web-service.component.html

<form [formGroup]="serviceForm" (ngSubmit)="onSubmit()" novalidate>

                Name:
                    <input formControlName="name">

                Type:
                    <input formControlName="type">

</form>

Body:
try to test if your service is not null before setting parameters :

ngOnChanges(changes: {[ propName: string]: SimpleChange}) {
        if(changes[service].currentValue)
              this.setParameters();
}

hope it helps you :)


问:
TypeError in Typescript
Here my problem:
I get this error:

Uncaught TypeError: Object prototype may only be an Object or null: undefined

```<code>export abstract class AbstractLogicExpression {
    protected _logicChildExpressions: AbstractLogicExpression[] = Array();
    protected _precedence = 0;
    protected _parsed = false;
    protected _expressionType = "";

    protected rightAssociative = false;

    public toDNF() {
        for (let i = 0; i < this.logicChildExpressions.length; i++) {
            let actualLogicExpression: AbstractLogicExpression = this.logicChildExpressions[i];

            if (actualLogicExpression._expressionType == "~") {

                let logicConjunction = actualLogicExpression.logicChildExpressions[0];

                let var1 = logicConjunction.logicChildExpressions[0];
                let var2 = logicConjunction.logicChildExpressions[1];

                if (logicConjunction._expressionType == "*") {
                    actualLogicExpression.logicChildExpressions[0] = new LogicOr();
                    //actualLogicExpression.logicChildExpressions[0].add(new LogicNeg(var1));
                    //actualLogicExpression.logicChildExpressions[0].add(new LogicNeg(var2));
                }
            }
        }
    }
}
</code>```

I get this error because of the line before the two commented lines:

```<code>actualLogicExpression.logicChildExpressions[0] = new LogicOr();
</code>```

I tested it by comment and uncomment the lines, because I get no line number in the error message.

Does someone know what I can do?
If you need a little more code. I can post something...

Here the code of LogicOr:
https://pastebin.com/T28Zjbtb

答:
You get an error on this line:

actualLogicExpression.logicChildExpressions[0] = new LogicOr();

The error message is

Uncaught TypeError: Object prototype may only be an Object or null: undefined

It is very easy to understand once you are familiar with Classes and how they work (https://basarat.gitbooks.io/typescript/docs/classes.html).

The error means that new LogicOr is failing because LogicOr is extending something that is undefined. Simple example:

```<code>let Bar;
class Foo extends Bar { } // Uncaught TypeError: Object prototype may only be an Object or null: undefined
</code>```

More

Fix the bug in LogicOr and its inheritance chain.

Title: TypeError in Typescript

Body:
Here my problem:
I get this error:

Uncaught TypeError: Object prototype may only be an Object or null: undefined

export abstract class AbstractLogicExpression {
    protected _logicChildExpressions: AbstractLogicExpression[] = Array();
    protected _precedence = 0;
    protected _parsed = false;
    protected _expressionType = "";

    protected rightAssociative = false;

    public toDNF() {
        for (let i = 0; i < this.logicChildExpressions.length; i++) {
            let actualLogicExpression: AbstractLogicExpression = this.logicChildExpressions[i];

            if (actualLogicExpression._expressionType == "~") {

                let logicConjunction = actualLogicExpression.logicChildExpressions[0];

                let var1 = logicConjunction.logicChildExpressions[0];
                let var2 = logicConjunction.logicChildExpressions[1];

                if (logicConjunction._expressionType == "*") {
                    actualLogicExpression.logicChildExpressions[0] = new LogicOr();
                    //actualLogicExpression.logicChildExpressions[0].add(new LogicNeg(var1));
                    //actualLogicExpression.logicChildExpressions[0].add(new LogicNeg(var2));
                }
            }
        }
    }
}

I get this error because of the line before the two commented lines:

actualLogicExpression.logicChildExpressions[0] = new LogicOr();

I tested it by comment and uncomment the lines, because I get no line number in the error message.

Does someone know what I can do?
If you need a little more code. I can post something...

Here the code of LogicOr:
https://pastebin.com/T28Zjbtb

Body:
You get an error on this line:

actualLogicExpression.logicChildExpressions[0] = new LogicOr();

The error message is

Uncaught TypeError: Object prototype may only be an Object or null: undefined

It is very easy to understand once you are familiar with Classes and how they work (https://basarat.gitbooks.io/typescript/docs/classes.html).

The error means that new LogicOr is failing because LogicOr is extending something that is undefined. Simple example:

let Bar;
class Foo extends Bar { } // Uncaught TypeError: Object prototype may only be an Object or null: undefined

More

Fix the bug in LogicOr and its inheritance chain.


问:
How to find out when a particular table was created in Oracle?
In Oracle, is there a way to find out when a particular table was created?

Similarly, is there a way to find out when a particular row was inserted/last updated?

答:
You can query the data dictionary/catalog views to find out when an object was created as well as the time of last DDL involving the object (example: alter table)

```<code>select *
  from all_objects
 where owner = '<name of schema owner>'
   and object_name = '<name of table>'
</code>```

The column "CREATED" tells you when the object was created.
The column "LAST_DDL_TIME" tells you when the last DDL was performed against the object.

As for when a particular row was inserted/updated, you can use audit columns like an "insert_timestamp" column or use a trigger and populate an audit table

Body:
You can query the data dictionary/catalog views to find out when an object was created as well as the time of last DDL involving the object (example: alter table)

select *
  from all_objects
 where owner = '<name of schema owner>'
   and object_name = '<name of table>'

The column "CREATED" tells you when the object was created.
The column "LAST_DDL_TIME" tells you when the last DDL was performed against the object.

As for when a particular row was inserted/updated, you can use audit columns like an "insert_timestamp" column or use a trigger and populate an audit table


问:
Can't find Pods.modulemap - looking in wrong directory
I'm trying to get CocoaPods working in a Swift project but this is my first time.

My Podfile is

```<code>source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!

pod 'Alamofire', '~> 1.2'
pod 'SwiftyJSON', '~> 2.2.0'
</code>```

I run pod install but building it gives me this error:

```<code>Error: unable to read module map contents from 'Target Support
Files/Pods/Pods.modulemap': Error Domain=NSCocoaErrorDomain Code=260
 "The file “Pods.modulemap” couldn’t be opened because there is no such file."
UserInfo=0x7fac488d5af0 {NSFilePath=/Users/jt/tmp-ios/my-template/Pods/Target
Support Files/Pods/Pods.modulemap, NSUnderlyingError=0x7fac457f0e90 "The operation
couldn’t be completed. No such file or directory"}
</code>```

The weird is that this is that /Users/jt/tmp-ios/ is not even the directory I am in.

```<code>Tue Jun 09$ pwd
/Users/jt/repos/EmbersSwift
Tue Jun 09$
</code>```

I did have something in that directory before by what it is referencing that is not clear. How would I fix this? I suspect it is something in Pods.debug.xconfig but was hoping somebody had dealt with this before.

答:
In my case I had made a few changes to my PodFile, got a similar error and just re-ran 'install':

```<code>% pod install
</code>```

And I was back in business.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to get CocoaPods working in a Swift project but this is my first time.

My Podfile is

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!

pod 'Alamofire', '~> 1.2'
pod 'SwiftyJSON', '~> 2.2.0'

I run pod install but building it gives me this error:

Error: unable to read module map contents from 'Target Support
Files/Pods/Pods.modulemap': Error Domain=NSCocoaErrorDomain Code=260
 "The file “Pods.modulemap” couldn’t be opened because there is no such file."
UserInfo=0x7fac488d5af0 {NSFilePath=/Users/jt/tmp-ios/my-template/Pods/Target
Support Files/Pods/Pods.modulemap, NSUnderlyingError=0x7fac457f0e90 "The operation
couldn’t be completed. No such file or directory"}

The weird is that this is that /Users/jt/tmp-ios/ is not even the directory I am in.

Tue Jun 09$ pwd
/Users/jt/repos/EmbersSwift
Tue Jun 09$

I did have something in that directory before by what it is referencing that is not clear. How would I fix this? I suspect it is something in Pods.debug.xconfig but was hoping somebody had dealt with this before.

Body:
In my case I had made a few changes to my PodFile, got a similar error and just re-ran 'install':

% pod install

And I was back in business.


问:
Stringbuilder inside loop efficiency?
Consider using something like

```<code>StringBuilder sb = new StringBuilder();
for(int i = 0; i < n; i++){
  sb.append('a');
}
</code>```

Is the efficiency of the code O(N^2) or O(N)?

答: It is O(N), meaning it takes the cost of how big you n variable is.

Title: Stringbuilder inside loop efficiency?

Body:
Consider using something like

StringBuilder sb = new StringBuilder();
for(int i = 0; i < n; i++){
  sb.append('a');
}

Is the efficiency of the code O(N^2) or O(N)?