问:
ARGV loop skips if statement in Ruby
In my script I use ARGV stream to get command-line arguments. There is a piece of code:

```<code>ARGV.each do|a|
item = JSON.parse(%x{curl -X GET https://puppetdb.ai:8081/pdb/query/v4/facts/#{a} --tlsv1 --interface x.x.x.x --cacert certificate.pem --cert certificate-pem.cer --key certificate-privkey.pem})
  item.each do |h|
     arr << {"name" => h['certname'], "#{a}" => h['value'], "environment" => h['environment']}
  end
end
</code>```

With curl I get some data using puppetdb API. It all works fine, bu I've wanted to add some if statement to print help for script. It looks like that:

```<code>ARGV.each do|a|
  if (a == "help")
    puts "this is help 4 U"
  else
    item = JSON.parse(%x{curl -X GET https://puppetdb.ai:8081/pdb/query/v4/facts/#{a} --tlsv1 --interface x.x.x.x --cacert certificate.pem --cert certificate-pem.cer --key certificate-privkey.pem})
      item.each do |h|
         arr << {"name" => h['certname'], "#{a}" => h['value'], "environment" => h['environment']}
      end
  end
end
</code>```

but the script ignore "help" and fills in "help" argument to curl. Can you help me with this?

答:
Try using .strip! and look at the Ruby String class documentation.

These can be used to clean up the input as you iterate through each argument supplied with the Ruby command. It may be better to just use the ARGV Array as an Array and look at the Ruby Array class documentation to see the methods methods available to you in Ruby when using the array datatype (which is the form ARGVs come in).. Such as substring search using .include?("help"). Using these method documentation early on is critical to understanding the tools that Ruby provides you.

Title: ARGV loop skips if statement in Ruby

Body:
In my script I use ARGV stream to get command-line arguments. There is a piece of code:

ARGV.each do|a|
item = JSON.parse(%x{curl -X GET https://puppetdb.ai:8081/pdb/query/v4/facts/#{a} --tlsv1 --interface x.x.x.x --cacert certificate.pem --cert certificate-pem.cer --key certificate-privkey.pem})
  item.each do |h|
     arr << {"name" => h['certname'], "#{a}" => h['value'], "environment" => h['environment']}
  end
end

With curl I get some data using puppetdb API. It all works fine, bu I've wanted to add some if statement to print help for script. It looks like that:

ARGV.each do|a|
  if (a == "help")
    puts "this is help 4 U"
  else
    item = JSON.parse(%x{curl -X GET https://puppetdb.ai:8081/pdb/query/v4/facts/#{a} --tlsv1 --interface x.x.x.x --cacert certificate.pem --cert certificate-pem.cer --key certificate-privkey.pem})
      item.each do |h|
         arr << {"name" => h['certname'], "#{a}" => h['value'], "environment" => h['environment']}
      end
  end
end

but the script ignore "help" and fills in "help" argument to curl. Can you help me with this?


来源: stackexchange

问:
Online code browser for GitHub
I'm looking for a code navigator that I was using to browse code located on GitHub. It looks like VSCode. It was very simple of use : no signing in, and you just need the url of the GitHub project to view the code, with hypertext links to browse from file to file.</p>

答: Was is Sourcegraph? It appears to be based on VSCode, here's the VSCode repo itself viewed from there:

ContentLicense: CC BY-SA 3.0

Title: Online code browser for GitHub


问:
PHP: is_array on $arr['key'] with non existing 'key'
One of my colleges seem to have an 'undefined index' error on a code I wrote

This code of mine looks like this:

```<code>if ( is_array ($arr['key']))
</code>```

My intention was to check whether $arr has a key named 'key', and if the value of that key is array itself. Should I do instead: if( isset($arr['key']) && is_array ($arr['key'])) ?

Maybe the following is equivavlent:
Let's assume $var is not set. Then, will is_array($var) cause an error or will it just return false?

Thank you

答:
check if it exists first, then if its an array.  Otherwise you will still get the same error.</p>

```<code>if ( isset($arr['key'])) {
    if (is_array ($arr['key']) {

    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
One of my colleges seem to have an 'undefined index' error on a code I wrote

This code of mine looks like this:

if ( is_array ($arr['key']))

My intention was to check whether $arr has a key named 'key', and if the value of that key is array itself. Should I do instead: if( isset($arr['key']) && is_array ($arr['key'])) ?

Maybe the following is equivavlent:
Let's assume $var is not set. Then, will is_array($var) cause an error or will it just return false?

Thank you

Body:
check if it exists first, then if its an array.  Otherwise you will still get the same error.

if ( isset($arr['key'])) {
    if (is_array ($arr['key']) {

    }
}


问:
Cannot find symbol variable activity_main
I am new. Whenever i try to build and run this code this message appears.

Here is the XML code:

```<code>xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.android.justjava.MainActivity">

<TextView
    android:id="@+id/quantity_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="quantity"
    android:textAllCaps="true"
    android:textSize="16sp"
    android:textColor="@android:color/black"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"/>

<TextView
    android:id="@+id/zero_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="0"
    android:layout_below="@+id/quantity_text_view"
    android:textSize="16sp"
    android:textColor="@android:color/black"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"/>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="order"
    android:textAllCaps="true"
    android:layout_below="@+id/zero_text_view"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"
    android:onClick="submitOrder"/>
</code>```

Here is the Java code:

/**  * IMPORTANT: Add your package below. Package name can be found in
  the project's AndroidManifest.xml file.  * This is the package name
  our example uses:  *  * package com.example.android.justjava;   *  */

import android.R; import android.os.Bundle; import
  android.support.v7.app.AppCompatActivity; import android.view.View;
  import android.widget.TextView;

import static com.example.android.justjava.R.id.quantity_text_view;

/**  * This app displays an order form to order coffee.  */ public
  class MainActivity extends AppCompatActivity {

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);
}

/**
 * This method is called when the order button is clicked.
 */
public void submitOrder(View view) {
    display(1);
}

/**
 * This method displays the given quantity value on the screen.
 */
private void display(int number) {
    TextView quantityTextView = (TextView) findViewById(R.id/quantity_text_view);
    quantityTextView.setText("" + number);
} }
</code>```

Here is the pic of the error:

https://i.stack.imgur.com/tlrUi.png

Please Help me

答: provide the file name of the layout exactly.. I think your layout file name is activity_main and not main_activity.</p>

Body:
I am new. Whenever i try to build and run this code this message appears.

Here is the XML code:

xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.android.justjava.MainActivity">

<TextView
    android:id="@+id/quantity_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="quantity"
    android:textAllCaps="true"
    android:textSize="16sp"
    android:textColor="@android:color/black"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"/>

<TextView
    android:id="@+id/zero_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="0"
    android:layout_below="@+id/quantity_text_view"
    android:textSize="16sp"
    android:textColor="@android:color/black"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"/>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="order"
    android:textAllCaps="true"
    android:layout_below="@+id/zero_text_view"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"
    android:onClick="submitOrder"/>

Here is the Java code:

/**  * IMPORTANT: Add your package below. Package name can be found in
  the project's AndroidManifest.xml file.  * This is the package name
  our example uses:  *  * package com.example.android.justjava;   *  */

import android.R; import android.os.Bundle; import
  android.support.v7.app.AppCompatActivity; import android.view.View;
  import android.widget.TextView;

import static com.example.android.justjava.R.id.quantity_text_view;

/**  * This app displays an order form to order coffee.  */ public
  class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);
}

/**
 * This method is called when the order button is clicked.
 */
public void submitOrder(View view) {
    display(1);
}

/**
 * This method displays the given quantity value on the screen.
 */
private void display(int number) {
    TextView quantityTextView = (TextView) findViewById(R.id/quantity_text_view);
    quantityTextView.setText("" + number);
} }

Here is the pic of the error:

https://i.stack.imgur.com/tlrUi.png

Please Help me


问:
Updating Toolstripstatuslabel in Thread of closing form
I have a Order form. Once a order is complete, I use a thread to email the order to the supplier. The Thread is use to prevent the system hanging while the order is exported to pdf and sent.

The Problem: I would like to place an message on the MDIParent Toolstripstatuslabel once the threat completes without error to confirm the order was sent. But I get an error: "System.NullReferenceException: Object reference not set to an instance of an object". Which I could be wrong, refers to the Child windows disposed the toolstripstatuslabel reference on the parent form when it closed, so the threat cant access it anymore. I know the easy solution would be to use a MessageBox to confirm all went good and well...but why make it easy if you can do it elegant?

So my question: How can I reference a control in the parent form from the threat? I tried looking at invoke, but not sure how to implement it or if it is actually the correct direction.

EDIT:

My code from the childform

```<code>public partial class frm_n_order : Form
{
     .
     .

private void bProcess_Click(object sender, EventArgs e)
{
     .
     .
     .

    new Thread(new ThreadStart(delegate
    {
        fExportOrder(strOrderNo);
        fSendMailv2(strPlant, strSupCode, strOrderNo);
    })).Start();

    this.close();
}

private void fExportOrder(string strOrderNo)
{
    //export order to pdf
}

private void fSendMailv2(string strPlant, string strSupCode, string strOrderNo);
{
    // get pdf
    // get email address

    try
    {
        // send email
        ((MDIParent1)MdiParent).tsslMain.Text = "Order No:" + strOrderNo + " was successfully send to " + strEmails;  //here I need to find a different way of accessing the Toolstripstatuslabel in the parent form
    }
    catch
    {
        MessageBox.Show("Email did not send");
    }
}

}
</code>```

EDIT:

Ok, so after spending more than a day trying to figure out how to use Invoke, I realize while it seems like good practice when working with threads, its not my answer. My problem is directly related to the childform closing disposing all the controls so it looses its reference to the MdiParent. To solve the problem I did the following:

In my child class I added:

```<code>public static Form IsFormAlreadyOpen(Type FormType)
{
    foreach (Form OpenForm in Application.OpenForms)
    {
    if (OpenForm.GetType() == FormType)
        return OpenForm;
    }
    return null;
 }
</code>```

I dont think it is the most elegant solution but the theory is that my Parent form will always be open when I need to access the Toolstripstatuslabel. So I basically loop through all the open forms to find the reference to the active MdiParent instance which then gets passed back to the caller. In the thread I then use the following code.

```<code> MDIParent1 fm = null;
 if ((fm = (MDIParent1)IsFormAlreadyOpen(typeof(MDIParent1))) != null)
 {
      fm.Toolstripstatuslabel1.Text = "Order No:" + strOrderNo + " was successfully send to " + strEmails;
 }
</code>```

I'm still looking for a better approach, but for now this works.

ContentLicense: CC BY-SA 4.0

Body:
I have a Order form. Once a order is complete, I use a thread to email the order to the supplier. The Thread is use to prevent the system hanging while the order is exported to pdf and sent.

The Problem: I would like to place an message on the MDIParent Toolstripstatuslabel once the threat completes without error to confirm the order was sent. But I get an error: "System.NullReferenceException: Object reference not set to an instance of an object". Which I could be wrong, refers to the Child windows disposed the toolstripstatuslabel reference on the parent form when it closed, so the threat cant access it anymore. I know the easy solution would be to use a MessageBox to confirm all went good and well...but why make it easy if you can do it elegant?

So my question: How can I reference a control in the parent form from the threat? I tried looking at invoke, but not sure how to implement it or if it is actually the correct direction.

EDIT:

My code from the childform

public partial class frm_n_order : Form
{
     .
     .

private void bProcess_Click(object sender, EventArgs e)
{
     .
     .
     .

    new Thread(new ThreadStart(delegate
    {
        fExportOrder(strOrderNo);
        fSendMailv2(strPlant, strSupCode, strOrderNo);
    })).Start();

    this.close();
}

private void fExportOrder(string strOrderNo)
{
    //export order to pdf
}

private void fSendMailv2(string strPlant, string strSupCode, string strOrderNo);
{
    // get pdf
    // get email address

    try
    {
        // send email
        ((MDIParent1)MdiParent).tsslMain.Text = "Order No:" + strOrderNo + " was successfully send to " + strEmails;  //here I need to find a different way of accessing the Toolstripstatuslabel in the parent form
    }
    catch
    {
        MessageBox.Show("Email did not send");
    }
}

}

EDIT:

Ok, so after spending more than a day trying to figure out how to use Invoke, I realize while it seems like good practice when working with threads, its not my answer. My problem is directly related to the childform closing disposing all the controls so it looses its reference to the MdiParent. To solve the problem I did the following:

In my child class I added:

public static Form IsFormAlreadyOpen(Type FormType)
{
    foreach (Form OpenForm in Application.OpenForms)
    {
    if (OpenForm.GetType() == FormType)
        return OpenForm;
    }
    return null;
 }

I dont think it is the most elegant solution but the theory is that my Parent form will always be open when I need to access the Toolstripstatuslabel. So I basically loop through all the open forms to find the reference to the active MdiParent instance which then gets passed back to the caller. In the thread I then use the following code.

 MDIParent1 fm = null;
 if ((fm = (MDIParent1)IsFormAlreadyOpen(typeof(MDIParent1))) != null)
 {
      fm.Toolstripstatuslabel1.Text = "Order No:" + strOrderNo + " was successfully send to " + strEmails;
 }

I'm still looking for a better approach, but for now this works.


问:
MVC Pagination in .Net
I need to implement pagination. In controller, I ma just returning json data. View is purely client side development, MVC helpers are not implemented. View is done fully with jquery. Parameters are passed to controller through Ajax call and I am returning json data based on parameters by filtering data. How to implement pagination in this case?

Thanks

答:
As example https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application

you have specific problems?

Title: MVC Pagination in .Net


问:
i have an error in column application can't get data from some column in table android
```<code>public void onCreate(SQLiteDatabase db) {
   String CREATE_TABLE= "CREATE TABLE " + Constants.TABLE1_NAME + "(" +
           Constants.KEY_ID + " INTEGER PRIMARY KEY, "+Constants.EMP_NAME+" Text, " + Constants.PHONE_NUMBER_NAME+" TEXT, " + Constants.EMP_ID+" INT ); ";
    db.execSQL(CREATE_TABLE);
}

public int getEmpId(){
    int EmpId=0;
    SQLiteDatabase db=this.getReadableDatabase();

    String query="SELECT "+Constants.EMP_ID +" FROM "+Constants.TABLE1_NAME;
    Cursor cursor=db.rawQuery(query,null);
    if(cursor.moveToFirst())
    {EmpId=cursor.getInt(0);}

    cursor.close();
    db.close();

    return EmpId;

}
</code>```

android.database.sqlite.SQLiteException: no such column: id (code 1):
  , while compiling: SELECT id FROM info
                                                                                at
  android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native
  Method)
                                                                                at
  android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
                                                                                at
  android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
                                                                                at
  android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                                at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:58)
                                                                                at android.database.sqlite.SQLiteQuery.(SQLiteQuery.java:37)
                                                                                at
  android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
                                                                                at
  android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)
                                                                                at
  android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1255)
                                                                                at Data.DatabaseHandeler$override.getEmpId(DatabaseHandeler.java:61)
                                                                                at
  Data.DatabaseHandeler$override.access$dispatch(DatabaseHandeler.java)
                                                                                at Data.DatabaseHandeler.getEmpId(DatabaseHandeler.java:0)
                                                                                at
  imageview.example.maged.taskforseautomation.MainActivity$override.suresignin(MainActivity.java:60)
                                                                                at
  imageview.example.maged.taskforseautomation.MainActivity$override.onClick(MainActivity.java:75)
                                                                                at
  imageview.example.maged.taskforseautomation.MainActivity$override.access$dispatch(MainActivity.java)
                                                                                at
  imageview.example.maged.taskforseautomation.MainActivity.onClick(MainActivity.java:0)
                                                                                at android.view.View.performClick(View.java:4780)
                                                                                at android.view.View$PerformClick.run(View.java:19866)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

答:
use this as your select statement
String query="SELECT "+Constants.KEY_ID +" FROM "+Constants.TABLE1_NAME;

There is no column Constants.EMP_IDin  your database schema. Check your Create table command.

Body:
public void onCreate(SQLiteDatabase db) {
   String CREATE_TABLE= "CREATE TABLE " + Constants.TABLE1_NAME + "(" +
           Constants.KEY_ID + " INTEGER PRIMARY KEY, "+Constants.EMP_NAME+" Text, " + Constants.PHONE_NUMBER_NAME+" TEXT, " + Constants.EMP_ID+" INT ); ";
    db.execSQL(CREATE_TABLE);
}

public int getEmpId(){
    int EmpId=0;
    SQLiteDatabase db=this.getReadableDatabase();

    String query="SELECT "+Constants.EMP_ID +" FROM "+Constants.TABLE1_NAME;
    Cursor cursor=db.rawQuery(query,null);
    if(cursor.moveToFirst())
    {EmpId=cursor.getInt(0);}

    cursor.close();
    db.close();

    return EmpId;

}

android.database.sqlite.SQLiteException: no such column: id (code 1):
  , while compiling: SELECT id FROM info
                                                                                at
  android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native
  Method)
                                                                                at
  android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
                                                                                at
  android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
                                                                                at
  android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                                at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:58)
                                                                                at android.database.sqlite.SQLiteQuery.(SQLiteQuery.java:37)
                                                                                at
  android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
                                                                                at
  android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)
                                                                                at
  android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1255)
                                                                                at Data.DatabaseHandeler$override.getEmpId(DatabaseHandeler.java:61)
                                                                                at
  Data.DatabaseHandeler$override.access$dispatch(DatabaseHandeler.java)
                                                                                at Data.DatabaseHandeler.getEmpId(DatabaseHandeler.java:0)
                                                                                at
  imageview.example.maged.taskforseautomation.MainActivity$override.suresignin(MainActivity.java:60)
                                                                                at
  imageview.example.maged.taskforseautomation.MainActivity$override.onClick(MainActivity.java:75)
                                                                                at
  imageview.example.maged.taskforseautomation.MainActivity$override.access$dispatch(MainActivity.java)
                                                                                at
  imageview.example.maged.taskforseautomation.MainActivity.onClick(MainActivity.java:0)
                                                                                at android.view.View.performClick(View.java:4780)
                                                                                at android.view.View$PerformClick.run(View.java:19866)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)


问:
Target webkit browsers for css3 exclusion
I have some text in a  paragraph

Aliquam tempor interdum volutpat. Suspendisse potenti. Nunc nibh
  elit, sagittis nec libero a, pretium fermentum sapien. Aliquam eu
  risus eu dui varius elementum. Curabitur ut ex luctus, egestas dui sit
  amet, malesuada lectus.

I am trying to use css exclusions in the paragraph using the code below but it does not seem to work.

```<code>#exclusion {
    position: absolute;
    background: lightblue;
    -webkit-wrap-flow:clear !important;
}
</code>```

Am i targeting webkit for exclusion correctly?.

Update

If you are not familiar with css exclusions, here are some examples http://galjot.si/css-exclusions

答:
there is no wrap-flow support in chrome, even with prefixes

http://caniuse.com/#search=wrap-flow

Body:
I have some text in a  paragraph

Aliquam tempor interdum volutpat. Suspendisse potenti. Nunc nibh
  elit, sagittis nec libero a, pretium fermentum sapien. Aliquam eu
  risus eu dui varius elementum. Curabitur ut ex luctus, egestas dui sit
  amet, malesuada lectus.

I am trying to use css exclusions in the paragraph using the code below but it does not seem to work.

#exclusion {
    position: absolute;
    background: lightblue;
    -webkit-wrap-flow:clear !important;
}

Am i targeting webkit for exclusion correctly?.

Update

If you are not familiar with css exclusions, here are some examples http://galjot.si/css-exclusions


问:
valid_email not working along with callback function in codeigniter
Hello all i was using form_validation Library in codeigniter inside my application. I am making a password retrieving function. I have made a submit form of the email . Now, on the email input field i want to apply these validations.

required

valid_email

check email exist or not.

For the 3rd one i am using call back function to check the database and it worked fine. But with the call back function valid_email is not functioning. This is my controller functions.

```<code>     public function password_retrieve()
    {
        if ($_SERVER['REQUEST_METHOD'] == 'POST')
    {

        $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|callback__email_exists');
        if ($this->form_validation->run() == false) {
            $this->load->view('login_header');
            $this->load->view('password_retrieve');
            $this->load->view('login_footer');
        } else {

        }
    } else {
        $this->load->view('login_header');
        $this->load->view('password_retrieve');
        $this->load->view('login_footer');
    }
    }

    function _email_exists($email)
    {
    $this->load->model('users_model');

    $result = $result = $this->users_model->check_email_is_exist($email);
    if (!$result) {
        $this->form_validation->set_message(__FUNCTION__, 'This %s address does not exist!');
        return false;
    } else {
        return true;
    }
    }
</code>```

It should checked the valid_email rather than the going to the callback function.

In other mean i want to know what is the order of the rules. Is callback rule runs before the valid_email?

答:
Try to remove "trim" and for check if email exist don't use another function. But use "is_unique[table_name.email]".</p>

```<code>$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[table_name.email]');
</code>```

Body:
Hello all i was using form_validation Library in codeigniter inside my application. I am making a password retrieving function. I have made a submit form of the email . Now, on the email input field i want to apply these validations.

required

valid_email

check email exist or not.

For the 3rd one i am using call back function to check the database and it worked fine. But with the call back function valid_email is not functioning. This is my controller functions.

     public function password_retrieve()
    {
        if ($_SERVER['REQUEST_METHOD'] == 'POST')
    {

        $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|callback__email_exists');
        if ($this->form_validation->run() == false) {
            $this->load->view('login_header');
            $this->load->view('password_retrieve');
            $this->load->view('login_footer');
        } else {

        }
    } else {
        $this->load->view('login_header');
        $this->load->view('password_retrieve');
        $this->load->view('login_footer');
    }
    }

    function _email_exists($email)
    {
    $this->load->model('users_model');

    $result = $result = $this->users_model->check_email_is_exist($email);
    if (!$result) {
        $this->form_validation->set_message(__FUNCTION__, 'This %s address does not exist!');
        return false;
    } else {
        return true;
    }
    }

It should checked the valid_email rather than the going to the callback function.

In other mean i want to know what is the order of the rules. Is callback rule runs before the valid_email?

Body:
Try to remove "trim" and for check if email exist don't use another function. But use "is_unique[table_name.email]".

$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[table_name.email]');


问:
ReactDOM.render has no effect in specific circumstances?
I have a method that renders an icon (font-awesome icon) inside provided container. Icon rendering can happen by user clicking on specific div or by program itself automatically calling rendering function when it mimics user clicking specific div.

To better understand this. I have created this so called TicTacToe game. It is possible to play player vs player or player vs cpu. If two players are playing then there is no problem, everything is rendered fine.

Now when player plays against CPU, something strange happens. If first player is CPU, then its first move is not rendered (icon does not appear). But the rest appears fine.

And if I make both players to be CPU (CPU plays against another CPU), then nothing gets rendered. Could it be that ReactDOM.render ignores changes if they happen too fast?;)

So here is part of the program (game):

```<code>$( document ).ready(function() {
    const ICONS_CLASSES = {
        x: 'fa fa-times fa-lg',
        o: 'fa fa-circle-o fa-5x'
    }
    function renderMove(el, turn){
        const classes = ICONS_CLASSES[turn];
        ReactDOM.render(
             React.createElement('span', {'className': classes}),
             el
         )
    }
...
...
});
</code>```

Also here is a function that is called by program itself to mimic clicking on a specific div in a game (well let say CPU "clicks" it):

```<code>function clickPosition(el, tic){
    if(tic.state == 'running'){
        // Save which player played, because after playing move, it will
        // switch turn for another player.
        const type = tic.turn.type;
        const res = tic.play(el.id);
        if(res != 'invalid')
            renderMove(el, type);
        updateInfo(tic.info)
        // Add start block to be able to play again.
        if(tic.state == 'stopped'){
            // Highlight win combo if there is any
            if(tic.winCombo)
                highlightWin(tic.winCombo)
            toggleEl($('#start'))
        }

    }
}
</code>```

So calling such render as previously said will not render all the time (when playing with CPU).

But if I change that render to this:

```<code>el.innerHTML = `<span class="${classes}"></span>`;
</code>```

Then it renders any icon just fine. No matter if game is played player vs player, cpu vs player, player vs cpu or even cpu vs cpu (in this case all icons are rendered instantly, because the end result is always draw).

Is there some gotcha with ReactDOM.render?

P.S. If you are interested, you can find full code here (currently it is enabled to be played cpu vs player, meaning first will play CPU. And because it is rendering with ReactDOM.render, first move will be invisible. Others should appear fine): https://codepen.io/andriusl/pen/qjyBdB

答:
It looks like everything is OK with ReactDOM.render. But I was kind of right with guess about rendering happening too fast. But from another place.

There was a function (that I haven't mentioned in question) which cleared all rendered icons. And it would clear after starting the game. When players are playing, then there is no problem, because clearing does happen later then user clicks a div. But when cpu does that, it does much faster, so it plays its turn before clearing up is called and it clears that move icon.

So technically it is rendered, but it is instantly removed, looking like it was never rendered, at least to us humans:)

So fix was to move ReactDOM.unmountComponentAtNode before tic.start. Then it always clears before starting game, not after (or before starting another game).

```<code>$('#x, #o').on('click', function() {
    const second = {'x': 'o', 'o': 'x'};
    // Clear filled positions if any.
    let positions = document.getElementsByClassName('pos');
    _.each(positions, pos => {
        ReactDOM.unmountComponentAtNode(pos);
    })
    tic.start(this.id, second[this.id]);
    toggleEl($('#start'));
    updateInfo(tic.info);

})
</code>```

Body:
I have a method that renders an icon (font-awesome icon) inside provided container. Icon rendering can happen by user clicking on specific div or by program itself automatically calling rendering function when it mimics user clicking specific div.

To better understand this. I have created this so called TicTacToe game. It is possible to play player vs player or player vs cpu. If two players are playing then there is no problem, everything is rendered fine.

Now when player plays against CPU, something strange happens. If first player is CPU, then its first move is not rendered (icon does not appear). But the rest appears fine.

And if I make both players to be CPU (CPU plays against another CPU), then nothing gets rendered. Could it be that ReactDOM.render ignores changes if they happen too fast?;)

So here is part of the program (game):

$( document ).ready(function() {
    const ICONS_CLASSES = {
        x: 'fa fa-times fa-lg',
        o: 'fa fa-circle-o fa-5x'
    }
    function renderMove(el, turn){
        const classes = ICONS_CLASSES[turn];
        ReactDOM.render(
             React.createElement('span', {'className': classes}),
             el
         )
    }
...
...
});

Also here is a function that is called by program itself to mimic clicking on a specific div in a game (well let say CPU "clicks" it):

function clickPosition(el, tic){
    if(tic.state == 'running'){
        // Save which player played, because after playing move, it will
        // switch turn for another player.
        const type = tic.turn.type;
        const res = tic.play(el.id);
        if(res != 'invalid')
            renderMove(el, type);
        updateInfo(tic.info)
        // Add start block to be able to play again.
        if(tic.state == 'stopped'){
            // Highlight win combo if there is any
            if(tic.winCombo)
                highlightWin(tic.winCombo)
            toggleEl($('#start'))
        }

    }
}

So calling such render as previously said will not render all the time (when playing with CPU).

But if I change that render to this:

el.innerHTML = `<span class="${classes}"></span>`;

Then it renders any icon just fine. No matter if game is played player vs player, cpu vs player, player vs cpu or even cpu vs cpu (in this case all icons are rendered instantly, because the end result is always draw).

Is there some gotcha with ReactDOM.render?

P.S. If you are interested, you can find full code here (currently it is enabled to be played cpu vs player, meaning first will play CPU. And because it is rendering with ReactDOM.render, first move will be invisible. Others should appear fine): https://codepen.io/andriusl/pen/qjyBdB

Body:
It looks like everything is OK with ReactDOM.render. But I was kind of right with guess about rendering happening too fast. But from another place.

There was a function (that I haven't mentioned in question) which cleared all rendered icons. And it would clear after starting the game. When players are playing, then there is no problem, because clearing does happen later then user clicks a div. But when cpu does that, it does much faster, so it plays its turn before clearing up is called and it clears that move icon.

So technically it is rendered, but it is instantly removed, looking like it was never rendered, at least to us humans:)

So fix was to move ReactDOM.unmountComponentAtNode before tic.start. Then it always clears before starting game, not after (or before starting another game).

$('#x, #o').on('click', function() {
    const second = {'x': 'o', 'o': 'x'};
    // Clear filled positions if any.
    let positions = document.getElementsByClassName('pos');
    _.each(positions, pos => {
        ReactDOM.unmountComponentAtNode(pos);
    })
    tic.start(this.id, second[this.id]);
    toggleEl($('#start'));
    updateInfo(tic.info);

})


问:
Namespace not defined in F# ASP.NET MVC project in VS Code
I'm currently trying to make some progress in learning F# and web development, and to that end I've used Yeoman to generate a F# ASP.NET project to start with (generator).

I've used Bower to install the dependencies, and the project both builds and runs with no issues, in both VS Code and just using dotnet run. However, navigating to the Startup.fs, it claims these namespaces opened aren't defined:

```<code>open Microsoft.AspNetCore.Builder
open Microsoft.AspNetCore.Hosting
open Microsoft.Extensions.Configuration
open Microsoft.Extensions.DependencyInjection
open Microsoft.Extensions.Logging
</code>```

In the .fsproj file, the following packages are included, and I have run dotnet restore:

```<code><PackageReference Include="FSharp.NET.Sdk" Version="1.0.0-beta-*" PrivateAssets="All"/>
<PackageReference Include="Microsoft.AspNetCore" Version="1.0.4" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.0.3"/>
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.0.2"/>
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.0.2"/>
<PackageReference Include="Microsoft.FSharp.Core.netcore" Version="1.0.0-alpha-161023"/>
<PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.0.1"/>
</code>```

To my mind, those lines should include at least some of the relevant NuGet packages for the namespace above. I would like to know how to let VS Code see that these namespaces are defined in the packages, and what's currently wrong. Any insight would be appreciated.

答:
Per comments under the question moving my comment to the answer:

I haven't used F# with core however I noticed that you have a reference

```<code><PackageReference Include="FSharp.NET.Sdk" Version="1.0.0-beta-*" PrivateAssets="All"/>
<PackageReference Include="Microsoft.FSharp.Core.netcore" Version="1.0.0-alpha-161023"/>.
</code>```

I have a .net core 2 preview installed and generating new web project via dotnet command generated reference to

```<code><PackageReference Include="FSharp.Core" Version="4.1.*" />
<PackageReference Include="FSharp.NET.Sdk" Version="1.0.*" PrivateAssets="All" />
</code>```

which has not issues in VS Code

Body:
I'm currently trying to make some progress in learning F# and web development, and to that end I've used Yeoman to generate a F# ASP.NET project to start with (generator).

I've used Bower to install the dependencies, and the project both builds and runs with no issues, in both VS Code and just using dotnet run. However, navigating to the Startup.fs, it claims these namespaces opened aren't defined:

open Microsoft.AspNetCore.Builder
open Microsoft.AspNetCore.Hosting
open Microsoft.Extensions.Configuration
open Microsoft.Extensions.DependencyInjection
open Microsoft.Extensions.Logging

In the .fsproj file, the following packages are included, and I have run dotnet restore:

<PackageReference Include="FSharp.NET.Sdk" Version="1.0.0-beta-*" PrivateAssets="All"/>
<PackageReference Include="Microsoft.AspNetCore" Version="1.0.4" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.0.3"/>
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.0.2"/>
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.0.2"/>
<PackageReference Include="Microsoft.FSharp.Core.netcore" Version="1.0.0-alpha-161023"/>
<PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.0.1"/>

To my mind, those lines should include at least some of the relevant NuGet packages for the namespace above. I would like to know how to let VS Code see that these namespaces are defined in the packages, and what's currently wrong. Any insight would be appreciated.

Body:
Per comments under the question moving my comment to the answer:

I haven't used F# with core however I noticed that you have a reference

<PackageReference Include="FSharp.NET.Sdk" Version="1.0.0-beta-*" PrivateAssets="All"/>
<PackageReference Include="Microsoft.FSharp.Core.netcore" Version="1.0.0-alpha-161023"/>.

I have a .net core 2 preview installed and generating new web project via dotnet command generated reference to

<PackageReference Include="FSharp.Core" Version="4.1.*" />
<PackageReference Include="FSharp.NET.Sdk" Version="1.0.*" PrivateAssets="All" />

which has not issues in VS Code


问:
FTP from unix to windows from shell script
Hi i know there are similar questions out there but i still have some doubt as i am new to this.I want to FTP my file(abc.txt) from UNiX box to windows box.I tried one script as given below.

```<code>#!/bin/bash
HOST='my window ip address?'
USER='unix user?'
PASSWD='unix password?'
FILE='/opt/sie/w44gq8as/abc.txt'
ftp $HOST <<END_SCRIPT
user $USER
$PASSWD
put $FILE
quit
END_SCRIPT
exit 0
</code>```

My doubts are already in my script i want to know few questions .

HOST-: Is this windows ip address i want to ftp?

User: Is this unix user or window user?

Password : unix server pass or window ?

Is above script ok for FTP from unix to windows? Sorry if i am asking something really silly but i am somewhat confused.

答: All the information will be relating to the server you are trying to connect to and so in your case the Windows server. So the Windows IP address, the Windows username and the Windows password</p>

Body:
Hi i know there are similar questions out there but i still have some doubt as i am new to this.I want to FTP my file(abc.txt) from UNiX box to windows box.I tried one script as given below.

#!/bin/bash
HOST='my window ip address?'
USER='unix user?'
PASSWD='unix password?'
FILE='/opt/sie/w44gq8as/abc.txt'
ftp $HOST <<END_SCRIPT
user $USER
$PASSWD
put $FILE
quit
END_SCRIPT
exit 0

My doubts are already in my script i want to know few questions .

HOST-: Is this windows ip address i want to ftp?

User: Is this unix user or window user?

Password : unix server pass or window ?

Is above script ok for FTP from unix to windows? Sorry if i am asking something really silly but i am somewhat confused.


问:
Datatables Using ssp.class.php gives up warning of syntax error
class.php of datatables and Getting a error as below

error
:

An SQL error occurred: 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 request_id ASC↵             LIMIT 0, 10' at line 4

My Server side code is as below named as request-list.php

```<code>    <?php
   $inc_files = array("ph_utils");
   require_once ('autoload.php');
   $db = new db();
   $table = 'wallet_load_request';
  $primaryKey = 'request_id';
  $columns = array(
   array('db' => 'request_id', 'dt' => 0),
   array('db' => 'request_date', 'dt' => 1),
   array('db' => 'trans_mode', 'dt' => 2),
   array('db' => 'trans_amt', 'dt' => 3),
   array('db' => 'request_status', 'dt' => 4),
   array('db' => 'org_id', 'dt' => 5)
  );
  $sql_details = array(
   'user' => PH_DB_USER,
   'pass' => PH_DB_PSWD,
   'db' => PH_DB,
   'host' => PH_DB_HOST
   );
require_once('ssp.class.php');
$filterByStaus = isset($_REQUEST['filter_by_status']) ?
$_REQUEST['filter_by_status'] : "PENDING";

switch ($filterByStaus) {
case 'REJECTED':
$fixedFilter .= " AND request_status = 'REJECTED'";
break;
case 'APPROVED':
$fixedFilter .= " AND request_status = 'APPROVED'";
break;
default:
break;
}
$output = SSP::simple($_GET, $sql_details, $table, $primaryKey, $columns,
$fixedFilter);
foreach ($output['data'] as $i => $d) {
$request_id = $output['data'][$i][0];
$trans_amt = $output['data'][$i][3];
$request_status = $output['data'][$i][4];
$org_id = $output['data'][$i][5];
$output['data'][$i][0] = '<div class="text-center"><h4><span class="label label-success"> #'. $request_id .'</span></h4></div>';

if ($request_status == 'APPROVED') {
$output['data'][$i][4] = '<div class="text-center"><span class="label label-success"> APPROVED </span></div>';
$output['data'][$i][5] = '<div class="text-center"><button id="accept" type="button" class="text-center btn btn-success accept disabled" data-request_id=\'' . $request_id . '\' data-org_id=\'' . $org_id . '\' data-trans_amt=\'' . $trans_amt . '\'><i class="fa fa-ban"></i> ACCEPT</button></div>';
$output['data'][$i][6] = '<div class="text-center"><button id="reject" type="button" class="text-center btn btn-danger reject disabled" data-request_id=\'' . $request_id . '\'><i class="fa fa-ban"></i> REJECT</button></div>';
} else if ($request_status == 'REJECTED') {
$output['data'][$i][4] = '<div class="text-center"><span class="label label-danger"> REJECTED </span></div>';
$output['data'][$i][5] = '<div class="text-center"><button type="button" id="accept"  class="text-center btn btn-success accept disabled" data-request_id=\'' . $request_id . '\' data-org_id=\'' . $org_id . '\' data-trans_amt=\'' . $trans_amt . '\'><i class="fa fa-ban"></i> ACCEPT</button></div>';
$output['data'][$i][6] = '<div class="text-center"><button type="button" id="reject" class="text-center btn btn-danger reject disabled" data-request_id=\'' . $request_id . '\'><i class="fa fa-ban"></i> REJECT</button></div>';
} else {
$output['data'][$i][4] = '<div class="text-center"><span class="label label-warning"> PENDING </span></div>';
$output['data'][$i][5] = '<div class="text-center"><button type="button" id="accept" class="text-center btn btn-success accept" data-request_id=\'' . $request_id . '\' data-org_id=\'' . $org_id . '\' data-trans_amt=\'' . $trans_amt . '\'><i class="fa fa-ban"></i> ACCEPT</button></div>';
$output['data'][$i][6] = '<div class="text-center"><button type="button" id="reject" class="text-center btn btn-danger reject" data-request_id=\'' . $request_id . '\'><i class="fa fa-ban"></i> REJECT</button></div>';
 }

}
SSP::sendJson($output);
</code>```

My jquery code is as below request-list.js

```<code>var requestList = {
  oTable: {},
  init: function () {

   requestList.oTable = $('#req_list').dataTable({
    "processing": true,
    "serverSide": true,
    "columnDefs": [{className: "data_middle ", "targets": [0, 1, 2, 3, 4, 5, 6]}],
    "columns": [null, null, null, {"orderable": false}, {"orderable": false}, {"orderable": false}, {"orderable": false}],
   "ajax": {
   "url": "web/request-list",
   "data": function (d) {
     return $.extend({}, d, {
     "filter_by_status": $('#status').val(),

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

My front end code is list.html

           Filter By :

            PENDING
            APPROVED
            REJECTED

```<code>    <br>

    <div class="row">
     <div class="col-md-10 col-md-offset-1">
      <table class="table table-bordered table-striped table-hover" id="req_list">
       <thead>
        <tr>
         <th>Request ID</th>
         <th>DATE</th>
         <th>Mode</th>
         <th class="text-center">AMOUNT</th>
         <th class="text-center">STATUS</th>
         <th class="text-center">ACCEPT</th>
         <th class="text-center">REJECT</th>
        </tr>
       </thead>
       <tbody>
       </tbody>
      </table>
     </div>
    </div>
</code>```

after running the code the page shows up warning as DataTables warning: table id=req_list - An SQL error occurred: SQLSTATE[42000]: Syntax error or acess violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server cersion for the right syntax to user near 'ORDER BY request_id ASC LIMIT 0, 10' at line 4

and in console i get the error as

jquery.dataTables.min.js:39 Uncaught TypeError: Cannot read property 'length' of undefined

The Custom ssp code is as below on below link

https://drive.google.com/open?id=0B-e2dOqifK3QOFFnRjhTYjhPQmM

答:
You don't need the leading AND in value of $fixedFilter variable. See the corrected excerpt below:

switch ($filterByStaus) {
case 'REJECTED':
   $fixedFilter = "request_status = 'REJECTED'";
   break;

case 'APPROVED':
   $fixedFilter = "request_status = 'APPROVED'";
   break;

default:
   break;
}
```

Body:
class.php of datatables and Getting a error as below

error
:

An SQL error occurred: 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 request_id ASC↵             LIMIT 0, 10' at line 4

My Server side code is as below named as request-list.php

    <?php
   $inc_files = array("ph_utils");
   require_once ('autoload.php');
   $db = new db();
   $table = 'wallet_load_request';
  $primaryKey = 'request_id';
  $columns = array(
   array('db' => 'request_id', 'dt' => 0),
   array('db' => 'request_date', 'dt' => 1),
   array('db' => 'trans_mode', 'dt' => 2),
   array('db' => 'trans_amt', 'dt' => 3),
   array('db' => 'request_status', 'dt' => 4),
   array('db' => 'org_id', 'dt' => 5)
  );
  $sql_details = array(
   'user' => PH_DB_USER,
   'pass' => PH_DB_PSWD,
   'db' => PH_DB,
   'host' => PH_DB_HOST
   );
require_once('ssp.class.php');
$filterByStaus = isset($_REQUEST['filter_by_status']) ?
$_REQUEST['filter_by_status'] : "PENDING";

switch ($filterByStaus) {
case 'REJECTED':
$fixedFilter .= " AND request_status = 'REJECTED'";
break;
case 'APPROVED':
$fixedFilter .= " AND request_status = 'APPROVED'";
break;
default:
break;
}
$output = SSP::simple($_GET, $sql_details, $table, $primaryKey, $columns,
$fixedFilter);
foreach ($output['data'] as $i => $d) {
$request_id = $output['data'][$i][0];
$trans_amt = $output['data'][$i][3];
$request_status = $output['data'][$i][4];
$org_id = $output['data'][$i][5];
$output['data'][$i][0] = '

 #'. $request_id .'

';

if ($request_status == 'APPROVED') {
$output['data'][$i][4] = '
 APPROVED
';
$output['data'][$i][5] = '
<button id="accept" type="button" class="text-center btn btn-success accept disabled" data-request_id=\'' . $request_id . '\' data-org_id=\'' . $org_id . '\' data-trans_amt=\'' . $trans_amt . '\'> ACCEPT</button>
';
$output['data'][$i][6] = '
<button id="reject" type="button" class="text-center btn btn-danger reject disabled" data-request_id=\'' . $request_id . '\'> REJECT</button>
';
} else if ($request_status == 'REJECTED') {
$output['data'][$i][4] = '
 REJECTED
';
$output['data'][$i][5] = '
<button type="button" id="accept"  class="text-center btn btn-success accept disabled" data-request_id=\'' . $request_id . '\' data-org_id=\'' . $org_id . '\' data-trans_amt=\'' . $trans_amt . '\'> ACCEPT</button>
';
$output['data'][$i][6] = '
<button type="button" id="reject" class="text-center btn btn-danger reject disabled" data-request_id=\'' . $request_id . '\'> REJECT</button>
';
} else {
$output['data'][$i][4] = '
 PENDING
';
$output['data'][$i][5] = '
<button type="button" id="accept" class="text-center btn btn-success accept" data-request_id=\'' . $request_id . '\' data-org_id=\'' . $org_id . '\' data-trans_amt=\'' . $trans_amt . '\'> ACCEPT</button>
';
$output['data'][$i][6] = '
<button type="button" id="reject" class="text-center btn btn-danger reject" data-request_id=\'' . $request_id . '\'> REJECT</button>
';
 }

}
SSP::sendJson($output);

My jquery code is as below request-list.js

var requestList = {
  oTable: {},
  init: function () {

   requestList.oTable = $('#req_list').dataTable({
    "processing": true,
    "serverSide": true,
    "columnDefs": [{className: "data_middle ", "targets": [0, 1, 2, 3, 4, 5, 6]}],
    "columns": [null, null, null, {"orderable": false}, {"orderable": false}, {"orderable": false}, {"orderable": false}],
   "ajax": {
   "url": "web/request-list",
   "data": function (d) {
     return $.extend({}, d, {
     "filter_by_status": $('#status').val(),

     });
   }
 }
});
}
}

My front end code is list.html

           Filter By :

            PENDING
            APPROVED
            REJECTED

         Request ID
         DATE
         Mode
         AMOUNT
         STATUS
         ACCEPT
         REJECT

after running the code the page shows up warning as DataTables warning: table id=req_list - An SQL error occurred: SQLSTATE[42000]: Syntax error or acess violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server cersion for the right syntax to user near 'ORDER BY request_id ASC LIMIT 0, 10' at line 4

and in console i get the error as

jquery.dataTables.min.js:39 Uncaught TypeError: Cannot read property 'length' of undefined

The Custom ssp code is as below on below link

https://drive.google.com/open?id=0B-e2dOqifK3QOFFnRjhTYjhPQmM


问:
Python socket wait for client connection
Is there a way to stop the while loop until the clients connect to this server?
The server shuld create a new thread for each new client connection, it is possible?</p>

```<code>import socket
import threading

def clientdialog(myS):
    conn, addr = myS.accept()
    print ("Connection from: " + str(addr))

    while 1:
                data = conn.recv(1024).decode("utf-8")
                if not data or data == 'q':
                    break
                print ("from connected  user: " + str(data))

host = "192.168.1.3"
port = 1998

mySocket = socket.socket()
mySocket.bind((host,port))

while True:

    mySocket.listen(10)
    #whait until socket don't connect

    try:
        threading._start_new_thread(clientdialog, (mySocket))
    except:
        print("error starting thread")
</code>```

答:
The socket.listen function is to be called once, because it sets the size of the connection queue.

Another function called socket.accept will block until connections are made. Modify your code like this:

```<code>mySocket = socket.socket()
mySocket.bind((host,port))
mySocket.listen(10)

while True:
    client_socket, client_address = mySocket.accept() # blocking call
    .... # do something with the connection
</code>```

For more information, visit the docs.

Additionally, you'd want to pass the details of the client socket to the thread. The server socket isn't required. In effect, something like this:

```<code>def handle_client(client_socket, client_address):
    .... # do something with client socket
    client_socket.close()

...

while True:
    client_socket, client_address = mySocket.accept()
    T = threading.Thread(target=handle_client, args=(client_socket, client_address))
    T.start()
</code>```

You accept the connection in the main loop, then pass the client details to the thread for processing.

Body:
Is there a way to stop the while loop until the clients connect to this server?
The server shuld create a new thread for each new client connection, it is possible?

import socket
import threading

def clientdialog(myS):
    conn, addr = myS.accept()
    print ("Connection from: " + str(addr))

    while 1:
                data = conn.recv(1024).decode("utf-8")
                if not data or data == 'q':
                    break
                print ("from connected  user: " + str(data))

host = "192.168.1.3"
port = 1998

mySocket = socket.socket()
mySocket.bind((host,port))

while True:

    mySocket.listen(10)
    #whait until socket don't connect

    try:
        threading._start_new_thread(clientdialog, (mySocket))
    except:
        print("error starting thread")

Body:
The socket.listen function is to be called once, because it sets the size of the connection queue.

Another function called socket.accept will block until connections are made. Modify your code like this:

mySocket = socket.socket()
mySocket.bind((host,port))
mySocket.listen(10)

while True:
    client_socket, client_address = mySocket.accept() # blocking call
    .... # do something with the connection

For more information, visit the docs.

Additionally, you'd want to pass the details of the client socket to the thread. The server socket isn't required. In effect, something like this:

def handle_client(client_socket, client_address):
    .... # do something with client socket
    client_socket.close()

...

while True:
    client_socket, client_address = mySocket.accept()
    T = threading.Thread(target=handle_client, args=(client_socket, client_address))
    T.start()

You accept the connection in the main loop, then pass the client details to the thread for processing.


问:
Is it possible to select text boxes with javaScript in acrobat
I would like to be able to use the JavaScript function of one of my form inputs to be able to show or hide a text box. After a lot of research I can only find how to select and hide other form input methods.

here is what I have:

var supplyBudget = this.getField("Supply Budget").value;
if (supplyBudget == ""){
/*text box selector*/.style.display = 3;
}
else if (supplyBudget =="0"){
/*text box selector*/.style.display = 3;
}
else{
/*text box selector*/.style.display = 1;
}```

This runs when the user leaves the input field.

*edited code in accordance with  freginold's comment

答: If you want to hide text that is part of the page content, you can't do that with PDF unless that particular text item is assigned to an Optional Content Group (OCG)... basically a layer that you can show or hide. There is no concept of "elements" for PDF page context like there is in HTML. Instead, there's a list of painting instructions for the page but JavaScript does not have access to it. </p>

Body:
I would like to be able to use the JavaScript function of one of my form inputs to be able to show or hide a text box. After a lot of research I can only find how to select and hide other form input methods.

here is what I have:

var supplyBudget = this.getField("Supply Budget").value;
if (supplyBudget == ""){
/*text box selector*/.style.display = 3;
}
else if (supplyBudget =="0"){
/*text box selector*/.style.display = 3;
}
else{
/*text box selector*/.style.display = 1;
}

This runs when the user leaves the input field.

*edited code in accordance with  freginold's comment


答:
Am i targeting webkit for exclusion correctly?.

No.

In general, new features in webkit today are added behind configuration flags instead of being vendor prefixes. (This is a consequence of developers using vendor prefixes in production).

Even when webkit browsers added new features behind vendor prefixes, you can't just use it and expect it to work.

See can I use. Currently only IE and Edge support Exclusions.

Title: Target webkit browsers for css3 exclusion


问:
Recursive-ish query for tags?
I have a table of tags that can be linked to other tags and I want to "recursively" select the tags in order of arrangement. So that when a search is made, we get the immediate (1-level) results and then carry on down to say 5-levels so that we always have a list of tags no matter if there wasn't enough exact matches on level 1.

I can manage this fine with making multiple queries until I get enough results, but surely there is a better, optimized, way via a one-trip query?

Any tips will be appreciated.
Thanks!

Results:

```<code>tagId, tagWord, child, child tagId
'513', 'Slap', 'Hog Slapper', '1518'
'513', 'Slap', 'Corporal Punishment', '147'
'513', 'Slap', 'Impact Play', '1394'
</code>```

Query:

```<code>SELECT t.tagId, t.tagWord as tag, tt.tagWord as child, tt.tagId as childId

FROM platform.tagWords t

INNER JOIN platform.tagsLinks l ON l.parentId = t.tagId
INNER JOIN platform.tagWords tt ON tt.tagId = l.tagId

WHERE t.tagWord = 'slap'
</code>```

Table Layouts:

```<code>mysql> explain tagWords;
+---------+---------------------+------+-----+---------+----------------+
| Field   | Type                | Null | Key | Default | Extra          |
+---------+---------------------+------+-----+---------+----------------+
| tagId   | bigint(20) unsigned | NO   | PRI | NULL    | auto_increment |
| tagWord | varchar(45)         | YES  | UNI | NULL    |                |
+---------+---------------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

mysql> explain tagsLinks;
+----------+---------------------+------+-----+---------+-------+
| Field    | Type                | Null | Key | Default | Extra |
+----------+---------------------+------+-----+---------+-------+
| tagId    | bigint(20) unsigned | NO   |     | NULL    |       |
| parentId | bigint(20)          | YES  |     | NULL    |       |
+----------+---------------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
</code>```

答:
AFAIK Mysql doesn't have any mechanism for querying data recursively

Oracle has Connected By construct and Sql Server has CTE(Common Table Expressions).

But Mysql,
Read Here and Here

Title: Recursive-ish query for tags?

Body:
I have a table of tags that can be linked to other tags and I want to "recursively" select the tags in order of arrangement. So that when a search is made, we get the immediate (1-level) results and then carry on down to say 5-levels so that we always have a list of tags no matter if there wasn't enough exact matches on level 1.

I can manage this fine with making multiple queries until I get enough results, but surely there is a better, optimized, way via a one-trip query?

Any tips will be appreciated.
Thanks!

Results:

tagId, tagWord, child, child tagId
'513', 'Slap', 'Hog Slapper', '1518'
'513', 'Slap', 'Corporal Punishment', '147'
'513', 'Slap', 'Impact Play', '1394'

Query:

SELECT t.tagId, t.tagWord as tag, tt.tagWord as child, tt.tagId as childId

FROM platform.tagWords t

INNER JOIN platform.tagsLinks l ON l.parentId = t.tagId
INNER JOIN platform.tagWords tt ON tt.tagId = l.tagId

WHERE t.tagWord = 'slap'

Table Layouts:

mysql> explain tagWords;
+---------+---------------------+------+-----+---------+----------------+
| Field   | Type                | Null | Key | Default | Extra          |
+---------+---------------------+------+-----+---------+----------------+
| tagId   | bigint(20) unsigned | NO   | PRI | NULL    | auto_increment |
| tagWord | varchar(45)         | YES  | UNI | NULL    |                |
+---------+---------------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

mysql> explain tagsLinks;
+----------+---------------------+------+-----+---------+-------+
| Field    | Type                | Null | Key | Default | Extra |
+----------+---------------------+------+-----+---------+-------+
| tagId    | bigint(20) unsigned | NO   |     | NULL    |       |
| parentId | bigint(20)          | YES  |     | NULL    |       |
+----------+---------------------+------+-----+---------+-------+
2 rows in set (0.00 sec)


问:
System.InvalidOperationException when modifiying value in an xml file in C#
So i... Have this snippet of code what writes to an existing xml file... the code to me is VERY simple...

```<code>            XElement element;
            XDocument xdoc = XDocument.Load(FileLoc);
            element = xdoc.Elements(XName.Get("gold", "http://schemas.datacontract.org/2004/07/DumaLegend")).Single();
            element.Value = Gold.Text;
</code>```

Good Right? good! but why does it give out that error which means that it can't find the thing? it's a very valid thing....

here is the xml file:

<?xml version="1.0" encoding="utf-8"?>
<Save xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/DumaLegend">
  <saveInfo>
    <energyPieces>0</energyPieces>
    <fullEnergyCells>4</fullEnergyCells>
    <fullHearts>4</fullHearts>
    <globalSwitches xmlns:d3p1="a">
      <d3p1:switchList xmlns:d4p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" />
    </globalSwitches>
    <gold>0</gold>
    <hasBigFireball>false</hasBigFireball>
    <hasCombo>false</hasCombo>
    <hasCrossbow>false</hasCrossbow>
    <hasDash>false</hasDash>
    <hasDashUpgrade>false</hasDashUpgrade>
    <hasDoubleJump>false</hasDoubleJump>
    <hasFireball>false</hasFireball>
    <hasHookshot>false</hasHookshot>
    <hasInvisPot>false</hasInvisPot>
    <hasSecondCombo>false</hasSecondCombo>
    <hasShieldUpgrade>false</hasShieldUpgrade>
    <hasSmallFireball>false</hasSmallFireball>
    <heartPieces>0</heartPieces>
    <heroPosOnMap>0</heroPosOnMap>
    <heroTokens>0</heroTokens>
    <itemSlot1 xmlns:d3p1="http://schemas.datacontract.org/2004/07/DumaLegend.Objects.Consumables" i:nil="true" />
    <itemSlot2 xmlns:d3p1="http://schemas.datacontract.org/2004/07/DumaLegend.Objects.Consumables" i:nil="true" />
    <lives>3</lives>
    <worldsUnlocked>0</worldsUnlocked>
    <worldsUnlockedOnMap>0</worldsUnlockedOnMap>
  </saveInfo>
  <saveSlot>0</saveSlot>
</Save>```

答:
From the docs for Elements

Returns a filtered collection of the child elements of this element or document, in document order. Only elements that have a matching XName are included in the collection.

There is only one child elements of your document, and that is the Save element.

What you are looking for is at the path Save/saveInfo/gold. So you can either use Elements like this:

```<code>XNamespace ns = "http://schemas.datacontract.org/2004/07/DumaLegend";
var gold = doc.Elements(ns + "Save")
    .Elements(ns + "saveInfo")
    .Elements(ns + "gold")
    .Single();
</code>```

Or you can use Descendants, which will search all child elements recursively.

```<code>XNamespace ns = "http://schemas.datacontract.org/2004/07/DumaLegend";
var gold = doc.Descendants(ns + "gold").Single();
</code>```

Body:
So i... Have this snippet of code what writes to an existing xml file... the code to me is VERY simple...

            XElement element;
            XDocument xdoc = XDocument.Load(FileLoc);
            element = xdoc.Elements(XName.Get("gold", "http://schemas.datacontract.org/2004/07/DumaLegend")).Single();
            element.Value = Gold.Text;

Good Right? good! but why does it give out that error which means that it can't find the thing? it's a very valid thing....

here is the xml file:

<?xml version="1.0" encoding="utf-8"?>
<Save xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/DumaLegend">
  <saveInfo>
    <energyPieces>0</energyPieces>
    <fullEnergyCells>4</fullEnergyCells>
    <fullHearts>4</fullHearts>
    <globalSwitches xmlns:d3p1="a">
      <d3p1:switchList xmlns:d4p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" />
    </globalSwitches>
    <gold>0</gold>
    <hasBigFireball>false</hasBigFireball>
    <hasCombo>false</hasCombo>
    <hasCrossbow>false</hasCrossbow>
    <hasDash>false</hasDash>
    <hasDashUpgrade>false</hasDashUpgrade>
    <hasDoubleJump>false</hasDoubleJump>
    <hasFireball>false</hasFireball>
    <hasHookshot>false</hasHookshot>
    <hasInvisPot>false</hasInvisPot>
    <hasSecondCombo>false</hasSecondCombo>
    <hasShieldUpgrade>false</hasShieldUpgrade>
    <hasSmallFireball>false</hasSmallFireball>
    <heartPieces>0</heartPieces>
    <heroPosOnMap>0</heroPosOnMap>
    <heroTokens>0</heroTokens>
    <itemSlot1 xmlns:d3p1="http://schemas.datacontract.org/2004/07/DumaLegend.Objects.Consumables" i:nil="true" />
    <itemSlot2 xmlns:d3p1="http://schemas.datacontract.org/2004/07/DumaLegend.Objects.Consumables" i:nil="true" />
    <lives>3</lives>
    <worldsUnlocked>0</worldsUnlocked>
    <worldsUnlockedOnMap>0</worldsUnlockedOnMap>
  </saveInfo>
  <saveSlot>0</saveSlot>
</Save>

Body:
From the docs for Elements

Returns a filtered collection of the child elements of this element or document, in document order. Only elements that have a matching XName are included in the collection.

There is only one child elements of your document, and that is the Save element.

What you are looking for is at the path Save/saveInfo/gold. So you can either use Elements like this:

XNamespace ns = "http://schemas.datacontract.org/2004/07/DumaLegend";
var gold = doc.Elements(ns + "Save")
    .Elements(ns + "saveInfo")
    .Elements(ns + "gold")
    .Single();

Or you can use Descendants, which will search all child elements recursively.

XNamespace ns = "http://schemas.datacontract.org/2004/07/DumaLegend";
var gold = doc.Descendants(ns + "gold").Single();


问:
Nodejs HTTP request, cant alter response headers
Hello I'm doing a request and then upon response i'm trying to add come headers but I get the following error:

```<code>Server listening on port 80 [Request]: test.domain.com//web/guest/retail-betting (GET) D:\Development\xampp\htdocs\lab\tests\12\proxy\index.js:19
        resp.setHeader("Access-Control-Allow-Origin", "*");
             ^

TypeError: resp.setHeader is not a function
    at ClientRequest.<anonymous> (D:\Development\xampp\htdocs\lab\tests\12\proxy\index.js:19:14)
    at ClientRequest.g (events.js:291:16)
    at emitOne (events.js:96:13)
    at ClientRequest.emit (events.js:188:7)
    at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:473:21)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)
    at Socket.socketOnData (_http_client.js:362:20)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at readableAddChunk (_stream_readable.js:176:18)
</code>```

An here is the code sample:

```<code>const http = require("http");
const clear = require("clear");
const server = http.createServer();

server.on('request', function(req, res) {

    var options = {
        host: HOST,
        path: req.url,
        method: req.method
    };

    console.log("[Request]:", HOST + "/" + options.path, "(" + options.method.toUpperCase() + ")");

    var connector = http.request(options, function(resp) {

        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
        resp.setHeader("Access-Control-Allow-Headers", "Content-Type");

        console.log("===============[Response Headers]===============");
        console.log(JSON.stringify(resp.headers, null, 4), "\n");

        resp.pipe(res);

    });

    req.pipe(connector);

});

server.listen(PORT);

clear();

console.log("Server listening on port", PORT);
</code>```

答: You cannot add header values to response, response header comes from server. if you want to add cross origin headers you must add it in your web application </p>

Body:
Hello I'm doing a request and then upon response i'm trying to add come headers but I get the following error:

Server listening on port 80 [Request]: test.domain.com//web/guest/retail-betting (GET) D:\Development\xampp\htdocs\lab\tests\12\proxy\index.js:19
        resp.setHeader("Access-Control-Allow-Origin", "*");
             ^

TypeError: resp.setHeader is not a function
    at ClientRequest.<anonymous> (D:\Development\xampp\htdocs\lab\tests\12\proxy\index.js:19:14)
    at ClientRequest.g (events.js:291:16)
    at emitOne (events.js:96:13)
    at ClientRequest.emit (events.js:188:7)
    at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:473:21)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)
    at Socket.socketOnData (_http_client.js:362:20)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at readableAddChunk (_stream_readable.js:176:18)

An here is the code sample:

const http = require("http");
const clear = require("clear");
const server = http.createServer();

server.on('request', function(req, res) {

    var options = {
        host: HOST,
        path: req.url,
        method: req.method
    };

    console.log("[Request]:", HOST + "/" + options.path, "(" + options.method.toUpperCase() + ")");

    var connector = http.request(options, function(resp) {

        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
        resp.setHeader("Access-Control-Allow-Headers", "Content-Type");

        console.log("===============[Response Headers]===============");
        console.log(JSON.stringify(resp.headers, null, 4), "\n");

        resp.pipe(res);

    });

    req.pipe(connector);

});

server.listen(PORT);

clear();

console.log("Server listening on port", PORT);


问:
ScriptManager is not declared - err msg

I've this class and it gave me an error name 'ScriptManager is not declared'

```<code>Public NotInheritable Class ResponseHelper
Private Sub New()
End Sub
Public Shared Sub Redirect(ByVal response As HttpResponse, ByVal url As String, ByVal target As String, ByVal windowFeatures As String)
    If ([String].IsNullOrEmpty(target) OrElse target.Equals("_self", StringComparison.OrdinalIgnoreCase)) AndAlso [String].IsNullOrEmpty(windowFeatures) Then
        response.Redirect(url)
    Else
        Dim page As Page = DirectCast(HttpContext.Current.Handler, Page)
        If page Is Nothing Then
            Throw New InvalidOperationException("Cannot redirect to new window outside Page context.")
        End If
        url = page.ResolveClientUrl(url)
        Dim script As String
        If Not [String].IsNullOrEmpty(windowFeatures) Then
            script = "window.open(""{0}"", ""{1}"", ""{2}"");"
        Else
            script = "window.open(""{0}"", ""{1}"");"
        End If
        script = [String].Format(script, url, target, windowFeatures)
        ScriptManager.RegisterStartupScript(page, GetType(Page), "Redirect", script, True)
    End If
End Sub
</code>```

End Class

This code from this link:

http://weblogs.asp.net/infinitiesloop/archive/2007/09/25/response-redirect-into-a-new-window-with-extension-methods.aspx

I've been 8 hours trying to figure out how to open a new page and send parameters to it. And found this code , and 6 hours trying to apply it but nothing.

Thanks.

答: Try put the full name space before scirptmananger, System.UI.Web.ScriptManager.RegisterStartupScript(...)</p>

Title: ScriptManager is not declared - err msg

Body:
I've this class and it gave me an error name 'ScriptManager is not declared'

Public NotInheritable Class ResponseHelper
Private Sub New()
End Sub
Public Shared Sub Redirect(ByVal response As HttpResponse, ByVal url As String, ByVal target As String, ByVal windowFeatures As String)
    If ([String].IsNullOrEmpty(target) OrElse target.Equals("_self", StringComparison.OrdinalIgnoreCase)) AndAlso [String].IsNullOrEmpty(windowFeatures) Then
        response.Redirect(url)
    Else
        Dim page As Page = DirectCast(HttpContext.Current.Handler, Page)
        If page Is Nothing Then
            Throw New InvalidOperationException("Cannot redirect to new window outside Page context.")
        End If
        url = page.ResolveClientUrl(url)
        Dim script As String
        If Not [String].IsNullOrEmpty(windowFeatures) Then
            script = "window.open(""{0}"", ""{1}"", ""{2}"");"
        Else
            script = "window.open(""{0}"", ""{1}"");"
        End If
        script = [String].Format(script, url, target, windowFeatures)
        ScriptManager.RegisterStartupScript(page, GetType(Page), "Redirect", script, True)
    End If
End Sub

End Class

This code from this link:

http://weblogs.asp.net/infinitiesloop/archive/2007/09/25/response-redirect-into-a-new-window-with-extension-methods.aspx

I've been 8 hours trying to figure out how to open a new page and send parameters to it. And found this code , and 6 hours trying to apply it but nothing.

Thanks.


问:
How do I click 1 of 2 links with same name, no id and same class. selenium java
I'm trying to get selenium to click the select button but I can't use by.linkText() because there are two buttons with the same name.
I'm using this xpath ".//*[contains(@id,'view-something_111111_2A22DF2_)']/div/a[text()='Select']"; to find the button but it can't find it.

I've also tried ".//*[contains(@id,'view-something_111111_2A22DF2_)']/div/a";.
I've looked over the Selenium documentation and can't seem to find a solution.

Here is the section of website code:

...

  Select```
</div>
</div>
</p>

<p>for reference, the second Select button has this code:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="view-something_111111_2A3B5DF2_0" class="coverage-wrap collapse" aria-expanded="false" style="height: 30px;">...</div>
<div class="btn-raplace">
  Select</code>```

which is why I am using the id in my xpath.

Thanks.

答:
I can see two mistakes in the Xpath you are using.

First Mistake:

.//*[contains(@id,'view-something_111111_2A22DF2_)'] is incorrect.You have placed the single quote at a wrong place. It should be
//div[contains(@id,'view-something_111111_2A22DF2')]

Second Mistake

The element div with the class="btn-raplace" is not the child of the above element. I can see in the HTML that the above element has the closing tags before this element.

Please replace your XPATH with:

             //div[contains(@id,'view-something_111111_2A22DF2')]/following-sibling::div[1]/a

Body:
I'm trying to get selenium to click the select button but I can't use by.linkText() because there are two buttons with the same name.
I'm using this xpath ".//*[contains(@id,'view-something_111111_2A22DF2_)']/div/a[text()='Select']"; to find the button but it can't find it.

I've also tried ".//*[contains(@id,'view-something_111111_2A22DF2_)']/div/a";.
I've looked over the Selenium documentation and can't seem to find a solution.

Here is the section of website code:

...

  Select

for reference, the second Select button has this code:

...

  Select

which is why I am using the id in my xpath.

Thanks.


问:
How do you hide auto x axis when y axis data is null or 0?
I'm trying to hide x axis value when y axis value is null o 0 in stacking column, that should be automatic when make filter with other field.

Code http://jsfiddle.net/o339uqLm/2/

答:
You can preprocess your data as Barabara Laird mentioned.

```<code>Array.prototype.clean = function(deleteValue) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] == deleteValue) {
      this.splice(i, 1)
      i--
    }
  }
  return this
}

const series = [{
  name: 'John',
  data: [4, 3, null, 7, 2]
}, {
  name: 'Jane',
  data: [5, 2, null, 2, 1]
}, {
  name: 'Joe',
  data: [1, 4, null, 2, 5]
}]

for (let i = 0; i < series.length; ++i) {
    // Remove nulls for data in all series
    series[i].data.clean()
}

const options = {
  chart: {
    type: 'column'
  },
  title: {
    text: 'Stacked column chart'
  },
  xAxis: {
    categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
  },
  yAxis: {
    min: 0,
    title: {
      text: 'Total fruit consumption'
    },
    stackLabels: {
      enabled: true,
      style: {
        fontWeight: 'bold',
        color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
      }
    }
  },
  legend: {
    align: 'right',
    x: -30,
    verticalAlign: 'top',
    y: 25,
    floating: true,
    backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || 'white',
    borderColor: '#CCC',
    borderWidth: 1,
    shadow: false
  },
  tooltip: {
    headerFormat: '<b>{point.x}</b><br/>',
    pointFormat: '{series.name}: {point.y}<br/>Total: {point.stackTotal}'
  },
  plotOptions: {
    column: {
      stacking: 'normal',
      dataLabels: {
        enabled: true,
        color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white'
      }
    }
  },
  series: series
}

const chart = Highcharts.chart('container', options)
</code>```

Live example:
http://jsfiddle.net/m62dxf9h/

Body:
You can preprocess your data as Barabara Laird mentioned.

Array.prototype.clean = function(deleteValue) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] == deleteValue) {
      this.splice(i, 1)
      i--
    }
  }
  return this
}

const series = [{
  name: 'John',
  data: [4, 3, null, 7, 2]
}, {
  name: 'Jane',
  data: [5, 2, null, 2, 1]
}, {
  name: 'Joe',
  data: [1, 4, null, 2, 5]
}]

for (let i = 0; i < series.length; ++i) {
    // Remove nulls for data in all series
    series[i].data.clean()
}

const options = {
  chart: {
    type: 'column'
  },
  title: {
    text: 'Stacked column chart'
  },
  xAxis: {
    categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
  },
  yAxis: {
    min: 0,
    title: {
      text: 'Total fruit consumption'
    },
    stackLabels: {
      enabled: true,
      style: {
        fontWeight: 'bold',
        color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
      }
    }
  },
  legend: {
    align: 'right',
    x: -30,
    verticalAlign: 'top',
    y: 25,
    floating: true,
    backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || 'white',
    borderColor: '#CCC',
    borderWidth: 1,
    shadow: false
  },
  tooltip: {
    headerFormat: '<b>{point.x}</b><br/>',
    pointFormat: '{series.name}: {point.y}<br/>Total: {point.stackTotal}'
  },
  plotOptions: {
    column: {
      stacking: 'normal',
      dataLabels: {
        enabled: true,
        color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white'
      }
    }
  },
  series: series
}

const chart = Highcharts.chart('container', options)

Live example:
http://jsfiddle.net/m62dxf9h/


问:
How to convert CSV file to XML format using linux script in linux box
I need to convert the CSV file to XML format to meet one of my requirement.
I am completely new for this process.

I have refereed some links like:
https://help.ubuntu.com/community/Converting%20CSV%20to%20XML

here they have asked to install tools.
But i don't have privilege to install any tool in the server.
So i need to try with any linux script to achieve my task.

before i have used xlsx2csv script for converting xlsx file to csv. in the same manner i am trying to get the script.

I have tried with https://gist.github.com/AnthonyNystrom/5547886
i am not able read the input file it self. I am trying in our linux server

Can any one help me on finding the solution.

Thanks for your help in advance.

答:
I have tried with the following code and got the result as excepted
I have created an shell script and added the below code with an sample csv file like
sample.csv

id,name,age
    1,Test,23
    2,Testing,32
    3,Cool, 23

csv2xml.sh

```<code>`#!/bin/bash
file_in="sample.csv"
file_out="sample.xml"
echo '<?xml version="1.0"?>' > $file_out
echo '<Customers>' >> $file_out
while IFS=$',' read -r -a arry
do
echo '  <Customer>' >> $file_out
echo '    <Name>'${arry[0]}'</Name>' >> $file_out
echo '    <Age>'${arry[1]}'</Age>' >> $file_out
echo '    <Country>'${arry[2]}'</Country>' >> $file_out
echo '  </Customer>' >> $file_out
done < $file_in
echo '</Customers>' >> $file_out`
</code>```

if we run the above script we will get an sample.xml file.
even we can change the format based on the requirement.
Thanks for the support.

Body:
I have tried with the following code and got the result as excepted
I have created an shell script and added the below code with an sample csv file like
sample.csv

id,name,age
    1,Test,23
    2,Testing,32
    3,Cool, 23

csv2xml.sh

`#!/bin/bash
file_in="sample.csv"
file_out="sample.xml"
echo '<?xml version="1.0"?>' > $file_out
echo '<Customers>' >> $file_out
while IFS=$',' read -r -a arry
do
echo '  <Customer>' >> $file_out
echo '    <Name>'${arry[0]}'</Name>' >> $file_out
echo '    <Age>'${arry[1]}'</Age>' >> $file_out
echo '    <Country>'${arry[2]}'</Country>' >> $file_out
echo '  </Customer>' >> $file_out
done < $file_in
echo '</Customers>' >> $file_out`

if we run the above script we will get an sample.xml file.
even we can change the format based on the requirement.
Thanks for the support.


问:
flask production and development mode
I have developed an application with flask, and I want to publish it for production, but I do not know how to make a separation between the production and development environment (database and code), have you documents to help me or  code.
I specify in the config.py file the two environment but I do not know how to do with.</p>

```<code>class DevelopmentConfig(Config):
    """
    Development configurations
    """
    DEBUG = True
    SQLALCHEMY_ECHO = True
    ASSETS_DEBUG = True
    DATABASE = 'teamprojet_db'
    print('THIS APP IS IN DEBUG MODE. YOU SHOULD NOT SEE THIS IN PRODUCTION.')

class ProductionConfig(Config):
    """
    Production configurations
    """
    DEBUG = False
    DATABASE = 'teamprojet_prod_db'
</code>```

答:
One convention used is to specify an environment variable before starting your application.

For example

```<code>$ ENV=prod; python run.py
</code>```

In your app, you check the value of that environment variable to determine which config to use. In your case:

run.py

```<code>import os
if os.environ['ENV'] == 'prod':
    config = ProductionConfig()
else:
    config = DevelopmentConfig()
</code>```

It is also worth noting that the statement

```<code>print('THIS APP IS IN DEBUG MODE. YOU SHOULD NOT SEE THIS IN PRODUCTION.')
</code>```

prints no matter which ENV you set since the interpreter executes all the code in the class definitions before running the rest of the script.

Title: flask production and development mode

Body:
I have developed an application with flask, and I want to publish it for production, but I do not know how to make a separation between the production and development environment (database and code), have you documents to help me or  code.
I specify in the config.py file the two environment but I do not know how to do with.

class DevelopmentConfig(Config):
    """
    Development configurations
    """
    DEBUG = True
    SQLALCHEMY_ECHO = True
    ASSETS_DEBUG = True
    DATABASE = 'teamprojet_db'
    print('THIS APP IS IN DEBUG MODE. YOU SHOULD NOT SEE THIS IN PRODUCTION.')

class ProductionConfig(Config):
    """
    Production configurations
    """
    DEBUG = False
    DATABASE = 'teamprojet_prod_db'

Body:
One convention used is to specify an environment variable before starting your application.

For example

$ ENV=prod; python run.py

In your app, you check the value of that environment variable to determine which config to use. In your case:

run.py

import os
if os.environ['ENV'] == 'prod':
    config = ProductionConfig()
else:
    config = DevelopmentConfig()

It is also worth noting that the statement

print('THIS APP IS IN DEBUG MODE. YOU SHOULD NOT SEE THIS IN PRODUCTION.')

prints no matter which ENV you set since the interpreter executes all the code in the class definitions before running the rest of the script.


问:
Pcre regex with lazy quantifier
I need a PCRE compatible regex to capture My-Test & 12345 from this string:

```<code>"My-Test:abc,def,ghi,jkl:12345"
</code>```

Here is what I have got so far:

```<code>/(?<=:)(.*)(?=:)/g
</code>```

https://regex101.com/r/xKgh7j/1
I need the other parts of the entire line. My-Test is before the first colon. 12345 will always come after second (or last) colon.

Title: Pcre regex with lazy quantifier

Body:
I need a PCRE compatible regex to capture My-Test & 12345 from this string:

"My-Test:abc,def,ghi,jkl:12345"

Here is what I have got so far:

/(?<=:)(.*)(?=:)/g

https://regex101.com/r/xKgh7j/1
I need the other parts of the entire line. My-Test is before the first colon. 12345 will always come after second (or last) colon.

Body:
Try this one ^([^:]+):[^:]+:(.*)$

https://regex101.com/r/Ebkzjb/1


问:
Angular - Date pipe
I'm trying to show a date correctly on IE in Angular. It's working fine in Chrome, Firefox, etc., but not on IE. This is my code :

```<code><span>{{menu.modifiedDate ? (menu.modifiedDate | date : "dd-MM-y HH:mm:ss") : '-'}}</span>
</code>```

This is what Google Chrome is showing :

```<code>15-06-2017 08:39:39
</code>```

And this is what IE is showing :

```<code>15-06-2017 08:00:6/15/2017 8:39:39 AM:6/15/2017 8:39:39 AM
</code>```

What's wrong ?

答:
That is an old issue
https://github.com/angular/angular.js/issues/13880

You might be working with an old version. Upgrading to the latest stable version should fix the problem.

Title: Angular - Date pipe

Body:
I'm trying to show a date correctly on IE in Angular. It's working fine in Chrome, Firefox, etc., but not on IE. This is my code :

{{menu.modifiedDate ? (menu.modifiedDate | date : "dd-MM-y HH:mm:ss") : '-'}}

This is what Google Chrome is showing :

15-06-2017 08:39:39

And this is what IE is showing :

15-06-2017 08:00:6/15/2017 8:39:39 AM:6/15/2017 8:39:39 AM

What's wrong ?


问:
Will code built with IDTSComponentMetaData100 work against SQL Server 2016
We have an application that generates SSIS packages for SQL Server based on user input and file scanning. The code that builds the packages is based on the methods in the IDTSComponentMetaData100 Interface.

Browsing that documentation, I note that the available "versions" only cover SQL Server 2012 and 2014. Does this mean that SQL Server 2016 will not be back compatible with this interface?

答:
I don't think so based on this:
https://msdn.microsoft.com/en-us/library/microsoft.sqlserver.dts.pipeline.wrapper.idtscomponentmetadata130.aspx</p>