问:
Type Inheritance Issue
I don't really know how to explain the problem I have. Below is an example of a few objects I have.

Lets say I have classes

```<code>public class Foo{}
public class FooBar extends Foo{}
</code>```

All of that is fine, however if I take a list and say I want it to be full of Foo objects, I cannot provide it a FooBar object. Why is this?

Example:

```<code>List<Foo> fooList = Arrays.asList(new FooBar());
</code>```

If FooBar extends Foo, why cant it be cast back to Foo?

答:
As already mentioned in comments Arrays.asList(T...) returns List<T>. Since you passed FooBar instance to that method type inference from Java 7 used FooBar type as T representation which means that this method returns List<FooBar> which can't be assigned to List<Foo> (you can read more about it at: Is List<Dog> a subclass of List<Animal>? Why aren't Java's generics implicitly polymorphic?)

In Java 8 type inference was improved to make lambdas more useful. Now T infers type not only from parameters, but also from target - reference variable which should hold result. This allows T to infer Foo from List<Foo> fooList rather than new FooBar() argument.

To solve this problem in earlier versions like in your case Java 7 you can explicitly set generic type for generic method asList like

```<code>List<Foo> fooList = Arrays.<Foo>asList(new FooBar());
//                         ^^^^^ -- set generic types before method name
</code>```

More info at: https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html (especially "Target Types" section)

Title: Type Inheritance Issue

Body:
I don't really know how to explain the problem I have. Below is an example of a few objects I have.

Lets say I have classes

public class Foo{}
public class FooBar extends Foo{}

All of that is fine, however if I take a list and say I want it to be full of Foo objects, I cannot provide it a FooBar object. Why is this?

Example:

List<Foo> fooList = Arrays.asList(new FooBar());

If FooBar extends Foo, why cant it be cast back to Foo?

Body:
As already mentioned in comments Arrays.asList(T...) returns List<T>. Since you passed FooBar instance to that method type inference from Java 7 used FooBar type as T representation which means that this method returns List<FooBar> which can't be assigned to List<Foo> (you can read more about it at: Is List<Dog> a subclass of List<Animal>? Why aren't Java's generics implicitly polymorphic?)

In Java 8 type inference was improved to make lambdas more useful. Now T infers type not only from parameters, but also from target - reference variable which should hold result. This allows T to infer Foo from List<Foo> fooList rather than new FooBar() argument.

To solve this problem in earlier versions like in your case Java 7 you can explicitly set generic type for generic method asList like

List<Foo> fooList = Arrays.<Foo>asList(new FooBar());
//                         ^^^^^ -- set generic types before method name

More info at: https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html (especially "Target Types" section)


来源: stackexchange

问:
Uploading an image in Codeigniter shows error The upload path does not appear to be valid
```<code>$config['upload_path'] = site_path().'photos/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '2048';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
    $this->data['alert'] = $this->upload->display_errors();
    $this->load->view('profile/photo', $this->data);
}
else
{
    $upload_data = $this->upload->data();

    $filename = $upload_data['file_name'];
    $width = $upload_data['image_width'];
    $height = $upload_data['image_height'];
    $config1 = array();
    $this->load->library('image_lib');
    $config1['source_image'] = site_path().'photos/'.$filename;

    $this->remove_existing_file($this->session->userdata('user_id'));
    $this->Profile_model->savephoto('Edit', $filename );
    redirect('/profile/photo');
}
</code>```

I am getting this error:

The upload path does not appear to be valid.

答:
Try out this code in your Controller

```<code>$config['upload_path'] = 'images'; //name of the uploading folder
$config['allowed_types'] = 'jpeg|png|jpg';
$config['file_name'] = 'name_for_file';

$this->load->library('upload', $config);
$this->upload->initialize($config);

if (!$this->upload->do_upload())
 {
  echo $this->upload->display_errors();
  exit;
 }
else
 {
  $upload_data = $this->upload->data();
 }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
$config['upload_path'] = site_path().'photos/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '2048';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
    $this->data['alert'] = $this->upload->display_errors();
    $this->load->view('profile/photo', $this->data);
}
else
{
    $upload_data = $this->upload->data();

    $filename = $upload_data['file_name'];
    $width = $upload_data['image_width'];
    $height = $upload_data['image_height'];
    $config1 = array();
    $this->load->library('image_lib');
    $config1['source_image'] = site_path().'photos/'.$filename;

    $this->remove_existing_file($this->session->userdata('user_id'));
    $this->Profile_model->savephoto('Edit', $filename );
    redirect('/profile/photo');
}

I am getting this error:

The upload path does not appear to be valid.

Body:
Try out this code in your Controller

$config['upload_path'] = 'images'; //name of the uploading folder
$config['allowed_types'] = 'jpeg|png|jpg';
$config['file_name'] = 'name_for_file';

$this->load->library('upload', $config);
$this->upload->initialize($config);

if (!$this->upload->do_upload())
 {
  echo $this->upload->display_errors();
  exit;
 }
else
 {
  $upload_data = $this->upload->data();
 }


问:
How to convert Ruby code using Selenium into Selenese script?
How can I convert Ruby code using Selenium commands into Selenese script?

For example, how could I get the Selenese version of the following Ruby code?

```<code>@driver = Selenium::WebDriver.for:firefox # firefox,ie,chrome
@driver.navigate.to "http://www.google.com"

ele =@driver.find_element(:name,'q')
ele.send_keys "Technologies"
ele.submit
</code>```

答:
Did you use Selenium IDE, the Firefox plugin ? you can convert Selenium test into an other language script : Ruby, test jUnit, TestNG !

But i am not sure you can do Ruby to Selenium.

Body:
How can I convert Ruby code using Selenium commands into Selenese script?

For example, how could I get the Selenese version of the following Ruby code?

@driver = Selenium::WebDriver.for:firefox # firefox,ie,chrome
@driver.navigate.to "http://www.google.com"

ele =@driver.find_element(:name,'q')
ele.send_keys "Technologies"
ele.submit

ContentLicense: CC BY-SA 2.5


问:
How to get all column values from csv using pandas
I have a table in .csv which contains some random messages:

```<code>id,msg
2,start
1,bot
1,run
2,san
</code>```

I want to get only rows which match certain condition. I managed to do that, but I want to get all cell values of column - msg which match condition.

My code:

```<code>df = pd.read_csv('msgs.csv')

# if id==2 and msg contains letter 'a'
p = df[(df['id'] == 2) & (df['msg'].str.contains('a'))]
print(p)

for row in p:
    print(p.iloc[0]['msg'])
</code>```

When I print(p) my result (which is good) is:

```<code>           id msg
1          2  start
5          2    san
</code>```

And I want to have output like this :

```<code>start
san
</code>```

But when I try to do it with iloc I get only first cell value:

```<code>start
start
</code>```

Probably the solution is easy but I don't know how to get it. Thanks in advance.

答:
You can always iterate through each row in the csv like this:

```<code>for row_number,id,msg in p:
    print(row-number,id,msg)
</code>```

This will get you the following result:

```<code>1 2  start
5 2  san
</code>```

So if you want just the 'msg' then print this:

```<code>for row_number,id,msg in p:
    print(msg)
</code>```

Hope this helps!

Body:
I have a table in .csv which contains some random messages:

id,msg
2,start
1,bot
1,run
2,san

I want to get only rows which match certain condition. I managed to do that, but I want to get all cell values of column - msg which match condition.

My code:

df = pd.read_csv('msgs.csv')

# if id==2 and msg contains letter 'a'
p = df[(df['id'] == 2) & (df['msg'].str.contains('a'))]
print(p)

for row in p:
    print(p.iloc[0]['msg'])

When I print(p) my result (which is good) is:

           id msg
1          2  start
5          2    san

And I want to have output like this :

start
san

But when I try to do it with iloc I get only first cell value:

start
start

Probably the solution is easy but I don't know how to get it. Thanks in advance.

Body:
You can always iterate through each row in the csv like this:

for row_number,id,msg in p:
    print(row-number,id,msg)

This will get you the following result:

1 2  start
5 2  san

So if you want just the 'msg' then print this:

for row_number,id,msg in p:
    print(msg)

Hope this helps!


问:
In UWP, how can I reset an app’s data?
I know that in order to reset an app’s data, I have to open the Settings app from Start menu. Head to System > Apps & Features, locate the app, then click the "Advance Options" and tap Reset but I want to achieve this by code. I think I have to call this line but I don't know if I have to do something else: Windows.Storage.ApplicationData.Current.ClearAsync()</p>

答:
As the document ClearAsync method,

Removes all application data from the local, roaming, and temporary app data stores.

If a UWP app is installed, there will be the following folders in the app package folder of the AppData folder in your device.

When you use Advance Options and Reset, all the app data your app puts into all these folders will be cleared, but the behavior of using the await ApplicationData.Current.ClearAsync() method will just delete the data in LocalCache, LocalState, RoamingState and TempState folders including the LocalSettings.

Usually, we just operate the data in above four folders in the Application data locations when we develop our apps, so this ClearAsync method should satisfy our requirement that clearing the application data.

Title: In UWP, how can I reset an app’s data?


问:
how to use subtotal in SQL

I have a table with following data

```<code> CODE  NAME   AMOUNT VAT  TOTALAMT FLAG
  10   test1   100    10    110     1
  08   test2    0     0      0      1
  05   test3   10     0      0      2
  03   test4    0     0      0      2
</code>```

I want a query which give the following output.
(Subtotal according to FLAG)

```<code> CODE  NAME   AMOUNT VAT  TOTALAMT FLAG
  10   test1   100    10    110      1
  08   test2    0     0      0       1
 NULL SUBTOTAL 100    10    110    NULL
  05   test3   10     0      0       2
  03   test4    0     0      0       2
 NULL SUBTOTAL  10    0     10     NULL
TOTAL          110    10    120    NULL
</code>```

答:
Use ROLLUP:

```<code>SELECT
    MAX(CODE) AS CODE,
    NAME,
    MAX(AMOUNT) AS AMOUNT,
    MAX(VAT) AS VAT,
    MAX(TOTALAMT) AS TOTALAMT,
    FLAG
FROM yourTable
GROUP BY
    FLAG, NAME
WITH ROLLUP;
</code>```

Demo

Title: how to use subtotal in SQL

Body:
I have a table with following data

 CODE  NAME   AMOUNT VAT  TOTALAMT FLAG
  10   test1   100    10    110     1
  08   test2    0     0      0      1
  05   test3   10     0      0      2
  03   test4    0     0      0      2

I want a query which give the following output.
(Subtotal according to FLAG)

 CODE  NAME   AMOUNT VAT  TOTALAMT FLAG
  10   test1   100    10    110      1
  08   test2    0     0      0       1
 NULL SUBTOTAL 100    10    110    NULL
  05   test3   10     0      0       2
  03   test4    0     0      0       2
 NULL SUBTOTAL  10    0     10     NULL
TOTAL          110    10    120    NULL

Body:
Use ROLLUP:

SELECT
    MAX(CODE) AS CODE,
    NAME,
    MAX(AMOUNT) AS AMOUNT,
    MAX(VAT) AS VAT,
    MAX(TOTALAMT) AS TOTALAMT,
    FLAG
FROM yourTable
GROUP BY
    FLAG, NAME
WITH ROLLUP;

Demo


问:
Merge two mongo collections with query condition in pentaho
I have a problem querying two collections and combining the results to form another collection.

Collection1:

```<code>{
    "ResourceCost" : 0.0032258065,
    "ResourceId" : "i-08c35f123eea43f30",
    "Unit" : "USD",
    "billdate" : ISODate("2017-12-01T16:30:00.000Z")
}
</code>```

Collection 2:

```<code>{
    "resource_id" : "i-08c35f123eea43f30",
    "Timestamp" : ISODate("2017-12-01T18:30:00.000Z"),
    "Avg" : 0.0,
    "total" : 0.0,
    "sample_cnt" : 1440.0,
    "max" : 0.0,
    "min" : 0.0
}
</code>```

I need to update the collection 1 with collection 2 data. So finally I am expecting collection 1 data as below

Check with same time for both fields and resource id. Update the data

collection 1:

```<code>{
   "ResourceCost" : 0.0032258065,
   "ResourceId" : "i-08c35f123eea43f30",
   "Unit" : "USD",
   "billdate" : ISODate("2017-12-01T16:30:00.000Z")
   "Avg" : 0.0,
   "total" : 0.0,
   "sample_cnt" : 1440.0,
   "max" : 0.0,
   "min" : 0.0
}
</code>```

答:
I hope this helps,

```<code>db.col1.aggregate([
{
    $lookup:{
            from:"col2",
            localField:"ResourceId",
            foreignField:"resource_id",
            as:"result"
        }
},{
    $unwind:"$result"
},{
    $project:{
            "ResourceCost":"$ResourceCost",
            "ResourceId":"$ResourceId",
            "Unit":"$Unit",
            "billdate":"$billdate",
            "_id":0,
            "avg":"$result.Avg",
            "total":"$result.total",
            "sample_cnt":"$result.sample_cnt",
            "max":"$result.max",
            "min":"$result.min"
        }
}
])
</code>```

read about $loopup, $unwind and $project for reference.

Body:
I have a problem querying two collections and combining the results to form another collection.

Collection1:

{
    "ResourceCost" : 0.0032258065,
    "ResourceId" : "i-08c35f123eea43f30",
    "Unit" : "USD",
    "billdate" : ISODate("2017-12-01T16:30:00.000Z")
}

Collection 2:

{
    "resource_id" : "i-08c35f123eea43f30",
    "Timestamp" : ISODate("2017-12-01T18:30:00.000Z"),
    "Avg" : 0.0,
    "total" : 0.0,
    "sample_cnt" : 1440.0,
    "max" : 0.0,
    "min" : 0.0
}

I need to update the collection 1 with collection 2 data. So finally I am expecting collection 1 data as below

Check with same time for both fields and resource id. Update the data

collection 1:

{
   "ResourceCost" : 0.0032258065,
   "ResourceId" : "i-08c35f123eea43f30",
   "Unit" : "USD",
   "billdate" : ISODate("2017-12-01T16:30:00.000Z")
   "Avg" : 0.0,
   "total" : 0.0,
   "sample_cnt" : 1440.0,
   "max" : 0.0,
   "min" : 0.0
}

Body:
I hope this helps,

db.col1.aggregate([
{
    $lookup:{
            from:"col2",
            localField:"ResourceId",
            foreignField:"resource_id",
            as:"result"
        }
},{
    $unwind:"$result"
},{
    $project:{
            "ResourceCost":"$ResourceCost",
            "ResourceId":"$ResourceId",
            "Unit":"$Unit",
            "billdate":"$billdate",
            "_id":0,
            "avg":"$result.Avg",
            "total":"$result.total",
            "sample_cnt":"$result.sample_cnt",
            "max":"$result.max",
            "min":"$result.min"
        }
}
])

read about $loopup, $unwind and $project for reference.


问:
Visual Studio Advanced Query Builder MySql adding “def.” before the table names
I am trying to create dataset (.xsd) and link it with stored procedure in MySQL database.

the problem is when i connect it it's changing the schema name.

like if I have this stored procedure name or table name or whatever  :

News.tbNews

the builder it self change it to :

def.News.tbNews.
MySql version 5.5.8, MySqlConnector 6.3.4
I searched for a solution for this problem and one of the answers was to change the MySqlConnector from 6.3.4 to 6.3.6 !!!

I download the new connector  6.3.6 but it's giving me Error while installing it.

any Idea People ???

thanks and best regards.

答:
Ok ,the problem is solved now

all what you have to do is : 1- install framework 4.0 before installing the .net connector 6.3.6


问:
Regexp for match second numeric values
Current Strings are

```<code>   ABC 70 1 MG-MCG Paper
   ABC 70 10 MCG Paper
   ABC 70 150 MG-MCG Paper
   ABC 70 1.50 MG-MCG Paper
   ABC 70 10.50 MG-MCG Paper
   ABC 70 10-50 MG-MCG Paper

   ABC 705 1 MG-MCG Paper
   ABC 705 10 MCG Paper
   ABC 705 150 MG-MCG Paper
   ABC 705 1.50 MG-MCG Paper
   ABC 705 10.50 MG-MCG Paper
   ABC 705 10-50 MG Paper
</code>```

Expected Output :

```<code>1
 10
 150
 1.50
 10.50
 10-50
 1
 10
 150
 1.50
 10.50
 10-50
</code>```

Treid Exp -

```<code>string c=Regex.Match(result,@"(\d{4}|\d{3}|(..\.\d{1,2}))").Value;
return c
</code>```

How to select second numeric value and Before MG or MCG value

答:
Other answers went for a regex, but since the data is so well ordered, I'd suggest something else.

I would go for this:

```<code>string input="ABC 70 10-50 MG-MCG Paper";
string[] fields = input.split(new string[] { " " } ,
     StringSplitOptions.RemoveEmptyEntries);
</code>```

And then field[2] will contain what you want.

Title: Regexp for match second numeric values

Body:
Current Strings are

   ABC 70 1 MG-MCG Paper
   ABC 70 10 MCG Paper
   ABC 70 150 MG-MCG Paper
   ABC 70 1.50 MG-MCG Paper
   ABC 70 10.50 MG-MCG Paper
   ABC 70 10-50 MG-MCG Paper

   ABC 705 1 MG-MCG Paper
   ABC 705 10 MCG Paper
   ABC 705 150 MG-MCG Paper
   ABC 705 1.50 MG-MCG Paper
   ABC 705 10.50 MG-MCG Paper
   ABC 705 10-50 MG Paper

Expected Output :

1
 10
 150
 1.50
 10.50
 10-50
 1
 10
 150
 1.50
 10.50
 10-50

Treid Exp -

string c=Regex.Match(result,@"(\d{4}|\d{3}|(..\.\d{1,2}))").Value;
return c

How to select second numeric value and Before MG or MCG value

Body:
Other answers went for a regex, but since the data is so well ordered, I'd suggest something else.

I would go for this:

string input="ABC 70 10-50 MG-MCG Paper";
string[] fields = input.split(new string[] { " " } ,
     StringSplitOptions.RemoveEmptyEntries);

And then field[2] will contain what you want.


问:
Android Radio Button Group, why I need this?
Why i need to add if (null != rb && checkedId > -1), if I remove the code, the program still work. What's the benefit of this line of code?

```<code>radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            RadioButton rb = (RadioButton) group.findViewById(checkedId);
            if (null != rb && checkedId > -1) {

                switch (rb.getId()){

                    case R.id.radioFast:
                        mAnimOption = FAST;
                        break;

                    case R.id.radioSlow:
                        mAnimOption = SLOW;
                        break;

                    case R.id.radioNone:
                        mAnimOption = NONE;
                        break;

                }
                // End switch block

                mEditor.putInt("anim option", mAnimOption);

            }

        }
    });
</code>```

答:
As other answers says it is required to avoid NullPointerException I agree with them.

But as per your code it's not required. You don't need to check for the null. Here's why?

The method

```<code>public void onCheckedChanged(RadioGroup group, int checkedId) {}
</code>```

returns group object of type RadioGroup and currently selected RadioButton id as checkedId. Hence you don't need to check for the null as you already have checkedId.

So directly use switch statement to compare between expected cases.

If checkedId is not matching with cases (i.e, -1 or other value) use default case.

Body:
Why i need to add if (null != rb && checkedId > -1), if I remove the code, the program still work. What's the benefit of this line of code?

radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            RadioButton rb = (RadioButton) group.findViewById(checkedId);
            if (null != rb && checkedId > -1) {

                switch (rb.getId()){

                    case R.id.radioFast:
                        mAnimOption = FAST;
                        break;

                    case R.id.radioSlow:
                        mAnimOption = SLOW;
                        break;

                    case R.id.radioNone:
                        mAnimOption = NONE;
                        break;

                }
                // End switch block

                mEditor.putInt("anim option", mAnimOption);

            }

        }
    });

Body:
As other answers says it is required to avoid NullPointerException I agree with them.

But as per your code it's not required. You don't need to check for the null. Here's why?

The method

public void onCheckedChanged(RadioGroup group, int checkedId) {}

returns group object of type RadioGroup and currently selected RadioButton id as checkedId. Hence you don't need to check for the null as you already have checkedId.

So directly use switch statement to compare between expected cases.

If checkedId is not matching with cases (i.e, -1 or other value) use default case.


问:
How to center a cell in UICollectionView?
I have a UICollectionView which consists of 12 cells from Jan to Dec as shown in the screenshot below:

How can I make the current month to always to be at the center of the collection view? For example, Dec shall be shown on the center for this month.

One of the solutions is to scroll automatically to the next page and center the 12th cell but how can I achieve that?

答:
You can use the cellForItem function to define how the cells are going to appear and the UICollectionView function reloadData() to update all the cells always you think it's necessary.

If December should be the cell in the middle, make sure that 5 or 6 cells come before December, you should be able to do this with simple conditions inside cellForItem.

For example, as you have 12 cells, you can get the current month as and integer (12 for December), and you will know that the first month will be 12 - 6 = 6 (June), so you can do this calculation for each indexPath.

To simplify your job:

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = ...
    let month = GetCurrentMonthAsInteger()
    var cellMonth = month - 6 + indexPath.row //or section if you have 12 sections
    if(cellMonth < 1) {cellMonth = 12 + cellMonth}
    else if(cellMonth > 12) {cellMonth = cellMonth - 12}
    cell.setInformationForMonth(cellMonth)
    ...
    return cell
}
</code>```

Body:
You can use the cellForItem function to define how the cells are going to appear and the UICollectionView function reloadData() to update all the cells always you think it's necessary.

If December should be the cell in the middle, make sure that 5 or 6 cells come before December, you should be able to do this with simple conditions inside cellForItem.

For example, as you have 12 cells, you can get the current month as and integer (12 for December), and you will know that the first month will be 12 - 6 = 6 (June), so you can do this calculation for each indexPath.

To simplify your job:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = ...
    let month = GetCurrentMonthAsInteger()
    var cellMonth = month - 6 + indexPath.row //or section if you have 12 sections
    if(cellMonth < 1) {cellMonth = 12 + cellMonth}
    else if(cellMonth > 12) {cellMonth = cellMonth - 12}
    cell.setInformationForMonth(cellMonth)
    ...
    return cell
}


问:
Calling Java method by passing a vector in JNI
How would one call a Java method by passing a vector object in JNI (using C++)? I've something like this:

Java:

```<code>public void methodOne(int[] data) {
    ...
}
</code>```

C++:

```<code>...
jMethodOne = env->GetMethodID(jActivityClass, "methodOne", "([I)V");
void mNativeMethod(std::vector<int> dataVector)
{
    // how to call method one by passing the vector? I've tried following way and I got SIGABRT error, even after converting dataVector to an int array
    env->CallVoidMethod(jObject, jMethodOne, dataVector);
}
</code>```

I've tried the above
 and I got SIGABRT error, even after converting dataVector to an int array

答:
I had to do something like this:</p>

```<code>void mNativeMethod(std::vector<int> dataVector)
{
    unsigned long size = dataVector.size();
    jfloat outCArray[size];
    std::copy(dataVector.begin(), dataVector.end(), outCArray);

    jfloatArray outJNIArray = jniEnv->NewFloatArray(size);
    jniEnv->SetFloatArrayRegion(outJNIArray, 0, size, outCArray);
    jniEnv->CallVoidMethod(jObject, jMethodOne, outJNIArray);
}
</code>```

Body:
How would one call a Java method by passing a vector object in JNI (using C++)? I've something like this:

Java:

public void methodOne(int[] data) {
    ...
}

C++:

...
jMethodOne = env->GetMethodID(jActivityClass, "methodOne", "([I)V");
void mNativeMethod(std::vector<int> dataVector)
{
    // how to call method one by passing the vector? I've tried following way and I got SIGABRT error, even after converting dataVector to an int array
    env->CallVoidMethod(jObject, jMethodOne, dataVector);
}

I've tried the above
 and I got SIGABRT error, even after converting dataVector to an int array

Body:
I had to do something like this:

void mNativeMethod(std::vector<int> dataVector)
{
    unsigned long size = dataVector.size();
    jfloat outCArray[size];
    std::copy(dataVector.begin(), dataVector.end(), outCArray);

    jfloatArray outJNIArray = jniEnv->NewFloatArray(size);
    jniEnv->SetFloatArrayRegion(outJNIArray, 0, size, outCArray);
    jniEnv->CallVoidMethod(jObject, jMethodOne, outJNIArray);
}


问:
Is there any expiry time for blob URL when it is stored in indexed db of chrome browser?
I am converting a normal image/video Url into a blob Url ,after conversion i'm storing it in INDEXED DB of chrome browser. To run the assets(image/video) in offline mode I have made this conversion.

When i run my application for three days continuously without internet,the image/video is not coming. As i'm running my application(it is a chrome extension ) in chrome box I cant able to inspect and see the error.Is there any expiry time for blob Url.

I have seen for whether auto clear of data is happening in indexed db  or not, but for chrome extensions the indexed db will not get clear unless the user deleted it manually.

Thanks in advance

答: Check out this module, it lets you set data in your indexedDB only for x mins. After which, data is cleared automatically.</p>


问:
how to populate gridview from ajax call using Yii2
In my project, I have created a search box. when I type something and click the button "get info" I get all information in console window using ajax call. now I want to populate this data in yii2 gridview. data will different at every runtime. I want to give this data to $dataprovider of gridview is it possible??

here is code-
CompaniesController.php

```<code>public function actionCompanyinfo(){

    $text_in_search = $_GET['text_in_search'];
    $left_items_cat = ltrim($_GET['left_items_cat']);

    if($left_items_cat == "Companies"){

         $query = (new \yii\db\Query())
                ->select(['c.name', 'c.id'])
                ->from(['companies as c'])
                ->where('c.name LIKE :query')
                ->addParams([':query'=>'%'.$text_in_search.'%'])
                ->all();

        $response['comapnies_matching'] = $query;
            return \yii\helpers\Json::encode([
        $response
    ]);

    }
}
</code>```

companies/index.php

```<code>$form = ActiveForm::begin();
 $typeahead = $form->field($model, 'name')->textInput(['maxlength' => true]);

$getinfobtn = Html::SubmitButton( 'Get info', [ 'class' => 'btn btn-success' , 'id' =>'getinfo']) ;
   ActiveForm::end();
</code>```

myjsfile.js

```<code>$("#getinfo").click(function(){
        var text_in_search = $("#companies-name").val();
        var left_items_cat = $('#left-items li.active').text();
        var url = "index.php?r=companies/companyinfo";

        $.ajax({
        url: url,
        dataType: 'json',
        method: 'GET',
        data: {text_in_search,left_items_cat},
        success: function (data, textStatus, jqXHR) {
             // $( "#country"+id ).html(data[0].countries);
             console.log(data[0]);
           // **want to show this data in yii2 grid view**
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log('An error occured!');
            alert('Error in ajax request');
        }
    });
</code>```

console window

```<code>comapnies_matching
:
Array(3)
0
:
{name: "ADC Therapeutics Sarl", id: "402"}
1
:
{name: "ADC Therapeutics Sarl", id: "407"}
2
:
{name: "ADC Therapeutics Sarl", id: "412"}
</code>```

how to show/ populate this data in gridview??

答:
CompaniesController.php

```<code>public function actionCompanyinfo(){

$text_in_search = $_GET['text_in_search'];
$left_items_cat = ltrim($_GET['left_items_cat']);

if($left_items_cat == "Companies"){

     $dataProvider= (new \yii\db\Query())
            ->select(['c.name', 'c.id'])
            ->from(['companies as c'])
            ->where('c.name LIKE :query')
            ->addParams([':query'=>'%'.$text_in_search.'%'])
            ->all();

    return $this->renderPartial('gridview', [
        'dataProvider' => $dataProvider,
    ]);

}}
</code>```

You need to render the gridview in gridview.php view file

myjsfile.js

```<code>$("#getinfo").click(function(){
    var text_in_search = $("#companies-name").val();
    var left_items_cat = $('#left-items li.active').text();
    var url = "index.php?r=companies/companyinfo";

    $.ajax({
    url: url,
    method: 'GET',
    data: {text_in_search,left_items_cat},
    success: function (data, textStatus, jqXHR) {
         //set the ajax response as your html content
         $('#myDiv').html(data);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        console.log('An error occured!');
        alert('Error in ajax request');
    }
});
</code>```

Body:
In my project, I have created a search box. when I type something and click the button "get info" I get all information in console window using ajax call. now I want to populate this data in yii2 gridview. data will different at every runtime. I want to give this data to $dataprovider of gridview is it possible??

here is code-
CompaniesController.php

public function actionCompanyinfo(){

    $text_in_search = $_GET['text_in_search'];
    $left_items_cat = ltrim($_GET['left_items_cat']);

    if($left_items_cat == "Companies"){

         $query = (new \yii\db\Query())
                ->select(['c.name', 'c.id'])
                ->from(['companies as c'])
                ->where('c.name LIKE :query')
                ->addParams([':query'=>'%'.$text_in_search.'%'])
                ->all();

        $response['comapnies_matching'] = $query;
            return \yii\helpers\Json::encode([
        $response
    ]);

    }
}

companies/index.php

$form = ActiveForm::begin();
 $typeahead = $form->field($model, 'name')->textInput(['maxlength' => true]);

$getinfobtn = Html::SubmitButton( 'Get info', [ 'class' => 'btn btn-success' , 'id' =>'getinfo']) ;
   ActiveForm::end();

myjsfile.js

$("#getinfo").click(function(){
        var text_in_search = $("#companies-name").val();
        var left_items_cat = $('#left-items li.active').text();
        var url = "index.php?r=companies/companyinfo";

        $.ajax({
        url: url,
        dataType: 'json',
        method: 'GET',
        data: {text_in_search,left_items_cat},
        success: function (data, textStatus, jqXHR) {
             // $( "#country"+id ).html(data[0].countries);
             console.log(data[0]);
           // **want to show this data in yii2 grid view**
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log('An error occured!');
            alert('Error in ajax request');
        }
    });

console window

comapnies_matching
:
Array(3)
0
:
{name: "ADC Therapeutics Sarl", id: "402"}
1
:
{name: "ADC Therapeutics Sarl", id: "407"}
2
:
{name: "ADC Therapeutics Sarl", id: "412"}

how to show/ populate this data in gridview??

Body:
CompaniesController.php

public function actionCompanyinfo(){

$text_in_search = $_GET['text_in_search'];
$left_items_cat = ltrim($_GET['left_items_cat']);

if($left_items_cat == "Companies"){

     $dataProvider= (new \yii\db\Query())
            ->select(['c.name', 'c.id'])
            ->from(['companies as c'])
            ->where('c.name LIKE :query')
            ->addParams([':query'=>'%'.$text_in_search.'%'])
            ->all();

    return $this->renderPartial('gridview', [
        'dataProvider' => $dataProvider,
    ]);

}}

You need to render the gridview in gridview.php view file

myjsfile.js

$("#getinfo").click(function(){
    var text_in_search = $("#companies-name").val();
    var left_items_cat = $('#left-items li.active').text();
    var url = "index.php?r=companies/companyinfo";

    $.ajax({
    url: url,
    method: 'GET',
    data: {text_in_search,left_items_cat},
    success: function (data, textStatus, jqXHR) {
         //set the ajax response as your html content
         $('#myDiv').html(data);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        console.log('An error occured!');
        alert('Error in ajax request');
    }
});


问:
If I want to connect EC2 to RDS in a VPC, what hostname should I use?
I have an application running in EC2 and a PostgreSQL db running in RDS, both inside the same VPC. I believe I have created the necessary security group, but how do I determine the hostname of the db server to use from my application?</p>

答:
Expand the row for that instance in the RDS dashboard. Then you can see the DNS name to use next to "Endpoint:".

My RDS instance in the image above has the domain: [redacted].us-west-2.rds.amazonaws.com. Hovering over the information icon (i on a dark circle) next to it shows me the security groups that can access it.


问:
ConstraintLayout Visibility Show not working after taking picture with camera
I need to take a picture and show it in SelectedImageView which is located inside SelectedImageConstraintLayout. It works perfectly when I open the gallery and select a picture, but it is not working for the camera. SelectedImageConstraintLayout is not visible at all.

```<code>void OpenCamera()
{
    Intent intent = new Intent(MediaStore.ActionImageCapture);
    var filename = new File(this.ViewModel.IssuePhotosDirPath,
                            this.ViewModel.TEMP_PHOTO_FILENAME);
    intent.PutExtra(MediaStore.ExtraOutput, Uri.FromFile(filename));
    StartActivityForResult(intent, OPEN_CAMERA_ID);
}

protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
    base.OnActivityResult(requestCode, resultCode, data);
    if (resultCode == Result.Ok)
    {
        var issuePhotoFilename = System.IO.Path.Combine(this.ViewModel.IssuePhotosDirPath,
                                                        this.ViewModel.TEMP_PHOTO_FILENAME);

        switch(requestCode)
        {
            case OPEN_CAMERA_ID:
                ShowIssueImage(issuePhotoFilename);
                break;
            case OPEN_GALLERY_ID:
                //do something to save the image in temp file before showing it
                ShowIssueImage(issuePhotoFilename);
                break;
        }
    }
}

void ShowIssueImage(string fileName)
{
     if (SelectedImageViewWidth > 0 && SelectedImageViewHeight > 0)
     {
          var bitmap = fileName.ResizeAndRotate(SelectedImageViewWidth, SelectedImageViewHeight);
          SelectedImageView.SetImageBitmap(bitmap);
          bitmap = null;
     }
     else
     {
          SelectedImageView.SetImageBitmap(BitmapFactory.DecodeFile(fileName));
     }

     AddImageConstraintLayout.Visibility = ViewStates.Gone;
     SelectedImageConstraintLayout.Visibility = ViewStates.Visible;
}

void RemoveIssueImage()
{
     SelectedImageConstraintLayout.Visibility = ViewStates.Gone;
     AddImageConstraintLayout.Visibility = ViewStates.Visible;

     var issuePhotoFilename = System.IO.Path.Combine(this.ViewModel.IssuePhotosDirPath, this.ViewModel.TEMP_PHOTO_FILENAME);
     System.IO.File.Delete(issuePhotoFilename);
}
</code>```

What is wrong with this?

答:
I have found that using ViewState.Invisible instead of ViewStates.Gone resolve it. Although I don't know why ViewState.Gone works for picking image from gallery.

```<code>void RemoveIssueImage()
{
     //Here, I need to change it from ViewStates.Gone to ViewStates.Invisible
     SelectedImageConstraintLayout.Visibility = ViewStates.Invisible;

     AddImageConstraintLayout.Visibility = ViewStates.Visible;

     var issuePhotoFilename = System.IO.Path.Combine(this.ViewModel.IssuePhotosDirPath, this.ViewModel.TEMP_PHOTO_FILENAME);
     System.IO.File.Delete(issuePhotoFilename);
}
</code>```

and later in ShowIssueImage function, change AddImageConstraintLayout.Visibility to ViewStates.Invisible.

Body:
I need to take a picture and show it in SelectedImageView which is located inside SelectedImageConstraintLayout. It works perfectly when I open the gallery and select a picture, but it is not working for the camera. SelectedImageConstraintLayout is not visible at all.

void OpenCamera()
{
    Intent intent = new Intent(MediaStore.ActionImageCapture);
    var filename = new File(this.ViewModel.IssuePhotosDirPath,
                            this.ViewModel.TEMP_PHOTO_FILENAME);
    intent.PutExtra(MediaStore.ExtraOutput, Uri.FromFile(filename));
    StartActivityForResult(intent, OPEN_CAMERA_ID);
}

protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
    base.OnActivityResult(requestCode, resultCode, data);
    if (resultCode == Result.Ok)
    {
        var issuePhotoFilename = System.IO.Path.Combine(this.ViewModel.IssuePhotosDirPath,
                                                        this.ViewModel.TEMP_PHOTO_FILENAME);

        switch(requestCode)
        {
            case OPEN_CAMERA_ID:
                ShowIssueImage(issuePhotoFilename);
                break;
            case OPEN_GALLERY_ID:
                //do something to save the image in temp file before showing it
                ShowIssueImage(issuePhotoFilename);
                break;
        }
    }
}

void ShowIssueImage(string fileName)
{
     if (SelectedImageViewWidth > 0 && SelectedImageViewHeight > 0)
     {
          var bitmap = fileName.ResizeAndRotate(SelectedImageViewWidth, SelectedImageViewHeight);
          SelectedImageView.SetImageBitmap(bitmap);
          bitmap = null;
     }
     else
     {
          SelectedImageView.SetImageBitmap(BitmapFactory.DecodeFile(fileName));
     }

     AddImageConstraintLayout.Visibility = ViewStates.Gone;
     SelectedImageConstraintLayout.Visibility = ViewStates.Visible;
}

void RemoveIssueImage()
{
     SelectedImageConstraintLayout.Visibility = ViewStates.Gone;
     AddImageConstraintLayout.Visibility = ViewStates.Visible;

     var issuePhotoFilename = System.IO.Path.Combine(this.ViewModel.IssuePhotosDirPath, this.ViewModel.TEMP_PHOTO_FILENAME);
     System.IO.File.Delete(issuePhotoFilename);
}

What is wrong with this?

Body:
I have found that using ViewState.Invisible instead of ViewStates.Gone resolve it. Although I don't know why ViewState.Gone works for picking image from gallery.

void RemoveIssueImage()
{
     //Here, I need to change it from ViewStates.Gone to ViewStates.Invisible
     SelectedImageConstraintLayout.Visibility = ViewStates.Invisible;

     AddImageConstraintLayout.Visibility = ViewStates.Visible;

     var issuePhotoFilename = System.IO.Path.Combine(this.ViewModel.IssuePhotosDirPath, this.ViewModel.TEMP_PHOTO_FILENAME);
     System.IO.File.Delete(issuePhotoFilename);
}

and later in ShowIssueImage function, change AddImageConstraintLayout.Visibility to ViewStates.Invisible.


问:
np.insert error in numpy version '1.13.3'
I try to insert specific values in an array at given indices, with the use of np.insert. Before I used Numpy 1.12 and the code was running fine but with the new Numpy 1.13.3 the following error occurs

```<code>ValueError: shape mismatch: value array of shape () could not be broadcast to indexing result of shape ()
</code>```

My Code:

```<code>intial_array= 1D numpy array
indices= 1D numpy array
values_to_insert= 1D numpy array

mt_new2=np.insert(intial_array, indices,values_to_insert)
</code>```

Is this problem known or does someone knows how to solve this issue?

答:
Early numpy can replicate values as needed to fit the index size:

```<code>>>> x = numpy.arange(10)
>>> numpy.insert(x,[1,3,4,5],[10,20])
array([ 0, 10,  1,  2, 20,  3, 10,  4, 20,  5,  6,  7,  8,  9])
>>> numpy.__version__
'1.12.0'
</code>```

New numpy expects matching size:

```<code>In [81]: x = np.arange(10)

In [82]: np.insert(x, [1,3,4,5],[10,20])
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-82-382864de5db0> in <module>()
----> 1 np.insert(x, [1,3,4,5],[10,20])

/usr/local/lib/python3.5/dist-packages/numpy/lib/function_base.py in insert(arr, obj, values, axis)
   5085     slobj[axis] = indices
   5086     slobj2[axis] = old_mask
-> 5087     new[slobj] = values
   5088     new[slobj2] = arr
   5089

ValueError: shape mismatch: value array of shape (2,) could not be broadcast to indexing result of shape (4,)

In [83]: np.insert(x, [1,3,4,5],[10,20,10,20])
Out[83]: array([ 0, 10,  1,  2, 20,  3, 10,  4, 20,  5,  6,  7,  8,  9])
</code>```

It looks like the earlier version used resize, explicitly or implicitly,

```<code>In [85]: np.insert(x, [1,3,4,5],np.resize([10,20,30],4))
Out[85]: array([ 0, 10,  1,  2, 20,  3, 30,  4, 10,  5,  6,  7,  8,  9])
</code>```

Body:
I try to insert specific values in an array at given indices, with the use of np.insert. Before I used Numpy 1.12 and the code was running fine but with the new Numpy 1.13.3 the following error occurs

ValueError: shape mismatch: value array of shape () could not be broadcast to indexing result of shape ()

My Code:

intial_array= 1D numpy array
indices= 1D numpy array
values_to_insert= 1D numpy array

mt_new2=np.insert(intial_array, indices,values_to_insert)

Is this problem known or does someone knows how to solve this issue?

Body:
Early numpy can replicate values as needed to fit the index size:

>>> x = numpy.arange(10)
>>> numpy.insert(x,[1,3,4,5],[10,20])
array([ 0, 10,  1,  2, 20,  3, 10,  4, 20,  5,  6,  7,  8,  9])
>>> numpy.__version__
'1.12.0'

New numpy expects matching size:

In [81]: x = np.arange(10)

In [82]: np.insert(x, [1,3,4,5],[10,20])
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-82-382864de5db0> in <module>()
----> 1 np.insert(x, [1,3,4,5],[10,20])

/usr/local/lib/python3.5/dist-packages/numpy/lib/function_base.py in insert(arr, obj, values, axis)
   5085     slobj[axis] = indices
   5086     slobj2[axis] = old_mask
-> 5087     new[slobj] = values
   5088     new[slobj2] = arr
   5089

ValueError: shape mismatch: value array of shape (2,) could not be broadcast to indexing result of shape (4,)

In [83]: np.insert(x, [1,3,4,5],[10,20,10,20])
Out[83]: array([ 0, 10,  1,  2, 20,  3, 10,  4, 20,  5,  6,  7,  8,  9])

It looks like the earlier version used resize, explicitly or implicitly,

In [85]: np.insert(x, [1,3,4,5],np.resize([10,20,30],4))
Out[85]: array([ 0, 10,  1,  2, 20,  3, 30,  4, 10,  5,  6,  7,  8,  9])


问:
C zip library that can create password protected zip files on windows?
Anyone know of a C library that can create password protected zip files on windows? It appears that the option to password protect zip files with the built-in zip utility has been removed from windows 7, but I don't think this is an issue.

Can either zziplib or the 7-Zip SDK do this?

答:
7-Zip SDK (LZMA SDK) supports password protected archive.

Related SO post:

https://stackoverflow.com/questions/221049/how-secure-is-7-zip

LZMA SDK:

http://www.7-zip.org/sdk.html

ContentLicense: CC BY-SA 4.0


问:
Reversing Characters within a List using a loop
This is my code I have come up with trying to reverse these strings

```<code>presidents = [ "George Washington " , " John Adams " , " Thomas Jefferson " , " James Madison " , " James Monroe " ," John Quincy Adams " ]

reversedPresidents=""
for ch in presidents:
    reversedPresidents=ch+reversedPresidents

print(reversedPresidents)
</code>```

As of now, it only prints the list backwards like this:

```<code>John Quincy Adams  James Monroe  James Madison  Thomas Jefferson  John Adams George Washington
</code>```

I need it to output the list like:

```<code>notgnihsaW egroeG
smadA nhoJ
</code>```

and so on

答:
You can try this also:</p>

```<code>>>> presidents = [ "George Washington " , " John Adams " , " Thomas Jefferson " , " James Madison " , " James Monroe " ," John Quincy Adams " ]

>>>> print(["".join(reversed(x)) for x in presidents])
[' notgnihsaW egroeG', ' smadA nhoJ ', ' nosreffeJ samohT ', ' nosidaM semaJ ', ' eornoM semaJ ', ' smadA ycniuQ nhoJ ']
</code>```

Body:
This is my code I have come up with trying to reverse these strings

presidents = [ "George Washington " , " John Adams " , " Thomas Jefferson " , " James Madison " , " James Monroe " ," John Quincy Adams " ]

reversedPresidents=""
for ch in presidents:
    reversedPresidents=ch+reversedPresidents

print(reversedPresidents)

As of now, it only prints the list backwards like this:

John Quincy Adams  James Monroe  James Madison  Thomas Jefferson  John Adams George Washington

I need it to output the list like:

notgnihsaW egroeG
smadA nhoJ

and so on

Body:
You can try this also:

>>> presidents = [ "George Washington " , " John Adams " , " Thomas Jefferson " , " James Madison " , " James Monroe " ," John Quincy Adams " ]

>>>> print(["".join(reversed(x)) for x in presidents])
[' notgnihsaW egroeG', ' smadA nhoJ ', ' nosreffeJ samohT ', ' nosidaM semaJ ', ' eornoM semaJ ', ' smadA ycniuQ nhoJ ']


问:
How to ignore the fail case and continues to next value
I am looping values from an Excel file by using ${txnExcel} to search and compare the value. But sometimes ${txnExcel} is doesn't exist in the system. In that case I want to ignore the fail (as there is no need to compare value) and continue to the next ${txnExcel} by skipping the error.

```<code>open excel      ${PATH_EXCEL}
    ${exp_row_count}    get row count   Sheet1
    :For    ${i}    in range     1       ${exp_row_count}
    \   ${excel_index}      evaluate  ${i}+1
    \   ${txnExcel}    Read Cell Data By Name    Sheet1    B${excel_index}
    \   ${ServiceTypeExcel}    Read Cell Data By Name    Sheet1    C${excel_index}
    \   ${TransferAmountExcelOrigin}    Read Cell Data By Name    Sheet1    D${excel_index}
    \   ${CurrencyExcel}    Read Cell Data By Name    Sheet1    E${excel_index}
    \   ${TransferAmountExcel}  set variable    ${TransferAmountExcelOrigin} ${CurrencyExcel}
#=======================================================================================
    \   input text       name=id_or_tsn     ${txnExcel}
    \   click button    name=Submit
    \   wait until element is visible   xpath=/html/body/div[2]/div[2]/div/div/div/div[1]/div[2]    5s

   #===========================Compare Transaction Element================================================
   \   ${txnCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[1]/div[2]
   \   ${ServiceTypeCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[3]/div[2]/span
   \   ${TransferAmountCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[5]/div[2]/span
   \   ${CurrencyCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[4]/div[2]
   \   should be equal as strings    ${txnExcel}    ${txnCompare}       invalid TXN comparison[${i}]
   \   should be equal as strings    ${ServiceTypeExcel}    ${ServiceTypeCompare}       invalid ServiceType comparison[${i}]
   \   should be equal as strings    ${TransferAmountExcel}    ${TransferAmountCompare}       invalid Transfer Amount comparison[${i}]
   \   should be equal as strings    ${CurrencyExcel}    ${CurrencyCompare}       invalid Currency comparison[${i}]
#============================End Compare Transaction Element====================================================
</code>```

答:
You can put a if condition on your code when dealing with ${txnExcel} .

Just check as below in your desired language.Below code is just a logic. Write it in your desired language.

```<code>if(${txnExcel} != NULL){
   // put your compare code inside this if statement.
}
</code>```

Body:
I am looping values from an Excel file by using ${txnExcel} to search and compare the value. But sometimes ${txnExcel} is doesn't exist in the system. In that case I want to ignore the fail (as there is no need to compare value) and continue to the next ${txnExcel} by skipping the error.

open excel      ${PATH_EXCEL}
    ${exp_row_count}    get row count   Sheet1
    :For    ${i}    in range     1       ${exp_row_count}
    \   ${excel_index}      evaluate  ${i}+1
    \   ${txnExcel}    Read Cell Data By Name    Sheet1    B${excel_index}
    \   ${ServiceTypeExcel}    Read Cell Data By Name    Sheet1    C${excel_index}
    \   ${TransferAmountExcelOrigin}    Read Cell Data By Name    Sheet1    D${excel_index}
    \   ${CurrencyExcel}    Read Cell Data By Name    Sheet1    E${excel_index}
    \   ${TransferAmountExcel}  set variable    ${TransferAmountExcelOrigin} ${CurrencyExcel}
#=======================================================================================
    \   input text       name=id_or_tsn     ${txnExcel}
    \   click button    name=Submit
    \   wait until element is visible   xpath=/html/body/div[2]/div[2]/div/div/div/div[1]/div[2]    5s

   #===========================Compare Transaction Element================================================
   \   ${txnCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[1]/div[2]
   \   ${ServiceTypeCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[3]/div[2]/span
   \   ${TransferAmountCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[5]/div[2]/span
   \   ${CurrencyCompare}  get text   xpath=/html/body/div[2]/div[2]/div/div/div/div[4]/div[2]
   \   should be equal as strings    ${txnExcel}    ${txnCompare}       invalid TXN comparison[${i}]
   \   should be equal as strings    ${ServiceTypeExcel}    ${ServiceTypeCompare}       invalid ServiceType comparison[${i}]
   \   should be equal as strings    ${TransferAmountExcel}    ${TransferAmountCompare}       invalid Transfer Amount comparison[${i}]
   \   should be equal as strings    ${CurrencyExcel}    ${CurrencyCompare}       invalid Currency comparison[${i}]
#============================End Compare Transaction Element====================================================

Body:
You can put a if condition on your code when dealing with ${txnExcel} .

Just check as below in your desired language.Below code is just a logic. Write it in your desired language.

if(${txnExcel} != NULL){
   // put your compare code inside this if statement.
}


问:
Remove subfolder name from WordPress site using htaccess
I've moved WordPress into sub-folder named /site but the URL now shows http://www.example.com/site. I want it to show without the /site/ subdirectory.

Here's my current .htaccess code

```<code>RewriteEngine On
RewriteBase /site/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /site/index.php [L]
</code>```

How do I remove the physical subdirectory from the visible URL?

答:
According to Giving WordPress Its Own Directory in the Codex, this is what you need (works for me).

Create a .htaccess file in root folder, and put this content inside (just change example.com and my_subdir):

```<code><IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www.)?example.com$
RewriteCond %{REQUEST_URI} !^/my_subdir/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /my_subdir/$1
RewriteCond %{HTTP_HOST} ^(www.)?example.com$
RewriteRule ^(/)?$ my_subdir/index.php [L]
</IfModule>
</code>```

There you will also find instructions to do it by changing the URL in the General Settings, which also requires you to copy .htaccess and index.php, and then edit this last.  The first method seems easier.

Body:
I've moved WordPress into sub-folder named /site but the URL now shows http://www.example.com/site. I want it to show without the /site/ subdirectory.

Here's my current .htaccess code

RewriteEngine On
RewriteBase /site/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /site/index.php [L]

How do I remove the physical subdirectory from the visible URL?

Body:
According to Giving WordPress Its Own Directory in the Codex, this is what you need (works for me).

Create a .htaccess file in root folder, and put this content inside (just change example.com and my_subdir):

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www.)?example.com$
RewriteCond %{REQUEST_URI} !^/my_subdir/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /my_subdir/$1
RewriteCond %{HTTP_HOST} ^(www.)?example.com$
RewriteRule ^(/)?$ my_subdir/index.php [L]
</IfModule>

There you will also find instructions to do it by changing the URL in the General Settings, which also requires you to copy .htaccess and index.php, and then edit this last.  The first method seems easier.


问:
Compare date times in java in DAY hh:mm-hh:mm
How do we comapare dates and get the remainig available slots in java?

```<code>Sun 10:00-11:00
Sun 12:00-14:00
Sun 15:00-16:00
</code>```

So how can we get alll the availble time for a day in other than these three slots? how do we compare these dates in java? Can anyone please suggest?

答: Use org.apache.commons.lang3.time.DateUtils Apache DateUtils for adding specific hours to the time and use java.util.Date for various comparisons. Hope this will help. Thank you.

Body:
How do we comapare dates and get the remainig available slots in java?

Sun 10:00-11:00
Sun 12:00-14:00
Sun 15:00-16:00

So how can we get alll the availble time for a day in other than these three slots? how do we compare these dates in java? Can anyone please suggest?


问:
How to eliminate if-else with same condition but different actions inside another if-else?
Suppose I have the code like following:

```<code>int age=(from user input);
int weight=(from user input);

if(age>60){
    if(weight>100){
        function1();
    }else if(weight<40){
        function2();
    }else{
        function3();
    }
}else if(age<20){
    if(weight>100){
        function4();
    }else if(weight<40){
        function5();
    }else{
        function6();
    }
}else{
    if(weight>100){
        function7();
    }else if(weight<40){
        function8();
    }else{
        function9();
    }
}
</code>```

the problem is that the code pattern:

```<code>if(weight>100){
    //do something different
}else if(weight<40){
    //do something different
}else{
    //do something different
}
</code>```

repeats as there are different ranges of age. And I can't enclose the inner if-else into a single function, because the things to do is different even through the condition is the same. Is there any way to modify this code so that the code pattern:

```<code>if(age>60){
    //do something different
}else if(age<20){
    //do something different
}else{
    //do something different
}
</code>```

and

```<code>if(weight>100){
    //do something different
}else if(weight<40){
    //do something different
}else{
    //do something different
}
</code>```

would appear once only?

答:
The best I could come up with was roughly this:

```<code>interface WeightFunc {
    void function();
}
</code>```

```<code>public static final List<WeightFunc> weightFuncs = Arrays.asList(weightFunc1, weightFunc2,...);
</code>```

Now inside your method

```<code>List<WeightFunc> choices = null;

if(age>60){
    choices = Arrays.asList(weightFuncs.get(0), weightFuncs.get(1), ...);
    // 1, 2, 3
}else if(age<20){
    choices = Arrays.asList(weightFuncs.get(3), weightFuncs.get(4), ...);
    // 4, 5, 6
}else{
    choices = Arrays.asList(weightFuncs.get(6), weightFuncs.get(7), ...);
    // 7, 8, 9
}

WeightFunc choice = null;

if(weight>100){
    choice = choices.get(0);
    //do something different
}else if(weight<40){
    choice = choices.get(1);
    //do something different
}else{
    choice = choices.get(2);
    //do something different
}
</code>```

Now call it:

```<code>choice.function();
</code>```

IMO, I prefer your initial method to this

Body:
Suppose I have the code like following:

int age=(from user input);
int weight=(from user input);

if(age>60){
    if(weight>100){
        function1();
    }else if(weight<40){
        function2();
    }else{
        function3();
    }
}else if(age<20){
    if(weight>100){
        function4();
    }else if(weight<40){
        function5();
    }else{
        function6();
    }
}else{
    if(weight>100){
        function7();
    }else if(weight<40){
        function8();
    }else{
        function9();
    }
}

the problem is that the code pattern:

if(weight>100){
    //do something different
}else if(weight<40){
    //do something different
}else{
    //do something different
}

repeats as there are different ranges of age. And I can't enclose the inner if-else into a single function, because the things to do is different even through the condition is the same. Is there any way to modify this code so that the code pattern:

if(age>60){
    //do something different
}else if(age<20){
    //do something different
}else{
    //do something different
}

and

if(weight>100){
    //do something different
}else if(weight<40){
    //do something different
}else{
    //do something different
}

would appear once only?

Body:
The best I could come up with was roughly this:

interface WeightFunc {
    void function();
}

public static final List<WeightFunc> weightFuncs = Arrays.asList(weightFunc1, weightFunc2,...);

Now inside your method

List<WeightFunc> choices = null;

if(age>60){
    choices = Arrays.asList(weightFuncs.get(0), weightFuncs.get(1), ...);
    // 1, 2, 3
}else if(age<20){
    choices = Arrays.asList(weightFuncs.get(3), weightFuncs.get(4), ...);
    // 4, 5, 6
}else{
    choices = Arrays.asList(weightFuncs.get(6), weightFuncs.get(7), ...);
    // 7, 8, 9
}

WeightFunc choice = null;

if(weight>100){
    choice = choices.get(0);
    //do something different
}else if(weight<40){
    choice = choices.get(1);
    //do something different
}else{
    choice = choices.get(2);
    //do something different
}

Now call it:

choice.function();

IMO, I prefer your initial method to this


问:
Codeigniter upload image - The upload path does not appear to be valid
I am having issues uploading an image using the codeigniter upload library, I keep getting the error,

The upload path does not appear to be valid.

The file path I am trying to upload too is as follows,

$config['upload_path'] = './media/images/site';

and when I dot the following,

```<code>die(var_dump(is_dir($config['upload_path'])));
</code>```

I get the following returned,

bool(true)

The folder is also writable (777), so I am not sure where I am going wrong, below is my upload code,

```<code>$config['upload_path'] = './media/images/site';
        //die(realpath($config['upload_path']));
        //die(var_dump(is_dir($config['upload_path'])));
        $config['allowed_types'] = 'gif|jpg|png|jpeg';
        $config['max_size'] = '1500';
        $config['max_width']  = '390';
        $config['max_height']  = '269';

        $this->load->library('upload',$config);
        if ( ! $this->upload->do_upload() && $_FILES['userfile']['error'] != 4)
        {
            $data['error'] = $this->upload->display_errors();
            $this->template->build('/admin/pages/about_us', $data);
        }
        else
        {
            $image = $this->upload->data();
            if(empty($image['file_name'])) {
                $image['file_name'] = $this->formbuilder->defaults['page_image'];
            }
            $page = array(
                //'page_title' => $this->input->post('page_title'),
                //'page_slug' => $this->input->post('page_slug'),
                'page_content' => $this->input->post('page_content'),
                'page_image' => $image['file_name'],
                'date_created' => date("Y-m-d h:i:s"),
                'created_by' => 1
            );

            if($this->pages_model->insert($this->security->xss_clean($page)))
            {
                redirect('/admin/dashboard');
            }
        }
</code>```

I cannot see anything glaringly obvious that would stop the file from being uploaded, below is my folder structure of my project

```<code>/application
/system
index.php
.htaccess
/media
    /images
        /site
        /admin
    /css
    /js
</code>```

If anyone can shed any light on my problem that would be great.

EDIT FOR THE PETULENT DOWNVOTER

What would be causing this problem?

(There is a question, as if it wasn't obvious enough anyway)

答:
Try out this code in your Controller

```<code>$config['upload_path'] = 'images'; //name of the uploading folder
$config['allowed_types'] = 'jpeg|png|jpg';

$this->load->library('upload', $config);
$this->upload->initialize($config);

if (!$this->upload->do_upload())
 {
  echo $this->upload->display_errors();
  exit;
 }
else
 {
  $upload_data = $this->upload->data();
 }
</code>```

Body:
I am having issues uploading an image using the codeigniter upload library, I keep getting the error,

The upload path does not appear to be valid.

The file path I am trying to upload too is as follows,

$config['upload_path'] = './media/images/site';

and when I dot the following,

die(var_dump(is_dir($config['upload_path'])));

I get the following returned,

bool(true)

The folder is also writable (777), so I am not sure where I am going wrong, below is my upload code,

$config['upload_path'] = './media/images/site';
        //die(realpath($config['upload_path']));
        //die(var_dump(is_dir($config['upload_path'])));
        $config['allowed_types'] = 'gif|jpg|png|jpeg';
        $config['max_size'] = '1500';
        $config['max_width']  = '390';
        $config['max_height']  = '269';

        $this->load->library('upload',$config);
        if ( ! $this->upload->do_upload() && $_FILES['userfile']['error'] != 4)
        {
            $data['error'] = $this->upload->display_errors();
            $this->template->build('/admin/pages/about_us', $data);
        }
        else
        {
            $image = $this->upload->data();
            if(empty($image['file_name'])) {
                $image['file_name'] = $this->formbuilder->defaults['page_image'];
            }
            $page = array(
                //'page_title' => $this->input->post('page_title'),
                //'page_slug' => $this->input->post('page_slug'),
                'page_content' => $this->input->post('page_content'),
                'page_image' => $image['file_name'],
                'date_created' => date("Y-m-d h:i:s"),
                'created_by' => 1
            );

            if($this->pages_model->insert($this->security->xss_clean($page)))
            {
                redirect('/admin/dashboard');
            }
        }

I cannot see anything glaringly obvious that would stop the file from being uploaded, below is my folder structure of my project

/application
/system
index.php
.htaccess
/media
    /images
        /site
        /admin
    /css
    /js

If anyone can shed any light on my problem that would be great.

EDIT FOR THE PETULENT DOWNVOTER

What would be causing this problem?

(There is a question, as if it wasn't obvious enough anyway)

Body:
Try out this code in your Controller

$config['upload_path'] = 'images'; //name of the uploading folder
$config['allowed_types'] = 'jpeg|png|jpg';

$this->load->library('upload', $config);
$this->upload->initialize($config);

if (!$this->upload->do_upload())
 {
  echo $this->upload->display_errors();
  exit;
 }
else
 {
  $upload_data = $this->upload->data();
 }


问:
Rotate a rect on canvas on user touch
I tried to check on web a lot about this but couldn't find any solution. I want to rotate a rect whenever a user drags it's bottom-right corner (pointed in the image) and the center of the rotation should be the same as center of the rect.

答:
You can rotate using canvas.

```<code>//Example

Path path = new Path();
path.addRect(166, 748, 314, 890, Path.Direction.CW);
canvas.save(); // first save the state of the canvas
canvas.rotate(45); // rotate it
canvas.drawPath(path, paint); // draw on it
canvas.restore(); // restore previous state (rotate it back)
</code>```

Android Implement onTouchListener on path objects
check this link. You can override onTouchEvent()

Title: Rotate a rect on canvas on user touch

Body:
You can rotate using canvas.

//Example

Path path = new Path();
path.addRect(166, 748, 314, 890, Path.Direction.CW);
canvas.save(); // first save the state of the canvas
canvas.rotate(45); // rotate it
canvas.drawPath(path, paint); // draw on it
canvas.restore(); // restore previous state (rotate it back)

Android Implement onTouchListener on path objects
check this link. You can override onTouchEvent()


问:
Why does git using ssh use git as a username

This is just a general question about how git functions. I couldn't find anything in the git manual related to this, maybe I'm not looking in the right place.

When you clone using an ssh link from a git server, the username it uses is git, not the username of the key you are trying to use. Why does git do this and how is git able to tell which keypair that it should use to authenticate the connection.

答:
Don't forget that you would not be able to actually open an interactive secure shell on the remote Git repositories hosting server:

You have no business executing any command you want on that server

Your account is never created anyway (because of 1.)

The only commands you should be interested in are Git commands (upload-pack, receive-pack, for implementing the git clone/pull/push you are doing.)

For all those reasons, the only account you need to request a remote shell for is an administrative account managing those Git remote repos, typically named 'git'.

Some of those server would use the ssh feature named 'forced command' (I presented it here for Gitolite, but it applies to GitLab too)

That means it knows your account name because it is written as a parameter of a forced command associated to your public key in the ~git/.ssh/authorized_keys, which keeps track of all the public keys authorized to open a (non-interactive) shell.

That is how the Git hosting service knows which accounts is making a Git request.


问:
WordPress Parse error: syntax error, unexpected T_FUNCTION
I am importing a Wordpress site for somebody and I am getting the white screen. In WP_DEBUG it is giving me this error:

Parse error: syntax error, unexpected T_FUNCTION in /wp-content/plugins/edit-guests.php on line 5

Here is the code surrounding line 5:

```<code>    <?php
/*
 * Plugin Name: iThemes Exchange Change Guest Customer Email
 */
add_action( 'add_meta_boxes_it_exchange_tran', function () {
    add_meta_box(
        'it-exchange-change-guest-customer-email',
        'Change Guest Customer Email ADdress',
        function ( $post ) {
            if ( ! $post ) {
                return;
            }
</code>```

Line 5 is the line that starts with "add_action".

I am sure this is a novice's mistake, but any help is greatly appreciated, thank you so much!

答:
You're dropping in that anonymous closure function and declaring another function within it:</p>

```<code>add_action('wherever_hook', function() {
  # Your Code here cannot contain a function() declaration
  # You will need to declare that function outside of this
});
</code>```

Body:
I am importing a Wordpress site for somebody and I am getting the white screen. In WP_DEBUG it is giving me this error:

Parse error: syntax error, unexpected T_FUNCTION in /wp-content/plugins/edit-guests.php on line 5

Here is the code surrounding line 5:

    <?php
/*
 * Plugin Name: iThemes Exchange Change Guest Customer Email
 */
add_action( 'add_meta_boxes_it_exchange_tran', function () {
    add_meta_box(
        'it-exchange-change-guest-customer-email',
        'Change Guest Customer Email ADdress',
        function ( $post ) {
            if ( ! $post ) {
                return;
            }

Line 5 is the line that starts with "add_action".

I am sure this is a novice's mistake, but any help is greatly appreciated, thank you so much!

Body:
You're dropping in that anonymous closure function and declaring another function within it:

add_action('wherever_hook', function() {
  # Your Code here cannot contain a function() declaration
  # You will need to declare that function outside of this
});


问:
Where is the main() method In a JSP/Servlet application?
The reason I'm asking this is that I want to write code that initializes the application once it starts and cleans up later on.

I dont want to use a servlet init() method since it is per servlet.

答:
There is no main() method, because the components are managed and the container invokes other methods - like the init() on servlets and filters. The container itself is started through a main method, but even that's hidden from you.

For per-application and initialization you can use a ServletContextListener

You have to map it in web.xml using <listener><listener-class>...</listener-class></listener>. In contextInitialized(..) and contextDestroyed(..) you can do initialization and cleanup respectively.


答:
Yes, I think it is easier to make the changes you want with a tidy approach using tidyr and dplyr.

```<code>library(dplyr)
library(tidyr)

df <- tribble(
         ~date, ~value, ~country,   ~indicator,
  "2016-01-01",      1,     "US",        "gdp",
  "2016-02-01",      2,     "US",        "gdp",
  "2016-03-01",      3,     "AU",        "gdp",
  "2016-04-01",      4,     "US",        "gdp",
  "2016-05-01",      5,     "US",        "gdp",
  "2016-02-01",      1,     "US", "population",
  "2016-03-01",      2,     "AU", "population",
  "2016-04-01",      3,     "US", "population",
  "2016-05-01",      4,     "US", "population",
  "2016-06-01",      5,     "US", "population"
)

df %>%
  group_by(country) %>%
  spread(indicator, value) %>%
  mutate(`gdp per capita` = gdp / population) %>%
  gather(indicator, value, -c(date, country)) %>%
  drop_na(value)

# # A tibble: 14 x 4
# # Groups:   country [2]
#          date country      indicator    value
#         <chr>   <chr>          <chr>    <dbl>
#  1 2016-01-01      US            gdp 1.000000
#  2 2016-02-01      US            gdp 2.000000
#  3 2016-03-01      AU            gdp 3.000000
#  4 2016-04-01      US            gdp 4.000000
#  5 2016-05-01      US            gdp 5.000000
#  6 2016-02-01      US     population 1.000000
#  7 2016-03-01      AU     population 2.000000
#  8 2016-04-01      US     population 3.000000
#  9 2016-05-01      US     population 4.000000
# 10 2016-06-01      US     population 5.000000
# 11 2016-02-01      US gdp per capita 2.000000
# 12 2016-03-01      AU gdp per capita 1.500000
# 13 2016-04-01      US gdp per capita 1.333333
# 14 2016-05-01      US gdp per capita 1.250000
</code>```

N.B. I've modified the data and added a group_by statement to demonstrate the solution with multiple values for country.

Title: Create new ratio indicator in long data

Body:
I have a long data frame

mydf <- data.frame(
+     date=c("2016-01-01","2016-02-01","2016-03-01","2016-04-01","2016-05-01", "2016-02-01", "2016-03-01", "2016-04-01", "2016-05-01", "2016-06-01"),
+     value=c(1,2,3,4,5,1,2,3,4,5),
+     country=c("US", "US", "US", "US", "US", "US", "US", "US", "US", "US"),
+     indicator=c("gdp", "gdp", "gdp", "gdp", "gdp", "population", "population", "population", "population", "population"))

         date value country  indicator
1  2016-01-01     1      US        gdp
2  2016-02-01     2      US        gdp
3  2016-03-01     3      US        gdp
4  2016-04-01     4      US        gdp
5  2016-05-01     5      US        gdp
6  2016-02-01     1      US population
7  2016-03-01     2      US population
8  2016-04-01     3      US population
9  2016-05-01     4      US population
10 2016-06-01     5      US population

I want to create specific new indicators that come from ratios, e.g. GDP/population*1000

It would look something like this, it has to match the right dates for each respective indicator

mydf <- data.frame(
+     date=c("2016-01-01","2016-02-01","2016-03-01","2016-04-01","2016-05-01", "2016-02-01", "2016-03-01", "2016-04-01", "2016-05-01", "2016-06-01", "2016-02-01", "2016-03-01", "2016-04-01", "2016-05-01"),
+     value=c(1,2,3,4,5,1,2,3,4,5,2,1.5,1.33,1.2),
+     country=c("US", "US", "US", "US", "US", "US", "US", "US", "US", "US", "US", "US", "US", "US"),
+     indicator=c("gdp", "gdp", "gdp", "gdp", "gdp", "population", "population", "population", "population", "population", "gdp per capita", "gdp per capita", "gdp per capita", "gdp per capita"))

         date value country      indicator
1  2016-01-01  1.00      US            gdp
2  2016-02-01  2.00      US            gdp
3  2016-03-01  3.00      US            gdp
4  2016-04-01  4.00      US            gdp
5  2016-05-01  5.00      US            gdp
6  2016-02-01  1.00      US     population
7  2016-03-01  2.00      US     population
8  2016-04-01  3.00      US     population
9  2016-05-01  4.00      US     population
10 2016-06-01  5.00      US     population
11 2016-02-01  2.00      US gdp per capita
12 2016-03-01  1.50      US gdp per capita
13 2016-04-01  1.33      US gdp per capita
14 2016-05-01  1.20      US gdp per capita

Is there an easy way to do this in R?

Body:
Yes, I think it is easier to make the changes you want with a tidy approach using tidyr and dplyr.

library(dplyr)
library(tidyr)

df <- tribble(
         ~date, ~value, ~country,   ~indicator,
  "2016-01-01",      1,     "US",        "gdp",
  "2016-02-01",      2,     "US",        "gdp",
  "2016-03-01",      3,     "AU",        "gdp",
  "2016-04-01",      4,     "US",        "gdp",
  "2016-05-01",      5,     "US",        "gdp",
  "2016-02-01",      1,     "US", "population",
  "2016-03-01",      2,     "AU", "population",
  "2016-04-01",      3,     "US", "population",
  "2016-05-01",      4,     "US", "population",
  "2016-06-01",      5,     "US", "population"
)

df %>%
  group_by(country) %>%
  spread(indicator, value) %>%
  mutate(`gdp per capita` = gdp / population) %>%
  gather(indicator, value, -c(date, country)) %>%
  drop_na(value)

# # A tibble: 14 x 4
# # Groups:   country [2]
#          date country      indicator    value
#         <chr>   <chr>          <chr>    <dbl>
#  1 2016-01-01      US            gdp 1.000000
#  2 2016-02-01      US            gdp 2.000000
#  3 2016-03-01      AU            gdp 3.000000
#  4 2016-04-01      US            gdp 4.000000
#  5 2016-05-01      US            gdp 5.000000
#  6 2016-02-01      US     population 1.000000
#  7 2016-03-01      AU     population 2.000000
#  8 2016-04-01      US     population 3.000000
#  9 2016-05-01      US     population 4.000000
# 10 2016-06-01      US     population 5.000000
# 11 2016-02-01      US gdp per capita 2.000000
# 12 2016-03-01      AU gdp per capita 1.500000
# 13 2016-04-01      US gdp per capita 1.333333
# 14 2016-05-01      US gdp per capita 1.250000

N.B. I've modified the data and added a group_by statement to demonstrate the solution with multiple values for country.


问:
Node js authentication in cross domain
I am working on a MEAN application, I am using Angular 4 for my project. For authentication, I have implemented the Passport js Local-strategy. And I am maintaining persistent session using Express-session. Things are working fine till here.

The Problem

In the same domain session works fine and I am able to authenticate the user. But in cross-domain, I am not able to maintain the session. It generates a new session id for each new request in cross-domain.

I then tried Passport-jwt but the problem with it is I don't have the control over user session. I mean I can't logout the user from the server if he is inactive or even on server re-start also the token don't get invalid.

So in simple words, I am looking for an authentication solution in Node js (Express js) in which I can manage authentication in cross-domain.

I have already seen some blog post and SO questions like this, but it doesn't help.

Thank you.

EDIT

Should I write my own code to achieve this? If so I have a plan.

My basic plan is:

The user will send credentials with the login request.

I will check for the credentials in the database. If credentials are valid, I will generate a random token and save it to the database, in the user table and the same token I will provide to the user with success response.

Now, with each request user will send the token and I will check the token for each request in the database. If the token is valid then I will allow the user to access the API otherwise I will generate an error with 401 status code.

I am using Mongoose (MongoDB) so I will be ok to check the token in each request (performance point of view).

I think this is also a good idea. I just want some suggestions, whether I am thinking in right direction or not.

What I will get with this:

The number of logged in user in the application (active sessions).

I can logout a user if he is idle for a certain interval of time.

I can manage multiple login session of the same user (by doing an entry in the database).

I can allow the end user to clear all other login sessions (like Facebook and Gmail offers).

Any customization related to authorization.

EDIT 2

Here I am shareing my app.js code

```<code>var express = require('express');
var helmet = require('helmet');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var dotenv = require('dotenv');
var env = dotenv.load();
var mongoose = require('mongoose');
var passport = require('passport');
var flash    = require('connect-flash');
var session      = require('express-session');
var cors = require('cors');

var databaseUrl = require('./config/database.js')[process.env.NODE_ENV || 'development'];
// configuration
mongoose.connect(databaseUrl); // connect to our database

var app = express();

// app.use(helmet());

// required for passport

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Origin', req.headers.origin);
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
  if ('OPTIONS' == req.method) {
       res.send(200);
   } else {
       next();
   }
});

app.use(cookieParser());

app.use(session({
    secret: 'ilovescotchscotchyscotchscotch', // session secret
    resave: true,
    saveUninitialized: true,
    name: 'Session-Id',
    cookie: {
      secure: false,
      httpOnly: false
    }
}));

require('./config/passport')(passport); // pass passport for configuration

var index = require('./routes/index');
var users = require('./routes/user.route');
var seeders = require('./routes/seeder.route');
var branches = require('./routes/branch.route');
var companies = require('./routes/company.route');
var dashboard = require('./routes/dashboard.route');
var navigation = require('./routes/navigation.route');
var roles = require('./routes/role.route');
var services = require('./routes/services.route');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session

require('./routes/auth.route')(app, passport);
app.use('/', index);
app.use('/users', users);
app.use('/seed', seeders);
app.use('/branches', branches);
app.use('/companies', companies);
app.use('/dashboard', dashboard);
app.use('/navigation', navigation);
app.use('/roles', roles);
app.use('/services', services);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  res.status(404).send({ status: 'NOT_FOUND', message: 'This resource is not available.'});
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  let errorObj = {
    status: 'INTERNAL_SERVER_ERROR',
    message: 'Something went wrong.',
    error: err.message
  };
  res.status(err.status || 500).send(errorObj);
});

module.exports = app;
</code>```

EDIT 3

For those who don't understand my problem. Explaining the problem in
  simple words:

My Express server is running on port 3000.

In order to consume any API from the server, a user must be logged in.

When a user gets logged in from localhost:3000, the server checks the credentials(using Passport-local) and returns a token in the response header.

Now after login, when a user hits any API from localhost:3000, a predefined Header comes with passport-session and then passport verifies the user session using req.isAuthenticated() and all the things works as expected.

When a user gets logged in from localhost:4000 and the server send a token in response header (same as localhost:3000).

When after successful login, the user hits any API from localhost:4000 the passport js function req.isAuthenticated() returns false.

This was happening because in cross-domain the cookie doesn't go to the server we need to set withCredentials header to true at the client side.

I have set withCredentials header to true but still at the server the req.isAuthenticated() is returning false.

答: You might have tried with passport-jwt. It generates tokens as per the JWT protocol on login. Your requirement is to blacklist the generated token when you logout. To achieve that, you can create a collection in mongodb named "BlacklistToken" with fields  userid and token. When the user logs out, you can insert the token and userid in the collection. Then write a middleware to check whether the token is blacklisted or not. if it is redirect to login page. </p>

Title: Node js authentication in cross domain

Body:
I am working on a MEAN application, I am using Angular 4 for my project. For authentication, I have implemented the Passport js Local-strategy. And I am maintaining persistent session using Express-session. Things are working fine till here.

The Problem

In the same domain session works fine and I am able to authenticate the user. But in cross-domain, I am not able to maintain the session. It generates a new session id for each new request in cross-domain.

I then tried Passport-jwt but the problem with it is I don't have the control over user session. I mean I can't logout the user from the server if he is inactive or even on server re-start also the token don't get invalid.

So in simple words, I am looking for an authentication solution in Node js (Express js) in which I can manage authentication in cross-domain.

I have already seen some blog post and SO questions like this, but it doesn't help.

Thank you.

EDIT

Should I write my own code to achieve this? If so I have a plan.

My basic plan is:

The user will send credentials with the login request.

I will check for the credentials in the database. If credentials are valid, I will generate a random token and save it to the database, in the user table and the same token I will provide to the user with success response.

Now, with each request user will send the token and I will check the token for each request in the database. If the token is valid then I will allow the user to access the API otherwise I will generate an error with 401 status code.

I am using Mongoose (MongoDB) so I will be ok to check the token in each request (performance point of view).

I think this is also a good idea. I just want some suggestions, whether I am thinking in right direction or not.

What I will get with this:

The number of logged in user in the application (active sessions).

I can logout a user if he is idle for a certain interval of time.

I can manage multiple login session of the same user (by doing an entry in the database).

I can allow the end user to clear all other login sessions (like Facebook and Gmail offers).

Any customization related to authorization.

EDIT 2

Here I am shareing my app.js code

var express = require('express');
var helmet = require('helmet');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var dotenv = require('dotenv');
var env = dotenv.load();
var mongoose = require('mongoose');
var passport = require('passport');
var flash    = require('connect-flash');
var session      = require('express-session');
var cors = require('cors');

var databaseUrl = require('./config/database.js')[process.env.NODE_ENV || 'development'];
// configuration
mongoose.connect(databaseUrl); // connect to our database

var app = express();

// app.use(helmet());

// required for passport

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Origin', req.headers.origin);
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
  if ('OPTIONS' == req.method) {
       res.send(200);
   } else {
       next();
   }
});

app.use(cookieParser());

app.use(session({
    secret: 'ilovescotchscotchyscotchscotch', // session secret
    resave: true,
    saveUninitialized: true,
    name: 'Session-Id',
    cookie: {
      secure: false,
      httpOnly: false
    }
}));

require('./config/passport')(passport); // pass passport for configuration

var index = require('./routes/index');
var users = require('./routes/user.route');
var seeders = require('./routes/seeder.route');
var branches = require('./routes/branch.route');
var companies = require('./routes/company.route');
var dashboard = require('./routes/dashboard.route');
var navigation = require('./routes/navigation.route');
var roles = require('./routes/role.route');
var services = require('./routes/services.route');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session

require('./routes/auth.route')(app, passport);
app.use('/', index);
app.use('/users', users);
app.use('/seed', seeders);
app.use('/branches', branches);
app.use('/companies', companies);
app.use('/dashboard', dashboard);
app.use('/navigation', navigation);
app.use('/roles', roles);
app.use('/services', services);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  res.status(404).send({ status: 'NOT_FOUND', message: 'This resource is not available.'});
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  let errorObj = {
    status: 'INTERNAL_SERVER_ERROR',
    message: 'Something went wrong.',
    error: err.message
  };
  res.status(err.status || 500).send(errorObj);
});

module.exports = app;

EDIT 3

For those who don't understand my problem. Explaining the problem in
  simple words:

My Express server is running on port 3000.

In order to consume any API from the server, a user must be logged in.

When a user gets logged in from localhost:3000, the server checks the credentials(using Passport-local) and returns a token in the response header.

Now after login, when a user hits any API from localhost:3000, a predefined Header comes with passport-session and then passport verifies the user session using req.isAuthenticated() and all the things works as expected.

When a user gets logged in from localhost:4000 and the server send a token in response header (same as localhost:3000).

When after successful login, the user hits any API from localhost:4000 the passport js function req.isAuthenticated() returns false.

This was happening because in cross-domain the cookie doesn't go to the server we need to set withCredentials header to true at the client side.

I have set withCredentials header to true but still at the server the req.isAuthenticated() is returning false.


问:
How to reduce the distance between options in dropdown in ionic 2
I m binding values dynamically in to the dropdown using ionic 2 and here allare working good except space between the options and and unable to set header name on the dropdown below is my code & although im using using interface="pop over" it is also not working & made changes in main.css and .scss file also but nothing works

```<code><ion-select  #sectionSelect [(ngModel)]="location" (ionChange)="onChange(sectionSelect.text)" interface="popover" placeholder=" " hidden>
        <ion-option *ngFor="let opt of Locations" [value]="opt.LocationId">{{opt.LocationName}}</ion-option>
      </ion-select>
</code>```

i am getting dropdown like the below format there i unable to remove or put name in header like Gender & unable to reduce the spaces between options

答:
Add ion-list and ion-item as mentioned in the document. Working demo

Extract from Component

```<code>selectedDropdown : any;
  dropDown : any = [];
 this.dropDown=[
    "100 - BISCUIT - 546156",
    "252 - CHOCO - 185268",
    "131 - CANDY - 478215"
]
this.selectedDropdown=this.dropDown[0];
  }
</code>```

Template

```<code><ion-list>
  <ion-item>
    <ion-label>Dishes</ion-label>
<ion-select [(ngModel)]="selectedDropdown">
  <ion-option *ngFor="let val of dropDown" value= {{val}}>{{val}}</ion-option>
</ion-select>
  </ion-item>
</ion-list>
</code>```

Body:
I m binding values dynamically in to the dropdown using ionic 2 and here allare working good except space between the options and and unable to set header name on the dropdown below is my code & although im using using interface="pop over" it is also not working & made changes in main.css and .scss file also but nothing works

<ion-select  #sectionSelect [(ngModel)]="location" (ionChange)="onChange(sectionSelect.text)" interface="popover" placeholder=" " hidden>
        <ion-option *ngFor="let opt of Locations" [value]="opt.LocationId">{{opt.LocationName}}</ion-option>
      </ion-select>

i am getting dropdown like the below format there i unable to remove or put name in header like Gender & unable to reduce the spaces between options

Body:
Add ion-list and ion-item as mentioned in the document. Working demo

Extract from Component

selectedDropdown : any;
  dropDown : any = [];
 this.dropDown=[
    "100 - BISCUIT - 546156",
    "252 - CHOCO - 185268",
    "131 - CANDY - 478215"
]
this.selectedDropdown=this.dropDown[0];
  }

Template

<ion-list>
  <ion-item>
    <ion-label>Dishes</ion-label>
<ion-select [(ngModel)]="selectedDropdown">
  <ion-option *ngFor="let val of dropDown" value= {{val}}>{{val}}</ion-option>
</ion-select>
  </ion-item>
</ion-list>


问:
How to convert Pandas NaN to NaT
I am trying to convert NaN (dtype: float64) values in a Pandas DataFrame column into NaT values.

Please note that I have several DataFrames with the same Order_date column. Some Order_date columns' dtypes are float64 (filled with NaN) while others' dtypes are datetime64[ns] (filled with NaT).

I tried the following:

```<code>df.loc[:,'Order_date'] = df.loc[:,'Order_date'].astype(np.datetime64).fillna(pd.NaT)
</code>```

However, I get an Error result:

```<code>TypeError: cannot astype a datatimelike from [datetime64[ns]] to [datetime64].
</code>```

What is reason behind this error? I think the error is due to how several Order_date columns in some DataFrames have NaT values (datetime64[ns]). What can I do to successfully convert only the Order_date columns with NaN values into NaT values in Pandas and leave the remaining Order_date columns that already have NaT values as is?

答:
I might be misunderstanding the requirements of the problem, but wouldn't

```<code>df['Order_date'].fillna(pd.NaT, inplace=True)
</code>```

do the job?

Title: How to convert Pandas NaN to NaT

Body:
I am trying to convert NaN (dtype: float64) values in a Pandas DataFrame column into NaT values.

Please note that I have several DataFrames with the same Order_date column. Some Order_date columns' dtypes are float64 (filled with NaN) while others' dtypes are datetime64[ns] (filled with NaT).

I tried the following:

df.loc[:,'Order_date'] = df.loc[:,'Order_date'].astype(np.datetime64).fillna(pd.NaT)

However, I get an Error result:

TypeError: cannot astype a datatimelike from [datetime64[ns]] to [datetime64].

What is reason behind this error? I think the error is due to how several Order_date columns in some DataFrames have NaT values (datetime64[ns]). What can I do to successfully convert only the Order_date columns with NaN values into NaT values in Pandas and leave the remaining Order_date columns that already have NaT values as is?

Body:
I might be misunderstanding the requirements of the problem, but wouldn't

df['Order_date'].fillna(pd.NaT, inplace=True)

do the job?