问:
Insert into Database using javafx not working properly
i m new in javafx so please excuse my silly mistake i had created a registration fxml using javafx but when i try to store data its will allways throw it into catch block of my modelcontroller where i have a insert query for sql

here is My RegistrationController

```<code>        public void Registersign(ActionEvent event){
        try {
        String Fname=fname.getText();
        String Lname=lname.getText();
        String Email=email.getText();
        String TXTusr=txtUser.getText();
        String TXTpass=txtPass.getText();
        String TXTPassconf=txtPassconf.getText();if(Fname.isEmpty()||Lname.isEmpty()||Email.isEmpty()||TXTusr.isEmpty()||TXTpass.isEmpty()){

                Alert alert=new Alert(Alert.AlertType.ERROR);
                alert.setHeaderText(null);
                alert.setContentText("Please Fill All DATA");
                alert.showAndWait();
                return;

        }
            loginModel.isRegister(TXTusr,TXTpass, Fname,Lname, Email);

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
</code>```

here is my modelcontroller to insert my registration data into database

```<code>          public void isRegister(String user,String pass,String firstname,String lastname,String email) throws SQLException
{
    PreparedStatement preparedStatement=null;
    ResultSet resultSet=null;
      String sql = "INSERT INTO login (username, password, firstname,lastname, email) VALUES (?, ?, ?,?, ?)";
      try {
    preparedStatement=Con.prepareStatement(sql);
    preparedStatement.setString(1, user);
    preparedStatement.setString(2, pass);
    preparedStatement.setString(3, firstname);
    preparedStatement.setString(4, lastname);
    preparedStatement.setString(5, email);
     resultSet=preparedStatement.executeQuery();

        System.out.println("A new user was inserted successfully!");

} catch (Exception e) {
    // TODO: handle exception
       System.out.println("A new user was insertion failed!");
}
</code>```

it allways throw at catch block in modelContoller i had check it through debugger

答:
Use executeUpdate() instead of executeQuery() if using non-SELECT SQL statement.

See: http://docs.oracle.com/javase/8/docs/api/java/sql/PreparedStatement.html#executeUpdate--

Body:
i m new in javafx so please excuse my silly mistake i had created a registration fxml using javafx but when i try to store data its will allways throw it into catch block of my modelcontroller where i have a insert query for sql

here is My RegistrationController

        public void Registersign(ActionEvent event){
        try {
        String Fname=fname.getText();
        String Lname=lname.getText();
        String Email=email.getText();
        String TXTusr=txtUser.getText();
        String TXTpass=txtPass.getText();
        String TXTPassconf=txtPassconf.getText();if(Fname.isEmpty()||Lname.isEmpty()||Email.isEmpty()||TXTusr.isEmpty()||TXTpass.isEmpty()){

                Alert alert=new Alert(Alert.AlertType.ERROR);
                alert.setHeaderText(null);
                alert.setContentText("Please Fill All DATA");
                alert.showAndWait();
                return;

        }
            loginModel.isRegister(TXTusr,TXTpass, Fname,Lname, Email);

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

here is my modelcontroller to insert my registration data into database

          public void isRegister(String user,String pass,String firstname,String lastname,String email) throws SQLException
{
    PreparedStatement preparedStatement=null;
    ResultSet resultSet=null;
      String sql = "INSERT INTO login (username, password, firstname,lastname, email) VALUES (?, ?, ?,?, ?)";
      try {
    preparedStatement=Con.prepareStatement(sql);
    preparedStatement.setString(1, user);
    preparedStatement.setString(2, pass);
    preparedStatement.setString(3, firstname);
    preparedStatement.setString(4, lastname);
    preparedStatement.setString(5, email);
     resultSet=preparedStatement.executeQuery();

        System.out.println("A new user was inserted successfully!");

} catch (Exception e) {
    // TODO: handle exception
       System.out.println("A new user was insertion failed!");
}

it allways throw at catch block in modelContoller i had check it through debugger


来源: stackexchange

问:
How to avoid java.net.URISyntaxException in URL.toURI()
In a particular program, I am passed a file: URL and I need to convert it to a URI object.  Using the toURI method will throw a java.net.URISyntaxException if there are spaces or any other invalid characters in the URL.

For example:

```<code>URL url = Platform.getInstallURL();  // file:/Applications/Program
System.out.println(url.toURI());  // prints file:/Applications/Program

URL url = Platform.getConfigurationURL();  // file:/Users/Andrew Eisenberg
System.out.println(url.toURI());  // throws java.net.URISyntaxException because of the space
</code>```

What is the best way of performing this conversion so that all special characters are handled?

答:
I guess the best way would be to remove deprecated File.toURL() which is usually responsible for producing these incorrect URLs.

If you can't do it, something like this may help:

```<code>public static URI fixFileURL(URL u) {
    if (!"file".equals(u.getProtocol())) throw new IllegalArgumentException();
    return new File(u.getFile()).toURI();
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
In a particular program, I am passed a file: URL and I need to convert it to a URI object.  Using the toURI method will throw a java.net.URISyntaxException if there are spaces or any other invalid characters in the URL.

For example:

URL url = Platform.getInstallURL();  // file:/Applications/Program
System.out.println(url.toURI());  // prints file:/Applications/Program

URL url = Platform.getConfigurationURL();  // file:/Users/Andrew Eisenberg
System.out.println(url.toURI());  // throws java.net.URISyntaxException because of the space

What is the best way of performing this conversion so that all special characters are handled?

Body:
I guess the best way would be to remove deprecated File.toURL() which is usually responsible for producing these incorrect URLs.

If you can't do it, something like this may help:

public static URI fixFileURL(URL u) {
    if (!"file".equals(u.getProtocol())) throw new IllegalArgumentException();
    return new File(u.getFile()).toURI();
}


问:
Unit test for C++ (Visual Studio / Arduino)
I'm doing an Arduino project, and want to use a unit tester. What I want is to stub all Arduino specific classes. I created a Visual Studio project for VMicro (for Arduino).

However, I tried to install NUnit, but I get the following error:

Severity    Code    Description Project File    Line    Suppression State
Error       Could not install package 'NUnit 3.7.1'. You are trying to install this package into a project that targets 'native,Version=v0.0', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.         0

I would expect NUnit would work with any C++ code but probably not. Is there something I can change within the project to make it work with C++ or can I better create a dedicated (Console?) C++ project and incorporate the C++ classes within the Arduino VMicro project?

答:
Maybe try to test your application with Google Test and Google Mock

Here's a link:
https://github.com/google/googletest/blob/master/googlemock/docs/ForDummies.md

ContentLicense: CC BY-SA 3.0


问:
Horizontal Recycler View inside ViewPager not scrolling

The Problem

I have a horizontal RecyclerView inside a NestedScrollView which is inside a ViewPager. Now when I try to scroll the RecyclerView, sometimes it scrolls, but sometimes only the ViewPager scrolls.

The Code

That's how my RecyclerView XML looks like:

```<code><android.support.v7.widget.RecyclerView
            android:id="@+id/sidescroll"
            android:layout_below="@+id/movie_more_movies2"
            android:layout_marginTop="@dimen/material_layout_keylines_horizontal_margin"
            android:layout_marginBottom="@dimen/material_layout_keylines_horizontal_margin"
            android:layout_width="match_parent"
            android:orientation="horizontal"
            app:layoutManager="android.support.v7.widget.LinearLayoutManager"
            android:layout_height="wrap_content"/>
</code>```

That's how the Nested Scroll, in which the RecyclerView is, looks like:

```<code><android.support.v4.widget.NestedScrollView
    android:id="@+id/detail_holder"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipToPadding="false"
    android:descendantFocusability="blocksDescendants"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    >
</code>```

And this is the viewpager xml:

```<code><com.mt.moviesiwanttowatch.ui.ViewPagerWithHorizontalRecyclerView
            android:id="@+id/viewpager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:clipChildren="false"
            android:clipToPadding="false"
            app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</code>```

I am using this Custom ViewPager:

```<code>public class ViewPagerWithHorizontalRecyclerView extends ViewPager {

    public ViewPagerWithHorizontalRecyclerView(Context context) {
        super(context);
    }

    public ViewPagerWithHorizontalRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return super.onInterceptTouchEvent(ev);
    }

    @Override
    protected boolean canScroll(View v, boolean checkV, int dx, int x, int y) {
        if(v instanceof RecyclerView){
            Log.e("PAGER", "IS");
            return false;
        } else {
            Log.e("PAGER", "IS NOT " + v.toString());
        }

        return super.canScroll(v, checkV, dx, x, y);
    }
}
</code>```

My Approach

What I tried so far, as you can see I wrote a custom ViewPager. I tried to tell the ViewPager that it can not scroll if the scroll comes from an RecyclerView. However this doesn't work.

The Logs:

This is a log when the ViewPager scrolls instead of the RecyclerView

```<code>>     06-27 17:50:53.506 32362-32362/com.mt.moviesiwanttowatch E/PAGER: IS NOT
> com.mt.moviesiwanttowatch.ui.ViewPagerWithHorizontalRecyclerView{c506165
> VFED..... ........ 0,341-1080,1794 #7f090287 app:id/viewpager}
>     06-27 17:50:53.506 32362-32362/com.mt.moviesiwanttowatch E/PAGER: IS NOT android.support.v4.widget.NestedScrollView{d21952 VFED.....
> ........ 0,0-1080,1453 #7f0900b9 app:id/detail_holder}
>     06-27 17:50:53.506 32362-32362/com.mt.moviesiwanttowatch E/PAGER: IS NOT android.widget.RelativeLayout{6ddeec0 V.E...... ........
> 0,0-1080,2860 #7f090199 app:id/movie_overview_holder}
>     06-27 17:50:53.506 32362-32362/com.mt.moviesiwanttowatch E/PAGER: IS
</code>```

答:
If you are using a RecyclerView in a NestedScrollView you should do this to your recycler (i use it for verical recycler).

```<code>recyclerView.setNestedScrollingEnabled(false);
</code>```

I have exactly the same scenario on an app that I am working on. The ViewPager is scrolling not when I scroll the Horizontal Recycler, but when the Recycler is at the end of the list and has nothing to show.
I hope I got your question right

Body:
The Problem

I have a horizontal RecyclerView inside a NestedScrollView which is inside a ViewPager. Now when I try to scroll the RecyclerView, sometimes it scrolls, but sometimes only the ViewPager scrolls.

The Code

That's how my RecyclerView XML looks like:

<android.support.v7.widget.RecyclerView
            android:id="@+id/sidescroll"
            android:layout_below="@+id/movie_more_movies2"
            android:layout_marginTop="@dimen/material_layout_keylines_horizontal_margin"
            android:layout_marginBottom="@dimen/material_layout_keylines_horizontal_margin"
            android:layout_width="match_parent"
            android:orientation="horizontal"
            app:layoutManager="android.support.v7.widget.LinearLayoutManager"
            android:layout_height="wrap_content"/>

That's how the Nested Scroll, in which the RecyclerView is, looks like:

<android.support.v4.widget.NestedScrollView
    android:id="@+id/detail_holder"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipToPadding="false"
    android:descendantFocusability="blocksDescendants"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    >

And this is the viewpager xml:

<com.mt.moviesiwanttowatch.ui.ViewPagerWithHorizontalRecyclerView
            android:id="@+id/viewpager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:clipChildren="false"
            android:clipToPadding="false"
            app:layout_behavior="@string/appbar_scrolling_view_behavior" />

I am using this Custom ViewPager:

public class ViewPagerWithHorizontalRecyclerView extends ViewPager {

    public ViewPagerWithHorizontalRecyclerView(Context context) {
        super(context);
    }

    public ViewPagerWithHorizontalRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return super.onInterceptTouchEvent(ev);
    }

    @Override
    protected boolean canScroll(View v, boolean checkV, int dx, int x, int y) {
        if(v instanceof RecyclerView){
            Log.e("PAGER", "IS");
            return false;
        } else {
            Log.e("PAGER", "IS NOT " + v.toString());
        }

        return super.canScroll(v, checkV, dx, x, y);
    }
}

My Approach

What I tried so far, as you can see I wrote a custom ViewPager. I tried to tell the ViewPager that it can not scroll if the scroll comes from an RecyclerView. However this doesn't work.

The Logs:

This is a log when the ViewPager scrolls instead of the RecyclerView

>     06-27 17:50:53.506 32362-32362/com.mt.moviesiwanttowatch E/PAGER: IS NOT
> com.mt.moviesiwanttowatch.ui.ViewPagerWithHorizontalRecyclerView{c506165
> VFED..... ........ 0,341-1080,1794 #7f090287 app:id/viewpager}
>     06-27 17:50:53.506 32362-32362/com.mt.moviesiwanttowatch E/PAGER: IS NOT android.support.v4.widget.NestedScrollView{d21952 VFED.....
> ........ 0,0-1080,1453 #7f0900b9 app:id/detail_holder}
>     06-27 17:50:53.506 32362-32362/com.mt.moviesiwanttowatch E/PAGER: IS NOT android.widget.RelativeLayout{6ddeec0 V.E...... ........
> 0,0-1080,2860 #7f090199 app:id/movie_overview_holder}
>     06-27 17:50:53.506 32362-32362/com.mt.moviesiwanttowatch E/PAGER: IS

Body:
If you are using a RecyclerView in a NestedScrollView you should do this to your recycler (i use it for verical recycler).

recyclerView.setNestedScrollingEnabled(false);

I have exactly the same scenario on an app that I am working on. The ViewPager is scrolling not when I scroll the Horizontal Recycler, but when the Recycler is at the end of the list and has nothing to show.
I hope I got your question right


问:
JSON extract subtree as string in android
I have the following json structure:

```<code> "interpretation": {
        "ComplexSearchRequest": {
            "BoostLanguage": 0,
            "Clauses": {
                "MustClauses": [
                    {
                        "Match": {
                            "Attribute": "Channel",
                            "Operator": "None",
                            "Value": "n twenty four c h"
                        }
                    }
                ],
                "MustNotClauses": []
            },
            "FilterLanguages": [],
            "ItemFilters": [],
            "MaxResults": 10
        },
        "GraphManagerRequestId": "baf28b69-0806-4725-9fb4-1d2acd1944ea",
        "GraphManagerRequestLanguage": "de",
        "Type": "Search"
    },
</code>```

How do I extract the entire node "Clauses" and convert it as string? The output should be:

```<code>"Clauses": {
                "MustClauses": [
                    {
                        "Match": {
                            "Attribute": "Channel",
                            "Operator": "None",
                            "Value": "n twenty four c h"
                        }
                    }
                ],
                "MustNotClauses": []
            },
</code>```

An optimal solution is needed.

For simple parsing I use JsonReader.

答:
Try using org.json. It's the best I've seen: https://mvnrepository.com/artifact/org.json/json</p>

```<code>import org.json.JSONException;
import org.json.JSONObject;

public class JsonSample
{

  public static void main(String[] args) throws JSONException
  {
    String json = "{ \"interpretation\": {        \"ComplexSearchRequest\": {            \"BoostLanguage\": 0,            \"Clauses\": {                \"MustClauses\": [                    {                        \"Match\": {                            \"Attribute\": \"Channel\",                            \"Operator\": \"None\",                            \"Value\": \"n twenty four c h\"                        }                    }                ],                \"MustNotClauses\": []            },            \"FilterLanguages\": [],            \"ItemFilters\": [],            \"MaxResults\": 10        },        \"GraphManagerRequestId\": \"baf28b69-0806-4725-9fb4-1d2acd1944ea\",        \"GraphManagerRequestLanguage\": \"de\",        \"Type\": \"Search\"    }}";

    JSONObject jsonObject = new JSONObject(json);

    System.out.println(jsonObject.getJSONObject("interpretation").getJSONObject("ComplexSearchRequest").getString("Clauses"));

  }

}
</code>```

Body:
I have the following json structure:

 "interpretation": {
        "ComplexSearchRequest": {
            "BoostLanguage": 0,
            "Clauses": {
                "MustClauses": [
                    {
                        "Match": {
                            "Attribute": "Channel",
                            "Operator": "None",
                            "Value": "n twenty four c h"
                        }
                    }
                ],
                "MustNotClauses": []
            },
            "FilterLanguages": [],
            "ItemFilters": [],
            "MaxResults": 10
        },
        "GraphManagerRequestId": "baf28b69-0806-4725-9fb4-1d2acd1944ea",
        "GraphManagerRequestLanguage": "de",
        "Type": "Search"
    },

How do I extract the entire node "Clauses" and convert it as string? The output should be:

"Clauses": {
                "MustClauses": [
                    {
                        "Match": {
                            "Attribute": "Channel",
                            "Operator": "None",
                            "Value": "n twenty four c h"
                        }
                    }
                ],
                "MustNotClauses": []
            },

An optimal solution is needed.

For simple parsing I use JsonReader.

Body:
Try using org.json. It's the best I've seen: https://mvnrepository.com/artifact/org.json/json

import org.json.JSONException;
import org.json.JSONObject;

public class JsonSample
{

  public static void main(String[] args) throws JSONException
  {
    String json = "{ \"interpretation\": {        \"ComplexSearchRequest\": {            \"BoostLanguage\": 0,            \"Clauses\": {                \"MustClauses\": [                    {                        \"Match\": {                            \"Attribute\": \"Channel\",                            \"Operator\": \"None\",                            \"Value\": \"n twenty four c h\"                        }                    }                ],                \"MustNotClauses\": []            },            \"FilterLanguages\": [],            \"ItemFilters\": [],            \"MaxResults\": 10        },        \"GraphManagerRequestId\": \"baf28b69-0806-4725-9fb4-1d2acd1944ea\",        \"GraphManagerRequestLanguage\": \"de\",        \"Type\": \"Search\"    }}";

    JSONObject jsonObject = new JSONObject(json);

    System.out.println(jsonObject.getJSONObject("interpretation").getJSONObject("ComplexSearchRequest").getString("Clauses"));

  }

}


问:
Mouseover, mouseEnter
I have a FAQ and Question page. And if a user hover with his mouse over a question, then the answer will be shown.

But if you will now hover over a question all the answers are shown. what not has to be. Only the answere of the selected question has to be visible.

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>A One Page Faq</title>
    <link href="Content/site.css" rel="stylesheet">
    <script src="Scripts/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            $('.answer').hide();
            var $answer = $(this).next('.answer');
            $('.main h2').mouseover(function () {
                $('.answer').show();
                $answer.slideDown();
                $(this).addClass('close');
            });
            $('.main h2').mouseout(function () {
                $('.answer').hide();
                $answer.fadeOut();
                 $(this).removeClass('close');
            });

        }); // end ready
    </script>
</head>
<body>
    <div class="wrapper">
        <div class="content">
            <div class="main">
                <h1>A One Page FAQ</h1>
                <div class="faq">
                    <h2>I've heard that JavaScript is the long-lost fountain of youth. Is this true?</h2>
                    <div class="answer">
                        <p>Why, yes it is! Studies prove that learning JavaScript freshens the mind and extends life span by several hundred years. (Note: some scientists disagree with these claims.)</p>
                    </div>
                </div>
                <div class="faq">
                    <h2>Can JavaScript really solve all of my problems?</h2>
                    <div class="answer">
                        <p>Why, yes it can! It's the most versatile programming language ever created and is trained to provide financial management advice, life-saving CPR, and even to take care of household pets.</p>
                    </div>
                </div>
                <div class="faq">
                    <h2>Is there nothing JavaScript <em>can’t</em> do?</h2>
                    <div class="answer">
                        <p>Why, no there isn’t! It’s even able to write its own public relations-oriented Frequently Asked Questions pages. Now that’s one smart programming language!</p>
                    </div>
                </div>
            </div>
        </div>
        <footer>
            <p>JavaScript & jQuery: The Missing Manual, 3rd Edition, by <a href="http://sawmac.com/">David McFarland</a>. Published by <a href="http://oreilly.com/">O'Reilly Media, Inc</a>.</p>
        </footer>
    </div>
</body>
</html>
</code>```

Thank you

If I do it like this:

```<code> $(document).ready(function () {
            $('.answer').hide();
            var $answer = $(this).next('.answer');

            $('.main h2').mouseover(function (e) {
                $('.answer').hide();//Hide All Other Answers
                $(e).closest('.answer').show();//Show Closest Answer To Question
            });

            $('.main h2').mouseout(function (e) {
                $('.answer').hide();
            });
</code>```

nothing happens

答:
Use $.next(). Just now you're changing all classes .answer to be shown and all .answer to slideDown (within your $(document).ready() you grab the element from the whole document ($this) and later in code you run it)

Try this

```<code>$('.main h2').mouseover(function () {
    $(this).next('.answer').show();
    $(this).next('.answer').slideDown();
    $(this).addClass('close');
});
</code>```

You should remove those two lines of code too.

```<code>$('.answer').hide();
var $answer = $(this).next('.answer');
</code>```

And apply display: hidden; to your .answer CSS class.

Title: Mouseover, mouseEnter

Body:
I have a FAQ and Question page. And if a user hover with his mouse over a question, then the answer will be shown.

But if you will now hover over a question all the answers are shown. what not has to be. Only the answere of the selected question has to be visible.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>A One Page Faq</title>
    <link href="Content/site.css" rel="stylesheet">

A One Page FAQ

I've heard that JavaScript is the long-lost fountain of youth. Is this true?

Why, yes it is! Studies prove that learning JavaScript freshens the mind and extends life span by several hundred years. (Note: some scientists disagree with these claims.)

Can JavaScript really solve all of my problems?

Why, yes it can! It's the most versatile programming language ever created and is trained to provide financial management advice, life-saving CPR, and even to take care of household pets.

Is there nothing JavaScript can’t do?

Why, no there isn’t! It’s even able to write its own public relations-oriented Frequently Asked Questions pages. Now that’s one smart programming language!

JavaScript & jQuery: The Missing Manual, 3rd Edition, by David McFarland. Published by O'Reilly Media, Inc.

Thank you

If I do it like this:

 $(document).ready(function () {
            $('.answer').hide();
            var $answer = $(this).next('.answer');

            $('.main h2').mouseover(function (e) {
                $('.answer').hide();//Hide All Other Answers
                $(e).closest('.answer').show();//Show Closest Answer To Question
            });

            $('.main h2').mouseout(function (e) {
                $('.answer').hide();
            });

nothing happens

Body:
Use $.next(). Just now you're changing all classes .answer to be shown and all .answer to slideDown (within your $(document).ready() you grab the element from the whole document ($this) and later in code you run it)

Try this

$('.main h2').mouseover(function () {
    $(this).next('.answer').show();
    $(this).next('.answer').slideDown();
    $(this).addClass('close');
});

You should remove those two lines of code too.

$('.answer').hide();
var $answer = $(this).next('.answer');

And apply display: hidden; to your .answer CSS class.


答:
Try this way ;]

$(document).ready(function () {
    $('.answer').hide();

    $('.main h2').on('mouseover', function () {
        $(this).next().slideDown(300);
        $(this).addClass('close');
    });
    $('.main h2').on('mouseout', function () {
        $(this).next().slideUp(300);
        $(this).removeClass('close');
    });

}); // end ready```
<pre class="snippet-code-css lang-css prettyprint-override"><code>h2 {
    background: url(_images/open.png) no-repeat 0 11px;
    padding: 10px 0 0 25px;
    cursor: pointer;
}

    h2.close {
        background-image: url(_images/close.png);
    }

.answer {
    margin-left: 25px;
}</code>```

A One Page FAQ

I've heard that JavaScript is the long-lost fountain of youth. Is this true?

Why, yes it is! Studies prove that learning JavaScript freshens the mind and extends life span by several hundred years. (Note: some scientists disagree with these claims.)

Can JavaScript really solve all of my problems?

Why, yes it can! It's the most versatile programming language ever created and is trained to provide financial management advice, life-saving CPR, and even to take care of household pets.

Is there nothing JavaScript can’t do?

Why, no there isn’t! It’s even able to write its own public relations-oriented Frequently Asked Questions pages. Now that’s one smart programming language!

JavaScript & jQuery: The Missing Manual, 3rd Edition, by David McFarland. Published by O'Reilly Media, Inc.

```

Title: Mouseover, mouseEnter

Body:
Try this way ;]

$(document).ready(function () {
    $('.answer').hide();

    $('.main h2').on('mouseover', function () {
        $(this).next().slideDown(300);
        $(this).addClass('close');
    });
    $('.main h2').on('mouseout', function () {
        $(this).next().slideUp(300);
        $(this).removeClass('close');
    });

}); // end ready

h2 {
    background: url(_images/open.png) no-repeat 0 11px;
    padding: 10px 0 0 25px;
    cursor: pointer;
}

    h2.close {
        background-image: url(_images/close.png);
    }

.answer {
    margin-left: 25px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
        <header>

        </header>
        <div class="content">
            <div class="main">
                <h1>A One Page FAQ</h1>
                <div class="faq">
                    <h2>I've heard that JavaScript is the long-lost fountain of youth. Is this true?</h2>
                    <div class="answer">
                        <p>Why, yes it is! Studies prove that learning JavaScript freshens the mind and extends life span by several hundred years. (Note: some scientists disagree with these claims.)</p>
                    </div>
                </div>
                <div class="faq">
                    <h2>Can JavaScript really solve all of my problems?</h2>
                    <div class="answer">
                        <p>Why, yes it can! It's the most versatile programming language ever created and is trained to provide financial management advice, life-saving CPR, and even to take care of household pets.</p>
                    </div>
                </div>
                <div class="faq">
                    <h2>Is there nothing JavaScript <em>can&#8217;t</em> do?</h2>
                    <div class="answer">
                        <p>Why, no there isn&#8217;t! It&#8217;s even able to write its own public relations-oriented Frequently Asked Questions pages. Now that&#8217;s one smart programming language!</p>
                    </div>
                </div>
            </div>
        </div>
        <footer>
            <p>JavaScript &amp; jQuery: The Missing Manual, 3rd Edition, by <a href="http://sawmac.com/">David McFarland</a>. Published by <a href="http://oreilly.com/">O'Reilly Media, Inc</a>.</p>
        </footer>
    </div>


问:
How to get newer Nixpkgs stdenv versions to set the NIX_CFLAGS/NIX_LDFLAGS for 'libav'?
The stdenv of newer Nixpkgs versions fails to set the NIX_CFLAGS/NIX_LDFLAGS for the package libav, which has worked in older versions.
What am I doing wong?

The following script illustrates the problem.
It runs several builds with buildInputs = [ libav ]; using different versions of the stdenv and prints the respective values of NIX_LDFLAGS and NIX_CFLAGS_COMPILE:

# Eval in shell
nix-build --no-out-link - <<'EOF'
let
pkgs = (import <nixpkgs> {});
fetchNixPkgs = { rev, sha256 }:
  pkgs.fetchFromGitHub rec {
    inherit sha256 rev;
    owner = "NixOS";
    repo = "nixpkgs-channels";
    name = "adhoc-nixpkgs";
  };
loadNixPkgs = args: import (fetchNixPkgs args) {};
pkgsVersions = {
  # Aug 21, 2016
  # This one works correctly: CFLAGS/LDFLAGS includes references to libav
  working = loadNixPkgs {
    rev = "5120af001f2bb163b58c41c84b11a0c136a207fe";
    sha256 = "18h0aww5m17fip90zld8yqbz9f76ax5ws13krqgrccghn9i9hjlj";
  };
  # Jul 5, 2017
  # The latest version: libav isn't included in CFLAGS/LDFLAGS
  # This issue is also present in older versions
  current = loadNixPkgs {
    rev = "c2e3f7b687660fed7e0056ef1300a2efdfca6e4e";
    sha256 = "0yp34xr8nkagn75d5sc0igynipvvr3mjcmz52scqd9isd7nmmfjs";
  };
  # Nov 11, 2016. An older version with the same issue
  older = loadNixPkgs {
    rev = "cf57b79fb1b4d1c261a1b27eaed75aefe99bd498";
    sha256 = "1m5yjfnjckl8qjz2kxjj7zy074jdmn4r1csqgmf65024hlhqdz8r";
  };
};
libav = pkgsVersions.current.libav.dev;
# libav = pkgsVersions.working.libav; # This one works, too
showEnv = pkgsVersion:
  let
  pkgs = pkgsVersions.${pkgsVersion};
  in
  pkgs.runCommand "test-env" { inherit pkgsVersion; buildInputs = [ libav ]; } ''
    mkdir -p $out
    echo
    echo "============ Build environment for pkgs version '$pkgsVersion' ============"
    echo NIX_LDFLAGS=$NIX_LDFLAGS
    echo NIX_CFLAGS_COMPILE=$NIX_CFLAGS_COMPILE
    echo
  '';
in
map showEnv (builtins.attrNames pkgsVersions)
EOF
```

<p>Output:</p>

```building path(s) ‘/nix/store/32jvx9cqafs54jcd0fbcdq6y93wyg8nm-test-env’

(Commentary: That's how it should look like)
 ↓
============ Build environment for pkgs version 'working' ============
NIX_LDFLAGS=-rpath /nix/store/32jvx9cqafs54jcd0fbcdq6y93wyg8nm-test-env/lib64 -rpath /nix/store/32jvx9cqafs54jcd0fbcdq6y93wyg8nm-test-env/lib -L/nix/store/b4viv3w9hzshp1i6zld219s3aszqdb4n-libav-11.9-dev/lib -L/nix/store/9li7l66zhd6lwhh34vbkx7zydk9cw3sz-libav-11.9/lib
NIX_CFLAGS_COMPILE= -isystem /nix/store/b4viv3w9hzshp1i6zld219s3aszqdb4n-libav-11.9-dev/include

building path(s) ‘/nix/store/j75z46xvfcl9512pi1rmahmslmlzk4ks-test-env’

============ Build environment for pkgs version 'current' ============
NIX_LDFLAGS=-rpath /nix/store/j75z46xvfcl9512pi1rmahmslmlzk4ks-test-env/lib64 -rpath /nix/store/j75z46xvfcl9512pi1rmahmslmlzk4ks-test-env/lib
NIX_CFLAGS_COMPILE=

building path(s) ‘/nix/store/1gic4s1jdv36pjkn5akrn98y215ll2al-test-env’

============ Build environment for pkgs version 'older' ============
NIX_LDFLAGS=-rpath /nix/store/1gic4s1jdv36pjkn5akrn98y215ll2al-test-env/lib64 -rpath /nix/store/1gic4s1jdv36pjkn5akrn98y215ll2al-test-env/lib
NIX_CFLAGS_COMPILE=
```

答:
The solution is to add gcc to buildInputs or to use runCommandCC instead of runCommand:

```<code>nix-build --no-out-link - <<'EOF'
with (import <nixpkgs> {});
runCommand "test-env" { buildInputs = [ gcc libav ]; } ''
  mkdir -p $out
  echo NIX_LDFLAGS=$NIX_LDFLAGS
  echo NIX_CFLAGS_COMPILE=$NIX_CFLAGS_COMPILE
''
EOF
</code>```

Body:
The stdenv of newer Nixpkgs versions fails to set the NIX_CFLAGS/NIX_LDFLAGS for the package libav, which has worked in older versions.
What am I doing wong?

The following script illustrates the problem.
It runs several builds with buildInputs = [ libav ]; using different versions of the stdenv and prints the respective values of NIX_LDFLAGS and NIX_CFLAGS_COMPILE:

# Eval in shell
nix-build --no-out-link - <<'EOF'
let
pkgs = (import <nixpkgs> {});
fetchNixPkgs = { rev, sha256 }:
  pkgs.fetchFromGitHub rec {
    inherit sha256 rev;
    owner = "NixOS";
    repo = "nixpkgs-channels";
    name = "adhoc-nixpkgs";
  };
loadNixPkgs = args: import (fetchNixPkgs args) {};
pkgsVersions = {
  # Aug 21, 2016
  # This one works correctly: CFLAGS/LDFLAGS includes references to libav
  working = loadNixPkgs {
    rev = "5120af001f2bb163b58c41c84b11a0c136a207fe";
    sha256 = "18h0aww5m17fip90zld8yqbz9f76ax5ws13krqgrccghn9i9hjlj";
  };
  # Jul 5, 2017
  # The latest version: libav isn't included in CFLAGS/LDFLAGS
  # This issue is also present in older versions
  current = loadNixPkgs {
    rev = "c2e3f7b687660fed7e0056ef1300a2efdfca6e4e";
    sha256 = "0yp34xr8nkagn75d5sc0igynipvvr3mjcmz52scqd9isd7nmmfjs";
  };
  # Nov 11, 2016. An older version with the same issue
  older = loadNixPkgs {
    rev = "cf57b79fb1b4d1c261a1b27eaed75aefe99bd498";
    sha256 = "1m5yjfnjckl8qjz2kxjj7zy074jdmn4r1csqgmf65024hlhqdz8r";
  };
};
libav = pkgsVersions.current.libav.dev;
# libav = pkgsVersions.working.libav; # This one works, too
showEnv = pkgsVersion:
  let
  pkgs = pkgsVersions.${pkgsVersion};
  in
  pkgs.runCommand "test-env" { inherit pkgsVersion; buildInputs = [ libav ]; } ''
    mkdir -p $out
    echo
    echo "============ Build environment for pkgs version '$pkgsVersion' ============"
    echo NIX_LDFLAGS=$NIX_LDFLAGS
    echo NIX_CFLAGS_COMPILE=$NIX_CFLAGS_COMPILE
    echo
  '';
in
map showEnv (builtins.attrNames pkgsVersions)
EOF

Output:

building path(s) ‘/nix/store/32jvx9cqafs54jcd0fbcdq6y93wyg8nm-test-env’

(Commentary: That's how it should look like)
 ↓
============ Build environment for pkgs version 'working' ============
NIX_LDFLAGS=-rpath /nix/store/32jvx9cqafs54jcd0fbcdq6y93wyg8nm-test-env/lib64 -rpath /nix/store/32jvx9cqafs54jcd0fbcdq6y93wyg8nm-test-env/lib -L/nix/store/b4viv3w9hzshp1i6zld219s3aszqdb4n-libav-11.9-dev/lib -L/nix/store/9li7l66zhd6lwhh34vbkx7zydk9cw3sz-libav-11.9/lib
NIX_CFLAGS_COMPILE= -isystem /nix/store/b4viv3w9hzshp1i6zld219s3aszqdb4n-libav-11.9-dev/include

building path(s) ‘/nix/store/j75z46xvfcl9512pi1rmahmslmlzk4ks-test-env’

============ Build environment for pkgs version 'current' ============
NIX_LDFLAGS=-rpath /nix/store/j75z46xvfcl9512pi1rmahmslmlzk4ks-test-env/lib64 -rpath /nix/store/j75z46xvfcl9512pi1rmahmslmlzk4ks-test-env/lib
NIX_CFLAGS_COMPILE=

building path(s) ‘/nix/store/1gic4s1jdv36pjkn5akrn98y215ll2al-test-env’

============ Build environment for pkgs version 'older' ============
NIX_LDFLAGS=-rpath /nix/store/1gic4s1jdv36pjkn5akrn98y215ll2al-test-env/lib64 -rpath /nix/store/1gic4s1jdv36pjkn5akrn98y215ll2al-test-env/lib
NIX_CFLAGS_COMPILE=

Body:
The solution is to add gcc to buildInputs or to use runCommandCC instead of runCommand:

nix-build --no-out-link - <<'EOF'
with (import <nixpkgs> {});
runCommand "test-env" { buildInputs = [ gcc libav ]; } ''
  mkdir -p $out
  echo NIX_LDFLAGS=$NIX_LDFLAGS
  echo NIX_CFLAGS_COMPILE=$NIX_CFLAGS_COMPILE
''
EOF


问:
Reactjs Uncaught error: Element type is invalid: expected a string
I get the following error:

"Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. Check the render method of App"

I have checked and doubled checked my code and I cannot workout the problem.

Anyone know why? See code below.

App.js

```<code>import React, {Component} from 'react';
import ReactDOM from 'react-dom';
//import ReactD3, {BarChart, LineChart} from 'react-d3-components';
import {MenuList} from './menu/menulist.js';
import {TabList} from './menu/tablist.js';
import {TabContainer, TabContent, TabPane, Nav, Tab, Row, Col} from 'react-bootstrap';

class App extends Component{
  constructor(props){
    super(props);
  }
  render(){
    console.log("Here 1")
    const menunames = [
      {id: "first", name: "Tab 1"},
      {id: "second", name: "Tab 2"}
    ];

    const plist = [
      {id: "first", name: "Content 1"},
      {id: "second", name: "Content 2"}
    ];
    console.log("Here 2")
    return (
       <div className="app">
        <Tab.Container id="left-tabs-example">
        <Row className="clearfix">
          <Col sm={4}>
            <MenuList items={menunames} />
          </Col>
          <Col sm={8}>
              <TabList panels={plist} />
          </Col>
        </Row>
      </Tab.Container>
     </div>
   );
  }
}

export default App
</code>```

menulist.js

```<code>import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import {TabContainer, TabContent, TabPane, Nav, NavItem, Tab, Row, Col} from 'react-bootstrap';

class MenuList extends Component{
  constructor(props){
    super(props);
  }

  MenuItem({ menuitems }){
    return menuitems.map(item => (
      <NavItem eventKey={item.id}>
        {item.name}
      </NavItem>
    ))
  }

  render(){
    return (
      <Nav bsStyle="pills" stacked>
        <MenuItem menuitems={this.props.items} />
      </Nav>
    )
  }
}

MenuList.propTypes = {
  items: React.PropTypes.array
}

export default MenuList
</code>```

tablist.js

```<code>import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import {TabContainer, TabContent, TabPane, Nav, Tab, Row, Col} from 'react-bootstrap';

class TabList extends Component{
  constructor(props){
    super(props);
  }

  TabPanel({ pans }){
    return pans.map(panel => (
      <Tab.Pane eventKey={panel.id}>
        {panel.name}
      </Tab.Pane>
    ))
  }

  render(){
    return (
      <Tab.Content animation>
        this.props.panels.map(panel => (
          <Tab.Pane eventKey={panel.id}>
            {panel.name}
            </Tab.Pane>
          )
      </Tab.Content>
    )
  }
}

TabList.propTypes = {
  panels: React.PropTypes.array
}

export default TabList
</code>```

答:
```<code>import {MenuList} from './menu/menulist.js'; // not correct
import {TabList} from './menu/tablist.js';
</code>```

If You have export default You don't need curly bracers in import.

```<code>import MenuList from './menu/menulist.js'; //correct
import TabList from './menu/tablist.js';

Export {MyComponent, MySecondComponent};  -> import {MyComponent, MySecondComponent} from './path';
Export default MyComponent -> import MyComponent from './path';
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I get the following error:

"Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. Check the render method of App"

I have checked and doubled checked my code and I cannot workout the problem.

Anyone know why? See code below.

App.js

import React, {Component} from 'react';
import ReactDOM from 'react-dom';
//import ReactD3, {BarChart, LineChart} from 'react-d3-components';
import {MenuList} from './menu/menulist.js';
import {TabList} from './menu/tablist.js';
import {TabContainer, TabContent, TabPane, Nav, Tab, Row, Col} from 'react-bootstrap';

class App extends Component{
  constructor(props){
    super(props);
  }
  render(){
    console.log("Here 1")
    const menunames = [
      {id: "first", name: "Tab 1"},
      {id: "second", name: "Tab 2"}
    ];

    const plist = [
      {id: "first", name: "Content 1"},
      {id: "second", name: "Content 2"}
    ];
    console.log("Here 2")
    return (

        <Tab.Container id="left-tabs-example">
        <Row className="clearfix">
          <Col sm={4}>
            <MenuList items={menunames} />
          </Col>
          <Col sm={8}>
              <TabList panels={plist} />
          </Col>
        </Row>
      </Tab.Container>

   );
  }
}

export default App

menulist.js

import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import {TabContainer, TabContent, TabPane, Nav, NavItem, Tab, Row, Col} from 'react-bootstrap';

class MenuList extends Component{
  constructor(props){
    super(props);
  }

  MenuItem({ menuitems }){
    return menuitems.map(item => (
      <NavItem eventKey={item.id}>
        {item.name}
      </NavItem>
    ))
  }

  render(){
    return (

        <MenuItem menuitems={this.props.items} />

    )
  }
}

MenuList.propTypes = {
  items: React.PropTypes.array
}

export default MenuList

tablist.js

import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import {TabContainer, TabContent, TabPane, Nav, Tab, Row, Col} from 'react-bootstrap';

class TabList extends Component{
  constructor(props){
    super(props);
  }

  TabPanel({ pans }){
    return pans.map(panel => (
      <Tab.Pane eventKey={panel.id}>
        {panel.name}
      </Tab.Pane>
    ))
  }

  render(){
    return (
      <Tab.Content animation>
        this.props.panels.map(panel => (
          <Tab.Pane eventKey={panel.id}>
            {panel.name}
            </Tab.Pane>
          )
      </Tab.Content>
    )
  }
}

TabList.propTypes = {
  panels: React.PropTypes.array
}

export default TabList

Body:
import {MenuList} from './menu/menulist.js'; // not correct
import {TabList} from './menu/tablist.js';

If You have export default You don't need curly bracers in import.

import MenuList from './menu/menulist.js'; //correct
import TabList from './menu/tablist.js';

Export {MyComponent, MySecondComponent};  -> import {MyComponent, MySecondComponent} from './path';
Export default MyComponent -> import MyComponent from './path';


问:
How I can upload files to Amazon S3 without listing bucket
I am uploading files to S3 using Angular front-end with S3 Bucket policy as:

```<code>{
  "Id": "Policy1499245520254",
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1499245493674",
      "Action": [
        "s3:*"
      ],
      "Effect": "Allow",
      "Resource": ["arn:aws:s3:::test-dev/*",
                "arn:aws:s3:::test-dev"],
      "Principal": "*"
    }
  ]
}
</code>```

But if I change the above policy to

```<code>{
  "Id": "Policy1499245520254",
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1499245493674",
      "Action": [
        "s3:*"
      ],
      "Effect": "Allow",
      "Resource": ["arn:aws:s3:::test-dev/*",
                "arn:aws:s3:::test-dev"],
      "Principal": "*"
    },
    {
      "Sid": "Stmt1499245517941",
      "Action": [
        "s3:ListBucket"
      ],
      "Effect": "Deny",
      "Resource": "arn:aws:s3:::test-dev",
      "Principal": "*"
    }
  ]
}
</code>```

Where I added:

```<code>{
      "Sid": "Stmt1499245517944",
      "Action": [
        "s3:ListBucket"
      ],
      "Effect": "Deny",
      "Resource": "arn:aws:s3:::test-dev",
      "Principal": "*"
 }
</code>```

adding bucket list deny, the upload fails. Any way how I can upload files without listing bucket.

答:
```<code>{
    "Version": "2008-10-17",
    "Statement": [
        {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
                "AWS": "*"
            },
            "Action": [
                "s3:GetObject",
                "s3:PutObject",
                "s3:GetObjectACL",
                "s3:PutObject",
                "s3:PutObjectAcl",
                "s3:PutObjectTagging",
                "s3:PutObjectVersionAcl",
                "s3:PutObjectVersionTagging"
            ],
            "Resource": [
                "arn:aws:s3:::test-dev",
                "arn:aws:s3:::test-dev/*"
            ]
        }
    ]
}
</code>```

I solved it by just allowing these permissions, apparently bucket list is not needed in this and solves the problem.

Body:
I am uploading files to S3 using Angular front-end with S3 Bucket policy as:

{
  "Id": "Policy1499245520254",
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1499245493674",
      "Action": [
        "s3:*"
      ],
      "Effect": "Allow",
      "Resource": ["arn:aws:s3:::test-dev/*",
                "arn:aws:s3:::test-dev"],
      "Principal": "*"
    }
  ]
}

But if I change the above policy to

{
  "Id": "Policy1499245520254",
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1499245493674",
      "Action": [
        "s3:*"
      ],
      "Effect": "Allow",
      "Resource": ["arn:aws:s3:::test-dev/*",
                "arn:aws:s3:::test-dev"],
      "Principal": "*"
    },
    {
      "Sid": "Stmt1499245517941",
      "Action": [
        "s3:ListBucket"
      ],
      "Effect": "Deny",
      "Resource": "arn:aws:s3:::test-dev",
      "Principal": "*"
    }
  ]
}

Where I added:

{
      "Sid": "Stmt1499245517944",
      "Action": [
        "s3:ListBucket"
      ],
      "Effect": "Deny",
      "Resource": "arn:aws:s3:::test-dev",
      "Principal": "*"
 }

adding bucket list deny, the upload fails. Any way how I can upload files without listing bucket.

Body:
{
    "Version": "2008-10-17",
    "Statement": [
        {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
                "AWS": "*"
            },
            "Action": [
                "s3:GetObject",
                "s3:PutObject",
                "s3:GetObjectACL",
                "s3:PutObject",
                "s3:PutObjectAcl",
                "s3:PutObjectTagging",
                "s3:PutObjectVersionAcl",
                "s3:PutObjectVersionTagging"
            ],
            "Resource": [
                "arn:aws:s3:::test-dev",
                "arn:aws:s3:::test-dev/*"
            ]
        }
    ]
}

I solved it by just allowing these permissions, apparently bucket list is not needed in this and solves the problem.


问:
"Package should contain a content type part [M1.13]"
I am attempting to write to an Excel file however I keep getting the error:

Exception in thread "main" org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package should contain a content type part [M1.13]

From what I understand I am missing a jar file.

Can anyone help me identify which file it is?

P.S. I am using Netbeans.

```<code>import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.JOptionPane;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 *
 * @author nicholaskissaun
 */

public class Tester {

    public static void main (String args \[\])throws FileNotFoundException, IOException, InvalidFormatException{
        int RowCount = 7, iChoice;
        String sChoice;
        XSSFSheet s;
        XSSFRow row1;
        XSSFWorkbook wb;
        XSSFCell r1c1, r1c2, r1c8, r1Episodes;

        FileInputStream fis = new FileInputStream("/Users/nicholaskissaun/Google Drive/Grade 11_12/Computer Science/Java/Term1/src/IA/Profiles/Becky/ShowDetails.xlsx");
        wb = new XSSFWorkbook(fis);
        s = wb.getSheetAt(0);

    }

}
</code>```

答: I got the same problem. Your excel isn't in right format. You can copy all work to new sheet or do Clear Format. Good luck. </p>

Body:
I am attempting to write to an Excel file however I keep getting the error:

Exception in thread "main" org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package should contain a content type part [M1.13]

From what I understand I am missing a jar file.

Can anyone help me identify which file it is?

P.S. I am using Netbeans.

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.JOptionPane;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 *
 * @author nicholaskissaun
 */

public class Tester {

    public static void main (String args \[\])throws FileNotFoundException, IOException, InvalidFormatException{
        int RowCount = 7, iChoice;
        String sChoice;
        XSSFSheet s;
        XSSFRow row1;
        XSSFWorkbook wb;
        XSSFCell r1c1, r1c2, r1c8, r1Episodes;

        FileInputStream fis = new FileInputStream("/Users/nicholaskissaun/Google Drive/Grade 11_12/Computer Science/Java/Term1/src/IA/Profiles/Becky/ShowDetails.xlsx");
        wb = new XSSFWorkbook(fis);
        s = wb.getSheetAt(0);

    }

}


问:
Returning to my if statement
This is my first time on this site and am new to programming. I need the user to be able to input another word if they say "y". As of now the program sends them back to the         while   statements. Any advice would be appreciated.

```<code>print('Welcome to Word Madness!!')

vowels = list('aeioyu')

consonants = list('bcdfghjklmnpqrstvwxz')

wordCount = 0

complete = False

while not complete:
    mode = input('Would you like to type Vowels, Consonants, or Quit?: ').lower().strip()
    print('You chose to enter: ',str(mode))

#When user chooses to quit program will system exit

    if mode == 'quit':
        print('Sorry to see you go! Come back to Word Madness soon!')
        import sys
        sys.exit(0)

#If vowels are selected then they will be counted

    if mode == 'vowels':
        word = input('Please enter your word!')
        number_of_vowels = sum(word.count(i) for i in vowels)
        print('Your word was : ',word,'Your Vowel count was: ',number_of_vowels)
        wordCount = wordCount + 1
        choice = input('Do you have another word? Y/N: ').lower().strip()

        if choice == 'n':
            averageV = int(number_of_vowels // wordCount)
            print('Your average number of Vowels was: ',averageV)
            print('Thank you for using Word Madness!')
            complete = True

        else:
            mode = 'vowels'

#If consonants are selected then they will be counted

    elif mode == 'consonants':
        word = input('Please enter your word!')
        number_of_consonants = sum(word.count(i) for i in consonants)
        print('Your word was : ',word,'Your Consonant count was: ',number_of_consonants)
        wordCount = wordCount + 1
        choice = input('Do you have another word? Y/N: ').lower().strip()

        if choice =='n':
            averageC = int(number_of_consonants // wordCount)
            print('Your average number of Consonants was: ',averageC)
            print('Thank you for using Word Madness!')
            complete = True
#If user has no more words to enter then they are given an average

         else:
            mode == 'consonants'

    else:
        print('ERROR! INVALID INPUT DETECTED!')
</code>```

答:
Ok,for what I understood you don't know how to go back in the code. For this you should learn how to use functions in Python.
What is a function?

A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. (Definition taken from internet)

So I would suggest you to find more about functions, because it's very useful.
After learning functions you should add that:

After every

```<code> if choice =='n':
        averageC = int(number_of_consonants // wordCount)
        print('Your average number of Consonants was: ',averageC)
        print('Thank you for using Word Madness!')
        complete = True
</code>```

Add

```<code>elif choice == 'n':
        function()
</code>```

Function() --> Calling the main function.

Title: Returning to my if statement

Body:
This is my first time on this site and am new to programming. I need the user to be able to input another word if they say "y". As of now the program sends them back to the         while   statements. Any advice would be appreciated.

print('Welcome to Word Madness!!')

vowels = list('aeioyu')

consonants = list('bcdfghjklmnpqrstvwxz')

wordCount = 0

complete = False

while not complete:
    mode = input('Would you like to type Vowels, Consonants, or Quit?: ').lower().strip()
    print('You chose to enter: ',str(mode))

#When user chooses to quit program will system exit

    if mode == 'quit':
        print('Sorry to see you go! Come back to Word Madness soon!')
        import sys
        sys.exit(0)

#If vowels are selected then they will be counted

    if mode == 'vowels':
        word = input('Please enter your word!')
        number_of_vowels = sum(word.count(i) for i in vowels)
        print('Your word was : ',word,'Your Vowel count was: ',number_of_vowels)
        wordCount = wordCount + 1
        choice = input('Do you have another word? Y/N: ').lower().strip()

        if choice == 'n':
            averageV = int(number_of_vowels // wordCount)
            print('Your average number of Vowels was: ',averageV)
            print('Thank you for using Word Madness!')
            complete = True

        else:
            mode = 'vowels'

#If consonants are selected then they will be counted

    elif mode == 'consonants':
        word = input('Please enter your word!')
        number_of_consonants = sum(word.count(i) for i in consonants)
        print('Your word was : ',word,'Your Consonant count was: ',number_of_consonants)
        wordCount = wordCount + 1
        choice = input('Do you have another word? Y/N: ').lower().strip()

        if choice =='n':
            averageC = int(number_of_consonants // wordCount)
            print('Your average number of Consonants was: ',averageC)
            print('Thank you for using Word Madness!')
            complete = True
#If user has no more words to enter then they are given an average

         else:
            mode == 'consonants'

    else:
        print('ERROR! INVALID INPUT DETECTED!')

Body:
Ok,for what I understood you don't know how to go back in the code. For this you should learn how to use functions in Python.
What is a function?

A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. (Definition taken from internet)

So I would suggest you to find more about functions, because it's very useful.
After learning functions you should add that:

After every

 if choice =='n':
        averageC = int(number_of_consonants // wordCount)
        print('Your average number of Consonants was: ',averageC)
        print('Thank you for using Word Madness!')
        complete = True

Add

elif choice == 'n':
        function()

Function() --> Calling the main function.


问:
Validate email address in PHP

Possible Duplicate:

  How to validate an emailaddress in PHP

I was wondering what everyone is doing in regards to validating email addresses and how extensive the validation needs to be.

For example, of those methods, which one is preferred and why?

Extensive check: http://www.linuxjournal.com/article/9585?page=0,3

PHP filter: http://php.net/manual/en/filter.filters.validate.php

Eregi: http://www.totallyphp.co.uk/code/validate_an_email_address_using_regular_expressions.htm

Preg match with DNS check: http://www.soaptray.com/blog/2008/04/validate-email-addresses-using-php/

My goal is to find a good and solid solution for the average project, so when the time comes to validate an email address, I know exactly what I'm going to use.

Any feedback much appreciated!

-Ryan

答: Use PHP’s build-in filters for a syntactic validation and send a verification e-mail for an intention confirmation.</p>

Title: Validate email address in PHP


问:
Shell script called from PHP does not work, but it works in command line
I want to copy a file by shell script called from PHP.
However cp command does not work properly.

My system is as follows:
 Linux: Ubuntu MATE 16.01, Apache2 (port 80), django (port 8000), php (port 80)

Shell script is like this:

```<code> #!/bin/sh
 cp /var/www/html/aaa.html /home/user/test/aaa.html
</code>```

aaa.html is a web page on django and is saved under /var/www/html/ by php.
I call php on aaa.html, and I upload aaa.html. After that I execute shell script above on php.

When I input 'cp /var/www/html/aaa.html /home/user/test/aaa.html' in command line (SSH connect), it works and aaa.html is updated even the django's runserver is under run. However when I do the command in shell script, aaa.html is not updated.

How can I update aaa.html by shell script called by PHP?
I think if I could kill runserver, aaa.html would be updated.
Though command kill called from shell script does not work too.
Are there anyway to do it?

Thank you.

答:
Usually for these kind of problems, it would be nice to have some more information like the error that is given.
But 9 times out of 10 this is a permission problem.

When you are doing this over SSH, it is being done as the user that you use to log in. This one obviously has the permission to change this file.

When PHP tries to do this, this is usually done by the user that is used for the web-server (for example: www-data). You need to make sure that this user has permissions on the file.

You can do this with a Chmod, which changes the file permissions:

```<code>chmod g+w <myfile>
adduser www-data(or the webserver user) <the group belonging to the file>
</code>```

This one changes the permissions to allow group writes, and adds the user to the group that the file belongs to.

Note: Possibly by changing-/creating this file over ssh, it belongs to your user and not the user using the webserver.

Body:
I want to copy a file by shell script called from PHP.
However cp command does not work properly.

My system is as follows:
 Linux: Ubuntu MATE 16.01, Apache2 (port 80), django (port 8000), php (port 80)

Shell script is like this:

 #!/bin/sh
 cp /var/www/html/aaa.html /home/user/test/aaa.html

aaa.html is a web page on django and is saved under /var/www/html/ by php.
I call php on aaa.html, and I upload aaa.html. After that I execute shell script above on php.

When I input 'cp /var/www/html/aaa.html /home/user/test/aaa.html' in command line (SSH connect), it works and aaa.html is updated even the django's runserver is under run. However when I do the command in shell script, aaa.html is not updated.

How can I update aaa.html by shell script called by PHP?
I think if I could kill runserver, aaa.html would be updated.
Though command kill called from shell script does not work too.
Are there anyway to do it?

Thank you.

Body:
Usually for these kind of problems, it would be nice to have some more information like the error that is given.
But 9 times out of 10 this is a permission problem.

When you are doing this over SSH, it is being done as the user that you use to log in. This one obviously has the permission to change this file.

When PHP tries to do this, this is usually done by the user that is used for the web-server (for example: www-data). You need to make sure that this user has permissions on the file.

You can do this with a Chmod, which changes the file permissions:

chmod g+w <myfile>
adduser www-data(or the webserver user) <the group belonging to the file>

This one changes the permissions to allow group writes, and adds the user to the group that the file belongs to.

Note: Possibly by changing-/creating this file over ssh, it belongs to your user and not the user using the webserver.


答:
Try this</p>

```<code>$(document).ready(function () {
    $('.answer').hide();
    var $answer = $(this).next('.answer');
    $('.main h2').mouseover(function () {
        $(this).find('.answer').show();
        $answer.slideDown();
        $(this).addClass('close');
    });
    $('.main h2').mouseout(function () {
        $(this).find('.answer').hide();
        $answer.fadeOut();
        $(this).removeClass('close');
    });

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

Title: Mouseover, mouseEnter

Body:
Try this

$(document).ready(function () {
    $('.answer').hide();
    var $answer = $(this).next('.answer');
    $('.main h2').mouseover(function () {
        $(this).find('.answer').show();
        $answer.slideDown();
        $(this).addClass('close');
    });
    $('.main h2').mouseout(function () {
        $(this).find('.answer').hide();
        $answer.fadeOut();
        $(this).removeClass('close');
    });

}); //


问:
Display annotations for 3D model object on iOS
Please suggest me a solution for displaying annotations (text or images) for 3D model object on iOS.

For details, so far, I'm able to load and display an 3D model object on iOS by following the guide at http://iosdeveloperzone.com/2016/05/10/getting-started-with-modelio/. But I cannot find a way to add annotations, then display them with the 3D model object. I expect the implementation on iOS will be similar with https://sketchfab.com/models/363e92268ff04a6ba8322332004bdaab (on web version).

Thank you for any suggestions and answers.

答: You can try to create node with SCNText geometry type. This allows to show text in 3D scene.</p>


问:
How to install something that read excel files in python 3.3
I am new to python and I need to read an excel file in pyscripter. I understand that I should

```<code>import xrld
</code>```

in Python and then use:

```<code>book = xlrd.open_workbook(os.path.join(file_source,file_name +".xlsx"))
</code>```

to open and read the excel file.

However, I just don't understand how to install this module 'xrld'. I have looked on several websites and even on stackoverflow itself, but I just don't understand anything from the explanations that are given. I just don't understand how to install 'easy install' or 'pip' (or understand what these things are in the first place) or understand how to install anything else I need to read an excel file for. So far I installed a file called 'setuptools-36.01.1' from https://pypi.python.org/pypi/setuptools which should contain something I could use for running, but I just don't understand what to do.

I thereby must admit (and think it is clear by now) that I am a real noob when it comes to programming or computers in the first place.

Can someone please help me by explaining in plain English what exactly to do in order to read an excel file in python. I have Python 3.3.2 and use Pyscripter to run my simulation.

Your help would be really appreciated!

答:
EasyInstall (easy_install) gives you a quick and painless way to install packages remotely by connecting other websites via HTTP.

Pip is a package management system used to install and manage software packages, such as those found in the Python Package Index. Pip is a replacement for easy_install.

Since you have installed the setuptools, easy_install will be already present in your system.

So just run easy_install pip in the command line to install pip . Then pip install xlrd for installing xlrd.

example code:

```<code>import xlrd
workbook = xlrd.open_workbook('C:/User/myaccount/Book1.xls')
worksheet = workbook.sheet_by_name('Sheet1')
print worksheet
</code>```

Please go through this link-Reading Excel file using Python XLRD for sample codes for reading data from excel files in python.

Hope this helps you..

Body:
I am new to python and I need to read an excel file in pyscripter. I understand that I should

import xrld

in Python and then use:

book = xlrd.open_workbook(os.path.join(file_source,file_name +".xlsx"))

to open and read the excel file.

However, I just don't understand how to install this module 'xrld'. I have looked on several websites and even on stackoverflow itself, but I just don't understand anything from the explanations that are given. I just don't understand how to install 'easy install' or 'pip' (or understand what these things are in the first place) or understand how to install anything else I need to read an excel file for. So far I installed a file called 'setuptools-36.01.1' from https://pypi.python.org/pypi/setuptools which should contain something I could use for running, but I just don't understand what to do.

I thereby must admit (and think it is clear by now) that I am a real noob when it comes to programming or computers in the first place.

Can someone please help me by explaining in plain English what exactly to do in order to read an excel file in python. I have Python 3.3.2 and use Pyscripter to run my simulation.

Your help would be really appreciated!

Body:
EasyInstall (easy_install) gives you a quick and painless way to install packages remotely by connecting other websites via HTTP.

Pip is a package management system used to install and manage software packages, such as those found in the Python Package Index. Pip is a replacement for easy_install.

Since you have installed the setuptools, easy_install will be already present in your system.

So just run easy_install pip in the command line to install pip . Then pip install xlrd for installing xlrd.

example code:

import xlrd
workbook = xlrd.open_workbook('C:/User/myaccount/Book1.xls')
worksheet = workbook.sheet_by_name('Sheet1')
print worksheet

Please go through this link-Reading Excel file using Python XLRD for sample codes for reading data from excel files in python.

Hope this helps you..


问:
Does assigning objects to null in Java impact garbage collection?
Does assigning an unused object reference to null in Java improve the garbage collection process in any measurable way?

My experience with Java (and C#) has taught me that is often counter intuitive to try and outsmart the virtual machine or JIT compiler, but I've seen co-workers use this method and I am curious if this is a good practice to pick up or one of those voodoo programming superstitions?

答:
Good article is today's coding horror.

The way GC's work is by looking for objects that do not have any pointers to them, the area of their search is heap/stack and any other spaces they have.  So if you set a variable to null, the actual object is now not pointed by anyone, and hence could be GC'd.

But since the GC might not run at that exact instant, you might not actually be buying yourself anything.  But if your method is fairly long (in terms of execution time) it might be worth it since you will be increasing your chances of GC collecting that object.

The problem can also be complicated with code optimizations, if you never use the variable after you set it to null, it would be a safe optimization to remove the line that sets the value to null (one less instruction to execute).  So you might not actually be getting any improvement.

So in summary, yes it can help, but it will not be deterministic.

OwnerDisplayName: nemo

LastEditorDisplayName: nemo

OwnerDisplayName: earlNameless

LastEditorDisplayName: Simucal


问:
WPF Binding Issue - UI Updates, Object Does Not
I'm having yet another WPF binding issue.  Just when I think I've got this stuff figured out, I run into more problems...  :S

Anyway... I've created a custom user control for selecting files.  It's a simple textbox followed by a button contained within a grid.  The property of the control with which I am working is called FilePath and the TextBox on this control is bound to that property.  When the button is clicked, a SaveFileDialog is opened and the user selects a file.  The UI correctly updates after the user selects the file.

The problem I seem to be having is that when I bind an object to the control (in this instance I have an object with a DocumentFilePath property) the object doesn't update when a new file is selected.

Here's the relevant code within my user control:

```<code>public static readonly DependencyProperty FilePathProperty = DependencyProperty.Register("FilePath", typeof(string), typeof(FileSave), new UIPropertyMetadata(string.Empty, OnFilePathChanged));

public string FilePath
{
    get
    {
        return this.GetValue(FilePathProperty) as string;
    }
    set
    {
        this.SetValue(FilePathProperty, value);
        this.OnPropertyChanged("FilePath");
    }
}

private void OnPropertyChanged(string propName)
{
    if (PropertyChanged != null)
    {
       PropertyChanged(this, new PropertyChangedEventArgs(propName));
    }
}

private static void OnFilePathChanged(object sender, DependencyPropertyChangedEventArgs e)
{
    ((FileSave)sender).OnPropertyChanged("FilePath");
}
</code>```

And the user control is added into my Window programatically by using reflection on my object:

```<code>private void AddFileSave(PropertyInfo pi)
{
     FileSave fs = new FileSave();
     Binding b = new Binding(pi.Name);

     fs.SetBinding(FileSave.FilePathProperty, b);
     this.AddToGrid(fs); //adds the control into my window's grid in the correct row and column; nothing fancy here
}
</code>```

It may be worth noting that if I load the window with an existing object, my user control displays properly but still won't register any changes within the object to which it is bound.

Please let me know if you guys need any more info.

Thanks in advance,

Sonny

EDIT:  I've found a way around the problem, but this probably isn't a good solution.  By watching the debugger carefully I found that when I set the FilePath property within my control, the object was being unbound.  If anyone can shed some light on that, I would be most appreciative.  In the mean time, I've changed the code that opens my SaveFileDialog to look like this:

```<code>private void Button_Click(object sender, RoutedEventArgs e)
{
    Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();

    ofd.Multiselect = false;
    ofd.Title = "Select document to import...";
    ofd.ValidateNames = true;

    ofd.ShowDialog();

    if (this.GetBindingExpression(FilePathProperty) == null)
    {
        this.FilePath = ofd.FileName;
    }
    else //set value on bound object (THIS IS THE NEW PORTION I JUST ADDED)
    {
        BindingExpression be = this.GetBindingExpression(FilePathProperty);
        string propName = be.ParentBinding.Path.Path;
        object entity = be.DataItem;
        System.Reflection.PropertyInfo pi = entity.GetType().GetProperty(propName);

        pi.SetValue(entity, ofd.FileName, null);
    }

    if (!string.IsNullOrWhiteSpace(this.FilePath))
    {
        _fileContents = new MemoryStream();
        using (StreamReader sr = new StreamReader(this.FilePath))
        {
            _fileContents = new MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes(sr.ReadToEnd()));
        }
    }
    else
    {
        _fileContents = null;
    }
}
</code>```

答:
Why, yes!  I most certainly can shed some light on that!

Also, if you're using .Net 4.0, today's your lucky day!

Consider the following fine method on your DependencyObject:

SetCurrentValue();

Yes!  With this SINGULAR method, all your woes will drift away as a bad dream at the rooster's crow!  (Well, ok, not really, but that is the method you're looking for.)

Short story very short:  When you programmatically SetValue() on a control in your view layer, you blow away your bindings.  SetCurrentValue() was added to the framework because you frequently want to drive a change in your bound object by setting that value directly.  An alternate design would be to set the value in your bound object programmatically and let the updated value get pulled back into the view, but that's frequently clumsy.

(I strongly suspect that the absence of this method up to this point is largely responsible for the utter failure of the vast majority of NumericUpDown controls in WPF.)

Body:
I'm having yet another WPF binding issue.  Just when I think I've got this stuff figured out, I run into more problems...  :S

Anyway... I've created a custom user control for selecting files.  It's a simple textbox followed by a button contained within a grid.  The property of the control with which I am working is called FilePath and the TextBox on this control is bound to that property.  When the button is clicked, a SaveFileDialog is opened and the user selects a file.  The UI correctly updates after the user selects the file.

The problem I seem to be having is that when I bind an object to the control (in this instance I have an object with a DocumentFilePath property) the object doesn't update when a new file is selected.

Here's the relevant code within my user control:

public static readonly DependencyProperty FilePathProperty = DependencyProperty.Register("FilePath", typeof(string), typeof(FileSave), new UIPropertyMetadata(string.Empty, OnFilePathChanged));

public string FilePath
{
    get
    {
        return this.GetValue(FilePathProperty) as string;
    }
    set
    {
        this.SetValue(FilePathProperty, value);
        this.OnPropertyChanged("FilePath");
    }
}

private void OnPropertyChanged(string propName)
{
    if (PropertyChanged != null)
    {
       PropertyChanged(this, new PropertyChangedEventArgs(propName));
    }
}

private static void OnFilePathChanged(object sender, DependencyPropertyChangedEventArgs e)
{
    ((FileSave)sender).OnPropertyChanged("FilePath");
}

And the user control is added into my Window programatically by using reflection on my object:

private void AddFileSave(PropertyInfo pi)
{
     FileSave fs = new FileSave();
     Binding b = new Binding(pi.Name);

     fs.SetBinding(FileSave.FilePathProperty, b);
     this.AddToGrid(fs); //adds the control into my window's grid in the correct row and column; nothing fancy here
}

It may be worth noting that if I load the window with an existing object, my user control displays properly but still won't register any changes within the object to which it is bound.

Please let me know if you guys need any more info.

Thanks in advance,

Sonny

EDIT:  I've found a way around the problem, but this probably isn't a good solution.  By watching the debugger carefully I found that when I set the FilePath property within my control, the object was being unbound.  If anyone can shed some light on that, I would be most appreciative.  In the mean time, I've changed the code that opens my SaveFileDialog to look like this:

private void Button_Click(object sender, RoutedEventArgs e)
{
    Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();

    ofd.Multiselect = false;
    ofd.Title = "Select document to import...";
    ofd.ValidateNames = true;

    ofd.ShowDialog();

    if (this.GetBindingExpression(FilePathProperty) == null)
    {
        this.FilePath = ofd.FileName;
    }
    else //set value on bound object (THIS IS THE NEW PORTION I JUST ADDED)
    {
        BindingExpression be = this.GetBindingExpression(FilePathProperty);
        string propName = be.ParentBinding.Path.Path;
        object entity = be.DataItem;
        System.Reflection.PropertyInfo pi = entity.GetType().GetProperty(propName);

        pi.SetValue(entity, ofd.FileName, null);
    }

    if (!string.IsNullOrWhiteSpace(this.FilePath))
    {
        _fileContents = new MemoryStream();
        using (StreamReader sr = new StreamReader(this.FilePath))
        {
            _fileContents = new MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes(sr.ReadToEnd()));
        }
    }
    else
    {
        _fileContents = null;
    }
}


问:
Does Hive Optimizer consider view definition while optimizing queries on views?
I have this schema (given through DDL for tables and views):

```<code>hive> create table t_realtime(cust_id int, name string, status string, active_flag int);

hive> create table t_hdfs(cust_id int, name string, status string, active_flag int);

hive> create view t_inactive as select * from t_hdfs where active_flag=0;

hive> create view t_view as select * from t_realtime union all select * from t_inactive;
</code>```

If I fire a query as follows:

```<code>hive> select * from t_view where active_flag = 1;
</code>```

This query ideally should not visit t_inactive view or t_hdfs at all, since the view definition for t_inactive itself has active_flag = 0 and query predicate has active_flag = 1. However, by default, it does not eliminate t_inactive part of this union view.

Is there anyway to achieve this for such hive query? Maybe some hive optimizer parameter or a hint?

答:
```<code>hive> explain extended select * from t_view where active_flag = 1;
OK
STAGE DEPENDENCIES:
  Stage-0 is a root stage

STAGE PLANS:
  Stage: Stage-0
    Fetch Operator
      limit: -1
      Processor Tree:
        TableScan
          alias: t_realtime
          properties:
            insideView TRUE
          GatherStats: false
          Filter Operator
            isSamplingPred: false
            predicate: (active_flag = 1) (type: boolean)
            Select Operator
              expressions: cust_id (type: int), name (type: string), status (type: string), 1 (type: int)
              outputColumnNames: _col0, _col1, _col2, _col3
              ListSink
</code>```

This is tested on yesterday's mainline (at d68630b6ed25884a76030a9073cd864032ab85c2). As you can see, it only scans t_realtime and pushes down the predicate active_flag = 1. Whether your particular installation will do this or not, it depends on what version you're using. This topic is subject to active development, not only on Hive but also on Calcite (used by Hive).

Body:
I have this schema (given through DDL for tables and views):

hive> create table t_realtime(cust_id int, name string, status string, active_flag int);

hive> create table t_hdfs(cust_id int, name string, status string, active_flag int);

hive> create view t_inactive as select * from t_hdfs where active_flag=0;

hive> create view t_view as select * from t_realtime union all select * from t_inactive;

If I fire a query as follows:

hive> select * from t_view where active_flag = 1;

This query ideally should not visit t_inactive view or t_hdfs at all, since the view definition for t_inactive itself has active_flag = 0 and query predicate has active_flag = 1. However, by default, it does not eliminate t_inactive part of this union view.

Is there anyway to achieve this for such hive query? Maybe some hive optimizer parameter or a hint?

Body:
hive> explain extended select * from t_view where active_flag = 1;
OK
STAGE DEPENDENCIES:
  Stage-0 is a root stage

STAGE PLANS:
  Stage: Stage-0
    Fetch Operator
      limit: -1
      Processor Tree:
        TableScan
          alias: t_realtime
          properties:
            insideView TRUE
          GatherStats: false
          Filter Operator
            isSamplingPred: false
            predicate: (active_flag = 1) (type: boolean)
            Select Operator
              expressions: cust_id (type: int), name (type: string), status (type: string), 1 (type: int)
              outputColumnNames: _col0, _col1, _col2, _col3
              ListSink

This is tested on yesterday's mainline (at d68630b6ed25884a76030a9073cd864032ab85c2). As you can see, it only scans t_realtime and pushes down the predicate active_flag = 1. Whether your particular installation will do this or not, it depends on what version you're using. This topic is subject to active development, not only on Hive but also on Calcite (used by Hive).


问:
U-SQL Job Failing in Data Factory
I keep getting following error from Data Factory whenever I run an U-SQL Job

```<code>Job submission failed, the user 'adla account name' does not have permissions to a subfolder in the /system/ path needed by Data Lake Analytics. Please run “Add User Wizard” from the Data Lake Analytics Azure Portal or use Azure PowerShell to grant access for the user to the /system/ and its children on the Data Lake Store.
</code>```

And I am not using any Firewall as suggested in this post:

Run U-SQL Script from C# code with Azure Data Factory

I am using the Azure Data Lake Store service principal authentication. When I start the Job from Visual Studio, it also works fine.

I would be grateful for any idea...

thanks

答:
If you are authorising the Azure Data Lake Analytics linked service from Azure Data Factory with a service principal that could be your problem.

I have an outstanding support ticket with Microsoft because the service principal authentication method only works with simple data factory activities like 'copy'. It does not work if you want to authenticate complex activities like 'DotNotActivity'.

My advise would be to change the linked service back to using session and token auth, then deploy your activities and try again.

Hope this helps.

Title: U-SQL Job Failing in Data Factory

Body:
I keep getting following error from Data Factory whenever I run an U-SQL Job

Job submission failed, the user 'adla account name' does not have permissions to a subfolder in the /system/ path needed by Data Lake Analytics. Please run “Add User Wizard” from the Data Lake Analytics Azure Portal or use Azure PowerShell to grant access for the user to the /system/ and its children on the Data Lake Store.

And I am not using any Firewall as suggested in this post:

Run U-SQL Script from C# code with Azure Data Factory

I am using the Azure Data Lake Store service principal authentication. When I start the Job from Visual Studio, it also works fine.

I would be grateful for any idea...

thanks


答: http://www.regular-expressions.info/email.html has the RFC2822 recommended reg ex.</p>

Title: Validate email address in PHP

Body:
Possible Duplicate:

  How to validate an emailaddress in PHP

I was wondering what everyone is doing in regards to validating email addresses and how extensive the validation needs to be.

For example, of those methods, which one is preferred and why?

Extensive check: http://www.linuxjournal.com/article/9585?page=0,3

PHP filter: http://php.net/manual/en/filter.filters.validate.php

Eregi: http://www.totallyphp.co.uk/code/validate_an_email_address_using_regular_expressions.htm

Preg match with DNS check: http://www.soaptray.com/blog/2008/04/validate-email-addresses-using-php/

My goal is to find a good and solid solution for the average project, so when the time comes to validate an email address, I know exactly what I'm going to use.

Any feedback much appreciated!

-Ryan


问:
HTML and AngularJS Interpolation for email form
I'm using formspree.io for some simple contact forms and want to dynamically change the email address with Angular1 so it looks something like this:

```<code><form action="https://formspree.io/{{ user.email }}" method="POST">
</code>```

Can anyone help shine some light on this? I can't quite work it out so any thoughts would be massively appreciated.

答:
go to the following link. it has clearly mensioned how to post a form in angular, jquery, etc.

https://scotch.io/tutorials/submitting-ajax-forms-the-angularjs-way

go to the formspree website. there you can see the clear explanation in traditional way

```<code><form action="https://formspree.io/your@email.com" method="POST">
   <input type="text" name="name">
   <input type="email" name="_replyto">
   <input type="submit" value="Send">
</form>
</code>```

just convert this form into angular supported form and your work will be pretty easy if you use twoway data binding

ng-submit also works well angular documentation

```<code><form ng-submit="submit()" ng-controller="ExampleController">
  <input type="text" ng-model="text" name="text" />
  <input type="submit" id="submit" value="Submit" />
</form>
</code>```

here submit() is a function that trigger the post request

Body:
I'm using formspree.io for some simple contact forms and want to dynamically change the email address with Angular1 so it looks something like this:

<form action="https://formspree.io/{{ user.email }}" method="POST">

Can anyone help shine some light on this? I can't quite work it out so any thoughts would be massively appreciated.

Body:
go to the following link. it has clearly mensioned how to post a form in angular, jquery, etc.

https://scotch.io/tutorials/submitting-ajax-forms-the-angularjs-way

go to the formspree website. there you can see the clear explanation in traditional way

<form action="https://formspree.io/your@email.com" method="POST">
   <input type="text" name="name">
   <input type="email" name="_replyto">
   <input type="submit" value="Send">
</form>

just convert this form into angular supported form and your work will be pretty easy if you use twoway data binding

ng-submit also works well angular documentation

<form ng-submit="submit()" ng-controller="ExampleController">
  <input type="text" ng-model="text" name="text" />
  <input type="submit" id="submit" value="Submit" />
</form>

here submit() is a function that trigger the post request


问:
Settype integer changing the value in php
I have a field in my database called time. It contains UNIX timestamp. However the data type is a string and in php the date function expects an integer.

So i tried parsing the string to an integer but the value changes.

```<code>    $time = $value['time'];
    echo "Time string is $time<br/>";

    settype($time,'integer');
    echo "time intenger is".$time."<br/>";
</code>```

This is the output i get

Time string is 1499327190163

time intenger is2147483647

What am i doing wrong here? Or is there a better way to convert timestamp to a date? Thanks

EDIT : I just read the manual on settype and it said Maximum value for "int" is PHP_INT_MAX. Perhaps this could be my issue, would it be alright to change this, or should there be any security related concern in changing the max integer value?

答:
1499327190163 appears to be a UNIX timestamp in milliseconds, whereas PHP date functions work in timestamps in seconds. The string vs. int issue is secondary since the value will be implicitly converted to an int as necessary.

The bigger issue is that the value surpasses the upper limit of a 32bit integer, yet you need to do a mathematical operation on it to turn it from milliseconds into seconds. Either:

Do it in the database; just SELECT timestamp / 1000.

Do it in PHP using bcdiv:

```<code>$ts = bcdiv($timestamp, '1000', 0);
</code>```

Convert it to a float and divide it as float; though accuracy may suffer slightly.

Just trim off the last 3 characters of the string, which essentially has the same effect; it just doesn't feel proper IMO.

Now you have a timestamp PHP's date functions can work with.

Body:
I have a field in my database called time. It contains UNIX timestamp. However the data type is a string and in php the date function expects an integer.

So i tried parsing the string to an integer but the value changes.

    $time = $value['time'];
    echo "Time string is $time
";

    settype($time,'integer');
    echo "time intenger is".$time."
";

This is the output i get

Time string is 1499327190163

time intenger is2147483647

What am i doing wrong here? Or is there a better way to convert timestamp to a date? Thanks

EDIT : I just read the manual on settype and it said Maximum value for "int" is PHP_INT_MAX. Perhaps this could be my issue, would it be alright to change this, or should there be any security related concern in changing the max integer value?

Body:
1499327190163 appears to be a UNIX timestamp in milliseconds, whereas PHP date functions work in timestamps in seconds. The string vs. int issue is secondary since the value will be implicitly converted to an int as necessary.

The bigger issue is that the value surpasses the upper limit of a 32bit integer, yet you need to do a mathematical operation on it to turn it from milliseconds into seconds. Either:

Do it in the database; just SELECT timestamp / 1000.

Do it in PHP using bcdiv:

$ts = bcdiv($timestamp, '1000', 0);

Convert it to a float and divide it as float; though accuracy may suffer slightly.

Just trim off the last 3 characters of the string, which essentially has the same effect; it just doesn't feel proper IMO.

Now you have a timestamp PHP's date functions can work with.


问:
how to remove quotes from csv in php
I have a array that i am getting from DB. In this project, im converting my array to csv file. But every time i open the file i get double quoetes. I have tried with str_replace and preg_place with no succes. How can i remove quotes

this is my csv code

```<code>$query = "SELECT t.transactiontime, t.restaurant_id, t.transactionid, t.cardid, emd.m_field_id_2, t.pricebefordiscount, t.menucard_cut
from transactions as t
left join exp_member_data AS emd ON (t.cardid-10000000 = emd.member_id) order by t.transactiontime desc limit 50";

$transactions_query = ee()->db->query($query);
$transactions_result = $transactions_query->result_array();

$transaction_array = array();
foreach ($transactions_result as $key)
{
  $date = new DateTime($key['transactiontime']);
  $newdate = $date->format('d.m.Y');

 $transaction_array[] = array(
    'transactiontime' => $newdate,
    'restaurant_id' =>  $key['restaurant_id'],
    'member' => $key['transactionid'] . " " . $key['m_field_id_2'],
    'pricebefordiscount' => $key['pricebefordiscount']/100,
    'menucard_cut' => $key['menucard_cut']
    );

}

function outputCSV($data)
    {

$outstream = fopen("php://output", 'w');

function __outputCSV(&$vals, $key, $filehandler)
{
    fputcsv($filehandler, $vals, ';');
}

array_walk($data, '__outputCSV', $outstream);

fclose($outstream);
}

outputCSV($transaction_array);
</code>```

my output

```<code>19.08.2013;47657;"12459 Abdullahi";60;
19.08.2013;47658;"12455 atima";30;
</code>```

答:
```<code>Re write the file and try to parse csv file:

$file_path = "Book1.csv";
$string = file_get_contents($file_path, FILE_USE_INCLUDE_PATH);
echo $string;
echo "<br><br><br>";
$string2 = str_replace('"', " ", $string);
echo $string2;
file_put_contents($file_path, $string2);
exit;
</code>```

Title: how to remove quotes from csv in php

Body:
I have a array that i am getting from DB. In this project, im converting my array to csv file. But every time i open the file i get double quoetes. I have tried with str_replace and preg_place with no succes. How can i remove quotes

this is my csv code

$query = "SELECT t.transactiontime, t.restaurant_id, t.transactionid, t.cardid, emd.m_field_id_2, t.pricebefordiscount, t.menucard_cut
from transactions as t
left join exp_member_data AS emd ON (t.cardid-10000000 = emd.member_id) order by t.transactiontime desc limit 50";

$transactions_query = ee()->db->query($query);
$transactions_result = $transactions_query->result_array();

$transaction_array = array();
foreach ($transactions_result as $key)
{
  $date = new DateTime($key['transactiontime']);
  $newdate = $date->format('d.m.Y');

 $transaction_array[] = array(
    'transactiontime' => $newdate,
    'restaurant_id' =>  $key['restaurant_id'],
    'member' => $key['transactionid'] . " " . $key['m_field_id_2'],
    'pricebefordiscount' => $key['pricebefordiscount']/100,
    'menucard_cut' => $key['menucard_cut']
    );

}

function outputCSV($data)
    {

$outstream = fopen("php://output", 'w');

function __outputCSV(&$vals, $key, $filehandler)
{
    fputcsv($filehandler, $vals, ';');
}

array_walk($data, '__outputCSV', $outstream);

fclose($outstream);
}

outputCSV($transaction_array);

my output

19.08.2013;47657;"12459 Abdullahi";60;
19.08.2013;47658;"12455 atima";30;


问:
How does c++ handle 0*(large expression)
Concerning speed, if I need to calculate a large expression, say:

```<code>switch1*(large expression 1)+switch2*(large expression 2)
</code>```

Depending on my input, switch1 can be 0 or 1, as can switch2 be. What would be the quickest for c++ to do, making an if statement or write it down as above?

答:
```<code>result = 0;
if(switch1) {
    result += large_expresion_1();
}
if(switch2)
    result += large_expression2();
}
</code>```

But if you are optimising "large expressions" be sure to check whether it's actually quicker to calculate them both then add them in a branchless manner. eg something like

```<code>result = ((-(uint64_t)(switch1)) & large_expression_1) + ((-(uint64_t)(switch2)) & large_expression_2);
</code>```

A bunch of such bithacks are documented here:
https://graphics.stanford.edu/~seander/bithacks.html

Benchmark and separate to that, read the generated assembly language to find out what the compiler is actually doing for (or to) you.

Body:
Concerning speed, if I need to calculate a large expression, say:

switch1*(large expression 1)+switch2*(large expression 2)

Depending on my input, switch1 can be 0 or 1, as can switch2 be. What would be the quickest for c++ to do, making an if statement or write it down as above?

Body:
result = 0;
if(switch1) {
    result += large_expresion_1();
}
if(switch2)
    result += large_expression2();
}

But if you are optimising "large expressions" be sure to check whether it's actually quicker to calculate them both then add them in a branchless manner. eg something like

result = ((-(uint64_t)(switch1)) & large_expression_1) + ((-(uint64_t)(switch2)) & large_expression_2);

A bunch of such bithacks are documented here:
https://graphics.stanford.edu/~seander/bithacks.html

Benchmark and separate to that, read the generated assembly language to find out what the compiler is actually doing for (or to) you.


问:
sphinx_rtd_theme is no longer a hard dependency since version 1.4.0

C:\Users\Administrator\Desktop\item\code_serv\documents\api>make html
  Running Sphinx v1.6.2 loading pickled environment... failed:

Can't get attribute 'WarningStream' on <module 'sphinx.util.nodes' from 'c:\\users\\administrator\\appdata\\local\\programs\\python\\python36-32\\lib\\site-packages\\sphinx\\util\\nodes.py'>

Theme error:

sphinx_rtd_theme is no longer a hard dependency since version 1.4.0.
  Please install it manually.(pip install sphinx_rtd_theme)

How do I solve this?

答:
Your question does not indicate whether you searched the web for "how to install sphinx_rtd_theme" or read its documentation.

The error message provides a clue:

Please install it manually. (pip install sphinx_rtd_theme)

Or you could try following the directions in the manual.


问:
How to edit row of cell?
I can not turn on editing mode in the first row of the cell. I tried this code but it didn't help.

```<code>   public func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
            if indexPath.row == 1{
                return true
            }
            return false
        }
</code>```

Can someone help me?

答:
Firstly, make sure your have added UITableViewDataSource protocol. Secondly, you may also need the following implementations.

```<code>func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let myAction = UITableViewRowAction(style: .normal, title: "MY_ACTION") { (action, indexPath) in
        print("I'm here")
    }

    return [myAction]
}

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

}
</code>```

Title: How to edit row of cell?

Body:
I can not turn on editing mode in the first row of the cell. I tried this code but it didn't help.

   public func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
            if indexPath.row == 1{
                return true
            }
            return false
        }

Can someone help me?

Body:
Firstly, make sure your have added UITableViewDataSource protocol. Secondly, you may also need the following implementations.

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let myAction = UITableViewRowAction(style: .normal, title: "MY_ACTION") { (action, indexPath) in
        print("I'm here")
    }

    return [myAction]
}

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

}