问:
Check Empty and zero on PHP
I want to add subtract and other function from user data in PHP. At first, I want to check the field is empty or not.When I check empty using empty() function and I submit zero then it shows required that means it is empty.How can I input zero and it add or subtract with my second value?Thank you.My code is here

```<code><html>
<head>

</head>
<body>
<?php
if ($_SERVER['REQUEST_METHOD']=='POST'){
    $num1=$_POST['num1'];
    $num2=$_POST['num2'];
    if (empty($num1 AND $num2)){
        echo "Required";
    }else{
    if ($_POST['submit']=='Add'){
        $num1=$_POST['num1'];
        $num2=$_POST['num2'];
        $add=$num1+$num2;
        echo $add;
    }
    elseif ($_POST['submit']=='Subtract'){
        $subtract=$num1-$num2;
        echo $subtract;
    }
    elseif ($_POST['submit']=='Multiplication'){
        $multiply=$num1*$num2;
        echo $multiply;
    }
    elseif ($_POST['submit']=='Division'){
        $division=$num1/$num2;
        echo $division;
    }

    }
}
?>

<form action="" method="post">
    <input type="number" name="num1">
    <input type="number" name="num2">
    <input type="submit" name="submit" value="Add">
    <input type="submit" name="submit" value="Subtract">
    <input type="submit" name="submit" value="Multiplication">
    <input type="submit" name="submit" value="Division">
</form>

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

答:
change this  line

```<code> if (empty($num1 AND $num2)){}
</code>```

to

```<code>if (isset($num1) && isset($num2)  && $num1>=0 && $num2>=0){}// this will show warning if $num1 or $num2 is not set
</code>```

or

```<code>if (!empty($num1) && !empty($num2)  && $num1>=0 && $num2>=0){}// this will not show warnings
</code>```

empty will consider 0 as empty but if $num1 or $num2 is not set already this will not show any error

Title: Check Empty and zero on PHP

Body:
I want to add subtract and other function from user data in PHP. At first, I want to check the field is empty or not.When I check empty using empty() function and I submit zero then it shows required that means it is empty.How can I input zero and it add or subtract with my second value?Thank you.My code is here

<?php
if ($_SERVER['REQUEST_METHOD']=='POST'){
    $num1=$_POST['num1'];
    $num2=$_POST['num2'];
    if (empty($num1 AND $num2)){
        echo "Required";
    }else{
    if ($_POST['submit']=='Add'){
        $num1=$_POST['num1'];
        $num2=$_POST['num2'];
        $add=$num1+$num2;
        echo $add;
    }
    elseif ($_POST['submit']=='Subtract'){
        $subtract=$num1-$num2;
        echo $subtract;
    }
    elseif ($_POST['submit']=='Multiplication'){
        $multiply=$num1*$num2;
        echo $multiply;
    }
    elseif ($_POST['submit']=='Division'){
        $division=$num1/$num2;
        echo $division;
    }

    }
}
?>

<form action="" method="post">
    <input type="number" name="num1">
    <input type="number" name="num2">
    <input type="submit" name="submit" value="Add">
    <input type="submit" name="submit" value="Subtract">
    <input type="submit" name="submit" value="Multiplication">
    <input type="submit" name="submit" value="Division">
</form>

</html

Body:
change this  line

 if (empty($num1 AND $num2)){}

to

if (isset($num1) && isset($num2)  && $num1>=0 && $num2>=0){}// this will show warning if $num1 or $num2 is not set

or

if (!empty($num1) && !empty($num2)  && $num1>=0 && $num2>=0){}// this will not show warnings

empty will consider 0 as empty but if $num1 or $num2 is not set already this will not show any error


来源: stackexchange

问:
How to convert array to specific array?
This is my array:

```<code>  Array(
[Priority] => 194.49
[Xpresspost] => 147.49
[Expedited] => 48.57
[Regular] => 48.57
</code>```

)

I want to show my array like this:

```<code>'Priority'=> '194.49','Xpresspost'=>'40','Expedited'=> '48.57','Regular'=>'48.57'
</code>```

答:
If you want your array to be printed in a single line like that you could use:</p>

```<code>$array = array(
    'Priority' => 194.49,
    'Xpresspost' => 147.49,
    'Expedited' => 48.57,
    'Regular' => 48.57
);

$output = array();
foreach($array as $key => $value) {
    $output[] = " '$key' => '$value'";
}
echo implode(',', $output);
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to convert array to specific array?

Body:
This is my array:

  Array(
[Priority] => 194.49
[Xpresspost] => 147.49
[Expedited] => 48.57
[Regular] => 48.57

)

I want to show my array like this:

'Priority'=> '194.49','Xpresspost'=>'40','Expedited'=> '48.57','Regular'=>'48.57'

Body:
If you want your array to be printed in a single line like that you could use:

$array = array(
    'Priority' => 194.49,
    'Xpresspost' => 147.49,
    'Expedited' => 48.57,
    'Regular' => 48.57
);

$output = array();
foreach($array as $key => $value) {
    $output[] = " '$key' => '$value'";
}
echo implode(',', $output);


问:
Apache: help converting .htaccess
I'm trying to convert the following .htaccess rewrite rule to the appropriate NGINX format.

```<code># Redirect /signup/PLANNAME or /signup/PLANNAME/ --> /signup/index.php?account_type=PLANNAME
RewriteEngine on
RewriteRule ^signup/([A-Za-z]+)/?$ /signup/index.php?account_type=$1 [NC,L]
</code>```

I tried using the following NGINX rule, but it's not working.

```<code>rewrite  ^signup/([A-Za-z]+)/?$ /signup/index.php?account_type=$1  last;
</code>```

Any idea what I'm doing wrong to make this work with NGINX? Looking at the official documentation isn't very helpful since the documentation is not very through.

答:
I found the problem, I was missing the forward slash (/) at the beginning.

Answer:

```<code>rewrite  ^/signup/([A-Za-z]+)/?$ /signup/index.php?account_type=$1  last;
</code>```

ContentLicense: CC BY-SA 2.5

Title: Apache: help converting .htaccess

Body:
I'm trying to convert the following .htaccess rewrite rule to the appropriate NGINX format.

# Redirect /signup/PLANNAME or /signup/PLANNAME/ --> /signup/index.php?account_type=PLANNAME
RewriteEngine on
RewriteRule ^signup/([A-Za-z]+)/?$ /signup/index.php?account_type=$1 [NC,L]

I tried using the following NGINX rule, but it's not working.

rewrite  ^signup/([A-Za-z]+)/?$ /signup/index.php?account_type=$1  last;

Any idea what I'm doing wrong to make this work with NGINX? Looking at the official documentation isn't very helpful since the documentation is not very through.

Body:
I found the problem, I was missing the forward slash (/) at the beginning.

Answer:

rewrite  ^/signup/([A-Za-z]+)/?$ /signup/index.php?account_type=$1  last;


问:
Android custom ProgressBar is distorted or doubled
I just stumbled into a problem with creating custom progress bar that i do not understand. I use the common method to create the animation-list then apply it to the progressbar:

```<code><?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"  android:oneshot="false">

    <item
        android:drawable="@drawable/dw_pb_1"
        android:duration="100"/>
    <item
        android:drawable="@drawable/dw_pb_2"
        android:duration="100"/>
    <item
        android:drawable="@drawable/dw_pb_3"
        android:duration="100"/>

</animation-list>
</code>```

And I apply it to a progressbar:

```<code> <ProgressBar
            android:id="@+id/progressBar1"
            android:layout_width="150"
            android:layout_height="150"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="10dp"
            android:indeterminate="true"
            android:indeterminateDrawable="@drawable/dw_loader" />
</code>```

But the result is the following:

It draws the drawable again next to the original progressbar. If I use wrap_content to width and height of the progressbar this is what i get:

****SOLUTION?: I cannot imagine why but if I set the drawable programmatically it works...

答:
This issue no longer occurs since the Android version 6.0 (Marshmallow API Level 23).
For prior versions support, the solution provided by @wrecker still working.</p>

Body:
I just stumbled into a problem with creating custom progress bar that i do not understand. I use the common method to create the animation-list then apply it to the progressbar:

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"  android:oneshot="false">

    <item
        android:drawable="@drawable/dw_pb_1"
        android:duration="100"/>
    <item
        android:drawable="@drawable/dw_pb_2"
        android:duration="100"/>
    <item
        android:drawable="@drawable/dw_pb_3"
        android:duration="100"/>

</animation-list>

And I apply it to a progressbar:

 <ProgressBar
            android:id="@+id/progressBar1"
            android:layout_width="150"
            android:layout_height="150"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="10dp"
            android:indeterminate="true"
            android:indeterminateDrawable="@drawable/dw_loader" />

But the result is the following:

It draws the drawable again next to the original progressbar. If I use wrap_content to width and height of the progressbar this is what i get:

****SOLUTION?: I cannot imagine why but if I set the drawable programmatically it works...


问:
Creating a File out of an XMLHttpRequest object response
First off, please allow me to apologise if none of what I'm about to say makes any sense. I'm well out of my comfort zone here and don't really know what I'm doing. With that said...

I'm using the Google Drive File Picker library to allow users to upload their CV from their Google Drive.

```<code>function downloadGDriveFile(file) {
    if (file.downloadUrl) {
        var accessToken = gapi.auth.getToken().access_token;
        var xhr = new XMLHttpRequest();
        xhr.open('GET', file.downloadUrl);
        xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
        xhr.onload = function () {
            var content = xhr.response;
            console.log(xhr);

            form_element = document.getElementById("new_guest_application");
            form_data = new FormData(form_element);
            new_file = new File([content], file.title, {type: file.mimeType});
            form_data.append('guest_application[curriculum_vitae]', new_file);
            console.log(new_file);

            var request = new XMLHttpRequest();
            request.open("POST", form_element.action);
            request.send(form_data);

        };
        xhr.onerror = function () {
            alert('Download failure.');
        };
        xhr.send();
    }
    else {
        alert('Unable to download file.');
    }
}
</code>```

Using the code above, I'm accepting the selected file object and using it, along with the relevant header token, to download the content of the file. This appears to be working as intended.

My issue then comes when trying to turn said content into a File for attaching to a form and submitting to my server.

The code above works, in so far as a file is accepted by the server and uploaded accordingly, but said file is corrupted. I'd imagine this is because I'm doing something wrong with the file = new File([content], file.title, {type: file.mimeType}); line, but I'm so far outside my comfort zone, that I don't even know where to begin.

(I don't do much JavaScript as a rule, and have only managed to get this far with a healthy dose of copy/paste trial and error)

Can someone help me out? thanks.

答:
xhr.response will return some data formatted depending on the data type defined in xhr.responseType.
If you a carrying binary data, and responseType is set to a text type, your data will be corrupted.

You can try to override xhr.responseType just before reading the response

```<code>xhr.responseType = "arraybuffer";
var content = xhr.response;
</code>```

Body:
First off, please allow me to apologise if none of what I'm about to say makes any sense. I'm well out of my comfort zone here and don't really know what I'm doing. With that said...

I'm using the Google Drive File Picker library to allow users to upload their CV from their Google Drive.

function downloadGDriveFile(file) {
    if (file.downloadUrl) {
        var accessToken = gapi.auth.getToken().access_token;
        var xhr = new XMLHttpRequest();
        xhr.open('GET', file.downloadUrl);
        xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
        xhr.onload = function () {
            var content = xhr.response;
            console.log(xhr);

            form_element = document.getElementById("new_guest_application");
            form_data = new FormData(form_element);
            new_file = new File([content], file.title, {type: file.mimeType});
            form_data.append('guest_application[curriculum_vitae]', new_file);
            console.log(new_file);

            var request = new XMLHttpRequest();
            request.open("POST", form_element.action);
            request.send(form_data);

        };
        xhr.onerror = function () {
            alert('Download failure.');
        };
        xhr.send();
    }
    else {
        alert('Unable to download file.');
    }
}

Using the code above, I'm accepting the selected file object and using it, along with the relevant header token, to download the content of the file. This appears to be working as intended.

My issue then comes when trying to turn said content into a File for attaching to a form and submitting to my server.

The code above works, in so far as a file is accepted by the server and uploaded accordingly, but said file is corrupted. I'd imagine this is because I'm doing something wrong with the file = new File([content], file.title, {type: file.mimeType}); line, but I'm so far outside my comfort zone, that I don't even know where to begin.

(I don't do much JavaScript as a rule, and have only managed to get this far with a healthy dose of copy/paste trial and error)

Can someone help me out? thanks.

Body:
xhr.response will return some data formatted depending on the data type defined in xhr.responseType.
If you a carrying binary data, and responseType is set to a text type, your data will be corrupted.

You can try to override xhr.responseType just before reading the response

xhr.responseType = "arraybuffer";
var content = xhr.response;


问:
instance Of Operator in java
```<code>class A {}

class B {}

public class Demo {

    public static void main(String[] args) {

        A a = new A();
        System.out.println(a instanceof B);
    }

}
</code>```

This code is giving compile time error.
How can I use instanceof to give false instead of compile time error when object is not an instance of class specified.

答:
Quoting JLS Sec 15.20.2:

If a cast (§15.16) of the RelationalExpression to the ReferenceType would be rejected as a compile-time error, then the instanceof relational expression likewise produces a compile-time error. In such a situation, the result of the instanceof expression could never be true.

(Where they are describing RelationalExpression instanceof ReferenceType)

You can't write B b = (B) a; either, because A and B are both classes (*), and are unrelated, in the sense that A does not directly or indirectly extend B, nor vice versa.

As such, a reference to an A can never contain an instance of a B, so it is nonsensical to test this. As such, the compiler stops you from testing this, as it likely indicates a logical error.

(*) You could write a instanceof B if B were an interface, because a might refer to a subclass of A which additionally implements B, e.g.

```<code>class ChildOfA extends A implements B {}
A a = new ChildOfA();
System.out.println(a instanceof B); // fine.
</code>```

Title: instance Of Operator in java

Body:
class A {}

class B {}

public class Demo {

    public static void main(String[] args) {

        A a = new A();
        System.out.println(a instanceof B);
    }

}

This code is giving compile time error.
How can I use instanceof to give false instead of compile time error when object is not an instance of class specified.

Body:
Quoting JLS Sec 15.20.2:

If a cast (§15.16) of the RelationalExpression to the ReferenceType would be rejected as a compile-time error, then the instanceof relational expression likewise produces a compile-time error. In such a situation, the result of the instanceof expression could never be true.

(Where they are describing RelationalExpression instanceof ReferenceType)

You can't write B b = (B) a; either, because A and B are both classes (*), and are unrelated, in the sense that A does not directly or indirectly extend B, nor vice versa.

As such, a reference to an A can never contain an instance of a B, so it is nonsensical to test this. As such, the compiler stops you from testing this, as it likely indicates a logical error.

(*) You could write a instanceof B if B were an interface, because a might refer to a subclass of A which additionally implements B, e.g.

class ChildOfA extends A implements B {}
A a = new ChildOfA();
System.out.println(a instanceof B); // fine.


问:
Mysql select only child from a table tree
I have a table name tbl_section this table is like that

```<code>db_secid   db_secname   db_secdesc    db_parent
1          Electrical                 NULL
2          Mechanical                 NULL
3          Plumbing                   NULL
4          Cables                      1
5          Lamps                       1
6          HDMI                        4
</code>```

I want to select only the children of a row with db_parent=NULL. From the table above the result will be only Cables and Lamps.

I try with this query

```<code>select
s1.db_secname
from tbl_section as s1
LEFT JOIN tbl_section as s2
ON
s1.db_secid=s2.db_parent
WHERE s2.db_parent IS NULL
</code>```

But this query give me a result I don't want this the result I have from this query

```<code>Mechanical,Plumbing,Lamps,HDMI
</code>```

How can i solve this problem and have only the children who have a parent with db_parent = NULL?

答:
Simply perform a JOIN, this will already filter out rows that have no parent. Furthermore you also swapped you parent-child relation: it should be s1.db_parent = s2.db_secid, not s1.db_secid=s2.db_parent:

```<code>SELECT s1.db_secname
FROM tbl_section AS s1
     <b>JOIN</b> tbl_section AS s2 ON <b>s1.db_parent = s2.db_secid</b>
WHERE s2.db_parent IS NULL</code>```

Body:
I have a table name tbl_section this table is like that

db_secid   db_secname   db_secdesc    db_parent
1          Electrical                 NULL
2          Mechanical                 NULL
3          Plumbing                   NULL
4          Cables                      1
5          Lamps                       1
6          HDMI                        4

I want to select only the children of a row with db_parent=NULL. From the table above the result will be only Cables and Lamps.

I try with this query

select
s1.db_secname
from tbl_section as s1
LEFT JOIN tbl_section as s2
ON
s1.db_secid=s2.db_parent
WHERE s2.db_parent IS NULL

But this query give me a result I don't want this the result I have from this query

Mechanical,Plumbing,Lamps,HDMI

How can i solve this problem and have only the children who have a parent with db_parent = NULL?

Body:
Simply perform a JOIN, this will already filter out rows that have no parent. Furthermore you also swapped you parent-child relation: it should be s1.db_parent = s2.db_secid, not s1.db_secid=s2.db_parent:

SELECT s1.db_secname
FROM tbl_section AS s1
     JOIN tbl_section AS s2 ON s1.db_parent = s2.db_secid
WHERE s2.db_parent IS NULL


问:
Transition from RecyclerView looks bad
When animating transitions between fragments I have found that animating from a fragment with RecyclerView the view tends to break.

Look carefully at the gif as it moves from second (middle) fragment to first and third. See how part of the CardViewis removed.

Is there some way I can make the transition smoother? I read something on databinding in RecyclerView.Adapter for immediate binding of data, but I don't know if that will help this particular case since it is transitioning from the RecyclerView fragment that is faulty.

MainActivity xml:

```<code><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<include
    android:id="@+id/toolbar"
    layout="@layout/toolbar"/>

<FrameLayout
    android:id="@+id/mainFragment"
    android:layout_below="@id/toolbar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>
</code>```

TasksFragment xml:

```<code><FrameLayout>
    <android.support.v7.widget.RecyclerView />
</FrameLayout>
</code>```

TasksAdapter:

```<code>public class TasksAdapter extends
    RecyclerView.Adapter<TasksAdapter.ViewHolder> {

static class ViewHolder extends RecyclerView.ViewHolder {
    TextView titleTextView;
    TextView subTitle;
    Button messageButton;
    ImageView taskImage;
    TextView taskDescription;
    CardView cv;

    ViewHolder(View itemView) {
        super(itemView);
        cv = (CardView) itemView.findViewById(R.id.cv);
        titleTextView = (TextView) itemView.findViewById(R.id.task_title);
        subTitle = (TextView) itemView.findViewById(R.id.task_subtitle);
        messageButton = (Button) itemView.findViewById(R.id.message_button);
        taskImage = (ImageView) itemView.findViewById(R.id.task_image);
        taskDescription = (TextView) itemView.findViewById(R.id.task_description);
    }
}

private List<Task> mTasks;
// Store the context for easy access
private Context mContext;
private Fragment fragment;

public TasksAdapter(Context context, List<Task> tasks) {
    mTasks = tasks;
    mContext = context;

}

private Context getContext() {
    return mContext;
}

@Override
public TasksAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    Context context = parent.getContext();
    LayoutInflater inflater = LayoutInflater.from(context);

    // Inflate the custom layout
    View taskView = inflater.inflate(R.layout.tasks_item, parent, false);

    // Return a new holder instance
    ViewHolder viewHolder = new ViewHolder(taskView);
    return viewHolder;
}

@Override
public void onBindViewHolder(final TasksAdapter.ViewHolder viewHolder, final int position) {
    // Get the data model based on position
    Task task = mTasks.get(position);

    // Set item views based on views and data model
    TextView textView = viewHolder.titleTextView;
    textView.setText(task.getTitle());
    TextView subTitleTextView = viewHolder.subTitle;
    subTitleTextView.setText(task.getSubTitle());
    ImageView imageView = viewHolder.taskImage;
    imageView.setImageResource(task.getImage());
    TextView taskDescriptionTextView = viewHolder.taskDescription;
    taskDescriptionTextView.setText(task.getDescription());
    Button button = viewHolder.messageButton;
    button.setText(task.getAction());
}
</code>```

答:
Solved it by adding setting android:layout_heightto fill_parent in MainActivity's FrameLayout.

Like this:

```<code><FrameLayout
    android:id="@+id/mainFragment"
    android:layout_below="@id/toolbar"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"/>
</code>```

Title: Transition from RecyclerView looks bad

Body:
When animating transitions between fragments I have found that animating from a fragment with RecyclerView the view tends to break.

Look carefully at the gif as it moves from second (middle) fragment to first and third. See how part of the CardViewis removed.

Is there some way I can make the transition smoother? I read something on databinding in RecyclerView.Adapter for immediate binding of data, but I don't know if that will help this particular case since it is transitioning from the RecyclerView fragment that is faulty.

MainActivity xml:

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<include
    android:id="@+id/toolbar"
    layout="@layout/toolbar"/>

<FrameLayout
    android:id="@+id/mainFragment"
    android:layout_below="@id/toolbar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

TasksFragment xml:

<FrameLayout>
    <android.support.v7.widget.RecyclerView />
</FrameLayout>

TasksAdapter:

public class TasksAdapter extends
    RecyclerView.Adapter<TasksAdapter.ViewHolder> {

static class ViewHolder extends RecyclerView.ViewHolder {
    TextView titleTextView;
    TextView subTitle;
    Button messageButton;
    ImageView taskImage;
    TextView taskDescription;
    CardView cv;

    ViewHolder(View itemView) {
        super(itemView);
        cv = (CardView) itemView.findViewById(R.id.cv);
        titleTextView = (TextView) itemView.findViewById(R.id.task_title);
        subTitle = (TextView) itemView.findViewById(R.id.task_subtitle);
        messageButton = (Button) itemView.findViewById(R.id.message_button);
        taskImage = (ImageView) itemView.findViewById(R.id.task_image);
        taskDescription = (TextView) itemView.findViewById(R.id.task_description);
    }
}

private List<Task> mTasks;
// Store the context for easy access
private Context mContext;
private Fragment fragment;

public TasksAdapter(Context context, List<Task> tasks) {
    mTasks = tasks;
    mContext = context;

}

private Context getContext() {
    return mContext;
}

@Override
public TasksAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    Context context = parent.getContext();
    LayoutInflater inflater = LayoutInflater.from(context);

    // Inflate the custom layout
    View taskView = inflater.inflate(R.layout.tasks_item, parent, false);

    // Return a new holder instance
    ViewHolder viewHolder = new ViewHolder(taskView);
    return viewHolder;
}

@Override
public void onBindViewHolder(final TasksAdapter.ViewHolder viewHolder, final int position) {
    // Get the data model based on position
    Task task = mTasks.get(position);

    // Set item views based on views and data model
    TextView textView = viewHolder.titleTextView;
    textView.setText(task.getTitle());
    TextView subTitleTextView = viewHolder.subTitle;
    subTitleTextView.setText(task.getSubTitle());
    ImageView imageView = viewHolder.taskImage;
    imageView.setImageResource(task.getImage());
    TextView taskDescriptionTextView = viewHolder.taskDescription;
    taskDescriptionTextView.setText(task.getDescription());
    Button button = viewHolder.messageButton;
    button.setText(task.getAction());
}

Body:
Solved it by adding setting android:layout_heightto fill_parent in MainActivity's FrameLayout.

Like this:

<FrameLayout
    android:id="@+id/mainFragment"
    android:layout_below="@id/toolbar"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"/>


问:
"general" variable in oracle apex
I'm developing an application in Oracle Application Express (APEX).

First page contains list of projects as a tabular report.

Clicking any of the rows forwards to the next page, where records can be edited. I've implemented it with following settings:

Link column: link to custom target

Target: Page in this application

Until this is fine.

My problem is how to pass actual report to the next page?

My table, which is the basis of the report has primary key (ID), and also owner & title combination is unique. Currently ID column is not included in the report.

Also the second page doesn't currently contain field showing ID, as this information isn't important to the users.

I know I could set ID column in report, and create a read only (even hidden) text box in the next page, however I'm looking for a more elegant solution. What is the standard way to solve this?

答:
I wonder if you are asking: "How do I pass a value from page 1 to page 2 so page 2 can use the value to do a query and present the results. If so, here is how it's done.

On page P1, the report, for example, select the attributes for the report region under the region in the Rendering pane on the left of the page designed.

Under Attribute Properties on the right side, look for Link Column and set it to "Link to custom target". Then click Target.

Select the page and then in the Set Items section, on the left, under name, select the PK ID field to receive the passed value ex: P2_ID. On the right under Value select the field to pass the value, ex: #P1_ID# and click ok.
Now, when the link on page 1 report is clicked, the P1_ID is saved into Session state by Apex and passed to P2 which then performs a FETCH using the passed value.
You can read more about Session State here. Also, be aware there are security settings which affect what params can and can't be passed in the URL.
Clicking "Session" in the developer toolbar will enable you to see the session variables being passed.

If you mean "How do I store values in the app that can be accessed anywhere in the app - like a global variable" Then look at Application Items.

As always, please include version numbers in these posts.

Title: "general" variable in oracle apex


问:
How to start svg animation only when the div is in view port
I want to start an svg animation only when it is visible in the viewport. Because my svg container is at the bottom. I tried using some methods which can be seen below. Kindly sho me how to fix it.

function isElementInViewport(elem) {
 var $elem = $(elem);
 // Get the scroll position of the page.
 var scrollElem = ((navigator.userAgent.toLowerCase().indexOf('webkit') != -1) ? 'body' : 'html');
 var viewportTop = $(scrollElem).scrollTop();
 var viewportBottom = viewportTop + $(window).height();

 // Get the position of the element on the page.
 var elemTop = Math.round( $elem.offset().top );
 var elemBottom = elemTop + $elem.height();

 return ((elemTop < viewportBottom) && (elemBottom > viewportTop));
}
function checkAnimation() {
 var $elem = $('#ourprocessFlowchartContainer');
 var animationTosquare =$("#contract_anim").get(0);
 console.log(isElementInViewport($elem));
 if (isElementInViewport($elem)==true) {
  // Start the animation
  animationTosquare.beginElement();
 } else{
  animationTosquare.endElement();
 }
}

$(document).ready(function(){

$(window).scroll(function(){
  checkAnimation();
 });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background-color: #555;
}</code>```

  <svg id="processFlowchart" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg" viewBox = '0 0 740 300'>

  </svg>

```

Please help me to get rid of this. This code will make my animation jerk as i visit my div container containing svg.

答:
Your problem is that you are re-triggering the animation every time checkAnimation() is called. I've added a flag to make sure this doesn't happen. Works here:

https://jsfiddle.net/FrancisMacDougall/bfngjsg0/

```<code>var waiting = true;
function checkAnimation() {
  var $elem = $('#ourprocessFlowchartContainer');
  var animationTosquare =$("#contract_anim").get(0);
  console.log(isElementInViewport($elem));
  if (isElementInViewport($elem)==true) {
    // Start the animation
    if(waiting) {
      animationTosquare.beginElement();
      waiting = false;
    }
  } else {
    if(!waiting) {
      animationTosquare.endElement();
      waiting = true;
    }
  }
}

$(document).ready(function(){
checkAnimation();
$(window).scroll(function(){
    checkAnimation();
  });
});
</code>```

Body:
I want to start an svg animation only when it is visible in the viewport. Because my svg container is at the bottom. I tried using some methods which can be seen below. Kindly sho me how to fix it.

function isElementInViewport(elem) {
 var $elem = $(elem);
 // Get the scroll position of the page.
 var scrollElem = ((navigator.userAgent.toLowerCase().indexOf('webkit') != -1) ? 'body' : 'html');
 var viewportTop = $(scrollElem).scrollTop();
 var viewportBottom = viewportTop + $(window).height();

 // Get the position of the element on the page.
 var elemTop = Math.round( $elem.offset().top );
 var elemBottom = elemTop + $elem.height();

 return ((elemTop < viewportBottom) && (elemBottom > viewportTop));
}
function checkAnimation() {
 var $elem = $('#ourprocessFlowchartContainer');
 var animationTosquare =$("#contract_anim").get(0);
 console.log(isElementInViewport($elem));
 if (isElementInViewport($elem)==true) {
  // Start the animation
  animationTosquare.beginElement();
 } else{
  animationTosquare.endElement();
 }
}

$(document).ready(function(){

$(window).scroll(function(){
  checkAnimation();
 });
});

body {
  background-color: #555;
}

  <svg id="processFlowchart" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg" viewBox = '0 0 740 300'>

  </svg>

Please help me to get rid of this. This code will make my animation jerk as i visit my div container containing svg.

Body:
Your problem is that you are re-triggering the animation every time checkAnimation() is called. I've added a flag to make sure this doesn't happen. Works here:

https://jsfiddle.net/FrancisMacDougall/bfngjsg0/

var waiting = true;
function checkAnimation() {
  var $elem = $('#ourprocessFlowchartContainer');
  var animationTosquare =$("#contract_anim").get(0);
  console.log(isElementInViewport($elem));
  if (isElementInViewport($elem)==true) {
    // Start the animation
    if(waiting) {
      animationTosquare.beginElement();
      waiting = false;
    }
  } else {
    if(!waiting) {
      animationTosquare.endElement();
      waiting = true;
    }
  }
}

$(document).ready(function(){
checkAnimation();
$(window).scroll(function(){
    checkAnimation();
  });
});


问:
Kotlin Error : Could not find org.jetbrains.kotlin:kotlin-stdlib-jre7:1.0.7
I installed the Kotlin plugin into my app (v. v1.1.1-release-Studio2.2-1) and then selected "Configure Kotlin in Project"   I selected compiler and runtime version of 1.0.7. Kotlin updated my Gradle files. Now when I try to build in I get:

Error: A problem occurred configuring project ':app'.
Could not resolve all dependencies for configuration ':app:_debugApkCopy'.
Could not find org.jetbrains.kotlin:kotlin-stdlib-jre7:1.0.7.
Required by:

MyApplication:app:unspecified

I'm not sure what I'm missing here.

答:
In "build.gradle" file, change current Kotlin version that line and press synk:

```<code>ext.kotlin_version = '1.1.1'
</code>```

/// That will look like:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

```<code>buildscript {
    ext.kotlin_version = '1.1.1'
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
</code>```

Body:
In "build.gradle" file, change current Kotlin version that line and press synk:

ext.kotlin_version = '1.1.1'

/// That will look like:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.1.1'
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}


问:
How to apply multiple textures on one model in aframe
a have a model in maya/blender, which has multiple UV's.

I thought that the .mtl has all the info about materials/textures ( as i can see the links in the .mtl ), but apperently i have to link every texture to an object @ src="texture.jpg".

Is there any other way than combining those textures in photoshop/gimp, or breaking my model into separate .obj's having their own texture ?

Should i look more into the custom shading options in aframe/three.js @ registerShader ?

答:
The OBJ/MTL format does not support multiple UV sets. It may not support multiple materials on the same geometry either, I'm not sure. FBX and Collada do support multiple UVs, so you could try one of those.

But, searching for "threejs multiple UVs" shows that it is not easy to do multiple UVs without custom shaders, even once you have a newer model format. I would maybe try to bake your multiple UVs down into a single set in the modeling software, if that's possible.


问:
Wordpress theme options page query_posts
I am busy building a small theme options page for one of clients and need some help with an issue.

currently i have the option to manually put in IDS of wordpress pages to extract the data with query_posts

based on the theme options is creates a variable called $euro_box_1_vehicles;

my options are filled in as 32,39,43,54 in the input, and when I print this statement with echo, I get the same result.

When I just replace array(32,39,43,45) with array($euro_box_1_vehicles) it only returns one result.

```<code><?php
    $vehicle1 = array(
        'post__in' => array(32,39,43,45),
        'post_type' => 'page',
    );

    query_posts( $vehicle1 );
    while (have_posts()) : the_post();
?>
</code>```

答:
When I echo var_dump = string(11) "32,39,43,45"

In which case, you need to explode $vehicle1, since post__in expects an array;

```<code>query_posts(array(
    'post_type' => 'page',
    'post__in' => @explode(',', $vehicle1)
));
</code>```

Body:
I am busy building a small theme options page for one of clients and need some help with an issue.

currently i have the option to manually put in IDS of wordpress pages to extract the data with query_posts

based on the theme options is creates a variable called $euro_box_1_vehicles;

my options are filled in as 32,39,43,54 in the input, and when I print this statement with echo, I get the same result.

When I just replace array(32,39,43,45) with array($euro_box_1_vehicles) it only returns one result.

<?php
    $vehicle1 = array(
        'post__in' => array(32,39,43,45),
        'post_type' => 'page',
    );

    query_posts( $vehicle1 );
    while (have_posts()) : the_post();
?>

Body:
When I echo var_dump = string(11) "32,39,43,45"

In which case, you need to explode $vehicle1, since post__in expects an array;

query_posts(array(
    'post_type' => 'page',
    'post__in' => @explode(',', $vehicle1)
));


问:
How to learn Drools well?
I am student and new to learn Drools. I am confused about how to learn the Drools. I know nothing about this area but my professor let me learn this things and make an expert system.

I have installed the drools workbench -- kie-drools-wb-distribution-wars-6.4.0.Final-tomcat7 this version. But I don't know how to learn it well.  That means next step and next next step. What I need to do? Would you tell me? Thank you very much!

答: There are couple of demo applications available on github, you can refer to them and also there is drools documentation you can refer to.</p>

Title: How to learn Drools well?


问:
form with progress bar
Have the form below with progress bar. Everything is working except of radio buttons. I need to change percent of fiiling form after each form field value filling.

```<code><form accept-charset="UTF-8" action="#" class="pro-form" id="pro-form" method="post">

      <h1>Progress Form</h1>
   <progress max="100" value="0" id="progress" class="bar"> </progress>
    <div class="progress-message" id="progress-message" >progress </div>

           <input type="radio" name="value1" required="required" value="yes">
           <input type="radio" name="value1" required="required" value="no">
          <input id="card_name" required="required" type="text">
          <input id="card_address_1" required="required" type="text">
          <input id="card_zip" maxlength="10"  required="required" type="text">

          <input name="commit" type="submit" value="ok" class="button">

      </form>
</code>```

How to deal with radio buttons? Why JQuery keyup function don't change
progress-message when clicking on them?

```<code> <script>
    $("#pro-form input[required]").keyup(function() {

    var numValid = 0;
    $("#pro-form input[required]").each(function() {
        if (this.validity.valid) {
            numValid++;
        }
    });

    var progress = $("#progress"),
        progressMessage = $("#progress-message");

    if (numValid == 0) {
        progress.attr("value", "0");
        progressMessage.text(" 0%");
    }
    if (numValid == 1) {
        progress.attr("value", "20");
        progressMessage.text(" 20%");
    }
    if (numValid == 2) {
        progress.attr("value", "40");
        progressMessage.text(" 40%");
    }
    if (numValid == 3) {
        progress.attr("value", "60");
        progressMessage.text(" 60%");
    }
    if (numValid == 4) {
        progress.attr("value", "80");
        progressMessage.text(" 80%");
    }
    if (numValid == 5) {
        progress.attr("value", "95");
        progressMessage.text(" 90%");
    }

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

答:
I created a function to contain your update progress bar code, then I assigned the change function properly for the radio buttons.  Comment if you're looking for something else.

$("[name=value1]").change(buildProgress);
$("#pro-form input[required]").keyup(buildProgress);

function buildProgress() {
    var numValid = 0;
    $("#pro-form input[required]").each(function() {
        if (this.validity.valid) {
            numValid++;
        }
    });
    if ($("[name=value1]:checked").length) {
        numValid++;
    }

    var progress = $("#progress"),
        progressMessage = $("#progress-message");

    if (numValid == 0) {
        progress.attr("value", "0");
        progressMessage.text(" 0%");
    }
    if (numValid == 1) {
        progress.attr("value", "20");
        progressMessage.text(" 20%");
    }
    if (numValid == 2) {
        progress.attr("value", "40");
        progressMessage.text(" 40%");
    }
    if (numValid == 3) {
        progress.attr("value", "60");
        progressMessage.text(" 60%");
    }
    if (numValid == 4) {
        progress.attr("value", "80");
        progressMessage.text(" 80%");
    }
    if (numValid == 5) {
        progress.attr("value", "95");
        progressMessage.text(" 90%");
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>input[type=text] {
  border:1px solid black;
}</code>```

<form accept-charset="UTF-8" action="#" class="pro-form" id="pro-form" method="post">

Progress Form

   <progress max="100" value="0" id="progress" class="bar"> </progress>

progress

           <input type="radio" name="value1" required="required" value="yes">
           <input type="radio" name="value1" required="required" value="no">
          <input id="card_name" required="required" type="text">
          <input id="card_address_1" required="required" type="text">
          <input id="card_zip" maxlength="10"  required="required" type="text">

          <input name="commit" type="submit" value="ok" class="button">

      </form>```

Title: form with progress bar

Body:
Have the form below with progress bar. Everything is working except of radio buttons. I need to change percent of fiiling form after each form field value filling.

<form accept-charset="UTF-8" action="#" class="pro-form" id="pro-form" method="post">

Progress Form

   <progress max="100" value="0" id="progress" class="bar"> </progress>

progress

           <input type="radio" name="value1" required="required" value="yes">
           <input type="radio" name="value1" required="required" value="no">
          <input id="card_name" required="required" type="text">
          <input id="card_address_1" required="required" type="text">
          <input id="card_zip" maxlength="10"  required="required" type="text">

          <input name="commit" type="submit" value="ok" class="button">

      </form>

How to deal with radio buttons? Why JQuery keyup function don't change
progress-message when clicking on them?

Body:
I created a function to contain your update progress bar code, then I assigned the change function properly for the radio buttons.  Comment if you're looking for something else.

$("[name=value1]").change(buildProgress);
$("#pro-form input[required]").keyup(buildProgress);

function buildProgress() {
    var numValid = 0;
    $("#pro-form input[required]").each(function() {
        if (this.validity.valid) {
            numValid++;
        }
    });
    if ($("[name=value1]:checked").length) {
        numValid++;
    }

    var progress = $("#progress"),
        progressMessage = $("#progress-message");

    if (numValid == 0) {
        progress.attr("value", "0");
        progressMessage.text(" 0%");
    }
    if (numValid == 1) {
        progress.attr("value", "20");
        progressMessage.text(" 20%");
    }
    if (numValid == 2) {
        progress.attr("value", "40");
        progressMessage.text(" 40%");
    }
    if (numValid == 3) {
        progress.attr("value", "60");
        progressMessage.text(" 60%");
    }
    if (numValid == 4) {
        progress.attr("value", "80");
        progressMessage.text(" 80%");
    }
    if (numValid == 5) {
        progress.attr("value", "95");
        progressMessage.text(" 90%");
    }
}

input[type=text] {
  border:1px solid black;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form accept-charset="UTF-8" action="#" class="pro-form" id="pro-form" method="post">

      <h1>Progress Form</h1>
   <progress max="100" value="0" id="progress" class="bar"> </progress>
    <div class="progress-message" id="progress-message" >progress </div>

           <input type="radio" name="value1" required="required" value="yes">
           <input type="radio" name="value1" required="required" value="no">
          <input id="card_name" required="required" type="text">
          <input id="card_address_1" required="required" type="text">
          <input id="card_zip" maxlength="10"  required="required" type="text">

          <input name="commit" type="submit" value="ok" class="button">

      </form>


问:
Cannot read property 'handleClick' of undefined when using map
I am trying to make a table row function like a Link with react-router.

I keep getting the error Cannot read property 'handleClick' of undefined

```<code>handleClick(user) {
   this.router.transitionTo('index', user);
}

render(){
   var userNodes = this.props.posts.map(function(user, i){
       return (
         <tr onClick={() => this.handleClick(user)}>
           <Td>{user.postId}</Td>
           <Td>{user.title}</Td>
           <Td>{user.body}</Td>
         </tr>
       )
   });
...
</code>```

答:
You have to bind it.</p>

```<code>var userNodes = this.props.posts.map(function(user, i){}.bind(this));
</code>```

Body:
I am trying to make a table row function like a Link with react-router.

I keep getting the error Cannot read property 'handleClick' of undefined

handleClick(user) {
   this.router.transitionTo('index', user);
}

render(){
   var userNodes = this.props.posts.map(function(user, i){
       return (

 this.handleClick(user)}>
           {user.postId}
           {user.title}
           {user.body}

       )
   });
...

Body:
You have to bind it.

var userNodes = this.props.posts.map(function(user, i){}.bind(this));


问:
Mediaplayer not opening selected file android (setDataSource failed.: status=0x80000000)
So I have set up the following code to pick a song from internal memory and play it.

```<code>Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
                            startActivityForResult(intent, 10);
</code>```

My onActivityResult:

```<code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if(resultCode == RESULT_OK){
        Uri uriSound = data.getData();

        play(this, uriSound);
    }
}
</code>```

and finally my play method:
     private void play(Context context, Uri uri) {

```<code>    MediaPlayer mip = new MediaPlayer();
    try {

        mip.setDataSource(context, uri);
        mip.prepare();
        mip.start();
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
</code>```

}

but when I run this I keep getting the following error:

```<code>java.io.IOException: setDataSource failed.: status=0x80000000
</code>```

I couldnt find a working solution anywhere.
Any ideas?

答: Granting permission in the manifest file to read external storage fixed it!</p>

Body:
So I have set up the following code to pick a song from internal memory and play it.

Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
                            startActivityForResult(intent, 10);

My onActivityResult:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if(resultCode == RESULT_OK){
        Uri uriSound = data.getData();

        play(this, uriSound);
    }
}

and finally my play method:
     private void play(Context context, Uri uri) {

    MediaPlayer mip = new MediaPlayer();
    try {

        mip.setDataSource(context, uri);
        mip.prepare();
        mip.start();
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}

but when I run this I keep getting the following error:

java.io.IOException: setDataSource failed.: status=0x80000000

I couldnt find a working solution anywhere.
Any ideas?


问:
Create banner, dynamically using all images in directory
I am currently working on some code to try and make an ad banner they rotates through all the images in my banner folder. I know I can make a banner which rotates if I state every image in the Array, but what I am wanting to do is create a banner that uses all the images inside the folder so I do not have to go back and recode every time a new image is uploaded to the banner folder. The banner images do not need to have a url assigned as they are only for display at this stage. I am trying to get the banner to display inside this div:

```<code><div id="banner" name="RotateBanner"><img src="Images/banner/1.jpg" /></div>
</code>```

Can anyone please provide me with a way for me to do this? Is this even possible?

答:
It's unclear if you just want to return all images in a directory, or if you want to select a specific one (such as the latest one uploaded).

The first thing you should do is to look at scandir() (Docs) and use that function to list all files in your directory and then select the one you're interested in. Notice that scandir() have a $sorting_order parameter where you can define to return the files alphabetically in ascending or descending order.

If you want to select the one that was latest uploaded, you could use the solution found here (PHP: Get the Latest File Addition in a Directory).

```<code>$lastMod = 0;
$lastModFile = null;
// Loop through all entries/files in the directory of the path.
foreach (scandir('path/to/directory/') as $entry) {
    // If the entry is a file, and the time updated is later than previous file.
    if (is_file($dir.$entry) && filectime($dir.$entry) > $lastMod) {
        // ... if it is, then set the current file as the latest file.
        $lastMod = filectime($dir.$entry);
        $lastModFile = $entry;
    }
}
</code>```

Body:
I am currently working on some code to try and make an ad banner they rotates through all the images in my banner folder. I know I can make a banner which rotates if I state every image in the Array, but what I am wanting to do is create a banner that uses all the images inside the folder so I do not have to go back and recode every time a new image is uploaded to the banner folder. The banner images do not need to have a url assigned as they are only for display at this stage. I am trying to get the banner to display inside this div:

Can anyone please provide me with a way for me to do this? Is this even possible?

Body:
It's unclear if you just want to return all images in a directory, or if you want to select a specific one (such as the latest one uploaded).

The first thing you should do is to look at scandir() (Docs) and use that function to list all files in your directory and then select the one you're interested in. Notice that scandir() have a $sorting_order parameter where you can define to return the files alphabetically in ascending or descending order.

If you want to select the one that was latest uploaded, you could use the solution found here (PHP: Get the Latest File Addition in a Directory).

$lastMod = 0;
$lastModFile = null;
// Loop through all entries/files in the directory of the path.
foreach (scandir('path/to/directory/') as $entry) {
    // If the entry is a file, and the time updated is later than previous file.
    if (is_file($dir.$entry) && filectime($dir.$entry) > $lastMod) {
        // ... if it is, then set the current file as the latest file.
        $lastMod = filectime($dir.$entry);
        $lastModFile = $entry;
    }
}


问:
Diagnosing RangeError: Maximum call stack size exceeded in React KeyEscapeUtils
Background

Our webapp is written with React and Redux using the official react-redux bindings. Another primary library used in this web app is PaperJS. We recently transitioned this to being a Redux app, though it has used React for a while.

The Problem

Refreshing sometimes (usually every other refresh) causes a

```<code>RangeError: Maximum call stack size exceeded
at String.replace (<anonymous>)
at Object.unescape (KeyEscapeUtils.js:49)
at flattenSingleChildIntoContext (flattenChildren.js:32)
at flattenChildren.js:53
at traverseAllChildrenImpl (traverseAllChildren.js:69)
at traverseAllChildrenImpl (traverseAllChildren.js:85)
at traverseAllChildren (traverseAllChildren.js:157)
at flattenChildren (flattenChildren.js:52)
at ReactDOMComponent._reconcilerUpdateChildren (ReactMultiChild.js:209)
at ReactDOMComponent._updateChildren (ReactMultiChild.js:315)
</code>```

Here's the React source code where it's failing:

```<code>return ('' + keySubstring).replace(unescapeRegex, function (match) {
  return unescaperLookup[match];
});
</code>```

and in context:

```<code>/**
 * Unescape and unwrap key for human-readable display
 *
 * @param {string} key to unescape.
 * @return {string} the unescaped key.
 */
function unescape(key) {
  var unescapeRegex = /(=0|=2)/g;
  var unescaperLookup = {
    '=0': '=',
    '=2': ':'
  };
  var keySubstring = key[0] === '.' && key[1] === '$' ? key.substring(2) : key.substring(1);

  return ('' + keySubstring).replace(unescapeRegex, function (match) {
    return unescaperLookup[match];
  });
}
</code>```

This is probably indicative that somewhere I'm misusing React in my code, but since the stacktrace does not include references to any of my own code, I'm not sure what to look for. It seems to be an infinite loop of re-rendering, and I'm suspicious that it might be due to an improperly placed call to setState.

The Question

Is my suspicion likely? How can I further diagnose this issue, given that my own codebase is fairly extensive? What does it mean that this failed in KeyEscapeUtils?

答:
I searched for unescape through the source code of React (version 15.4) and have found only one place where it is used. The file is react/lib/flattenChildren.js:

```<code>function flattenSingleChildIntoContext(traverseContext, child, name, selfDebugID) {
  // We found a component instance.
  if (traverseContext && typeof traverseContext === 'object') {
    var result = traverseContext;
    var keyUnique = result[name] === undefined;
    if (process.env.NODE_ENV !== 'production') {
      if (!ReactComponentTreeHook) {
        ReactComponentTreeHook = require('./ReactComponentTreeHook');
      }
      if (!keyUnique) {
        process.env.NODE_ENV !== 'production' ? warning(false, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.%s', KeyEscapeUtils.unescape(name), ReactComponentTreeHook.getStackAddendumByID(selfDebugID)) : void 0;
      }
    }
    if (keyUnique && child != null) {
      result[name] = child;
    }
  }
}
</code>```

It is in the flattenSingleChildIntoContext - exactly how it is shown in your stack trace. The line with the problem tries to show a warning:

```<code>process.env.NODE_ENV !== 'production' ? warning(false, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.%s', KeyEscapeUtils.unescape(name), ReactComponentTreeHook.getStackAddendumByID(selfDebugID)) : void 0;
</code>```

It means that the maximum call stack error occurs only in development mode. And the problem is that you are rendering somewhere two or more elements with the same key. To know what key is that you can use breakpoint in this line in Chrome Dev Tools. Or you can add console.log there and throw exception so that it stops execution right there:

```<code>  if (!keyUnique) {
    console.log('key is not unique', name);
    throw new Error('Key is not unique');
  }
</code>```

If you'll get the key this way you'll be able to find the place where you have elements with duplicate key.

Body:
Background

Our webapp is written with React and Redux using the official react-redux bindings. Another primary library used in this web app is PaperJS. We recently transitioned this to being a Redux app, though it has used React for a while.

The Problem

Refreshing sometimes (usually every other refresh) causes a

RangeError: Maximum call stack size exceeded
at String.replace (<anonymous>)
at Object.unescape (KeyEscapeUtils.js:49)
at flattenSingleChildIntoContext (flattenChildren.js:32)
at flattenChildren.js:53
at traverseAllChildrenImpl (traverseAllChildren.js:69)
at traverseAllChildrenImpl (traverseAllChildren.js:85)
at traverseAllChildren (traverseAllChildren.js:157)
at flattenChildren (flattenChildren.js:52)
at ReactDOMComponent._reconcilerUpdateChildren (ReactMultiChild.js:209)
at ReactDOMComponent._updateChildren (ReactMultiChild.js:315)

Here's the React source code where it's failing:

return ('' + keySubstring).replace(unescapeRegex, function (match) {
  return unescaperLookup[match];
});

and in context:

/**
 * Unescape and unwrap key for human-readable display
 *
 * @param {string} key to unescape.
 * @return {string} the unescaped key.
 */
function unescape(key) {
  var unescapeRegex = /(=0|=2)/g;
  var unescaperLookup = {
    '=0': '=',
    '=2': ':'
  };
  var keySubstring = key[0] === '.' && key[1] === '$' ? key.substring(2) : key.substring(1);

  return ('' + keySubstring).replace(unescapeRegex, function (match) {
    return unescaperLookup[match];
  });
}

This is probably indicative that somewhere I'm misusing React in my code, but since the stacktrace does not include references to any of my own code, I'm not sure what to look for. It seems to be an infinite loop of re-rendering, and I'm suspicious that it might be due to an improperly placed call to setState.

The Question

Is my suspicion likely? How can I further diagnose this issue, given that my own codebase is fairly extensive? What does it mean that this failed in KeyEscapeUtils?

Body:
I searched for unescape through the source code of React (version 15.4) and have found only one place where it is used. The file is react/lib/flattenChildren.js:

function flattenSingleChildIntoContext(traverseContext, child, name, selfDebugID) {
  // We found a component instance.
  if (traverseContext && typeof traverseContext === 'object') {
    var result = traverseContext;
    var keyUnique = result[name] === undefined;
    if (process.env.NODE_ENV !== 'production') {
      if (!ReactComponentTreeHook) {
        ReactComponentTreeHook = require('./ReactComponentTreeHook');
      }
      if (!keyUnique) {
        process.env.NODE_ENV !== 'production' ? warning(false, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.%s', KeyEscapeUtils.unescape(name), ReactComponentTreeHook.getStackAddendumByID(selfDebugID)) : void 0;
      }
    }
    if (keyUnique && child != null) {
      result[name] = child;
    }
  }
}

It is in the flattenSingleChildIntoContext - exactly how it is shown in your stack trace. The line with the problem tries to show a warning:

process.env.NODE_ENV !== 'production' ? warning(false, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.%s', KeyEscapeUtils.unescape(name), ReactComponentTreeHook.getStackAddendumByID(selfDebugID)) : void 0;

It means that the maximum call stack error occurs only in development mode. And the problem is that you are rendering somewhere two or more elements with the same key. To know what key is that you can use breakpoint in this line in Chrome Dev Tools. Or you can add console.log there and throw exception so that it stops execution right there:

  if (!keyUnique) {
    console.log('key is not unique', name);
    throw new Error('Key is not unique');
  }

If you'll get the key this way you'll be able to find the place where you have elements with duplicate key.


问:
@Scripts doesn't exist in Asp.Net MVC
I'm trying to add Model validation in Asp.Net MVC ,

So I need to import the libraries at first inside Views\Share_Layout.cshtml .

Then it kills me in a second.

@Scripts doesn't exist

What is going on ?
If some further information needed , please tell me. Thanks :)

答:
Install Microsoft.AspNet.Web.Optimization

In web.config (Views folder) make sure you have under namespaces <add namespace="System.Web.Optimization"/>

Title: @Scripts doesn't exist in Asp.Net MVC


问:
PHP: Is it better to concatenate on 1 line or multiple lines? Or is there a difference?
Is there a difference or is one better than the other of the following:

```<code>$var = '';
...
$var .= 'blah blah';
$var .= $var2;
$var .= 'blah blah';
</code>```

Or

```<code>$var = '';
...
$var .= 'blah blah' . $var2 . 'blah blah';
</code>```

Is there a speed difference or is there a reason why you'd pick one over the other?

答:
There is a small difference if you echo the string.

```<code>echo $var1,$var2,$var3 // comma (echo with multiple arguments)
</code>```

is slightly faster than

```<code>echo $var1.$var2.$var3 // dot   (concat and echo)
</code>```

OwnerDisplayName: Darryl Hein

Body:
Is there a difference or is one better than the other of the following:

$var = '';
...
$var .= 'blah blah';
$var .= $var2;
$var .= 'blah blah';

Or

$var = '';
...
$var .= 'blah blah' . $var2 . 'blah blah';

Is there a speed difference or is there a reason why you'd pick one over the other?

LastEditorDisplayName: Paul Dixon

Body:
There is a small difference if you echo the string.

echo $var1,$var2,$var3 // comma (echo with multiple arguments)

is slightly faster than

echo $var1.$var2.$var3 // dot   (concat and echo)

OwnerDisplayName: Ivan


问:
Which is better: Several SQL queries or one sql data with lots of data?
I am making a quiz and I am expecting a lot of players for it. The quiz has a fixed number of questions.The quiz system can either fetch individual questions one by one from the MySql database and display it to the user. Or alternatively  I can fetch all the questions when he/she logs in and display them one by one. Can the second method significantly help in reducing the load on the server due to large number of SQL queries? Here I am talking about 500-600 users simultaneously playing the game.</p>

答:
Except 15 select queries each user's answer is a individual insert query. Maximum advantage for DB server is 2 batches of queries: 1 select and 1 insert for every user.

In theory you may receive 500-600 inserts per second. In practice there will be less inserts.

Anyway you should avoid large number of queries cause there are overheads for insert locks.


问:
Is it possible to have a form component with submit button located in the parent component. Angular
(I'm creating an angular 2 project. The project is that it has a forms inside a modal component). I would like to create a form components (3 child components each of which are form component) inside a modal (the parent component).

Switching/navigation of the form components( child component ) is done using the buttons of the modal (parent component). So basically the submit event of each form are all handled by the same button (next button) of the modal parent component. I would like to disabled the next button of the modal (which is also the submit button of each form) base on my validation. I've been trying to figure out how to implement this for a week now but I can't seem to find any solution.

答:
Try something like this:

@Component({
  template: `
    <button md-button [class.xs]="'mat-icon-button'" (click)="reset.emit()" [disabled]="!canReset">
      <md-icon>restore</md-icon>
      Reset
    </button>

      <button md-button color="warn" #d [disabled]="!d._" (click)="delete.emit()">
        <md-icon>delete</md-icon>
        Delete
      </button>
      <md-slide-toggle color="warn" (change)="d._=!d._"></md-slide-toggle>

    <button md-raised-button [class.xs]="'mat-icon-button'" color="accent" (click)="save.emit()">
      <md-icon>check</md-icon>
      Save
    </button>`,
})
export class FormButtonsComponent {
  @Input() canReset: boolean;
  @Input() canDelete: boolean;
  @Output() delete: EventEmitter<any> = new EventEmitter();
  @Output() reset: EventEmitter<any> = new EventEmitter();
  @Output() save: EventEmitter<any> = new EventEmitter();
}
```

You can disable/hide buttons with @Inputs, and handle clicks with @Outputs.

Body:
Try something like this:

@Component({
  template: `
    <button md-button [class.xs]="'mat-icon-button'" (click)="reset.emit()" [disabled]="!canReset">
      <md-icon>restore</md-icon>
      <span fxHide.xs i18n="button label">Reset</span>
    </button>

    <hr class="flex">

    <div class="inline-container" *ngIf="canDelete">
      <button md-button color="warn" #d [disabled]="!d._" (click)="delete.emit()">
        <md-icon>delete</md-icon>
        <span i18n="button label">Delete</span>
      </button>
      <md-slide-toggle color="warn" (change)="d._=!d._"></md-slide-toggle>
    </div>

    <button md-raised-button [class.xs]="'mat-icon-button'" color="accent" (click)="save.emit()">
      <md-icon>check</md-icon>
      <span fxHide.xs i18n="button label">Save</span>
    </button>`,
})
export class FormButtonsComponent {
  @Input() canReset: boolean;
  @Input() canDelete: boolean;
  @Output() delete: EventEmitter<any> = new EventEmitter();
  @Output() reset: EventEmitter<any> = new EventEmitter();
  @Output() save: EventEmitter<any> = new EventEmitter();
}

You can disable/hide buttons with @Inputs, and handle clicks with @Outputs.


问:
VueJS: one component for many routes
I'm a newbie to the world of VueJS.

My app uses vue-router to handle with routes changing. This's how it's configured:

```<code>new Router({
  routes: [{
    path: "/",
    component: Articles
  }, {
    path: "/articles/:category",
    component: Articles
  }]
});
</code>```

As you can see, I've got 2 routes handled by the same component. The idea is very simple. When we're on a home page, show articles from any category. When we're on a category page, show articles from that category.

The question is, how a component can detect whether the route's changed, e.g, from home page to category page?

I've come with this solution:

```<code>function loadArticles() {};

Vue.component("Articles", {
  mounted: loadArticles,
  watch: { "$route": loadArticles }
});
</code>```

But I think, that's a bad solution.

答:
Here's what I have done on a little project of mine, I'm using the template to display single article

This is my router

```<code>   '/post/:id': {
    name: 'post',
    component: require('./components/article.vue')
},
</code>```

In my .vue file, I get the $route.params to get the id of the article then displayed it in my ready function.

```<code>  $.get('api/posts/' + this.$route.params.id, function(data){
            myPost.current = data;
        })
</code>```

You'll need to get the category parameter then rendered the template according to it.

Title: VueJS: one component for many routes

Body:
I'm a newbie to the world of VueJS.

My app uses vue-router to handle with routes changing. This's how it's configured:

new Router({
  routes: [{
    path: "/",
    component: Articles
  }, {
    path: "/articles/:category",
    component: Articles
  }]
});

As you can see, I've got 2 routes handled by the same component. The idea is very simple. When we're on a home page, show articles from any category. When we're on a category page, show articles from that category.

The question is, how a component can detect whether the route's changed, e.g, from home page to category page?

I've come with this solution:

function loadArticles() {};

Vue.component("Articles", {
  mounted: loadArticles,
  watch: { "$route": loadArticles }
});

But I think, that's a bad solution.

Body:
Here's what I have done on a little project of mine, I'm using the template to display single article

This is my router

   '/post/:id': {
    name: 'post',
    component: require('./components/article.vue')
},

In my .vue file, I get the $route.params to get the id of the article then displayed it in my ready function.

  $.get('api/posts/' + this.$route.params.id, function(data){
            myPost.current = data;
        })

You'll need to get the category parameter then rendered the template according to it.


问:
Oracle 11g-Could not open Connection using Hibernate
[enter image description here][1]

[1]: https://i.stack.imgur.com/6sttv.pngstrong text

Not able to open the connection for Oracle 11g using hibernate-I also verified the service and hostname in the file "tnsnames.ora"

答: please check if you are providing right user name and password</p>