问:
WordPress : Password Protected Page (2)
I just upgraded my site to a new version WordPress 3.9.2. I noticed that one of my page is not working the way it usually does. This page is password protected and I made changes on how it looks. When I upgraded, it doesn't work anymore. In the password protected page, I have this code:

```<code><?php
echo "<script type='text/javascript'>\nwindow.location = 'http://www.google.com'</script>";
?>
</code>```

The purpose of that one is to redirect to another page. And they go hand in hand with this code below.
Here is my old code:

```<code>    <?php
function my_password_form() {
    global $post;
    $label = 'pwbox-'.( empty( $post->ID ) ? rand() : $post->ID );
    $o = '<form action="' . get_option('siteurl') . '/wp-pass.php" method="post">
    ' . __( "To view this protected post, enter the password below:" ) . '
    <label for="' . $label . '">' . __( "Password:" ) . ' </label><input name="post_password" id="' . $label . '" type="password" size="20" maxlength="20" /><input type="submit" name="Submit" value="' . esc_attr__( "Submit" ) . '" />
    </form>
    ';
    return $o;
}
add_filter( 'the_password_form', 'my_password_form' );
?>
</code>```

Before the upgrade, after inputting the password it redirects me to another page, which is how I wanted it to work. But take note of the action attribute of form. In the WP 3.9.2, wp-pass.php does not exist anymore so I was looking for another code. I saw this line:

```<code>action="' . esc_url( site_url( 'wp-login.php?action=postpass', 'login_post' ) ) . '"
</code>```

But after inputting the password, it redirects me to the wp-login which is not what I wanted. I need help with this, which works the same way with the old code I'm using. I am not going to downgrade my WP or install any plugin. I just want the value of the action="" changed. Thanks!

答:
I had the same problem and i found a solution

1) Set your page private with a password

2) Insert this form in an other page (typique postpass wordpress form) :

```<code><form action="https://exemple.com/wp-login.php?action=postpass" class="post-password-form" method="post" id="go-pro-espace">
     <input name="post_password" id="exemple" type="password" size="20" /><br />
     <input type="submit" value="submit">
</form>
</code>```

3) Change your /wp-login.php file (root directory, at this time, this is located line 460) :

```<code>from:
wp_safe_redirect( wp_get_referer() );
to:
wp_safe_redirect( "https://exemple.fr/your-protected-page" );
</code>```

Take a look to the answer: Wordpress protected page, POST form on a other page

Title: WordPress : Password Protected Page (2)

Body:
I just upgraded my site to a new version WordPress 3.9.2. I noticed that one of my page is not working the way it usually does. This page is password protected and I made changes on how it looks. When I upgraded, it doesn't work anymore. In the password protected page, I have this code:

<?php
echo "";
?>

The purpose of that one is to redirect to another page. And they go hand in hand with this code below.
Here is my old code:

    <?php
function my_password_form() {
    global $post;
    $label = 'pwbox-'.( empty( $post->ID ) ? rand() : $post->ID );
    $o = '<form action="' . get_option('siteurl') . '/wp-pass.php" method="post">
    ' . __( "To view this protected post, enter the password below:" ) . '
    ' . __( "Password:" ) . ' <input name="post_password" id="' . $label . '" type="password" size="20" maxlength="20" /><input type="submit" name="Submit" value="' . esc_attr__( "Submit" ) . '" />
    </form>
    ';
    return $o;
}
add_filter( 'the_password_form', 'my_password_form' );
?>

Before the upgrade, after inputting the password it redirects me to another page, which is how I wanted it to work. But take note of the action attribute of form. In the WP 3.9.2, wp-pass.php does not exist anymore so I was looking for another code. I saw this line:

action="' . esc_url( site_url( 'wp-login.php?action=postpass', 'login_post' ) ) . '"

But after inputting the password, it redirects me to the wp-login which is not what I wanted. I need help with this, which works the same way with the old code I'm using. I am not going to downgrade my WP or install any plugin. I just want the value of the action="" changed. Thanks!

Body:
I had the same problem and i found a solution

1) Set your page private with a password

2) Insert this form in an other page (typique postpass wordpress form) :

<form action="https://exemple.com/wp-login.php?action=postpass" class="post-password-form" method="post" id="go-pro-espace">
     <input name="post_password" id="exemple" type="password" size="20" /><br />
     <input type="submit" value="submit">
</form>

3) Change your /wp-login.php file (root directory, at this time, this is located line 460) :

from:
wp_safe_redirect( wp_get_referer() );
to:
wp_safe_redirect( "https://exemple.fr/your-protected-page" );

Take a look to the answer: Wordpress protected page, POST form on a other page


来源: stackexchange

问:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error
I'm using php and pdo

Here is my code:

```<code>try {
    $sql="LOCK TABLE appleid WRITE, appleid AS appleid1 READ;";
    $stmt = $GLOBALS['$connection']->prepare($sql);
    $stmt->execute();
    $sql="SELECT MAX(num) FROM appleid;";//to know how many rows it has
    $stmt = $GLOBALS['$connection']->prepare($sql);
    $stmt->execute();
    $result=$stmt->fetch();
    $table_top=$result[0];

    if (empty($head)) $head = 1;
    $check=$table_top - $head;
    $check++;//number of available rows that are ready to use

    if($check>=$this->apple_id_num)
    {
        $sql = "SELECT id,pass,en_b_y,en_b_m,en_b_d,sqa1,sqa2,sqa3 FROM
        appleid AS appleid1
        WHERE num>=$head LIMIT $this->apple_id_num ORDER BY `TimeStamp`
        DESC;";
        $stmt = $GLOBALS['$connection']->prepare($sql);
        $stmt->execute();
        $this->pre_head=$head;
        $head=1+$head+$this->apple_id_num;
        $sql="UNLOCK TABLES;";
        $this->num_rows = $stmt->rowCount();
        echo $stmt->rowCount();
    }
}
catch(PDOException $e)
{
    echo $sql . "<br>" . $e->getMessage();
}
</code>```

I get this error :

SELECT id,pass,en_b_y,en_b_m,en_b_d,sqa1,sqa2,sqa3 FROM appleid AS
  appleid1 WHERE num>=1 LIMIT 1 ORDER BY TimeStamp DESC;
  SQLSTATE[42000]: Syntax error

or access violation: 1064 You have an error in your SQL syntax; check
  the manual that corresponds to your MySQL server version for the right
  syntax to use near 'ORDER BY TimeStamp DESC' at line 2

I got confused and I don't know what is wrong with this query and how to fix it.

答:
I have not tested, but timeStamp sound like a reserved word of mysql,

maybe you can try a correct quote of this field, or best pratice change the name of the field.

ContentLicense: CC BY-SA 3.0

Body:
I'm using php and pdo

Here is my code:

try {
    $sql="LOCK TABLE appleid WRITE, appleid AS appleid1 READ;";
    $stmt = $GLOBALS['$connection']->prepare($sql);
    $stmt->execute();
    $sql="SELECT MAX(num) FROM appleid;";//to know how many rows it has
    $stmt = $GLOBALS['$connection']->prepare($sql);
    $stmt->execute();
    $result=$stmt->fetch();
    $table_top=$result[0];

    if (empty($head)) $head = 1;
    $check=$table_top - $head;
    $check++;//number of available rows that are ready to use

    if($check>=$this->apple_id_num)
    {
        $sql = "SELECT id,pass,en_b_y,en_b_m,en_b_d,sqa1,sqa2,sqa3 FROM
        appleid AS appleid1
        WHERE num>=$head LIMIT $this->apple_id_num ORDER BY `TimeStamp`
        DESC;";
        $stmt = $GLOBALS['$connection']->prepare($sql);
        $stmt->execute();
        $this->pre_head=$head;
        $head=1+$head+$this->apple_id_num;
        $sql="UNLOCK TABLES;";
        $this->num_rows = $stmt->rowCount();
        echo $stmt->rowCount();
    }
}
catch(PDOException $e)
{
    echo $sql . "
" . $e->getMessage();
}

I get this error :

SELECT id,pass,en_b_y,en_b_m,en_b_d,sqa1,sqa2,sqa3 FROM appleid AS
  appleid1 WHERE num>=1 LIMIT 1 ORDER BY TimeStamp DESC;
  SQLSTATE[42000]: Syntax error

or access violation: 1064 You have an error in your SQL syntax; check
  the manual that corresponds to your MySQL server version for the right
  syntax to use near 'ORDER BY TimeStamp DESC' at line 2

I got confused and I don't know what is wrong with this query and how to fix it.


问:
Is there any way to set year in crontab parameter list?
I want to set a cronjob for a specific date and time.
For example, date time like this 2017 July 12, 12 35.
Is it possible to set Year in the crontab parameter list?
I can set without the year field.</p>

答:
There is no parameter to specify the year in crontab.

You can move the year logic to the bash script and add that script to crontab.


问:
SQL: columns name based on variable
I have a temporary table aaa that I use as an array.

```<code>    USE tempdb
    GO

    IF OBJECT_ID('tempdb..aaa') IS NOT NULL DROP TABLE aaa
    CREATE TABLE aaa (
        #1 char(40),
        #2 char(40),
        #3 char(40)
    );
    insert into aaa values ('aaaa','qqqq','eeee');
    declare @sql varchar(40);
    declare @var varchar(40)='#3';
    set @sql= '(select '+@var +' from aaa)';
       print @sql;
</code>```

What I'm trying to achieve is to store into the variable @sql the executed value of '(select '+@var +' from aaa)' which is: eeee and NOT simply the string (select #3 from aaa)

I know that ''this is not how SQL is supposed to work'' but after 320 questions read on SO(my history tab can prove) I'm out of ideas:)

答:
You can create temp table (or table variable) and insert the result of your dynamic sql into.

```<code>create table #tmpResult (res CHAR(40));

declare @sql varchar(40);
declare @var varchar(40)='#3';
set @sql= '(select '+@var +' from aaa)';
insert #tmpResult
exec (@sql)

select * from  #tmpResult --you can easily fill @sql variable from here
</code>```

or you can even change your dynamic sql to include this insert:

```<code>create table #tmpResult (res CHAR(40));

declare @sql varchar(40);
declare @var varchar(40)='#3';
set @sql= 'insert #tmpResult select '+@var +' from aaa';
exec (@sql)

select * from  #tmpResult
</code>```

Title: SQL: columns name based on variable

Body:
I have a temporary table aaa that I use as an array.

    USE tempdb
    GO

    IF OBJECT_ID('tempdb..aaa') IS NOT NULL DROP TABLE aaa
    CREATE TABLE aaa (
        #1 char(40),
        #2 char(40),
        #3 char(40)
    );
    insert into aaa values ('aaaa','qqqq','eeee');
    declare @sql varchar(40);
    declare @var varchar(40)='#3';
    set @sql= '(select '+@var +' from aaa)';
       print @sql;

What I'm trying to achieve is to store into the variable @sql the executed value of '(select '+@var +' from aaa)' which is: eeee and NOT simply the string (select #3 from aaa)

I know that ''this is not how SQL is supposed to work'' but after 320 questions read on SO(my history tab can prove) I'm out of ideas:)

Body:
You can create temp table (or table variable) and insert the result of your dynamic sql into.

create table #tmpResult (res CHAR(40));

declare @sql varchar(40);
declare @var varchar(40)='#3';
set @sql= '(select '+@var +' from aaa)';
insert #tmpResult
exec (@sql)

select * from  #tmpResult --you can easily fill @sql variable from here

or you can even change your dynamic sql to include this insert:

create table #tmpResult (res CHAR(40));

declare @sql varchar(40);
declare @var varchar(40)='#3';
set @sql= 'insert #tmpResult select '+@var +' from aaa';
exec (@sql)

select * from  #tmpResult


问:
which is the best Camera API for image processing in Android
I am working on an Android project which should capture an image by the camera API and the do some image processing to classify the image and give result to user (I used opencv to process the image and classify result). My question is which is the best camera API? Shall I use Java camera view in opencv or use Camera API using intent or finally use camera 2 API which can give me control to manage some characteristics related to ambient conditions. </p>

<p>Please clear my confusion and suggest which is the best one to control the quality of the image and and other conditions that affect the image taken.  </p>

答:
native camera:

higher framerate

capture RGBA, no need to convert from android yuv format

and much more features

so i would say use standard Camera API

Body:
I am working on an Android project which should capture an image by the camera API and the do some image processing to classify the image and give result to user (I used opencv to process the image and classify result). My question is which is the best camera API? Shall I use Java camera view in opencv or use Camera API using intent or finally use camera 2 API which can give me control to manage some characteristics related to ambient conditions.

Please clear my confusion and suggest which is the best one to control the quality of the image and and other conditions that affect the image taken.


答: No. Crontab is for events that REPEAT on cycles within the year. It's got no capacity for scheduling events on a particular year, nor even for events that happen in some years and not others. It's just not something the designers of cron needed to do.</p>

Title: Is there any way to set year in crontab parameter list?

Body:
I want to set a cronjob for a specific date and time.
For example, date time like this 2017 July 12, 12 35.
Is it possible to set Year in the crontab parameter list?
I can set without the year field.


问:
My program unfortunately stops when the send mail button is clicked. I have added the the three jar files and the permission for internet
I have been trying to send an email for sometime now using the java mail api for android.I have tried several codes on the internet but still keep getting the same error message when the apk is run on a mobile device which says "appName unfortunately stopped".I am new to android and i would be very happy if someone could help me on this platform.Also i am using android studio as my IDE. Thank you

Below is the code for my XML

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.rollxreuben.mailing.MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btn"
        android:text="Send Mail"
        android:gravity="center_horizontal"
        />

</android.support.constraint.ConstraintLayout>
</code>```

Below is the code for the java class

```<code>    package com.example.rollxreuben.mailing;

    import android.app.ProgressDialog;
    import android.content.Context;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.view.View;
    import android.widget.Button;
    import android.widget.Toast;

    import java.util.Properties;

    import javax.mail.Authenticator;
    import javax.mail.Message;
    import javax.mail.PasswordAuthentication;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;

    public class MainActivity extends AppCompatActivity implements View.OnClickListener {
            private Button btn;
        Session session = null;
        ProgressDialog pDialog = null;
        Context context = null;
        String rec, receipt;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            context = this;
            btn = (Button)findViewById(R.id.btn);
            btn.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {

            Properties props = new Properties();
            props.put("mail.smtp.port","smtp.gmail.com");
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.socketFactory.port", "465");

            session  = Session.getDefaultInstance(props, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("email@gmail.com","PASSWORD");
                }
            });

            pDialog = ProgressDialog.show(context,"","Sending Mail",true);
            SendMail sendMail = new SendMail();
            sendMail.execute();
        }
    }
</code>```

SendMail class:

```<code>private class SendMail extends AsyncTask<String, Void, String> {

        private ProgressDialog progressDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = ProgressDialog.show(MainActivity.this, "Please wait", "Sending mail", true, false);
        }

        @Override
        protected void onPostExecute(String aVoid) {
            progressDialog.dismiss();
            Toast.makeText(MainActivity.this, "Email was sent successfully.", Toast.LENGTH_LONG).show();
            super.onPostExecute(aVoid);

        }

        protected String doInBackground(String... params) {

            try {

                Message message = new MimeMessage(session);
                message.setFrom(new InternetAddress("busben97@gmail.com"));
                message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("busben97@gmail.com"));
                message.setSubject("Testing Mail");
                message.setContent("Hello ","text/html; charset=utf-8");
                Transport.send(message);

            } catch(Exception e) {
                Toast.makeText(MainActivity.this,e.toString(),Toast.LENGTH_LONG).show();
            }
            return null;
        }
    }

}
</code>```

Finally this is my manifest:

```<code>    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.rollxreuben.mailing">
        <uses-permission android:name="android.permission.INTERNET"/>

        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

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

    </manifest>

//This is the log file
07-05 17:00:37.129 4376-4376/? I/art: Not late-enabling -Xcheck:jni (already on)
07-05 17:00:37.129 4376-4376/? W/art: Unexpected CPU variant for X86 using defaults: x86
07-05 17:00:38.381 4376-4376/com.example.rollxreuben.mailing W/System: ClassLoader referenced unknown path: /data/app/com.example.rollxreuben.mailing-2/lib/x86
07-05 17:00:38.389 4376-4376/com.example.rollxreuben.mailing I/InstantRun: starting instant run server: is main process
07-05 17:00:38.446 4376-4376/com.example.rollxreuben.mailing W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
07-05 17:00:39.785 4376-4402/com.example.rollxreuben.mailing I/OpenGLRenderer: Initialized EGL, version 1.4
07-05 17:00:39.785 4376-4402/com.example.rollxreuben.mailing D/OpenGLRenderer: Swap behavior 1
07-05 17:00:40.838 4376-4376/com.example.rollxreuben.mailing W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
07-05 17:00:40.848 4376-4376/com.example.rollxreuben.mailing I/Choreographer: Skipped 96 frames!  The application may be doing too much work on its main thread.
07-05 17:00:44.293 4376-4376/com.example.rollxreuben.mailing I/Choreographer: Skipped 206 frames!  The application may be doing too much work on its main thread.
07-05 17:01:17.648 4376-4939/com.example.rollxreuben.mailing W/art: Verification of java.lang.String javax.mail.internet.MimeUtility.encodeWord(java.lang.String, java.lang.String, java.lang.String, boolean) took 105.438ms
07-05 17:01:17.752 4376-4939/com.example.rollxreuben.mailing E/Exception: For input string: "smtp.gmail.com"
                                                                          java.lang.NumberFormatException: For input string: "smtp.gmail.com"
                                                                              at java.lang.Integer.parseInt(Integer.java:521)
                                                                              at java.lang.Integer.parseInt(Integer.java:556)
                                                                              at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:398)
                                                                              at javax.mail.Service.connect(Service.java:310)
                                                                              at javax.mail.Service.connect(Service.java:169)
                                                                              at javax.mail.Service.connect(Service.java:118)
                                                                              at javax.mail.Transport.send0(Transport.java:188)
                                                                              at javax.mail.Transport.send(Transport.java:118)
                                                                              at com.example.rollxreuben.mailing.MainActivity$SendMail.doInBackground(MainActivity.java:93)
                                                                              at com.example.rollxreuben.mailing.MainActivity$SendMail.doInBackground(MainActivity.java:66)
                                                                              at android.os.AsyncTask$2.call(AsyncTask.java:305)
                                                                              at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                              at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
                                                                              at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
                                                                              at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
                                                                              at java.lang.Thread.run(Thread.java:761)
07-05 17:01:18.733 4376-4376/com.example.rollxreuben.mailing I/Choreographer: Skipped 71 frames!  The application may be doing too much work on its main thread.
07-05 17:01:20.603 4376-4376/com.example.rollxreuben.mailing I/Choreographer: Skipped 111 frames!  The application may be doing too much work on its main thread.
</code>```

答:
java.lang.NumberFormatException: For input string: "smtp.gmail.com"

The error is caused by parseInt() for a non-numeric value smtp.gmail.com

this is caused by this line props.put("mail.smtp.port","smtp.gmail.com");

port should be a number you are passing a host address, either change the key mail.smtp.port or change the value smtp.gmail.com.

Body:
I have been trying to send an email for sometime now using the java mail api for android.I have tried several codes on the internet but still keep getting the same error message when the apk is run on a mobile device which says "appName unfortunately stopped".I am new to android and i would be very happy if someone could help me on this platform.Also i am using android studio as my IDE. Thank you

Below is the code for my XML

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.rollxreuben.mailing.MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btn"
        android:text="Send Mail"
        android:gravity="center_horizontal"
        />

</android.support.constraint.ConstraintLayout>

Below is the code for the java class

    package com.example.rollxreuben.mailing;

    import android.app.ProgressDialog;
    import android.content.Context;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.view.View;
    import android.widget.Button;
    import android.widget.Toast;

    import java.util.Properties;

    import javax.mail.Authenticator;
    import javax.mail.Message;
    import javax.mail.PasswordAuthentication;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;

    public class MainActivity extends AppCompatActivity implements View.OnClickListener {
            private Button btn;
        Session session = null;
        ProgressDialog pDialog = null;
        Context context = null;
        String rec, receipt;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            context = this;
            btn = (Button)findViewById(R.id.btn);
            btn.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {

            Properties props = new Properties();
            props.put("mail.smtp.port","smtp.gmail.com");
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.socketFactory.port", "465");

            session  = Session.getDefaultInstance(props, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("email@gmail.com","PASSWORD");
                }
            });

            pDialog = ProgressDialog.show(context,"","Sending Mail",true);
            SendMail sendMail = new SendMail();
            sendMail.execute();
        }
    }

SendMail class:

private class SendMail extends AsyncTask<String, Void, String> {

        private ProgressDialog progressDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = ProgressDialog.show(MainActivity.this, "Please wait", "Sending mail", true, false);
        }

        @Override
        protected void onPostExecute(String aVoid) {
            progressDialog.dismiss();
            Toast.makeText(MainActivity.this, "Email was sent successfully.", Toast.LENGTH_LONG).show();
            super.onPostExecute(aVoid);

        }

        protected String doInBackground(String... params) {

            try {

                Message message = new MimeMessage(session);
                message.setFrom(new InternetAddress("busben97@gmail.com"));
                message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("busben97@gmail.com"));
                message.setSubject("Testing Mail");
                message.setContent("Hello ","text/html; charset=utf-8");
                Transport.send(message);

            } catch(Exception e) {
                Toast.makeText(MainActivity.this,e.toString(),Toast.LENGTH_LONG).show();
            }
            return null;
        }
    }

}

Finally this is my manifest:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.rollxreuben.mailing">
        <uses-permission android:name="android.permission.INTERNET"/>

        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

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

    </manifest>

//This is the log file
07-05 17:00:37.129 4376-4376/? I/art: Not late-enabling -Xcheck:jni (already on)
07-05 17:00:37.129 4376-4376/? W/art: Unexpected CPU variant for X86 using defaults: x86
07-05 17:00:38.381 4376-4376/com.example.rollxreuben.mailing W/System: ClassLoader referenced unknown path: /data/app/com.example.rollxreuben.mailing-2/lib/x86
07-05 17:00:38.389 4376-4376/com.example.rollxreuben.mailing I/InstantRun: starting instant run server: is main process
07-05 17:00:38.446 4376-4376/com.example.rollxreuben.mailing W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
07-05 17:00:39.785 4376-4402/com.example.rollxreuben.mailing I/OpenGLRenderer: Initialized EGL, version 1.4
07-05 17:00:39.785 4376-4402/com.example.rollxreuben.mailing D/OpenGLRenderer: Swap behavior 1
07-05 17:00:40.838 4376-4376/com.example.rollxreuben.mailing W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
07-05 17:00:40.848 4376-4376/com.example.rollxreuben.mailing I/Choreographer: Skipped 96 frames!  The application may be doing too much work on its main thread.
07-05 17:00:44.293 4376-4376/com.example.rollxreuben.mailing I/Choreographer: Skipped 206 frames!  The application may be doing too much work on its main thread.
07-05 17:01:17.648 4376-4939/com.example.rollxreuben.mailing W/art: Verification of java.lang.String javax.mail.internet.MimeUtility.encodeWord(java.lang.String, java.lang.String, java.lang.String, boolean) took 105.438ms
07-05 17:01:17.752 4376-4939/com.example.rollxreuben.mailing E/Exception: For input string: "smtp.gmail.com"
                                                                          java.lang.NumberFormatException: For input string: "smtp.gmail.com"
                                                                              at java.lang.Integer.parseInt(Integer.java:521)
                                                                              at java.lang.Integer.parseInt(Integer.java:556)
                                                                              at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:398)
                                                                              at javax.mail.Service.connect(Service.java:310)
                                                                              at javax.mail.Service.connect(Service.java:169)
                                                                              at javax.mail.Service.connect(Service.java:118)
                                                                              at javax.mail.Transport.send0(Transport.java:188)
                                                                              at javax.mail.Transport.send(Transport.java:118)
                                                                              at com.example.rollxreuben.mailing.MainActivity$SendMail.doInBackground(MainActivity.java:93)
                                                                              at com.example.rollxreuben.mailing.MainActivity$SendMail.doInBackground(MainActivity.java:66)
                                                                              at android.os.AsyncTask$2.call(AsyncTask.java:305)
                                                                              at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                              at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
                                                                              at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
                                                                              at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
                                                                              at java.lang.Thread.run(Thread.java:761)
07-05 17:01:18.733 4376-4376/com.example.rollxreuben.mailing I/Choreographer: Skipped 71 frames!  The application may be doing too much work on its main thread.
07-05 17:01:20.603 4376-4376/com.example.rollxreuben.mailing I/Choreographer: Skipped 111 frames!  The application may be doing too much work on its main thread.


问:
Update partial view using Ajax not working
Experimenting with partial views in MVC 5, can't refresh my partial view using Ajax on button click:

This is my partial view:

```<code>@model dbsapplication.Models.CarRepository

   @{
        Layout = null;
   }

@Html.DisplayFor(model => model.Engine)
</code>```

in my Index page, I have:

```<code><div id="@car.ID">
       @Html.Partial("PartialView", car)
</div>
</code>```

and my button:

```<code><button onclick="loadProject(@car.ID)">Car ID: @car.ID</button>
</code>```

My Ajax call:

```<code><script>
function loadProject(car_ID) {
//alert('#' + car_ID);
    $.ajax({
        type: "GET",
        url: '/Home/partialView/',
        data: { id: car_ID },
        async: true,
        cache: false,
        dataType: "html",
        success: function (data) {
            $('#' + car_ID).empty();
            $('#' + car_ID).html(data);
            alert("Updated!");
            },
        });
    }
</script>
</code>```

my controller:

```<code>public PartialViewResult partialView(int id)
{
   CarRepository car = new CarRepository();
   car.updateCar_partial(id);
   return PartialView("PartialView", car);
}
</code>```

car.updateCar_partial(id);

This method simply sets the Engine for a given car back to default value which is ("Not specififed"). When I click the button, the ajax call runs and the alert is triggered but the DIV the data is meant to load into goes blank. Only when I refresh the page, the partial view is updated to the correct value.

Refreshed via F5 or when I add location.reload which i think defeats the purpose as this reloads the whole page not the div.

Not sure if what i'm doing is possible, any help would be appreciated.

Other question I have to try and fix:

Update Partial View Within Partial View Using MVC Ajax
AJAX not updating partial view

答:
I would suggest to use jquery load() function to fill partial view into your target html element like following.

```<code>function loadProject(car_ID) {

     var url = '@Url.Action("partialView", "Home")' + "?id=" + car_ID;
     var targetElement = $("#" + car_ID);

     targetElement.load(url, function(responseTxt, statusTxt, xhr){
         if(statusTxt == "success")
         console.log("It worked");
     })
}
</code>```

Body:
Experimenting with partial views in MVC 5, can't refresh my partial view using Ajax on button click:

This is my partial view:

@model dbsapplication.Models.CarRepository

   @{
        Layout = null;
   }

@Html.DisplayFor(model => model.Engine)

in my Index page, I have:

       @Html.Partial("PartialView", car)

and my button:

<button onclick="loadProject(@car.ID)">Car ID: @car.ID</button>

My Ajax call:

my controller:

public PartialViewResult partialView(int id)
{
   CarRepository car = new CarRepository();
   car.updateCar_partial(id);
   return PartialView("PartialView", car);
}

car.updateCar_partial(id);

This method simply sets the Engine for a given car back to default value which is ("Not specififed"). When I click the button, the ajax call runs and the alert is triggered but the DIV the data is meant to load into goes blank. Only when I refresh the page, the partial view is updated to the correct value.

Refreshed via F5 or when I add location.reload which i think defeats the purpose as this reloads the whole page not the div.

Not sure if what i'm doing is possible, any help would be appreciated.

Other question I have to try and fix:

Update Partial View Within Partial View Using MVC Ajax
AJAX not updating partial view

Body:
I would suggest to use jquery load() function to fill partial view into your target html element like following.

function loadProject(car_ID) {

     var url = '@Url.Action("partialView", "Home")' + "?id=" + car_ID;
     var targetElement = $("#" + car_ID);

     targetElement.load(url, function(responseTxt, statusTxt, xhr){
         if(statusTxt == "success")
         console.log("It worked");
     })
}


问:
To create an array that contains each digit as separate element from integer in JavaScript
My understanding is that bellow code will create an array name digits which contains all digits from n, I'm I right?

var n =  123456789;
var digits = (""+n).split("");

But I did'n understood (""+n) ?
Can anyone help me?
Thanks in advance.

答: var n = 123456789; create a variable n of numeric type. When you use +"" with a variable of numeric type javascript autamatically treat it as string and the operation return a string. So  (""+n) will cast the n variable to string type.


问:
Any way to css select all EXCEPT the first page?
I just found the CSS @page directive, and using it with :first to apply CSS to the first page of an html print. Is there any way to go the opposite, and apply CSS to all pages except the first?

答: If you're using CSS2, you can do it indirectly. Use @page to set the style that you want for all your pages except the first, then use @page along with :first to "undo" those styles for the first page.

ContentLicense: CC BY-SA 2.5


问:
Parsing react app using phantom.js not loading whole page
I have react app running fine. I want to use phantom.js for SEO. With the help of phantom.js, I want to store my page somewhere, and whenever a request comes from search bots, I want to serve them these saved pages.

The phantom.js code is:

```<code>var page;
var myurl="http://localhost:8080/login";

var renderPage = function (url) {
    page = require('webpage').create();
    page.settings.userAgent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1';

    page.onNavigationRequested = function(url, type, willNavigate, main) {
        if (main && url!=myurl) {
            myurl = url;
            console.log("redirect caught");
            page.close()
            renderPage(url);
        }
    };
page.open(url, function (status) {

    if (status !== 'success') {
        console.log('Unable to load the address!');
        phantom.exit();
    } else {
        window.setTimeout(function () {
            console.log(page.content);
            phantom.exit();
        }, 1000); // Change timeout as required to allow sufficient time
    }
});

    // page.open(url, function(status) {
    //     console.log(status);
    //     if (status==="success") {
    //         console.log("success")
    //         console.log(page.content);
    //             // page.render('yourscreenshot.png');
    //             phantom.exit(0);
    //     } else {
    //         console.log("failed")
    //             phantom.exit(1);
    //     }
    // });
}

renderPage(myurl);
</code>```

Above code works fine, but with two constraints:

It works only on localhost, i.e., if myurl="http://localhost:8080/login"; is changed to myurl="http://192.168.x.x/login";, it doesn't work.

If I am dynamically loading my component in react.js, above code doesn't work, even for localhost.

e.g., this works fine:

```<code>import Login from './containers/Login';
</code>```

But, this doesn't:

```<code>const login = asyncComponent(() => import('./containers/login')
  .then(module => module.default), { name: 'login' });
</code>```

Where asyncComponent() is:

```<code>import React from 'react';

export default (loader, collection) => (
  class AsyncComponent extends React.Component {
    constructor(props) {
      super(props);

      this.Component = null;
      this.state = { Component: AsyncComponent.Component };
    }

    componentWillMount() {
      if (!this.state.Component) {
        loader().then((Component) => {
          AsyncComponent.Component = Component;

          this.setState({ Component });
        });
      }
    }

    render() {
      if (this.state.Component) {
        return (
          <this.state.Component { ...this.props } { ...collection } />
        )
      }

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

I am looking for some help/guidance for:

How to manage SEO pages for reactjs? Is phantom.js a feasible solution?

How to manage redirects, i.e., for request on servers, I first redirect request to index.html and then render the page. I want to do the same in phantom.js, get the page after redirection, which is not working fine.

答:
Previous versions of PhantomJS wouldn't support ES6, see a solution here: https://stackoverflow.com/a/38471938/2715393

Or you could download and use a newer 2.5 beta version with modern Webkit engine that should open ReactJS sites fine from here: https://bitbucket.org/ariya/phantomjs/downloads

Body:
I have react app running fine. I want to use phantom.js for SEO. With the help of phantom.js, I want to store my page somewhere, and whenever a request comes from search bots, I want to serve them these saved pages.

The phantom.js code is:

var page;
var myurl="http://localhost:8080/login";

var renderPage = function (url) {
    page = require('webpage').create();
    page.settings.userAgent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1';

    page.onNavigationRequested = function(url, type, willNavigate, main) {
        if (main && url!=myurl) {
            myurl = url;
            console.log("redirect caught");
            page.close()
            renderPage(url);
        }
    };
page.open(url, function (status) {

    if (status !== 'success') {
        console.log('Unable to load the address!');
        phantom.exit();
    } else {
        window.setTimeout(function () {
            console.log(page.content);
            phantom.exit();
        }, 1000); // Change timeout as required to allow sufficient time
    }
});

    // page.open(url, function(status) {
    //     console.log(status);
    //     if (status==="success") {
    //         console.log("success")
    //         console.log(page.content);
    //             // page.render('yourscreenshot.png');
    //             phantom.exit(0);
    //     } else {
    //         console.log("failed")
    //             phantom.exit(1);
    //     }
    // });
}

renderPage(myurl);

Above code works fine, but with two constraints:

It works only on localhost, i.e., if myurl="http://localhost:8080/login"; is changed to myurl="http://192.168.x.x/login";, it doesn't work.

If I am dynamically loading my component in react.js, above code doesn't work, even for localhost.

e.g., this works fine:

import Login from './containers/Login';

But, this doesn't:

const login = asyncComponent(() => import('./containers/login')
  .then(module => module.default), { name: 'login' });

Where asyncComponent() is:

import React from 'react';

export default (loader, collection) => (
  class AsyncComponent extends React.Component {
    constructor(props) {
      super(props);

      this.Component = null;
      this.state = { Component: AsyncComponent.Component };
    }

    componentWillMount() {
      if (!this.state.Component) {
        loader().then((Component) => {
          AsyncComponent.Component = Component;

          this.setState({ Component });
        });
      }
    }

    render() {
      if (this.state.Component) {
        return (
          <this.state.Component { ...this.props } { ...collection } />
        )
      }

      return null;
    }
  }
);

I am looking for some help/guidance for:

How to manage SEO pages for reactjs? Is phantom.js a feasible solution?

How to manage redirects, i.e., for request on servers, I first redirect request to index.html and then render the page. I want to do the same in phantom.js, get the page after redirection, which is not working fine.


问:
filter by is_active boolean field in django
I want to have an is_active field for all the models in my application and when ever I create an api, I want to filter only the active ones and send the response. Is there a generic way to do this? As of now I am keeping a boolean field is_active and every time I retrieve the objects, I am writing a filter. below is the code :

My models.py

```<code>class Crew(models.Model):
    crew_id = models.AutoField(primary_key=True)
    crew_code = models.CharField(max_length=200, null=False, unique=True)
    crew_name = models.CharField(max_length=200, null=False)
    crew_password = models.CharField(max_length=200, null=False)
    is_active = models.BooleanField(default=True)
</code>```

My views.py :

```<code>@api_view(['GET'])
def get_crews(request):
    c = Crew.objects.filter(is_active=True)
    serializer = CrewSerializer(c, many=True)
    return Response(serializer.data, status=status.HTTP_200_OK)
</code>```

答:
You can write a mixin in mixin.py file something like this

```<code>class TimeFieldsMixin(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    active = models.BooleanField(default=True, db_index=True)
    class Meta:
        abstract = True
</code>```

And Import this in your models like this:

```<code>class User(TimeFieldsMixin):
     // model fields
</code>```

This will add this fields by default wherever you use this mixin.

Let me know if this is not clear.

Body:
I want to have an is_active field for all the models in my application and when ever I create an api, I want to filter only the active ones and send the response. Is there a generic way to do this? As of now I am keeping a boolean field is_active and every time I retrieve the objects, I am writing a filter. below is the code :

My models.py

class Crew(models.Model):
    crew_id = models.AutoField(primary_key=True)
    crew_code = models.CharField(max_length=200, null=False, unique=True)
    crew_name = models.CharField(max_length=200, null=False)
    crew_password = models.CharField(max_length=200, null=False)
    is_active = models.BooleanField(default=True)

My views.py :

@api_view(['GET'])
def get_crews(request):
    c = Crew.objects.filter(is_active=True)
    serializer = CrewSerializer(c, many=True)
    return Response(serializer.data, status=status.HTTP_200_OK)

Body:
You can write a mixin in mixin.py file something like this

class TimeFieldsMixin(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    active = models.BooleanField(default=True, db_index=True)
    class Meta:
        abstract = True

And Import this in your models like this:

class User(TimeFieldsMixin):
     // model fields

This will add this fields by default wherever you use this mixin.

Let me know if this is not clear.


问:
How to count total number of table rows from ajax response? How to create search field for that table?
I am getting table data from ajax response like this :

```<code>function fetch_data(){
  $.ajax({
    url: "menu_table.php",
    method: "POST",
    success: function(data) {
      $('#menu_table_data').html(data);
    }
  });
}

fetch_data();
</code>```

Table:

```<code><table id="menu_table">
  <thead>
    <tr>
      <th class="centerText" data-field="item_id">ID</th>
      <th class="centerText" data-field="name">Name</th>
      <th class="centerText" data-field="price">Price</th>
      <th class="centerText" data-field="type">Type</th>
      <th class="centerText" data-field="image">Image</th>
      <th class="centerText" data-field="description">Description</th>
      <th class="centerText" data-field="cooking">Instructions</th>
      <th class="centerText" data-field="ingredients">Ingredients</th>
      <th class="centerText" data-field="warnings">Warnings</th>
      <th class="centerText" data-field="Storage">Storage</th>
      <th class="centerText" data-field="Size">Size</th>
      <th class="centerText" data-field="edit">Edit</th>
      <th class="centerText" data-field="delete">Delete</th>
    </tr>
  </thead>
  <tbody style="text-align:center;" id="menu_table_data"></tbody>
</table>
</code>```

How do I count total number of rows from ajax response?

How can I create a search field to search from this table?

menu_table.php:

```<code>while($data = mysqli_fetch_array($search))
{
$output .= '<tr><td>'.$data['id'].'</td>
            <td><div class="text_area">'.$data['name'].'</div></td>
            <td>'.$data['price'].'</td>
            <td>'.$data['type'].'</td>
            <td><div id="div_image">
            <img src="uploaded_images/'.$data['image'].'" class="thumbnail" height="100" width="80" /></div></td>
            <td><div class="text_area">'.$data['description'].'</div></td>
            <td><div class="text_area">'.$data['cooking_instructions'].'<div></td>
            <td><div class="text_area">'.$data['ingredients'].'</div></td>
            <td><div class="text_area">'.$data['allergen_warnings'].'</div></td>
            <td>'.$data['storage_instructions'].'</td>
            <td>'.$data['case_size'].'</td>   <td><a class="btn btn-primary glyphicon glyphicon-edit" role="button" onclick="EditModal(`'.$data['id'].'`,`'.$data['name'].'`,`'.$data['price'].'`,`'.$data['description'].'`,`'.$data['type'].'`,`'.$data['cooking_instructions'].'`,`'.$data['ingredients'].'`,`'.$data['allergen_warnings'].'`,`'.$data['storage_instructions'].'`,`'.$data['case_size'].'`,`'."uploaded_images/".$data['image'].'`)"></a></td>   <td><a class="btn btn-danger glyphicon glyphicon-remove" role="button" onclick="DeleteModal('.$data['id'].')"></a></td><tr>';}
</code>```

答:
Assuming that the response to the request is the plain HTML in your second code example, you can put it in a jQuery selector, then find() the tr elements in it, like this:

```<code>function fetch_data(){
  $.ajax({
    url: "menu_table.php",
    method: "POST",
    success: function(data) {
      var rowCount = $('#menu_table_data').html(data).find('tr').length;
    }
  });
}
</code>```

Body:
I am getting table data from ajax response like this :

function fetch_data(){
  $.ajax({
    url: "menu_table.php",
    method: "POST",
    success: function(data) {
      $('#menu_table_data').html(data);
    }
  });
}

fetch_data();

Table:

      ID
      Name
      Price
      Type
      Image
      Description
      Instructions
      Ingredients
      Warnings
      Storage
      Size
      Edit
      Delete

How do I count total number of rows from ajax response?

How can I create a search field to search from this table?

menu_table.php:

while($data = mysqli_fetch_array($search))
{
$output .= '
'.$data['id'].'

'.$data['name'].'

            '.$data['price'].'
            '.$data['type'].'

'.$data['description'].'

'.$data['cooking_instructions'].'

'.$data['ingredients'].'

'.$data['allergen_warnings'].'

            '.$data['storage_instructions'].'
            '.$data['case_size'].'	   <a class="btn btn-primary glyphicon glyphicon-edit" role="button" onclick="EditModal(`'.$data['id'].'`,`'.$data['name'].'`,`'.$data['price'].'`,`'.$data['description'].'`,`'.$data['type'].'`,`'.$data['cooking_instructions'].'`,`'.$data['ingredients'].'`,`'.$data['allergen_warnings'].'`,`'.$data['storage_instructions'].'`,`'.$data['case_size'].'`,`'."uploaded_images/".$data['image'].'`)">
';}

Body:
Assuming that the response to the request is the plain HTML in your second code example, you can put it in a jQuery selector, then find() the tr elements in it, like this:

function fetch_data(){
  $.ajax({
    url: "menu_table.php",
    method: "POST",
    success: function(data) {
      var rowCount = $('#menu_table_data').html(data).find('tr').length;
    }
  });
}


问:
Angular 2 Jax-RS with GET faster than POST
I have a REST application using Jax-RS and Angular 2, Apache 8.5 and Postgres database using Hibernate.

The problem is when I save a new object, the GET from my list runs before the POST run completely. Here are the codes.

tabela-servicos.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { Servico } from '../servico';
import { CrudServicosService } from '../crud-servicos.service';

@Component({
  selector: 'app-tabela-servicos',
  templateUrl: './tabela-servicos.component.html',
  styleUrls: ['./tabela-servicos.component.css']
})
export class TabelaServicosComponent implements OnInit {

  titulo = "Tabela de Serviços";
  servicos: Servico[] = [];

  constructor(private servicoService: CrudServicosService) {

  }

  ngOnInit() {
    console.log('called ngOnInit')
    this.servicoService.getServicos()
        .subscribe(s => {
          console.log(s);
            this.servicos = s;
        }, erro => console.log(erro));
  }

  remover(servico: Servico){
    this.servicoService.removerServico(servico)
    .subscribe(()  => {
      let novosServicos = this.servicos.slice(0);
      let indice = novosServicos.indexOf(servico);
      novosServicos.splice(indice, 1);
      this.servicos = novosServicos;
    });
  }
}
</code>```

form-servicos.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { CrudServicosService } from '../../app/crud-servicos.service';
import { Servico } from '../../app/servico';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-form-servicos',
  templateUrl: './form-servicos.component.html',
  styleUrls: ['./form-servicos.component.css']
})
export class FormServicosComponent implements OnInit {

  titulo = "Cadastro de Servicos";
  servico: Servico;
  codigo;

  constructor(private servicoService: CrudServicosService,
              private router: Router,
              private rota:ActivatedRoute) { }

  ngOnInit() {
    this.codigo = this.rota.snapshot.params['cod'];
    if(isNaN(this.codigo)){
      this.servico = new Servico();
    } else {
      this.servico = Object.assign({},
          this.servicoService.getServicoPorCodigo(this.codigo));
    }
  }

  salvarServico(){
    if(isNaN(this.codigo)){
      this.servicoService.adicionarServico(this.servico)
    } else {
      this.servicoService.atualizaServico(this.codigo, this.servico);
    }
//    console.log("waiting 2 seconds to return page list...");
//    setTimeout(()=>{
      this.router.navigate(['/lista']);
 //   },2000);
  }

  cancelar(){
    this.router.navigate(['/lista']);
  }
}
</code>```

ServicoResource.java

```<code>package resource;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.google.gson.Gson;

import dao.ServicoDAO;
import model.Servico;

@Path("servico")
public class ServicoResource {

    private static ServicoDAO servicoDao = new ServicoDAO();

    @GET
    @Path("servicos")
    @Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
    public Response test() {
        List<Servico> serv = servicoDao.getList();
        System.out.println("GET Objectos from Jax-RS");
        System.out.println("");
        return Response.ok(serv).build();
    }

    @Path("servicos/delete/{id}")
    @DELETE
    public Response removeProduto(@PathParam("id") long id){
        System.out.println("DELETE Object ID: " + id + " Jax-RS ");
        System.out.println("");
        servicoDao.remover(id);
        return Response.ok().build();
    }

    @POST//consume o objeto enviado pro back-end
    @Consumes(MediaType.APPLICATION_JSON)
    public Response adiciona(String conteudo){
        Gson gson = new Gson();
        Servico s = gson.fromJson(conteudo, Servico.class);
        servicoDao.salvar(s);
        System.out.println("POST Object Jax-RS");
        System.out.println("");
        return Response.status(200).build();
    }
}
</code>```

When I reload the list page, after the saved object, it appears.
When I use the code below in the form-servicos.component.ts class, it works, but I know this is a bad practice.

```<code> console.log ("waiting 2 seconds to return page list ...");
 setTimeout (() => {
   This.router.navigate (['/ list']);
}, 2000);
</code>```

Does anyone know how to resolve this problem from the list being requested before the object is persisted ???

答:
(Posted on behalf of the OP).

This was solved.

```<code>adicionarServico(servico: Servico){
    console.log("Called persist POST "+JSON.stringify(servico));
    return this.http.post(this.baseUrl + '/servico', JSON.stringify(servico), {headers: this.headers});
  }
</code>```

I changed my crud-service.ts to return an Observable < Responde > and using it in:

```<code>salvarServico(){
    this.servicoService.adicionarServico(this.servico)
      .subscribe(() => {
        console.log("Saved Success");
        this.router.navigate(['/lista']);
      });
  }
</code>```

Body:
I have a REST application using Jax-RS and Angular 2, Apache 8.5 and Postgres database using Hibernate.

The problem is when I save a new object, the GET from my list runs before the POST run completely. Here are the codes.

tabela-servicos.component.ts

import { Component, OnInit } from '@angular/core';
import { Servico } from '../servico';
import { CrudServicosService } from '../crud-servicos.service';

@Component({
  selector: 'app-tabela-servicos',
  templateUrl: './tabela-servicos.component.html',
  styleUrls: ['./tabela-servicos.component.css']
})
export class TabelaServicosComponent implements OnInit {

  titulo = "Tabela de Serviços";
  servicos: Servico[] = [];

  constructor(private servicoService: CrudServicosService) {

  }

  ngOnInit() {
    console.log('called ngOnInit')
    this.servicoService.getServicos()
        .subscribe(s => {
          console.log(s);
            this.servicos = s;
        }, erro => console.log(erro));
  }

  remover(servico: Servico){
    this.servicoService.removerServico(servico)
    .subscribe(()  => {
      let novosServicos = this.servicos.slice(0);
      let indice = novosServicos.indexOf(servico);
      novosServicos.splice(indice, 1);
      this.servicos = novosServicos;
    });
  }
}

form-servicos.component.ts

import { Component, OnInit } from '@angular/core';
import { CrudServicosService } from '../../app/crud-servicos.service';
import { Servico } from '../../app/servico';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-form-servicos',
  templateUrl: './form-servicos.component.html',
  styleUrls: ['./form-servicos.component.css']
})
export class FormServicosComponent implements OnInit {

  titulo = "Cadastro de Servicos";
  servico: Servico;
  codigo;

  constructor(private servicoService: CrudServicosService,
              private router: Router,
              private rota:ActivatedRoute) { }

  ngOnInit() {
    this.codigo = this.rota.snapshot.params['cod'];
    if(isNaN(this.codigo)){
      this.servico = new Servico();
    } else {
      this.servico = Object.assign({},
          this.servicoService.getServicoPorCodigo(this.codigo));
    }
  }

  salvarServico(){
    if(isNaN(this.codigo)){
      this.servicoService.adicionarServico(this.servico)
    } else {
      this.servicoService.atualizaServico(this.codigo, this.servico);
    }
//    console.log("waiting 2 seconds to return page list...");
//    setTimeout(()=>{
      this.router.navigate(['/lista']);
 //   },2000);
  }

  cancelar(){
    this.router.navigate(['/lista']);
  }
}

ServicoResource.java

package resource;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.google.gson.Gson;

import dao.ServicoDAO;
import model.Servico;

@Path("servico")
public class ServicoResource {

    private static ServicoDAO servicoDao = new ServicoDAO();

    @GET
    @Path("servicos")
    @Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
    public Response test() {
        List<Servico> serv = servicoDao.getList();
        System.out.println("GET Objectos from Jax-RS");
        System.out.println("");
        return Response.ok(serv).build();
    }

    @Path("servicos/delete/{id}")
    @DELETE
    public Response removeProduto(@PathParam("id") long id){
        System.out.println("DELETE Object ID: " + id + " Jax-RS ");
        System.out.println("");
        servicoDao.remover(id);
        return Response.ok().build();
    }

    @POST//consume o objeto enviado pro back-end
    @Consumes(MediaType.APPLICATION_JSON)
    public Response adiciona(String conteudo){
        Gson gson = new Gson();
        Servico s = gson.fromJson(conteudo, Servico.class);
        servicoDao.salvar(s);
        System.out.println("POST Object Jax-RS");
        System.out.println("");
        return Response.status(200).build();
    }
}

When I reload the list page, after the saved object, it appears.
When I use the code below in the form-servicos.component.ts class, it works, but I know this is a bad practice.

 console.log ("waiting 2 seconds to return page list ...");
 setTimeout (() => {
   This.router.navigate (['/ list']);
}, 2000);

Does anyone know how to resolve this problem from the list being requested before the object is persisted ???

Body:
(Posted on behalf of the OP).

This was solved.

adicionarServico(servico: Servico){
    console.log("Called persist POST "+JSON.stringify(servico));
    return this.http.post(this.baseUrl + '/servico', JSON.stringify(servico), {headers: this.headers});
  }

I changed my crud-service.ts to return an Observable < Responde > and using it in:

salvarServico(){
    this.servicoService.adicionarServico(this.servico)
      .subscribe(() => {
        console.log("Saved Success");
        this.router.navigate(['/lista']);
      });
  }


问:
Formatting JSON data and displaying in a PHP for loop
I have some form data which I'm saving in JSON format using jQuery (this is all working fine).

But I then want to take the JSON data and display it in a PHP for loop. This is where I'm having trouble as jQuery's serializeArray and JSON.stringify just adds each form value in one bit chunk e.g.

```<code>check in, check out, room, adults, children, check in, check out, room, adults, children, check in, check out, room, adults, children
</code>```

But I want to separate each room e.g.

```<code>(Room 1) check in, check out, room, adults, children
(Room 2) check in, check out, room, adults, children
(Room 3) check in, check out, room, adults, children
</code>```

JSFiddle of how the form data is created (everything working fine): https://jsfiddle.net/kuohhm2q/

PHP I'm using to try a display JSON data in for loop (not working):

```<code><?php

$json_data = '[{"name":"check_in","value":"07/11/2017"},{"name":"check_out","value":"07/26/2017"},{"name":"room_type","value":"option_1"},{"name":"adults","value":"2"},{"name":"children","value":"3"},{"name":"check_in","value":"07/27/2017"},{"name":"check_out","value":"07/29/2017"},{"name":"room_type","value":"option_2"},{"name":"adults","value":"3"},{"name":"children","value":"2"}]';

$data = json_decode($json_data, true);

//print_r($data);

foreach($data as $key => $val) { ?>

    <?php echo $key; ?>

<?php } ?>
</code>```

答:
Use json_decode to read the json value and you can use array_slice to keep the first two elements.Try this one:

```<code><?php

$json_data = '[{"name":"check_in","value":"07/11/2017"},{"name":"check_out","value":"07/26/2017"},{"name":"room_type","value":"option_1"},{"name":"adults","value":"2"},{"name":"children","value":"3"},{"name":"check_in","value":"07/27/2017"},{"name":"check_out","value":"07/29/2017"},{"name":"room_type","value":"option_2"},{"name":"adults","value":"3"},{"name":"children","value":"2"}]';

$data = json_decode($json_data);

foreach(array_slice($data,0,2) as $key => $val) {

 echo $val->name."-".$val->value."<br>";

} ?>
</code>```

check the Output here

Body:
I have some form data which I'm saving in JSON format using jQuery (this is all working fine).

But I then want to take the JSON data and display it in a PHP for loop. This is where I'm having trouble as jQuery's serializeArray and JSON.stringify just adds each form value in one bit chunk e.g.

check in, check out, room, adults, children, check in, check out, room, adults, children, check in, check out, room, adults, children

But I want to separate each room e.g.

(Room 1) check in, check out, room, adults, children
(Room 2) check in, check out, room, adults, children
(Room 3) check in, check out, room, adults, children

JSFiddle of how the form data is created (everything working fine): https://jsfiddle.net/kuohhm2q/

PHP I'm using to try a display JSON data in for loop (not working):

<?php

$json_data = '[{"name":"check_in","value":"07/11/2017"},{"name":"check_out","value":"07/26/2017"},{"name":"room_type","value":"option_1"},{"name":"adults","value":"2"},{"name":"children","value":"3"},{"name":"check_in","value":"07/27/2017"},{"name":"check_out","value":"07/29/2017"},{"name":"room_type","value":"option_2"},{"name":"adults","value":"3"},{"name":"children","value":"2"}]';

$data = json_decode($json_data, true);

//print_r($data);

foreach($data as $key => $val) { ?>

    <?php echo $key; ?>

<?php } ?>

Body:
Use json_decode to read the json value and you can use array_slice to keep the first two elements.Try this one:

<?php

$json_data = '[{"name":"check_in","value":"07/11/2017"},{"name":"check_out","value":"07/26/2017"},{"name":"room_type","value":"option_1"},{"name":"adults","value":"2"},{"name":"children","value":"3"},{"name":"check_in","value":"07/27/2017"},{"name":"check_out","value":"07/29/2017"},{"name":"room_type","value":"option_2"},{"name":"adults","value":"3"},{"name":"children","value":"2"}]';

$data = json_decode($json_data);

foreach(array_slice($data,0,2) as $key => $val) {

 echo $val->name."-".$val->value."<br>";

} ?>

check the Output here


问:
Executing an application after a period of time
I'm writing a small app that needs to be executed once a week.
I could write it as a service that runs constantly but only executes the task that I need it to once a week, but that seems like overkill.

Is there another way of executing an application once every x period of time?
I'm looking for a solution that doesn't involve user interaction.

答:
If you need full control on the process (result values, parameters to be provided, etc), I would suggest you to create your own task scheduler, where you can use the cron algorithm to schedule the time you want execute your task.
I know it may sounds overkill to create a service to run once a week, but if you make a generic scheduler, you will be able to reuse your schedule for other purposes.

I created this scheduler in the past, and it has been used for years in production. I implemented the cron algorithm in .Net, based in the open source algorithm that one developer (Artif Aziz) wrote. Check out my blog for more information on this:

CronTab schedule parser algorithm

If you think in a higher level (enterprise level), you could consider buying Control-M, one of the most powerful scheduler tools I have ever used, however it is quite expensive.

Cheers!

Roberto.


问:
Angular Unknown Provider [$injector:unpr] Unknown provider
It's working locally (localhost:3000) but not when I deploy to heroku
( https://get-started.herokuapp.com/ ). I get a jquery error saying

```<code>[$injector:unpr] Unknown provider
</code>```

this is the main

```<code>function config($locationProvider, $urlRouterProvider) {
  'ngInject';

  $locationProvider.html5Mode(true);

  $urlRouterProvider.otherwise('/');
}
</code>```

home

```<code>function config($stateProvider) {
  'ngInject';

  $stateProvider
  .state('home', {
    url: '/',
    template: '<home></home>'
  });
}
</code>```

about

```<code>function config($stateProvider) {
  'ngInject';

  $stateProvider
  .state('about', {
    url: '/about',
    template: '<about></about>'
  });
}
</code>```

答:
It's happen because of minification. When you minify, that $scope variable may be called something totally different, like a, and Angular won't know what that means -- it uses the strings to solve that issue

You need smth like this :

```<code>app.controller('HeadMenuController', ['$scope', '$log',
    function($scope, $log){...}
]);
</code>```

This way, Angular can still match the dependencies up

Body:
It's working locally (localhost:3000) but not when I deploy to heroku
( https://get-started.herokuapp.com/ ). I get a jquery error saying

[$injector:unpr] Unknown provider

this is the main

function config($locationProvider, $urlRouterProvider) {
  'ngInject';

  $locationProvider.html5Mode(true);

  $urlRouterProvider.otherwise('/');
}

home

function config($stateProvider) {
  'ngInject';

  $stateProvider
  .state('home', {
    url: '/',
    template: '<home></home>'
  });
}

about

function config($stateProvider) {
  'ngInject';

  $stateProvider
  .state('about', {
    url: '/about',
    template: '<about></about>'
  });
}

Body:
It's happen because of minification. When you minify, that $scope variable may be called something totally different, like a, and Angular won't know what that means -- it uses the strings to solve that issue

You need smth like this :

app.controller('HeadMenuController', ['$scope', '$log',
    function($scope, $log){...}
]);

This way, Angular can still match the dependencies up


问:
Why does my scrapy ItemLoader fail?
I have a very simple web spider to crawl for some football team data. So far I'm just interested in some metadata on the top of the page.

I tried to use scrapy ItemLoader to retrieve data from the page. But it doesn't work. Only I can get the first field. What did I miss?

```<code>ft = FootballTeamItem()
    sel = Selector(text = response.text)
    headerLoader = ItemLoader(ft,  selector= sel)
    # headerLoader.add_xpath('name',  '//h2[@class="team-logo"]/strong/text()')
    headerLoader.add_xpath('league','//div[contains(@class, "intro-con team-con")]/table/tbody/tr[1]/td[1]/a/text()')
    headerLoader.add_xpath('coach', '//div[contains(@class, "intro-con team-con")]/table/tbody/tr[1]/td[2]/text()')
    headerLoader.add_xpath('city',  '//div[contains(@class, "intro-con team-con")]/table/tbody/tr[1]/td[3]/text()')
    headerLoader.add_xpath('start', '//div[contains(@class, "intro-con team-con")]/table/tbody/tr[2]/td[1]/text()')
    headerLoader.add_xpath('court', '//div[contains(@class, "intro-con team-con")]/table/tbody/tr[2]/td[2]/text()')
    headerLoader.load_item()
</code>```

I tried different ways to construct ItemLoader, with response directly or like this, using a selector instance. But it still didn't work.
The interesting thing is that the code segment runs well without scrapy. But it always fail while running within a scrapy project.

答: You need a period at the beginning of your xpath to treat it as relative to you 'sel' element.</p>

Title: Why does my scrapy ItemLoader fail?

Body:
I have a very simple web spider to crawl for some football team data. So far I'm just interested in some metadata on the top of the page.

I tried to use scrapy ItemLoader to retrieve data from the page. But it doesn't work. Only I can get the first field. What did I miss?

ft = FootballTeamItem()
    sel = Selector(text = response.text)
    headerLoader = ItemLoader(ft,  selector= sel)
    # headerLoader.add_xpath('name',  '//h2[@class="team-logo"]/strong/text()')
    headerLoader.add_xpath('league','//div[contains(@class, "intro-con team-con")]/table/tbody/tr[1]/td[1]/a/text()')
    headerLoader.add_xpath('coach', '//div[contains(@class, "intro-con team-con")]/table/tbody/tr[1]/td[2]/text()')
    headerLoader.add_xpath('city',  '//div[contains(@class, "intro-con team-con")]/table/tbody/tr[1]/td[3]/text()')
    headerLoader.add_xpath('start', '//div[contains(@class, "intro-con team-con")]/table/tbody/tr[2]/td[1]/text()')
    headerLoader.add_xpath('court', '//div[contains(@class, "intro-con team-con")]/table/tbody/tr[2]/td[2]/text()')
    headerLoader.load_item()

I tried different ways to construct ItemLoader, with response directly or like this, using a selector instance. But it still didn't work.
The interesting thing is that the code segment runs well without scrapy. But it always fail while running within a scrapy project.


问:
How to force creating the DocumentsByEntityName index for a entity in RavenDB?
For DB migrations I use StreamQuery with DocumentsByEntityName index. But for some entities the index does not exist I get an exception:

Could not find index named: Raven/DocumentsByEntityName

After creating the DB the index is not yet created, but as soon as I open RavenStudio the index is created.

My code:

```<code>var databaseCommands = this.DocumentStore.DatabaseCommands.ForDatabase(database);
var query = new IndexQuery { Query = "Tag:" + "MyEntities"};
using (var queryResultStream = databaseCommands.StreamQuery("Raven/DocumentsByEntityName", query, out QueryHeaderInformation _))
{
    ...
</code>```

How can I check if the index exists before executing the StreamQuery?

Or can I force the creation of that index?

答:
Calling

```<code>new RavenDocumentsByEntityName().Execute(databaseCommands, new DocumentConvention());
</code>```

before querying the index solved the problem.

Body:
For DB migrations I use StreamQuery with DocumentsByEntityName index. But for some entities the index does not exist I get an exception:

Could not find index named: Raven/DocumentsByEntityName

After creating the DB the index is not yet created, but as soon as I open RavenStudio the index is created.

My code:

var databaseCommands = this.DocumentStore.DatabaseCommands.ForDatabase(database);
var query = new IndexQuery { Query = "Tag:" + "MyEntities"};
using (var queryResultStream = databaseCommands.StreamQuery("Raven/DocumentsByEntityName", query, out QueryHeaderInformation _))
{
    ...

How can I check if the index exists before executing the StreamQuery?

Or can I force the creation of that index?

Body:
Calling

new RavenDocumentsByEntityName().Execute(databaseCommands, new DocumentConvention());

before querying the index solved the problem.


答:
Just use the Selector.length to get row count. and even you don't need to initialize a variable if u directly call the $('#menu_table_data > tr').length and that's it.
EDITED

```<code>$('#menu_table_data tr').length;
</code>```

EDIT

```<code> $output .= '<tr><td>'.$data['id'].'</td>
        <td><div class="text_area">'.$data['name'].'</div></td>
        <td>'.$data['price'].'</td>
        <td>'.$data['type'].'</td>
        <td><div id="div_image">
        <img src="uploaded_images/'.$data['image'].'" class="thumbnail" height="100" width="80" /></div></td>
        <td><div class="text_area">'.$data['description'].'</div></td>
        <td><div class="text_area">'.$data['cooking_instructions'].'<div></td>
        <td><div class="text_area">'.$data['ingredients'].'</div></td>
        <td><div class="text_area">'.$data['allergen_warnings'].'</div></td>
        <td>'.$data['storage_instructions'].'</td>
        <td>'.$data['case_size'].'</td>   <td><a class="btn btn-primary glyphicon glyphicon-edit" role="button" onclick="EditModal(`'.$data['id'].'`,`'.$data['name'].'`,`'.$data['price'].'`,`'.$data['description'].'`,`'.$data['type'].'`,`'.$data['cooking_instructions'].'`,`'.$data['ingredients'].'`,`'.$data['allergen_warnings'].'`,`'.$data['storage_instructions'].'`,`'.$data['case_size'].'`,`'."uploaded_images/".$data['image'].'`)"></a></td>   <td><a class="btn btn-danger glyphicon glyphicon-remove" role="button" onclick="DeleteModal('.$data['id'].')"></a></td></tr>';
</code>```

use this..

Title: How to count total number of table rows from ajax response? How to create search field for that table?

Body:
Just use the Selector.length to get row count. and even you don't need to initialize a variable if u directly call the $('#menu_table_data > tr').length and that's it.
EDITED

$('#menu_table_data tr').length;

EDIT

 $output .= '<tr><td>'.$data['id'].'</td>
        <td><div class="text_area">'.$data['name'].'</div></td>
        <td>'.$data['price'].'</td>
        <td>'.$data['type'].'</td>
        <td><div id="div_image">
        <img src="uploaded_images/'.$data['image'].'" class="thumbnail" height="100" width="80" /></div></td>
        <td><div class="text_area">'.$data['description'].'</div></td>
        <td><div class="text_area">'.$data['cooking_instructions'].'<div></td>
        <td><div class="text_area">'.$data['ingredients'].'</div></td>
        <td><div class="text_area">'.$data['allergen_warnings'].'</div></td>
        <td>'.$data['storage_instructions'].'</td>
        <td>'.$data['case_size'].'</td>   <td><a class="btn btn-primary glyphicon glyphicon-edit" role="button" onclick="EditModal(`'.$data['id'].'`,`'.$data['name'].'`,`'.$data['price'].'`,`'.$data['description'].'`,`'.$data['type'].'`,`'.$data['cooking_instructions'].'`,`'.$data['ingredients'].'`,`'.$data['allergen_warnings'].'`,`'.$data['storage_instructions'].'`,`'.$data['case_size'].'`,`'."uploaded_images/".$data['image'].'`)"></a></td>   <td><a class="btn btn-danger glyphicon glyphicon-remove" role="button" onclick="DeleteModal('.$data['id'].')"></a></td></tr>';

use this..


答:
How do I count total number of rows from ajax response?

You could use the JQuery .length function after successfully loading the tbody contents.

```<code>function fetch_data(){
  $.ajax({
    url: "menu_table.php",
    method: "POST",
    success: function(data) {
      $('#menu_table_data').html(data);
      var no_of_rows = $('#menu_table_data').find('tr').length;
    }
  });
}
</code>```

Body:
How do I count total number of rows from ajax response?

You could use the JQuery .length function after successfully loading the tbody contents.

function fetch_data(){
  $.ajax({
    url: "menu_table.php",
    method: "POST",
    success: function(data) {
      $('#menu_table_data').html(data);
      var no_of_rows = $('#menu_table_data').find('tr').length;
    }
  });
}


问:
Android ListView doesn't (re) populate on "back"
I have a simple Android app - a dictionary. I am using a ListView to populate the dictionary words on the main glossary screen. If a word is touched a new intent launches a wordscreen that shows the word and the definition. The problem is that if I hit "back" to go from the wordscreen back to the glossary the ListView does not populate.

I am using onStop() to close the database cursor when moving from the glossary screen, and onRestart() to open the cursor and (I thought) to populate the ListView. It doesn't seem to be working.

One important thing, if after going back to the glossary screen from the word screen (and getting a black screen with no ListView) I change the orientation of the app the ListView populates.

I thought that pressing "back" would always cause onRestart() to execute. Why would pressing back NOT cause the ListView to populate, but changing the orientation does?

Thanks

答:
Use onPause and onResume instead. Changing orientation causes your activity to be destroyed and restarted, navigating to another activity causes your activity to be paused. When you click back it's resumed.

Check this out for an overview - http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle


问:
implementing drag and resize on the same element
I am trying ti implement resize and drag on the same element. Check this out:

http://jsfiddle.net/Lo8n75dg/

my code so far:

```<code>   $('#dragbar').mousedown(function(e){
        e.preventDefault();
        $(document).mousemove(function(e){
          //$('#position').html(e.pageX +', '+ e.pageY);
          $('#sidebar').css("width",e.pageX+2-100);
          $('#main').css("left",e.pageX+2);
       });
    });

   $(document).mouseup(function(e){
       $(document).unbind('mousemove');
   });

      $('#sidebar').mousedown(function(e){
        e.preventDefault();
        $(document).mousemove(function(e){
          //$('#position').html(e.pageX +', '+ e.pageY);
          $('#sidebar').css("margin-left",e.pageX-100-$('#sidebar').offset().left);
          //$('#main').css("left",e.pageX+2);
       });
    });
</code>```

The idea is that if mouse down happened on the black line, the code preforms resize. If mouse down is on red rectangle, the code make horizontal drag.

This 2 event currently conflict, that is why you see flickering. Any idea how do I fix that?

UPDATE:
http://jsfiddle.net/Lo8n75dg/2/
I added e.stopPropagation() which does part of the trick. There is unfortunately still a lot of flickering going on for reasons unknown to me.

答:
To prevent mousemove conflict you can store which block is currently being dragged.

```<code>const resizebar = {
  node: wrap.querySelector('.resizebar'),
  isDragged: false,
}
const dragbar = {
  node: document.querySelector('.dragbar'),
  width: 200,
  x: 0,
  isDragged: false,
}
</code>```

Also I think that flickering in your code is caused by calculation of margin-left

I tried making pretty much same block in native js -
 https://jsfiddle.net/Ellaylone/48h5L8t1/

Body:
I am trying ti implement resize and drag on the same element. Check this out:

http://jsfiddle.net/Lo8n75dg/

my code so far:

   $('#dragbar').mousedown(function(e){
        e.preventDefault();
        $(document).mousemove(function(e){
          //$('#position').html(e.pageX +', '+ e.pageY);
          $('#sidebar').css("width",e.pageX+2-100);
          $('#main').css("left",e.pageX+2);
       });
    });

   $(document).mouseup(function(e){
       $(document).unbind('mousemove');
   });

      $('#sidebar').mousedown(function(e){
        e.preventDefault();
        $(document).mousemove(function(e){
          //$('#position').html(e.pageX +', '+ e.pageY);
          $('#sidebar').css("margin-left",e.pageX-100-$('#sidebar').offset().left);
          //$('#main').css("left",e.pageX+2);
       });
    });

The idea is that if mouse down happened on the black line, the code preforms resize. If mouse down is on red rectangle, the code make horizontal drag.

This 2 event currently conflict, that is why you see flickering. Any idea how do I fix that?

UPDATE:
http://jsfiddle.net/Lo8n75dg/2/
I added e.stopPropagation() which does part of the trick. There is unfortunately still a lot of flickering going on for reasons unknown to me.

Body:
To prevent mousemove conflict you can store which block is currently being dragged.

const resizebar = {
  node: wrap.querySelector('.resizebar'),
  isDragged: false,
}
const dragbar = {
  node: document.querySelector('.dragbar'),
  width: 200,
  x: 0,
  isDragged: false,
}

Also I think that flickering in your code is caused by calculation of margin-left

I tried making pretty much same block in native js -
 https://jsfiddle.net/Ellaylone/48h5L8t1/


问:
I am creating a Framework in Objective C, Which needs a good constructor pattern
I am creating a Framework in objective C , which has multiple features, where all the features are need to be initialized while instatiating the library instance, where I am also giving flexibility of providing alternate implementation to any of the feature, to acheive this I am using builder pattern as follow, My question is, Which better Design pattern suits here? Or how Can I improve performace/Memory usage, Please suggest me some pattern for this problem</p>

```<code>-(instancetype)initWithBuilder:(LibraryBuilder *)builder {
    self = [super init];
    if (self) {
        // allocate feature1 instance
        if (builder.feature1)
            self.feature1 = builder.feature1;
        else
            self.feature1 = [[InterfaceA alloc] initWithLib:self];

        // allocate feature2 instance
        if (builder.feature2)
            self.feature2 = builder.feature2;
        else
            self.feature2 = [[InterfaceB alloc] init];

        // allocate App Configuration instance
        if (builder.feature3)
            self.feature3 = builder.feature3;
        else
            self.feature3 = [[InterfaceC alloc] init];

        // allocate feature4 instance
        if (builder.feature4)
            self.feature4 = builder.feature4;
        else
            self.feature4 = [[InterfaceD alloc] init];

        // allocate feature5 instance
        if (builder.feature5)
            self.feature5 = builder.feature5;
        else
            self.feature5 = [[InterfaceE alloc] init];

        // allocate feature6 instance
        if (builder.feature6)
            self.feature6 = builder.feature6;
        else
            self.feature6 = [[InterfaceF alloc] init];

        // allocate feature7 instance
        if (builder.feature7)
            self.feature7 = builder.feature7;
        else
            self.feature7 = [[InterfaceG alloc] init];

        // allocate feature8 instance
        if (builder.feature8)
            self.feature8 = builder.feature8;
        else
            self.feature8 = [[InterfaceH alloc] init];

 return self;
}
</code>```

答:
Assuming that I understood you correctly (Doesn't any answer assume this?), it seems to be easier in Objective-C.

First of all yo do not need a separate class LibraryBuilder. Simply use a dictionary.

Secondly you can take advantage out of KVC and the dynamic binding of Objective-C.

A. Create a look-up for all features, i. e. in a class method (or +initialize or whatever)

```<code>+(NSDictionary*)defaultFeatureClasses
{
  return
  @{
    @"featureName1" : [FeatureClass1 class],
    @"featureName2" : [FeatureClass2 class],
    // …
    @"featureNameN" : [FeatureClassN class],
  };
});
</code>```

If the class name correspondents to the feature name, one could simplify that, but this does not look like a big deal.

Next, write an initializer, that takes a feature dictionary:

```<code>- (instancetype)initWithFeatureSet:(NSDictionary*)features
{
  self = [super init];
  if (self)
  {
    [defaultClasses enumerateKeysAndObjectsUsingBlock:
    ^(NSString *key, Class featureClass, BOOL *stop)
    {
      id feature = features[key];
      if (feature==nil)
      {
        feature = [featureClass new];
      }
      [self setValue:feature forKey:key];
    }

  }
  return self;
}
</code>```

Then you can easily set-up a library

```<code> … [[Library alloc] initWithFeatures:
 @{
   @"Feature1" : myFeaatureA,
   @"Feature2" : anotherCustomFeature,
 }];
</code>```

To expand the features you only have to change a single line in a single method.

Body:
I am creating a Framework in objective C , which has multiple features, where all the features are need to be initialized while instatiating the library instance, where I am also giving flexibility of providing alternate implementation to any of the feature, to acheive this I am using builder pattern as follow, My question is, Which better Design pattern suits here? Or how Can I improve performace/Memory usage, Please suggest me some pattern for this problem

-(instancetype)initWithBuilder:(LibraryBuilder *)builder {
    self = [super init];
    if (self) {
        // allocate feature1 instance
        if (builder.feature1)
            self.feature1 = builder.feature1;
        else
            self.feature1 = [[InterfaceA alloc] initWithLib:self];

        // allocate feature2 instance
        if (builder.feature2)
            self.feature2 = builder.feature2;
        else
            self.feature2 = [[InterfaceB alloc] init];

        // allocate App Configuration instance
        if (builder.feature3)
            self.feature3 = builder.feature3;
        else
            self.feature3 = [[InterfaceC alloc] init];

        // allocate feature4 instance
        if (builder.feature4)
            self.feature4 = builder.feature4;
        else
            self.feature4 = [[InterfaceD alloc] init];

        // allocate feature5 instance
        if (builder.feature5)
            self.feature5 = builder.feature5;
        else
            self.feature5 = [[InterfaceE alloc] init];

        // allocate feature6 instance
        if (builder.feature6)
            self.feature6 = builder.feature6;
        else
            self.feature6 = [[InterfaceF alloc] init];

        // allocate feature7 instance
        if (builder.feature7)
            self.feature7 = builder.feature7;
        else
            self.feature7 = [[InterfaceG alloc] init];

        // allocate feature8 instance
        if (builder.feature8)
            self.feature8 = builder.feature8;
        else
            self.feature8 = [[InterfaceH alloc] init];

 return self;
}

Body:
Assuming that I understood you correctly (Doesn't any answer assume this?), it seems to be easier in Objective-C.

First of all yo do not need a separate class LibraryBuilder. Simply use a dictionary.

Secondly you can take advantage out of KVC and the dynamic binding of Objective-C.

A. Create a look-up for all features, i. e. in a class method (or +initialize or whatever)

+(NSDictionary*)defaultFeatureClasses
{
  return
  @{
    @"featureName1" : [FeatureClass1 class],
    @"featureName2" : [FeatureClass2 class],
    // …
    @"featureNameN" : [FeatureClassN class],
  };
});

If the class name correspondents to the feature name, one could simplify that, but this does not look like a big deal.

Next, write an initializer, that takes a feature dictionary:

- (instancetype)initWithFeatureSet:(NSDictionary*)features
{
  self = [super init];
  if (self)
  {
    [defaultClasses enumerateKeysAndObjectsUsingBlock:
    ^(NSString *key, Class featureClass, BOOL *stop)
    {
      id feature = features[key];
      if (feature==nil)
      {
        feature = [featureClass new];
      }
      [self setValue:feature forKey:key];
    }

  }
  return self;
}

Then you can easily set-up a library

 … [[Library alloc] initWithFeatures:
 @{
   @"Feature1" : myFeaatureA,
   @"Feature2" : anotherCustomFeature,
 }];

To expand the features you only have to change a single line in a single method.


答:
Use CSS3's :not() together with @page:

```<code>@page :not(:first) {
}
</code>```

If you need better browser compatibility, Donut's solution of styling everything then "undoing" them for :first also works (relying on specificity/the cascade).

```<code>@page {
    /* Styles for everything but the first page */
}

@page :first {
    /* Override with perhaps your stylesheet's defaults */
}
</code>```

Title: Any way to css select all EXCEPT the first page?

Body: I just found the CSS @page directive, and using it with :first to apply CSS to the first page of an html print. Is there any way to go the opposite, and apply CSS to all pages except the first?

Body:
Use CSS3's :not() together with @page:

@page :not(:first) {
}

If you need better browser compatibility, Donut's solution of styling everything then "undoing" them for :first also works (relying on specificity/the cascade).

@page {
    /* Styles for everything but the first page */
}

@page :first {
    /* Override with perhaps your stylesheet's defaults */
}

ContentLicense: CC BY-SA 4.0