问:
Cannot read property 'map' of undefined in react datatable error
getting Error in map function.

```<code> generateRows: function() {
    var cols = this.props.cols,  // [{key, label}]
        data = this.props.data;
</code>```

Getting error in data (undefined value getting)

```<code>    return data.map(function(item) {

        // handle the column data within each row
        var cells = cols.map(function(colData) {
            // colData.key might be "firstName"
            return <td> {item[colData.key]} </td>;
        });
        return <tr key={item.BlogId}> {cells} </tr>;
    });
},
</code>```

答:
Since you are getting cols from props ,to make sure they exist at the initialRender you can add a check  and have the return in map in a single statement like

```<code> return data && data.map(function(item) {

        // handle the column data within each row

        return <tr key={item.BlogId}> {cols && cols.map(function(colData, index) {
            // colData.key might be "firstName"
            return <td key={index}> {item[colData.key]} </td>;
        })} </tr>;
    });
</code>```

Also provide a key for the elements returned from inner map function

Body:
getting Error in map function.

 generateRows: function() {
    var cols = this.props.cols,  // [{key, label}]
        data = this.props.data;

Getting error in data (undefined value getting)

    return data.map(function(item) {

        // handle the column data within each row
        var cells = cols.map(function(colData) {
            // colData.key might be "firstName"
            return  {item[colData.key]} 	;
        });
        return
 {cells}
;
    });
},

Body:
Since you are getting cols from props ,to make sure they exist at the initialRender you can add a check  and have the return in map in a single statement like

 return data && data.map(function(item) {

        // handle the column data within each row

        return <tr key={item.BlogId}> {cols && cols.map(function(colData, index) {
            // colData.key might be "firstName"
            return <td key={index}> {item[colData.key]} </td>;
        })} </tr>;
    });

Also provide a key for the elements returned from inner map function


来源: stackexchange

问:
Unity3D AssetBundle workflow
In my game, I need to  click clothes icon to dynamically download and generate a clothes model, is my flow correct:

WWW.LoadFromCacheOrDownload(myurl) , since this is first download, I will download the assetbundle and store in the disk.

Then I use LoadAsset() to load the instantiate the clothes object.

Game closed.

Before enter the game, use  WWW.LoadFromCacheOrDownload(myurl) again, Unity will automatically detect I downloaded before, and I will directly load it into clothes gameobject. Make the clothes gameobject inactive and will be activated if I want it to be shown.

答:
The flow seems ok, with one note:

If the app is closed and you use WWW.LoadFromCacheOrDownload it will not load the clothes gameobject, or any other object for that matter.

You have to use the same flow even if the asset bundle is loaded from cache or not. This is good as you don't need special checks to make it work.

Note: Unity is deprecating LoadFromCacheOrDownload in favour of UnityWebRequest. You can read some more here.

ContentLicense: CC BY-SA 3.0

Title: Unity3D AssetBundle workflow


问:
c# delete excel sheets using for loop
I am trying to delete excel sheets using for loop except selected sheet by User using Dropdown menu in asp.net web application. So, I have written a code in c#.

```<code>int index = DropDownList1.SelectedIndex;
int max = DropDownList1.Items.Count;
int i=3;
for (i=1; i <= max; i++)
{
    if (i != index+1)
    {
        Excel.Worksheet worksheets = (Excel.Worksheet)xlWorkBook.Sheets[i];
        worksheets.Delete();
    }

}
</code>```

And I am getting an error like this -

System.Runtime.InteropServices.COMException: 'Invalid index.
  (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))'

答:
Lets index=5;

The error means that the sheet at index 5 is not available.

You are correct that the index of worksheet starts with 1 and not 0.

I have done some modification in your code. I am performing an additional check of your current index (i) with the Sheets count present in the workbook to skip the Bad Index Error. Hope this will work.

```<code> using System;
 using Excel = Microsoft.Office.Interop.Excel;
 public partial class WebForm1 : System.Web.UI.Page
 {
     protected void Page_Load(object sender, EventArgs e)
     {
         int i = 3, max = 5, index = 1;
         string filePath = @"C:\Users\anandra\Desktop\Book1.xlsx";
         Excel.Application excelApp = new Excel.Application();
         Excel.Workbook workBook = excelApp.Workbooks.Open(filePath);
         for (i = 1; i <= max; i++)
         {
           //Adding an extra check here to skip your error
             if (i != index + 1 && workBook.Sheets.Count>i )
             {
                 Excel.Worksheet worksheets = (Excel.Worksheet)workBook.Sheets[i];
                 excelApp.DisplayAlerts = false;
                 worksheets.Delete();
                 excelApp.DisplayAlerts = true;
                 //Decreasing the value of index and i as after deleting the sheet the index will start agarin from 1.
                 i--;
                 index--;
             }
         }
     }
 }
</code>```

Title: c# delete excel sheets using for loop

Body:
I am trying to delete excel sheets using for loop except selected sheet by User using Dropdown menu in asp.net web application. So, I have written a code in c#.

int index = DropDownList1.SelectedIndex;
int max = DropDownList1.Items.Count;
int i=3;
for (i=1; i <= max; i++)
{
    if (i != index+1)
    {
        Excel.Worksheet worksheets = (Excel.Worksheet)xlWorkBook.Sheets[i];
        worksheets.Delete();
    }

}

And I am getting an error like this -

System.Runtime.InteropServices.COMException: 'Invalid index.
  (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))'

Body:
Lets index=5;

The error means that the sheet at index 5 is not available.

You are correct that the index of worksheet starts with 1 and not 0.

I have done some modification in your code. I am performing an additional check of your current index (i) with the Sheets count present in the workbook to skip the Bad Index Error. Hope this will work.

 using System;
 using Excel = Microsoft.Office.Interop.Excel;
 public partial class WebForm1 : System.Web.UI.Page
 {
     protected void Page_Load(object sender, EventArgs e)
     {
         int i = 3, max = 5, index = 1;
         string filePath = @"C:\Users\anandra\Desktop\Book1.xlsx";
         Excel.Application excelApp = new Excel.Application();
         Excel.Workbook workBook = excelApp.Workbooks.Open(filePath);
         for (i = 1; i <= max; i++)
         {
           //Adding an extra check here to skip your error
             if (i != index + 1 && workBook.Sheets.Count>i )
             {
                 Excel.Worksheet worksheets = (Excel.Worksheet)workBook.Sheets[i];
                 excelApp.DisplayAlerts = false;
                 worksheets.Delete();
                 excelApp.DisplayAlerts = true;
                 //Decreasing the value of index and i as after deleting the sheet the index will start agarin from 1.
                 i--;
                 index--;
             }
         }
     }
 }


问:
Connection has been already closed for Spring Boot and MySQL
We are migrating our system from MS SQL Server to MySQL and we are using spring boot for our application. Our application facing "Connection has been already closed" SQLException for some days and we use to restart our application and it started working fine but here is the catch after some hours it start giving same connection closed SQLException.

Here is the configs properties xfor connection:

```<code>database.jndiName=jdbc/SmartData
database.driverClassName=com.mysql.jdbc.Driver
database.url=XXXXXX
database.username=XXXXXXXXXXX
database.password=XXXXXX
database.factory=org.apache.tomcat.jdbc.pool.DataSourceFactory
database.initialSize=2
database.logAbandoned=false
database.maxIdle=4
database.maxWaitMillis=29998
database.minEvictableIdleTimeMillis=3000
database.minIdle=2
database.removeAbandonedTimeout=6
database.removeAbandoned=true
database.testOnBorrow=true
database.testOnReturn=false
database.testWhileIdle=false
database.timeBetweenEvictionRunsMillis=3000
database.validationQuery=SELECT 2+2
database.maxActive=10
database.validationInterval=3000
</code>```

答:
Few suggestions that you can follow from similar posts here on SO, for example the verified Validation Query seems to be SELECT 1 which is not used in your case.

Refer to this question on SO, which illustrates the usage of Validation queries for different DBs.

```<code>database.validationQuery=SELECT 1
</code>```

Another suggestion that can work for you is the connectionTimeout parameter which can be set to a higher value, or else a smaller value will force the session to close.

```<code>connectionTimeout="300000"
</code>```

Hope these suggestions help!

Body:
We are migrating our system from MS SQL Server to MySQL and we are using spring boot for our application. Our application facing "Connection has been already closed" SQLException for some days and we use to restart our application and it started working fine but here is the catch after some hours it start giving same connection closed SQLException.

Here is the configs properties xfor connection:

database.jndiName=jdbc/SmartData
database.driverClassName=com.mysql.jdbc.Driver
database.url=XXXXXX
database.username=XXXXXXXXXXX
database.password=XXXXXX
database.factory=org.apache.tomcat.jdbc.pool.DataSourceFactory
database.initialSize=2
database.logAbandoned=false
database.maxIdle=4
database.maxWaitMillis=29998
database.minEvictableIdleTimeMillis=3000
database.minIdle=2
database.removeAbandonedTimeout=6
database.removeAbandoned=true
database.testOnBorrow=true
database.testOnReturn=false
database.testWhileIdle=false
database.timeBetweenEvictionRunsMillis=3000
database.validationQuery=SELECT 2+2
database.maxActive=10
database.validationInterval=3000

Body:
Few suggestions that you can follow from similar posts here on SO, for example the verified Validation Query seems to be SELECT 1 which is not used in your case.

Refer to this question on SO, which illustrates the usage of Validation queries for different DBs.

database.validationQuery=SELECT 1

Another suggestion that can work for you is the connectionTimeout parameter which can be set to a higher value, or else a smaller value will force the session to close.

connectionTimeout="300000"

Hope these suggestions help!

ContentLicense: CC BY-SA 4.0


问:
Creating a New Array in a Particular Order
Once a particular promise is resolved, i wish to loop through each of the items in the response and push them into an array in a specific order.

status-start

status-in-progress

status-completed

How can I go about doing this? Here is my code so far:

```<code>dashService.getBatches(refresh)
.then(function (response) {
  if (response.error) {
    console.log("No data received");
  } else {
    angular.forEach(response.items, function (item) {
      if (item.status === 'start') {
        currentBatches.push(job);
      }
    });
  }
});
</code>```

答:
Once you get your response, do the following:

```<code>    dataList = response.items;
    var currentBatches = [];

    var statusStartItems = dataList.filter(function(item){ return item.status === 'status-start';});
    //Loop through status-start items and push into currentbatches array
    statusStartItems.each(function(item){
      currentBatches.push(item);
    }

    var statusInItems = dataList.filter(function(item){ return item.status === 'status-in';});
    //Loop through status-in items and push into currentbatches array
    statusInItems .each(function(item){
      currentBatches.push(item);
    }
</code>```

..so on

Body:
Once a particular promise is resolved, i wish to loop through each of the items in the response and push them into an array in a specific order.

status-start

status-in-progress

status-completed

How can I go about doing this? Here is my code so far:

dashService.getBatches(refresh)
.then(function (response) {
  if (response.error) {
    console.log("No data received");
  } else {
    angular.forEach(response.items, function (item) {
      if (item.status === 'start') {
        currentBatches.push(job);
      }
    });
  }
});

Body:
Once you get your response, do the following:

    dataList = response.items;
    var currentBatches = [];

    var statusStartItems = dataList.filter(function(item){ return item.status === 'status-start';});
    //Loop through status-start items and push into currentbatches array
    statusStartItems.each(function(item){
      currentBatches.push(item);
    }

    var statusInItems = dataList.filter(function(item){ return item.status === 'status-in';});
    //Loop through status-in items and push into currentbatches array
    statusInItems .each(function(item){
      currentBatches.push(item);
    }

..so on


问:
AngularJS Authentication / Authorization via oAuth2 functionality
Can someone help to find a solve how to write this functionality on AngularJS?

Have java rest API and authorization server on one port and ui on other.
 Back-end authorization made by oAuth2. Need to make UI authorization.
 can someone help, please?

Thanks and best regards.

答:
if you are using AngularJs 1, you can use Satellizer. It's an AngularJs library to easily implement a token-based authentication.

Here is the GitHub link -> https://github.com/sahat/satellizer/

It is compatible with OAuth1, OAuth2 and has built-in support for the most popular provider (Google, Facebook, GitHub etc). I am using it for a current project and it perfectly works.

Please provide some details if you need any further help :)


问:
Form Dynamic JSON array in C#
For a web service, I need to create dynamic JSON array to be sent as response based on the data given by a stored procedure.

```<code>var t = new Dictionary<string, dynamic>();
for (int i = 0; i < reader.FieldCount; i++)
{
  columnName = reader.GetName(i);
  fieldValue = reader.GetValue(i).ToString();
  t[columnName] = fieldValue;
}
_response.data.Add(t);
</code>```

But the response received is data: [[{"key": "name", "value": "123"}, {"date": "01-Jun-2017"}],[{"key": "name", "value": "abc"}]]

whereas the response needed is : [{ "name": "abc", "date": "01-Jun-2017"},{ "name": "123"}]

Can anyone let me know what could the issue be?

Thanks in Advance.

答:
Maybe this library could help you, it could save you time

http://www.newtonsoft.com/json

Title: Form Dynamic JSON array in C#

Body:
For a web service, I need to create dynamic JSON array to be sent as response based on the data given by a stored procedure.

var t = new Dictionary<string, dynamic>();
for (int i = 0; i < reader.FieldCount; i++)
{
  columnName = reader.GetName(i);
  fieldValue = reader.GetValue(i).ToString();
  t[columnName] = fieldValue;
}
_response.data.Add(t);

But the response received is data: [[{"key": "name", "value": "123"}, {"date": "01-Jun-2017"}],[{"key": "name", "value": "abc"}]]

whereas the response needed is : [{ "name": "abc", "date": "01-Jun-2017"},{ "name": "123"}]

Can anyone let me know what could the issue be?

Thanks in Advance.


问:
How to separate Hours minutes and seconds from data using tidyr Package in R language?
Here is the data i had

```<code>  temp           time_hour
1 37.04      2013-01-01 05:30:00
2 37.04      2013-01-01 06:30:00
3 37.94      2013-01-01 07:30:00
4 37.94      2013-01-01 08:30:00
5 37.94      2013-01-01 09:30:00
</code>```

Now i need to separate the time_hour column to "date","month","year" and also to "Hours","minutes","seconds" using tidyr package in R programming languages. I used separate variables to separate date, month, year. i don't know how to separate time like hours, minutes, seconds. Thanks in advance...

Body:
Here is the data i had

  temp           time_hour
1 37.04      2013-01-01 05:30:00
2 37.04      2013-01-01 06:30:00
3 37.94      2013-01-01 07:30:00
4 37.94      2013-01-01 08:30:00
5 37.94      2013-01-01 09:30:00

Now i need to separate the time_hour column to "date","month","year" and also to "Hours","minutes","seconds" using tidyr package in R programming languages. I used separate variables to separate date, month, year. i don't know how to separate time like hours, minutes, seconds. Thanks in advance...

Body:
We can use separate

library(tidyr)
df1 %>%
    separate(time_hour, into = c("year", "month", "day", "hour", "minutes", "seconds"))
#   temp year month day hour minutes seconds
#1 37.04 2013    01  01   05      30      00
#2 37.04 2013    01  01   06      30      00
#3 37.94 2013    01  01   07      30      00
#4 37.94 2013    01  01   08      30      00
#5 37.94 2013    01  01   09      30      00


问:
Using JavaScript to edit HTML style in .cshtml
I am making a MVC Web Application and trying to edit the width of a progress bar to show an increase or decrease in the progress and am using a basic javascript function to do it but it is not working.

Can anyone tell me what am I doing wrong? Thanks.

@{
    ViewBag.Title = "About";
}

@ViewBag.Title.

@ViewBag.Message

Use this area to provide additional information.

        45% Complete

<input type="button" value="Change Width" onclick="increase()" class="btn btn-default btn-sm" />

```

答:
Here's a fixed version for you, you're setting the width incorrectly.

@{
    ViewBag.Title = "About";
}

@ViewBag.Title.

@ViewBag.Message

Use this area to provide additional information.

        45% Complete

<input type="button" value="Change Width" onclick="increase()" class="btn btn-default btn-sm" />

```

Body:
Here's a fixed version for you, you're setting the width incorrectly.

@{
    ViewBag.Title = "About";
}

<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>

<p>Use this area to provide additional information.</p>

<div class="progress progress-striped active progress-sm">
    <div class="progress-bar progress-bar-success" name="blah" role="progressbar" aria-valuenow="45" aria-valuemin="0" aria-valuemax="100" style="width: 45%; border: 1px solid black;"  id="pb1">
        <span class="sr-only">45% Complete</span>
    </div>
</div>

<input type="button" value="Change Width" onclick="increase()" class="btn btn-default btn-sm" />

<script type="text/javascript">
    function increase()
    {
        document.getElementById("pb1").style.width = "80%";
    }
</script>


问:
Updating python numpy array columns multiple times
Suppose I have a 2x3 matrix A:

```<code>1 2 3
4 5 6
</code>```

and a vector y of length 4:

```<code>0 1 2 1
</code>```

as well as another 4x2 matrix B:

```<code>0 0
1 1
2 2
3 3
</code>```

I want to update the columns of A multiple times by adding from rows of B.
And the index of columns of A to be updated is given by y.

Using for loops, this can be done as:

```<code>for i in np.arange(4):
  A[:,y[i]] += B[i,:]
</code>```

I had implemented this using ufunc.at as:

```<code>np.add.at(A.T,y,B)
</code>```

However, the performance of ufunc.at is almost as bad as using for loops.

How can I get a different vectorized implementation?

Updating using A[:,y]+=B.T seems to update each column only once.

答:
Approach #1

Here's one approach using summations at intervals with np.add.reduceat -

```<code>def reduceat_app(A, y, B):
    idx = y.argsort()
    y0 = y[idx]
    sep_idx = np.concatenate(([0], np.flatnonzero(y0[1:] != y0[:-1])+1))
    A += np.add.reduceat(B[idx],sep_idx).T
</code>```

Approach #2

With relatively lesser number of rows in A, we can also use np.bincount to perform those bin-based summations in an iterative manner for each row, like so -

```<code>def bincount_loopy_app(A, y, B):
    n = A.shape[1]
    for i,a in enumerate(A):
        a += np.bincount(y,B[:,i],minlength=n).astype(A.dtype)
</code>```

Approach #3

We can vectorize previous approach by creating a 2D grid of y indices/bins for all elements such that for each row, we would have offsetted bins. With that offsetting, bincount could be used to perform bin based summations across all rows in a vectorized manner.

Thus, the implementation would be -

```<code>def bincount_vectorized_app(A, y, B):
    m,n = A.shape
    IDs = y[:,None] + n*np.arange(B.shape[1])
    vals = np.bincount(IDs.ravel(), B.ravel(), minlength=m*n)
    A += vals.astype(A.dtype).reshape((m,n))
</code>```

Body:
Suppose I have a 2x3 matrix A:

1 2 3
4 5 6

and a vector y of length 4:

0 1 2 1

as well as another 4x2 matrix B:

0 0
1 1
2 2
3 3

I want to update the columns of A multiple times by adding from rows of B.
And the index of columns of A to be updated is given by y.

Using for loops, this can be done as:

for i in np.arange(4):
  A[:,y[i]] += B[i,:]

I had implemented this using ufunc.at as:

np.add.at(A.T,y,B)

However, the performance of ufunc.at is almost as bad as using for loops.

How can I get a different vectorized implementation?

Updating using A[:,y]+=B.T seems to update each column only once.

Body:
Approach #1

Here's one approach using summations at intervals with np.add.reduceat -

def reduceat_app(A, y, B):
    idx = y.argsort()
    y0 = y[idx]
    sep_idx = np.concatenate(([0], np.flatnonzero(y0[1:] != y0[:-1])+1))
    A += np.add.reduceat(B[idx],sep_idx).T

Approach #2

With relatively lesser number of rows in A, we can also use np.bincount to perform those bin-based summations in an iterative manner for each row, like so -

def bincount_loopy_app(A, y, B):
    n = A.shape[1]
    for i,a in enumerate(A):
        a += np.bincount(y,B[:,i],minlength=n).astype(A.dtype)

Approach #3

We can vectorize previous approach by creating a 2D grid of y indices/bins for all elements such that for each row, we would have offsetted bins. With that offsetting, bincount could be used to perform bin based summations across all rows in a vectorized manner.

Thus, the implementation would be -

def bincount_vectorized_app(A, y, B):
    m,n = A.shape
    IDs = y[:,None] + n*np.arange(B.shape[1])
    vals = np.bincount(IDs.ravel(), B.ravel(), minlength=m*n)
    A += vals.astype(A.dtype).reshape((m,n))


问:
ListViewItem as EditableTextBlock
I have a ListView. The Itemsource of this ListView is populated by a ObservableCollection.

What I try to achieve is making the ListViewItems editable. Therefor I downloaded this soluation https://www.codeproject.com/Articles/31592/Editable-TextBlock-in-WPF-for-In-place-Editing

I can make this work as long as my ListView doesn't get populated with the ObservableCollection.

My Code without ObservableCollection:

```<code>private void ListView1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.F2)
        SetCurrentItemInEditMode(true);
}

private void SetCurrentItemInEditMode(bool EditMode)
{
    ListViewItem m = (ListViewItem)ListView1.SelectedItem;
    EditableTextBlock e = m.Content as EditableTextBlock;
    e.IsInEditMode = EditMode;
}
</code>```

However, when I populate the ListView Items with the ObservableCollection it doesn't work.

```<code>MyFiles m = (MyFiles)ListView1.SelectedItem;
EditableTextBlock e = m.FileName as EditableTextBlock;
e.IsInEditMode = EditMode;
</code>```

MyFiles contains (FileName, FileCreation and FileIcon). I want to convert the FileName selected ListViewItem to the EditableTextBlock control.

Thank you for your help.

P.S. I'm pretty new to WPF so please apologize if my question is stupid.

答:
You should define an ItemTemplate with an EditableTextBlock in your XAML markup. Note the bindings:

```<code><ListView x:Name="ListView1">
    <ListView.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <local:EditableTextBlock Text="{Binding FileName}" IsInEditMode="{Binding IsInEditMode}" />
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
</code>```

Then you should add an IsInEditMode property to your MyFiles class and set this one to true whenever you want to put the item into edit mode:

```<code>private void SetCurrentItemInEditMode(bool EditMode)
{
    MyFiles obj = ListView1.SelectedItem as MyFiles;
    obj.IsInEditMode = EditMode;
}
</code>```

For this to work, your MyFiles class should implement the INotifyPropertyChanged interface and raise the PropertyChanged event in the setter of the IsInEditMode property as explained on MSDN: https://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged(v=vs.110).aspx

Title: ListViewItem as EditableTextBlock

Body:
I have a ListView. The Itemsource of this ListView is populated by a ObservableCollection.

What I try to achieve is making the ListViewItems editable. Therefor I downloaded this soluation https://www.codeproject.com/Articles/31592/Editable-TextBlock-in-WPF-for-In-place-Editing

I can make this work as long as my ListView doesn't get populated with the ObservableCollection.

My Code without ObservableCollection:

private void ListView1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.F2)
        SetCurrentItemInEditMode(true);
}

private void SetCurrentItemInEditMode(bool EditMode)
{
    ListViewItem m = (ListViewItem)ListView1.SelectedItem;
    EditableTextBlock e = m.Content as EditableTextBlock;
    e.IsInEditMode = EditMode;
}

However, when I populate the ListView Items with the ObservableCollection it doesn't work.

MyFiles m = (MyFiles)ListView1.SelectedItem;
EditableTextBlock e = m.FileName as EditableTextBlock;
e.IsInEditMode = EditMode;

MyFiles contains (FileName, FileCreation and FileIcon). I want to convert the FileName selected ListViewItem to the EditableTextBlock control.

Thank you for your help.

P.S. I'm pretty new to WPF so please apologize if my question is stupid.

Body:
You should define an ItemTemplate with an EditableTextBlock in your XAML markup. Note the bindings:

<ListView x:Name="ListView1">
    <ListView.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <local:EditableTextBlock Text="{Binding FileName}" IsInEditMode="{Binding IsInEditMode}" />
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

Then you should add an IsInEditMode property to your MyFiles class and set this one to true whenever you want to put the item into edit mode:

private void SetCurrentItemInEditMode(bool EditMode)
{
    MyFiles obj = ListView1.SelectedItem as MyFiles;
    obj.IsInEditMode = EditMode;
}

For this to work, your MyFiles class should implement the INotifyPropertyChanged interface and raise the PropertyChanged event in the setter of the IsInEditMode property as explained on MSDN: https://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged(v=vs.110).aspx


问:
Read data from excel in Selenium Webdriver with c#
I am working with selenium webdriver c#. I need to read data from excel.

Code:

```<code>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using Excel = Microsoft.Office.Interop.Excel;

namespace UIL
{
    [TestClass]
    public class UIL_Login : UtilityHelper
    {
        IWebDriver driver;
        Excel.Application loginapp;
        Excel.Workbook loginworkbook;
        Excel._Worksheet loginworksheet;
        Excel.Range loginrange;

        public UIL_Login()
        {
            loginapp = new Excel.Application();
            loginworkbook = loginapp.Workbooks.Open(@"D:\\MyProjects\\Selenium_C#\\SeleniumProjects\\UIL\\UIL\\Resources\\login.xls");
            //loginworksheet = loginworkbook.Sheets[1];
            loginworksheet = (Excel.Worksheet)loginworkbook.Worksheets.get_Item(1);
            loginrange = loginworksheet.UsedRange;
        }

        [TestInitialize]
        public void SetUp()
        {
            driver = new ChromeDriver(@"D:\\MyProjects\\Selenium_C#\\Selenium\\chromedriver");
            driver.Navigate().GoToUrl("http://192.168.0.35:92");
            driver.Manage().Window.Maximize();
        }

        /*Login without username*/
        [TestMethod]
        public void loginWithoutUsername()
        {
            try
            {
                int emptyUsernameRowNumber = 1;
                driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(1000);
                IWebElement username = webElement(driver, Constants.VAR_EMAIL);
                username.Clear();
                //username.SendKeys("amrutha.u@teamta.in");
                username.SendKeys(loginrange.Cells[emptyUsernameRowNumber][1]);
                driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(1000);
                IWebElement password = webElement(driver, Constants.VAR_PASSWORD);
                password.Clear();
                // password.SendKeys("UIL@123#");
                password.SendKeys(loginrange.Cells[emptyUsernameRowNumber][2]);
                driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(1000);
                IWebElement signinButton = driver.FindElement(By.XPath("//*[@id='mainDiv']/div[4]/div/div/form/a/button"));
                signinButton.Click();
            }
            catch (Exception e)
            {
                Console.Write(e);

            }

        }
    }
}
</code>```

But i am getting the following exception:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: The best
  overloaded method match for
  'OpenQA.Selenium.IWebElement.SendKeys(string)' has some invalid
  arguments    at CallSite.Target(Closure , CallSite , IWebElement ,
  Object )    at
  System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid2[T0,T1](CallSite
  site, T0 arg0, T1 arg1)

Can anybody help to solve this issue?

答:
well, you're passing a parameter of Cells type to the SendKeys() method, when it's expecting a string.

Try loginrange.Cells[emptyUsernameRowNumber][1].Value2.ToString()

Note:
I'm assuming that the you have the data you need in your cell.

Body:
I am working with selenium webdriver c#. I need to read data from excel.

Code:

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using Excel = Microsoft.Office.Interop.Excel;

namespace UIL
{
    [TestClass]
    public class UIL_Login : UtilityHelper
    {
        IWebDriver driver;
        Excel.Application loginapp;
        Excel.Workbook loginworkbook;
        Excel._Worksheet loginworksheet;
        Excel.Range loginrange;

        public UIL_Login()
        {
            loginapp = new Excel.Application();
            loginworkbook = loginapp.Workbooks.Open(@"D:\\MyProjects\\Selenium_C#\\SeleniumProjects\\UIL\\UIL\\Resources\\login.xls");
            //loginworksheet = loginworkbook.Sheets[1];
            loginworksheet = (Excel.Worksheet)loginworkbook.Worksheets.get_Item(1);
            loginrange = loginworksheet.UsedRange;
        }

        [TestInitialize]
        public void SetUp()
        {
            driver = new ChromeDriver(@"D:\\MyProjects\\Selenium_C#\\Selenium\\chromedriver");
            driver.Navigate().GoToUrl("http://192.168.0.35:92");
            driver.Manage().Window.Maximize();
        }

        /*Login without username*/
        [TestMethod]
        public void loginWithoutUsername()
        {
            try
            {
                int emptyUsernameRowNumber = 1;
                driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(1000);
                IWebElement username = webElement(driver, Constants.VAR_EMAIL);
                username.Clear();
                //username.SendKeys("amrutha.u@teamta.in");
                username.SendKeys(loginrange.Cells[emptyUsernameRowNumber][1]);
                driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(1000);
                IWebElement password = webElement(driver, Constants.VAR_PASSWORD);
                password.Clear();
                // password.SendKeys("UIL@123#");
                password.SendKeys(loginrange.Cells[emptyUsernameRowNumber][2]);
                driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(1000);
                IWebElement signinButton = driver.FindElement(By.XPath("//*[@id='mainDiv']/div[4]/div/div/form/a/button"));
                signinButton.Click();
            }
            catch (Exception e)
            {
                Console.Write(e);

            }

        }
    }
}

But i am getting the following exception:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: The best
  overloaded method match for
  'OpenQA.Selenium.IWebElement.SendKeys(string)' has some invalid
  arguments    at CallSite.Target(Closure , CallSite , IWebElement ,
  Object )    at
  System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid2[T0,T1](CallSite
  site, T0 arg0, T1 arg1)

Can anybody help to solve this issue?


问:
Android 7 BroadcastReceiver onReceive intent.getExtras missing data
My app isn't working on Android 7.  My BroadcastReceiver.onReceive method is called but the contents of the intent.getExtras is missing.  I've verified that the data was correctly loaded.  Here's a snippet from my onReceive method, where intent is passed as a parameter to onReceive.

```<code>Bundle bundle = intent.getExtras();
textMessage = bundle.getString("TEXT_MESSAGE");
ArrayList<MyPhoneNumber> phoneNumbersToText = bundle.getParcelableArrayList("PHONE_NUMBERS");
</code>```

Both textMessage and phoneNumbersToText are null.

Here's a snippet from my manifest file:

```<code><receiver android:process=":remote" android:name="com.friscosoftware.timelytextbase.AlarmReceiver"></receiver>
</code>```

Here's a snippet where the data is loaded:

```<code>Intent intent = new Intent(context , AlarmReceiver.class);
intent.putExtra(Constants.TEXT_MESSAGE, scheduledItem.getMessageToSend());
intent.putExtra(Constants.PHONE_NUMBERS, scheduledItem.getPhoneNumbersToText());

PendingIntent sender = PendingIntent.getBroadcast(context, getRequestCodeFromKey(key), intent, PendingIntent.FLAG_UPDATE_CURRENT);

// Get the AlarmManager service
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, selectedDateTime.getTimeInMillis(), sender);
</code>```

The same code works fine in Android 6.

Any thoughts on what changes are required here for Android 7?

Thank you

答:
I had a similar problem but I think I found an easy solution. Put your data inside a Bundle and send that Bundle with your alarm intent. In my case I wanted to send a serializable object with my intent.

Setup the alarm:

```<code>AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
`
Intent intent = new Intent(context, AlarmReciever.class);
Bundle bundle = new Bundle();

// creating an example object
ExampleClass exampleObject = new ExampleClass();

// put the object inside the Bundle
bundle.putSerializable("exapmle", exampleObject);

// put the Bundle inside the intent
intent.putExtra("bundle",bundle);

PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);

// setup the alarm
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmIntent);
</code>```

Receive the alarm:

```<code>public class AlarmReciever extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        // get the Bundle
        Bundle bundle = intent.getBundleExtra("bundle");
        // get the object
        ExampleClass exampleObject = (ExampleClass)bundle.getSerializable("example");
    }

}
</code>```

It worked fine for me. Hope it helps :)

Body:
My app isn't working on Android 7.  My BroadcastReceiver.onReceive method is called but the contents of the intent.getExtras is missing.  I've verified that the data was correctly loaded.  Here's a snippet from my onReceive method, where intent is passed as a parameter to onReceive.

Bundle bundle = intent.getExtras();
textMessage = bundle.getString("TEXT_MESSAGE");
ArrayList<MyPhoneNumber> phoneNumbersToText = bundle.getParcelableArrayList("PHONE_NUMBERS");

Both textMessage and phoneNumbersToText are null.

Here's a snippet from my manifest file:

<receiver android:process=":remote" android:name="com.friscosoftware.timelytextbase.AlarmReceiver"></receiver>

Here's a snippet where the data is loaded:

Intent intent = new Intent(context , AlarmReceiver.class);
intent.putExtra(Constants.TEXT_MESSAGE, scheduledItem.getMessageToSend());
intent.putExtra(Constants.PHONE_NUMBERS, scheduledItem.getPhoneNumbersToText());

PendingIntent sender = PendingIntent.getBroadcast(context, getRequestCodeFromKey(key), intent, PendingIntent.FLAG_UPDATE_CURRENT);

// Get the AlarmManager service
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, selectedDateTime.getTimeInMillis(), sender);

The same code works fine in Android 6.

Any thoughts on what changes are required here for Android 7?

Thank you

Body:
I had a similar problem but I think I found an easy solution. Put your data inside a Bundle and send that Bundle with your alarm intent. In my case I wanted to send a serializable object with my intent.

Setup the alarm:

AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
`
Intent intent = new Intent(context, AlarmReciever.class);
Bundle bundle = new Bundle();

// creating an example object
ExampleClass exampleObject = new ExampleClass();

// put the object inside the Bundle
bundle.putSerializable("exapmle", exampleObject);

// put the Bundle inside the intent
intent.putExtra("bundle",bundle);

PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);

// setup the alarm
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmIntent);

Receive the alarm:

public class AlarmReciever extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        // get the Bundle
        Bundle bundle = intent.getBundleExtra("bundle");
        // get the object
        ExampleClass exampleObject = (ExampleClass)bundle.getSerializable("example");
    }

}

It worked fine for me. Hope it helps :)


问:
Java - Which version was a .jar file built too?
Is there a way to find out the JDK version used to build a .jar file?</p>

答:
That's not possible reliably, since you don't even need a JDK to build a JAR file - it's just a ZIP file with the classes and a manifest file inside.

What you can find out is what version of the class file format is used. The major version number maps to majorJDK releases:

```<code>J2SE 6.0 = 50 (0x32 hex)
J2SE 5.0 = 49 (0x31 hex)
JDK 1.4 = 48 (0x30 hex)
JDK 1.3 = 47 (0x2F hex)
JDK 1.2 = 46 (0x2E hex)
JDK 1.1 = 45 (0x2D hex)
</code>```

However, the java compiler has an option to use the class file format of a previous version, which is frequently used to achieve downwards compatibility. But if you find a class file version major number of 50, you know that the classes were definitely not compiled with a Java 5 or earlier JDK.

Body:
That's not possible reliably, since you don't even need a JDK to build a JAR file - it's just a ZIP file with the classes and a manifest file inside.

What you can find out is what version of the class file format is used. The major version number maps to majorJDK releases:

J2SE 6.0 = 50 (0x32 hex)
J2SE 5.0 = 49 (0x31 hex)
JDK 1.4 = 48 (0x30 hex)
JDK 1.3 = 47 (0x2F hex)
JDK 1.2 = 46 (0x2E hex)
JDK 1.1 = 45 (0x2D hex)

However, the java compiler has an option to use the class file format of a previous version, which is frequently used to achieve downwards compatibility. But if you find a class file version major number of 50, you know that the classes were definitely not compiled with a Java 5 or earlier JDK.


问:
oracle 11 :want to pass cursor variable to variable defined in procedure
Previously i used a temp table which created outside the procedure and inserted data in SP and used,,,but if i want to create a temp table inside procedure it throwing some errors..to avoid that trying to using cursor.. </p>

```<code>CREATE OR REPLACE PROCEDURE P_EMAIL_update
AS
   I    NUMBER := 1;
   J    NUMBER := 0;
   ID   NUMBER;
BEGIN
   INSERT INTO ENTITY_TEMP                                    --(RN,ENTITY_ID)
      SELECT ROWNUM, e.id
        FROM entity e, company c
       WHERE e.companyid = c.id AND e.status = 3;

   SELECT MAX (rn) INTO j FROM ENTITY_TEMP;

   WHILE i <= j
   LOOP
      SELECT entity_id
        INTO id
        FROM ENTITY_TEMP
       WHERE rn = i;

      INSERT INTO ACTIONS_EMAIL_MAPPING (ID,
                                         ISACTIVE,
                                         ACTIONNAME,
                                         EMAILFROM,
                                         EMAILSUBJECT,
                                         EMAILBODY
                                         )
         (SELECT SEQ_ENT.NEXTVAL,
                 'N',
                 ACTIONNAME,
                 EMAILFROM,
                 EMAILSUBJECT,
                 EMAILBODY || var_id
            FROM ACTIONS
           WHERE ISACTIVE = 'T' AND ACTIONNAME NOT IN ('sample'));

      I := I + 1;
   END LOOP;
   END;
</code>```

答:
The procedure in your question could be rewritten more simply as:

```<code>CREATE OR REPLACE PROCEDURE p_email_update AS
BEGIN

  INSERT INTO actions_email_mapping (id, isactive, actionname, emailfrom, emailsubject, emailbody)
  SELECT seq_ent.nextval,
         'N',
         a.actionname,
         a.emailfrom,
         a.emailsubject,
         a.emailbody || ent.id -- assuming var_id is a column of actions
  FROM   actions a
         CROSS JOIN (SELECT e.id
                     FROM   entity e
                            inner join company c on e.companyid = c.id
                     WHERE  e.status = 3) ent -- maybe this should be an inner join with some join conditions?
  WHERE  a.isactive = 'T'
  AND    a.actionname NOT IN ('sample');

END p_email_update;
/
</code>```

There is no need to reinvent a cross join (which is what your code was doing, in a very roundabout way). There is also no need to store the data in a temp table either, based on what you've told us in your question, since you can just reference the subquery directly in the insert-as-select.

I would question why there aren't any join conditions between your actions table, and the subquery on the entity and company tables, though.

Body:
Previously i used a temp table which created outside the procedure and inserted data in SP and used,,,but if i want to create a temp table inside procedure it throwing some errors..to avoid that trying to using cursor..

CREATE OR REPLACE PROCEDURE P_EMAIL_update
AS
   I    NUMBER := 1;
   J    NUMBER := 0;
   ID   NUMBER;
BEGIN
   INSERT INTO ENTITY_TEMP                                    --(RN,ENTITY_ID)
      SELECT ROWNUM, e.id
        FROM entity e, company c
       WHERE e.companyid = c.id AND e.status = 3;

   SELECT MAX (rn) INTO j FROM ENTITY_TEMP;

   WHILE i <= j
   LOOP
      SELECT entity_id
        INTO id
        FROM ENTITY_TEMP
       WHERE rn = i;

      INSERT INTO ACTIONS_EMAIL_MAPPING (ID,
                                         ISACTIVE,
                                         ACTIONNAME,
                                         EMAILFROM,
                                         EMAILSUBJECT,
                                         EMAILBODY
                                         )
         (SELECT SEQ_ENT.NEXTVAL,
                 'N',
                 ACTIONNAME,
                 EMAILFROM,
                 EMAILSUBJECT,
                 EMAILBODY || var_id
            FROM ACTIONS
           WHERE ISACTIVE = 'T' AND ACTIONNAME NOT IN ('sample'));

      I := I + 1;
   END LOOP;
   END;

Body:
The procedure in your question could be rewritten more simply as:

CREATE OR REPLACE PROCEDURE p_email_update AS
BEGIN

  INSERT INTO actions_email_mapping (id, isactive, actionname, emailfrom, emailsubject, emailbody)
  SELECT seq_ent.nextval,
         'N',
         a.actionname,
         a.emailfrom,
         a.emailsubject,
         a.emailbody || ent.id -- assuming var_id is a column of actions
  FROM   actions a
         CROSS JOIN (SELECT e.id
                     FROM   entity e
                            inner join company c on e.companyid = c.id
                     WHERE  e.status = 3) ent -- maybe this should be an inner join with some join conditions?
  WHERE  a.isactive = 'T'
  AND    a.actionname NOT IN ('sample');

END p_email_update;
/

There is no need to reinvent a cross join (which is what your code was doing, in a very roundabout way). There is also no need to store the data in a temp table either, based on what you've told us in your question, since you can just reference the subquery directly in the insert-as-select.

I would question why there aren't any join conditions between your actions table, and the subquery on the entity and company tables, though.


问:
How can i share a variable value between 2 components in angular 2
I am playing around with angular2. I have created 1 component using angular cli called appmenu.

appmenu.html as follows:

```<code><ul>
  <li (click)="menuitem1()">Menu Item 1</li>
  <li>Menu Item 2</li>
  <li>Menu Item 3</li>
</ul>
</code>```

i wish to fetch the value of testvariable on app.component.html, but i dont know what should i do in my app.component.ts

appmenu.ts as follows

```<code>   import { Component, OnInit } from '@angular/core';
import { Injectable } from '@angular/core';

@Component({
  providers: [AppMenuService], // GIVING ERROR HERE
  selector: 'app-appmenu',
  templateUrl: './appmenu.component.html',
  styleUrls: ['./appmenu.component.css']
})
export class AppmenuComponent implements OnInit {
public testvariable = "1st";
public data: any;
 // constructor(private sharedData: AppMenuService) { }

  ngOnInit() {
   // this.data = this.sharedData.data;
   // console.log(this.data);
  }

  menuitem1(){
    console.log("Menu item 1 clicked");
  }

}
</code>```

appmenu.service.ts

```<code>import { Injectable } from '@angular/core';

@Injectable()
export class AppMenuService{
public data: any;
    constructor() {
        this.data = 'Lorem ipsum dolor sit.';
    }
}
</code>```

Getting error on appmenu.component.ts here -> providers: [AppMenuService] , it says cannot find name AppMenuService

答:
If you want to statically share a variable between two components you can declare this variable in some service and use this variable by injecting this service. E.g.

```<code>// shared-data.service.ts

export class SharedDataService {
    public data: any;
    constructor() {
        this.data = 'Lorem ipsum dolor sit.';
    }
}

// app.component.ts

@Component({ ... })
export class AppComponent implements OnInit {
    public data: any;

    constructor(private sharedData: SharedDataService) { }

    public ngOnInit() {
        this.data = this.sharedData.data;
    }
}

// app-menu/app-menu.component.ts

@Component({ ... })
export class AppMenuComponent implements OnInit {
    public data: any;

    constructor(private sharedData: SharedDataService) { }

    public ngOnInit() {
        this.data = this.sharedData.data;
    }
}
</code>```

But commonly when you need to shared some data between parent and child components you need to use @Input and @Output. @Input allows you to pass data directly to the child component/directive. @Output allows you to listen events of child component. Learn more here.

E.g.

```<code>// app.component.ts

@Component({
    template: `
        <app-menu
            [someData]="dataForChild"
            (menuClick)="handleMenuClick($event)">
        </app-menu>
    `
})
export class AppComponent implements OnInit {
    public dataForChild: any;

    constructor() { }

    public ngOnInit() {
        this.dataForChild = 'Lorem ipsum dolor sit.'
    }

    public handleMenuClick(itemIndex) {
        console.log(itemIndex);
    }
}

// app-menu/app-menu.component.ts

@Component({
    selector: 'app-menu',
    template: `
        <ul>
            <li (click)="transferMenuClick(1)">Menu item 1</li>
            <li (click)="transferMenuClick(2)">Menu item 2</li>
            <li (click)="transferMenuClick(3)">Menu item 3</li>
        </ul>
    `
})
export class AppMenuComponent implements OnInit {
    @Output('menuClick')
    public menuClick: EventEmitter<number>;

    @Input('someData')
    public someData: any;

    constructor(private sharedData: SharedDataService) {
        this.menuClick = new EventEmitter<number>;
    }

    public ngOnInit() {
        console.log(this.someData);
    }

    public transferMenuClick(itemIndex) {
        this.menuClick.emit(itemIndex);
    }
}
</code>```

Body:
I am playing around with angular2. I have created 1 component using angular cli called appmenu.

appmenu.html as follows:

Menu Item 1

Menu Item 2

Menu Item 3

i wish to fetch the value of testvariable on app.component.html, but i dont know what should i do in my app.component.ts

appmenu.ts as follows

   import { Component, OnInit } from '@angular/core';
import { Injectable } from '@angular/core';

@Component({
  providers: [AppMenuService], // GIVING ERROR HERE
  selector: 'app-appmenu',
  templateUrl: './appmenu.component.html',
  styleUrls: ['./appmenu.component.css']
})
export class AppmenuComponent implements OnInit {
public testvariable = "1st";
public data: any;
 // constructor(private sharedData: AppMenuService) { }

  ngOnInit() {
   // this.data = this.sharedData.data;
   // console.log(this.data);
  }

  menuitem1(){
    console.log("Menu item 1 clicked");
  }

}

appmenu.service.ts

import { Injectable } from '@angular/core';

@Injectable()
export class AppMenuService{
public data: any;
    constructor() {
        this.data = 'Lorem ipsum dolor sit.';
    }
}

Getting error on appmenu.component.ts here -> providers: [AppMenuService] , it says cannot find name AppMenuService

Body:
If you want to statically share a variable between two components you can declare this variable in some service and use this variable by injecting this service. E.g.

// shared-data.service.ts

export class SharedDataService {
    public data: any;
    constructor() {
        this.data = 'Lorem ipsum dolor sit.';
    }
}

// app.component.ts

@Component({ ... })
export class AppComponent implements OnInit {
    public data: any;

    constructor(private sharedData: SharedDataService) { }

    public ngOnInit() {
        this.data = this.sharedData.data;
    }
}

// app-menu/app-menu.component.ts

@Component({ ... })
export class AppMenuComponent implements OnInit {
    public data: any;

    constructor(private sharedData: SharedDataService) { }

    public ngOnInit() {
        this.data = this.sharedData.data;
    }
}

But commonly when you need to shared some data between parent and child components you need to use @Input and @Output. @Input allows you to pass data directly to the child component/directive. @Output allows you to listen events of child component. Learn more here.

E.g.

// app.component.ts

@Component({
    template: `
        <app-menu
            [someData]="dataForChild"
            (menuClick)="handleMenuClick($event)">
        </app-menu>
    `
})
export class AppComponent implements OnInit {
    public dataForChild: any;

    constructor() { }

    public ngOnInit() {
        this.dataForChild = 'Lorem ipsum dolor sit.'
    }

    public handleMenuClick(itemIndex) {
        console.log(itemIndex);
    }
}

// app-menu/app-menu.component.ts

@Component({
    selector: 'app-menu',
    template: `
        <ul>
            <li (click)="transferMenuClick(1)">Menu item 1</li>
            <li (click)="transferMenuClick(2)">Menu item 2</li>
            <li (click)="transferMenuClick(3)">Menu item 3</li>
        </ul>
    `
})
export class AppMenuComponent implements OnInit {
    @Output('menuClick')
    public menuClick: EventEmitter<number>;

    @Input('someData')
    public someData: any;

    constructor(private sharedData: SharedDataService) {
        this.menuClick = new EventEmitter<number>;
    }

    public ngOnInit() {
        console.log(this.someData);
    }

    public transferMenuClick(itemIndex) {
        this.menuClick.emit(itemIndex);
    }
}


问:
Populate a variant array from a comma-delimited string
Usually if I want to create an array from a comma-delimited string then it's a String array I want and the Split() function I'll use. However right now I need to convert a comma-delimited string into a Variant array so it can be used as a function argument.

Unfortunately attempting to populate a variant array using Split() is throwing a Type Mismatch error, test example below.

```<code>Public Sub GetTheStuff()
    Dim varArray() As Variant

    varArray = Split("Bob,Alice,Joe,Jane", ",") '<~~ Error 13, Type Mismatch

    DoTheThing varArray
End Sub

Private Sub DoTheThing(Args() As Variant)
    Dim i As Long

    For i = LBound(Args) To UBound(Args)
        Debug.Print Args(i)
    Next i
End Sub
</code>```

Is there a simple way to populate a Variant array from a delimited string, or am I going to have to write my own function to do so?

Note: I can't change the fact that the function I'm calling requires a Variant array as an argument, nor can I get my input as anything other than a delimited string.

答:
Import CSV data into a two dimensional variant array with
numeric as value,
date as date,
string as string.</p>

```<code>' Import CSV data into two dimensional variant array with numeric as value, date as date, string as string.
Private Function CSV_to_Array(CSV As String)

 Dim CSV_Rows() As String

 CSV_Rows() = Split(CSV, Chr(10)) ' split the CSV into rows

 ' Import CSV data into two dimensional variant array with numeric as value, date as date, string as string.
 aryWidth = 0
 ReDim Ary(0 To UBound(CSV_Rows), 0 To aryWidth) As Variant

 For Y = LBound(CSV_Rows) To UBound(CSV_Rows)

    CSV_Fields = Split(CSV_Rows(Y), ",")

    If UBound(CSV_Fields) > aryWidth Then
        aryWidth = UBound(CSV_Fields)
        ReDim Preserve Ary(0 To UBound(CSV_Rows), 0 To aryWidth) As Variant
    End If

    For X = LBound(CSV_Fields) To UBound(CSV_Fields)
        If IsNumeric(CSV_Fields(X)) Then
            Ary(Y, X) = Val(CSV_Fields(X))
        ElseIf IsDate(CSV_Fields(X)) Then
            Ary(Y, X) = CDate(CSV_Fields(X))
        Else
            Ary(Y, X) = CStr(CSV_Fields(X))
        End If
    Next

 Next

 CSV_to_Array = Ary()

End Function

Dim Ary() As Variant
Ary() = CSV_to_Array(strCSV)
</code>```

Body:
Usually if I want to create an array from a comma-delimited string then it's a String array I want and the Split() function I'll use. However right now I need to convert a comma-delimited string into a Variant array so it can be used as a function argument.

Unfortunately attempting to populate a variant array using Split() is throwing a Type Mismatch error, test example below.

Public Sub GetTheStuff()
    Dim varArray() As Variant

    varArray = Split("Bob,Alice,Joe,Jane", ",") '<~~ Error 13, Type Mismatch

    DoTheThing varArray
End Sub

Private Sub DoTheThing(Args() As Variant)
    Dim i As Long

    For i = LBound(Args) To UBound(Args)
        Debug.Print Args(i)
    Next i
End Sub

Is there a simple way to populate a Variant array from a delimited string, or am I going to have to write my own function to do so?

Note: I can't change the fact that the function I'm calling requires a Variant array as an argument, nor can I get my input as anything other than a delimited string.

Body:
Import CSV data into a two dimensional variant array with
numeric as value,
date as date,
string as string.

' Import CSV data into two dimensional variant array with numeric as value, date as date, string as string.
Private Function CSV_to_Array(CSV As String)

 Dim CSV_Rows() As String

 CSV_Rows() = Split(CSV, Chr(10)) ' split the CSV into rows

 ' Import CSV data into two dimensional variant array with numeric as value, date as date, string as string.
 aryWidth = 0
 ReDim Ary(0 To UBound(CSV_Rows), 0 To aryWidth) As Variant

 For Y = LBound(CSV_Rows) To UBound(CSV_Rows)

    CSV_Fields = Split(CSV_Rows(Y), ",")

    If UBound(CSV_Fields) > aryWidth Then
        aryWidth = UBound(CSV_Fields)
        ReDim Preserve Ary(0 To UBound(CSV_Rows), 0 To aryWidth) As Variant
    End If

    For X = LBound(CSV_Fields) To UBound(CSV_Fields)
        If IsNumeric(CSV_Fields(X)) Then
            Ary(Y, X) = Val(CSV_Fields(X))
        ElseIf IsDate(CSV_Fields(X)) Then
            Ary(Y, X) = CDate(CSV_Fields(X))
        Else
            Ary(Y, X) = CStr(CSV_Fields(X))
        End If
    Next

 Next

 CSV_to_Array = Ary()

End Function

Dim Ary() As Variant
Ary() = CSV_to_Array(strCSV)


问:
PasteSpecial is pasting multiple times
My goal is : to filter some rows, copy those filtered rows and paste it on another sheet.
I'm doing it twice : the first time, it's working well but the second time, not at all.
Before my sample of code, you need to know : wsData ---filter--> wsDataUpdated --- filter ---> wsDataUpdated2 .

The problem is : the second filter is quite ok, but the paste is like awkward : it's pasting all over the range, I mean : if I have only 2 rows after the filter, and i'm pasting it on the wsDataUpdated2 with the range : ("A1:A100") it'll paste it 50 times !! The awkward part is that it's exactly the same code of my first filter, and on my first filter, even if I have less rows than my range, it's not pasting twice or more... By the way, with some breakpoints, I've seen that the filtered part and the copy part is perfect. The paste part is not okay at all.

Here's a sample of my code :

```<code>    wsDataUpdated.Range("B4").CurrentRegion.AdvancedFilter xlFilterInPlace, wsCriteria2.Range("A1").CurrentRegion
    wsDataUpdated.Range("A1:AG10150").SpecialCells(xlCellTypeVisible).Copy
    wsDataUpdated2.Range("A1:AG10150").PasteSpecial Paste:=xlPasteValues
    wsDataUpdated2.Range("A1:AG10150").PasteSpecial Paste:=xlPasteFormats
</code>```

答:
Have you tried pasting it only on the first cell?</p>

```<code>     wsDataUpdated2.Range("A1").PasteSpecial Paste:=xlPasteValues
</code>```

Title: PasteSpecial is pasting multiple times

Body:
My goal is : to filter some rows, copy those filtered rows and paste it on another sheet.
I'm doing it twice : the first time, it's working well but the second time, not at all.
Before my sample of code, you need to know : wsData ---filter--> wsDataUpdated --- filter ---> wsDataUpdated2 .

The problem is : the second filter is quite ok, but the paste is like awkward : it's pasting all over the range, I mean : if I have only 2 rows after the filter, and i'm pasting it on the wsDataUpdated2 with the range : ("A1:A100") it'll paste it 50 times !! The awkward part is that it's exactly the same code of my first filter, and on my first filter, even if I have less rows than my range, it's not pasting twice or more... By the way, with some breakpoints, I've seen that the filtered part and the copy part is perfect. The paste part is not okay at all.

Here's a sample of my code :

    wsDataUpdated.Range("B4").CurrentRegion.AdvancedFilter xlFilterInPlace, wsCriteria2.Range("A1").CurrentRegion
    wsDataUpdated.Range("A1:AG10150").SpecialCells(xlCellTypeVisible).Copy
    wsDataUpdated2.Range("A1:AG10150").PasteSpecial Paste:=xlPasteValues
    wsDataUpdated2.Range("A1:AG10150").PasteSpecial Paste:=xlPasteFormats

Body:
Have you tried pasting it only on the first cell?

     wsDataUpdated2.Range("A1").PasteSpecial Paste:=xlPasteValues


问:
Repeat element from a 2D matrix to a 3D matrix with numpy
I have a 2-D numpy matrix, an example

```<code>M = np.matrix([[1,2],[3,4],[5,6]])
</code>```

I would like, starting from M, to have a matrix like:

```<code>M = np.matrix([[[1,2],[1,2],[1,2]],[[3,4],[3,4],[3,4]],[[5,6],[5,6],[5,6]]])
</code>```

thus, the new matrix has 3 dimensions. How can I do?

答:
as another answerer already said, the matrix can't be three-dimensional.
instead of it, you can make 3-dimensional np.array like below.

```<code>import numpy as np
M = np.matrix([[1,2],[3,4],[5,6]])
M = np.array(M)
M = np.array([ [x, x, x] for x in M])
M
</code>```

Body:
I have a 2-D numpy matrix, an example

M = np.matrix([[1,2],[3,4],[5,6]])

I would like, starting from M, to have a matrix like:

M = np.matrix([[[1,2],[1,2],[1,2]],[[3,4],[3,4],[3,4]],[[5,6],[5,6],[5,6]]])

thus, the new matrix has 3 dimensions. How can I do?

Body:
as another answerer already said, the matrix can't be three-dimensional.
instead of it, you can make 3-dimensional np.array like below.

import numpy as np
M = np.matrix([[1,2],[3,4],[5,6]])
M = np.array(M)
M = np.array([ [x, x, x] for x in M])
M


问:
how to change values for a selection field in odoo 10
How can I  update values for a selection field? I'm working on the module purchase article and I want to change the values of the type of article, for example, the article is Consumable, Service or stockable and I want it "beton", "nettoyage" or "d'entretien".</p>

答:
There are tow ways to add a value to an existing selection fields :

copy/paste the existing fields and add a vlue :

```<code>_columns = {
'type': fields.selection([('new_type', 'New type'),('consu', 'Consumable'),('service','Service')], 'Product Type', required=True, help="Consumable are product where you don't manage stock, a service is a non-material product provided by a company or an individual."),
}
</code>```

using selection_add:

```<code>type = fields.Selection(selection_add=[('new_type', 'New type')])
</code>```

Body:
There are tow ways to add a value to an existing selection fields :

copy/paste the existing fields and add a vlue :

_columns = {
'type': fields.selection([('new_type', 'New type'),('consu', 'Consumable'),('service','Service')], 'Product Type', required=True, help="Consumable are product where you don't manage stock, a service is a non-material product provided by a company or an individual."),
}

using selection_add:

type = fields.Selection(selection_add=[('new_type', 'New type')])


问:
Accessing Google Datastore from Google App engine via PHP
I'm really new to the whole GCP platform and I'm trying to create my first web app, specifically in PHP.
I've went through every thread, tutorials, etc. but they are too advance from me.

Could someone please let me know what are the most basic steps for querying a data in Cloud datastore using PHP from APP Engine?

This is my setup:
In my Datastore, there's 1 entry which basically has 2 properties called name and address, a PHP file on APP Engine that would just query the datastore.

I've enabled Datastore API access for my app. I've also deployed it.
But I can't make it to work.

This is my view.php file:

```<code><?php
use Google\Cloud\Datastore\DatastoreClient;

# Your Google Cloud Platform project ID
$projectId = '<my project id>';
# Instantiates a client
$datastore = new DatastoreClient(['projectId' => $projectId]);

$query = $datastore->query()
    ->kind('person');

$result = $datastore->runQuery($query);

foreach ($result as $entity) {
        echo 'Entity found: ' . $entity['name'] . PHP_EOL;
    }

?>
</code>```

note: I deployed my app with these 3 files:

app.yaml

index.php (hello world page)

view.php

app.yaml content:

```<code>runtime: php55
api_version: 1

handlers:
- url: /
  script: index.php

- url: /index\.html
  script: index.php

- url: /view
  script: view.php

- url: /view\.html
  script: view.php

- url: /.*
  script: not_found.php
</code>```

答:
You also have not included any files in your view.php script. PHP/GAE need to know where to find

```<code>Google\Cloud\Datastore\DatastoreClient;
</code>```

One way is to install composer and allow composer to manage all your includes/requires. The other option is to manually include everything you will need to use. With Google though, there are many many components, so using composer would be much easier. Install composer, require the Google PHP SDK package, and then all you need to do is include vendor/autoload.php at the start of your PHP file.

Body:
I'm really new to the whole GCP platform and I'm trying to create my first web app, specifically in PHP.
I've went through every thread, tutorials, etc. but they are too advance from me.

Could someone please let me know what are the most basic steps for querying a data in Cloud datastore using PHP from APP Engine?

This is my setup:
In my Datastore, there's 1 entry which basically has 2 properties called name and address, a PHP file on APP Engine that would just query the datastore.

I've enabled Datastore API access for my app. I've also deployed it.
But I can't make it to work.

This is my view.php file:

<?php
use Google\Cloud\Datastore\DatastoreClient;

# Your Google Cloud Platform project ID
$projectId = '<my project id>';
# Instantiates a client
$datastore = new DatastoreClient(['projectId' => $projectId]);

$query = $datastore->query()
    ->kind('person');

$result = $datastore->runQuery($query);

foreach ($result as $entity) {
        echo 'Entity found: ' . $entity['name'] . PHP_EOL;
    }

?>

note: I deployed my app with these 3 files:

app.yaml

index.php (hello world page)

view.php

app.yaml content:

runtime: php55
api_version: 1

handlers:
- url: /
  script: index.php

- url: /index\.html
  script: index.php

- url: /view
  script: view.php

- url: /view\.html
  script: view.php

- url: /.*
  script: not_found.php

Body:
You also have not included any files in your view.php script. PHP/GAE need to know where to find

Google\Cloud\Datastore\DatastoreClient;

One way is to install composer and allow composer to manage all your includes/requires. The other option is to manually include everything you will need to use. With Google though, there are many many components, so using composer would be much easier. Install composer, require the Google PHP SDK package, and then all you need to do is include vendor/autoload.php at the start of your PHP file.


问:
CSS :target pseudo-class is not applied after click on link
I'm using Rails5 (with turbolinks)

HTML markup:

```<code><a href="/post/slug#target1">Target1</a>
<a href="/post/slug#target2">Target1</a>
...
<p id="target1">Content1</p>
<p id="target2">Content2</p>
</code>```

CSS:

```<code>p:target {
  background-color: red;
}
</code>```

Problem is that :target pseudo-class is applied only after page refresh. Style is not applied when clicking on links.

I'm almost sure, that this behaviour caused by turbolinks. How to fix this?

答:
I've found the solution, while writing this question.

To make things work well, we need to add data attribute to such links, as follows:

```<code><a href="/post/slug#target2" data-turbolinks="false">Target1</a>
</code>```

This attribute disables turbolinks on per-link basis.

More details here: Disabling Turbolinks on Specific Links

Body:
I'm using Rails5 (with turbolinks)

HTML markup:

Target1
Target1
...

Content1

Content2

CSS:

p:target {
  background-color: red;
}

Problem is that :target pseudo-class is applied only after page refresh. Style is not applied when clicking on links.

I'm almost sure, that this behaviour caused by turbolinks. How to fix this?

Body:
I've found the solution, while writing this question.

To make things work well, we need to add data attribute to such links, as follows:

<a href="/post/slug#target2" data-turbolinks="false">Target1</a>

This attribute disables turbolinks on per-link basis.

More details here: Disabling Turbolinks on Specific Links


问:
Send multiple content-type Ajax
I have succeed upload image using ajax with codeigniter. But now i want to sending array too so i can insert data inside controller and model.

This is my code for better explanation :

```<code><form method="POST" id="quiz_file" action="<?php echo site_url('home/upload_quiz/' . $kelas);?>" enctype="multipart/form-data">
<input name="filequiz" id="filequiz" type="file" />
</form>

This is the controller :
function upload_quiz($kelas)
{
    $temp = explode(".", $_FILES["filequiz"]["name"]);
    $extension = end($temp);
    $new_name = time() . "." . $extension;
    $config['upload_path']          = './assets/images/quiz_images/';
    $config['allowed_types']        = 'gif|jpg|png|jpeg';
    $config['max_size']             = 2000;
    $config['file_name']            = $new_name;
    $config['max_width']            = 10000;
    $config['max_height']           = 10000;
    $this->load->library('upload', $config);

    $session_data = $this->session->userdata('logged_in');
    $data['user_name'] = $session_data['user_name'];
    $data['kelas'] = $kelas;
    if ( ! $this->upload->do_upload('filequiz'))
    {
        print_r(array('error' => $this->upload->display_errors()));
        $data['error'] = array('error' => $this->upload->display_errors());
        $this->load->view('course', $data);
    }
    else
    {
        $this->load->model('Model');
        $asid = $this->input->post('asid');
        $value = $this->input->post('value');
        $this->Model->inputassignmentscore($asid,$value); <---- The error come from this
        $data['status'] = array('upload_data' => $this->upload->data());
        $quiz_name = $this->input->post('quiz_name');
        if($this->Model->input_quiz($quiz_name,$new_name,$kelas) == TRUE)
        {
            echo $asid;
            $this->load->view('course', $data);
        }
        elseif($this->Model->input_quiz($quiz_name,$new_name,$kelas) == FALSE)
        {
            $this->load->view('course', $data);
        }
    }
}
</code>```

This is the script code

```<code>var cmbvalue = [];
if(asid_quiz.length > 0)
{
    for(i=0;i<asid_quiz.length;i++)
    {
        cmbass = document.getElementsByName('quizcmb')[i].value;
        cmbvalue.push(cmbass);
        console.log('cmbass : ' + cmbvalue);
    }
}

$.ajax({
url: uploadURI,
type: 'post',
data:
{
    formData : formData,
    asid : asid_quiz,
    value : cmbvalue
},
processData: false,
contentType: false,
beforeSend: function ( xhr ) {
},
success: function(data)
{
}
});
</code>```

The formData is sending correctly. But the asid and value is empty. So i cannot insert data using controller and model.
How can i fix this ?

This is the complete code if you want to see : this is my post

When i try using console or alert, the value is exists.

答:
while sending Ajax data, you send (name: string,value:string) pair.Since cmbvalue is an array, you need to convert it into string. May be array to CSV or some string that can be parsed.
if cmbvalue=[apple,banana] you might want to send it as string cmbval="apple,banana" while sending it in data and parse csv/string in server side.
In Javascript, to convert array to string using toString()</p>

```<code>data:
{
    formData : formData,
    asid : asid_quiz,
    value:cmbval.toString();
}
</code>```

Title: Send multiple content-type Ajax

Body:
I have succeed upload image using ajax with codeigniter. But now i want to sending array too so i can insert data inside controller and model.

This is my code for better explanation :

<form method="POST" id="quiz_file" action="<?php echo site_url('home/upload_quiz/' . $kelas);?>" enctype="multipart/form-data">
<input name="filequiz" id="filequiz" type="file" />
</form>

This is the controller :
function upload_quiz($kelas)
{
    $temp = explode(".", $_FILES["filequiz"]["name"]);
    $extension = end($temp);
    $new_name = time() . "." . $extension;
    $config['upload_path']          = './assets/images/quiz_images/';
    $config['allowed_types']        = 'gif|jpg|png|jpeg';
    $config['max_size']             = 2000;
    $config['file_name']            = $new_name;
    $config['max_width']            = 10000;
    $config['max_height']           = 10000;
    $this->load->library('upload', $config);

    $session_data = $this->session->userdata('logged_in');
    $data['user_name'] = $session_data['user_name'];
    $data['kelas'] = $kelas;
    if ( ! $this->upload->do_upload('filequiz'))
    {
        print_r(array('error' => $this->upload->display_errors()));
        $data['error'] = array('error' => $this->upload->display_errors());
        $this->load->view('course', $data);
    }
    else
    {
        $this->load->model('Model');
        $asid = $this->input->post('asid');
        $value = $this->input->post('value');
        $this->Model->inputassignmentscore($asid,$value); <---- The error come from this
        $data['status'] = array('upload_data' => $this->upload->data());
        $quiz_name = $this->input->post('quiz_name');
        if($this->Model->input_quiz($quiz_name,$new_name,$kelas) == TRUE)
        {
            echo $asid;
            $this->load->view('course', $data);
        }
        elseif($this->Model->input_quiz($quiz_name,$new_name,$kelas) == FALSE)
        {
            $this->load->view('course', $data);
        }
    }
}

This is the script code

var cmbvalue = [];
if(asid_quiz.length > 0)
{
    for(i=0;i<asid_quiz.length;i++)
    {
        cmbass = document.getElementsByName('quizcmb')[i].value;
        cmbvalue.push(cmbass);
        console.log('cmbass : ' + cmbvalue);
    }
}

$.ajax({
url: uploadURI,
type: 'post',
data:
{
    formData : formData,
    asid : asid_quiz,
    value : cmbvalue
},
processData: false,
contentType: false,
beforeSend: function ( xhr ) {
},
success: function(data)
{
}
});

The formData is sending correctly. But the asid and value is empty. So i cannot insert data using controller and model.
How can i fix this ?

This is the complete code if you want to see : this is my post

When i try using console or alert, the value is exists.

Body:
while sending Ajax data, you send (name: string,value:string) pair.Since cmbvalue is an array, you need to convert it into string. May be array to CSV or some string that can be parsed.
if cmbvalue=[apple,banana] you might want to send it as string cmbval="apple,banana" while sending it in data and parse csv/string in server side.
In Javascript, to convert array to string using toString()

data:
{
    formData : formData,
    asid : asid_quiz,
    value:cmbval.toString();
}


问:
PHP/MySQL - Best way to create unique random string?
How do I create a random unique string in MySQL?

when I need to create a random string in PHP I use this function:

```<code>public function generateString($length)
{
    $charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    for($i=0; $i<$length; $i++)
        $key .= $charset[(mt_rand(0,(strlen($charset)-1)))];

    return $key;
}
</code>```

Then I would take the generated string and store it in a MySQL database.

What is the best way to make sure the generated random string is unique to all the other random strings created for other entries in the database?

Maybe something like this?

```<code>while(++$i < 100)
{
  //query db with random key to see if there is a match

  //if no match found break out of loop
  break;

}
</code>```

This seems messy and long, and I could potentially hit the database multiple times.  How can I quickly be sure my new random string is unique?

答:
Unique random strings can be used as character keys or tokens to identify database records and check to database table and provides Unique key with store $refer_by variable.</p>

```<code>define('DB_SERVER', "localhost");
define('DB_USER', "root");
define('DB_PASS', "");
define('DB_DATABASE', "student");
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);

function refercode()
{
    $string = '';
    $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    $max = strlen($characters) - 1;
    for ($i = 0; $i < 6; $i++) {
        $string .= $characters[mt_rand(0, $max)];
    }
    $refer = "select * from user_detail where refer_code = '".$string."' ";
    $coderefertest = mysqli_query($con,$refer);

    if(mysqli_num_rows($coderefertest)>0)
    {
        return refercode();
    }
    else
    {
        return $string;
    }
}
$refer_by = refercode();
</code>```

Body:
How do I create a random unique string in MySQL?

when I need to create a random string in PHP I use this function:

public function generateString($length)
{
    $charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    for($i=0; $i<$length; $i++)
        $key .= $charset[(mt_rand(0,(strlen($charset)-1)))];

    return $key;
}

Then I would take the generated string and store it in a MySQL database.

What is the best way to make sure the generated random string is unique to all the other random strings created for other entries in the database?

Maybe something like this?

while(++$i < 100)
{
  //query db with random key to see if there is a match

  //if no match found break out of loop
  break;

}

This seems messy and long, and I could potentially hit the database multiple times.  How can I quickly be sure my new random string is unique?

Body:
Unique random strings can be used as character keys or tokens to identify database records and check to database table and provides Unique key with store $refer_by variable.

define('DB_SERVER', "localhost");
define('DB_USER', "root");
define('DB_PASS', "");
define('DB_DATABASE', "student");
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);

function refercode()
{
    $string = '';
    $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    $max = strlen($characters) - 1;
    for ($i = 0; $i < 6; $i++) {
        $string .= $characters[mt_rand(0, $max)];
    }
    $refer = "select * from user_detail where refer_code = '".$string."' ";
    $coderefertest = mysqli_query($con,$refer);

    if(mysqli_num_rows($coderefertest)>0)
    {
        return refercode();
    }
    else
    {
        return $string;
    }
}
$refer_by = refercode();


问:
JMS connection handshake is failing for SSLCipherSuite SSL_RSA_WITH_3DES_EDE_CBC_SHA
I am using Spring boot 1.2.2 and JDK1.8.0.40, I have specified the SSL cipher suit as SSL_RSA_WITH_3DES_EDE_CBC_SHA and also import cer file to keystore.

When I run my project, I set the jvm arguments as following:

```<code>-Djavax.net.debug=all -Djavax.net.ssl.keyStore=/java_home/jre/lib/security/cacerts -Djava.net.keyStorePassword=changeit
</code>```

But I always get

```<code>handing exception:javax.net.ssl.SSLHandshakeException: No appropriate protocol(protocol is disabled or cipher suites are inappropriate)
SEND TLSv1.2 ALERT: fatal, description = handshake_failure
WRITE: TLSv1.2 Alert, length = 2
[Raw write]: length = 7
0000: 15 03 03 00 02 02 28       ......(
called closeSocket()
com.ibm.msg.client.jms.DetailedJMSException: JMSWMQ0018: Failed to connect to queue manager 'XXXX' with connection mode 'Client' and host name 'xxx.xxx.com(xxxxx)'.
</code>```

Indeed I have do several operations to fix the issue, such as:

Replace jce jars to unlimit encrypt

Import cer file to jks

specified jks path in jvm arguments

Using matched SSL Cipher Suite

Using SSL channel

But now, I still failed on handshake and the error logs are same as above.

Or do I need generate the cer from my machine and upload to the server? Could you kindly give some advice?

答:
New JDK versions keep on updating the minimal security level, which is good. But it's not always easy (or possible) to keep these protocol restrictions up-to-date on all components involved.

The best way is really to pick a cipher suite that is supported.

But if you are in development (and know what you are doing) you can, for testing, remove this restriction by editing your JDK's jre\lib\security\java.security file.

Search for jdk.tls.disabledAlgorithms and remove or edit the restrictions

```<code># previously:
# jdk.tls.disabledAlgorithms=SSLv3, RC4, MD5withRSA, DH keySize < 768
jdk.tls.disabledAlgorithms=MD5withRSA, DH keySize < 768
</code>```

Body:
I am using Spring boot 1.2.2 and JDK1.8.0.40, I have specified the SSL cipher suit as SSL_RSA_WITH_3DES_EDE_CBC_SHA and also import cer file to keystore.

When I run my project, I set the jvm arguments as following:

-Djavax.net.debug=all -Djavax.net.ssl.keyStore=/java_home/jre/lib/security/cacerts -Djava.net.keyStorePassword=changeit

But I always get

handing exception:javax.net.ssl.SSLHandshakeException: No appropriate protocol(protocol is disabled or cipher suites are inappropriate)
SEND TLSv1.2 ALERT: fatal, description = handshake_failure
WRITE: TLSv1.2 Alert, length = 2
[Raw write]: length = 7
0000: 15 03 03 00 02 02 28       ......(
called closeSocket()
com.ibm.msg.client.jms.DetailedJMSException: JMSWMQ0018: Failed to connect to queue manager 'XXXX' with connection mode 'Client' and host name 'xxx.xxx.com(xxxxx)'.

Indeed I have do several operations to fix the issue, such as:

Replace jce jars to unlimit encrypt

Import cer file to jks

specified jks path in jvm arguments

Using matched SSL Cipher Suite

Using SSL channel

But now, I still failed on handshake and the error logs are same as above.

Or do I need generate the cer from my machine and upload to the server? Could you kindly give some advice?

Body:
New JDK versions keep on updating the minimal security level, which is good. But it's not always easy (or possible) to keep these protocol restrictions up-to-date on all components involved.

The best way is really to pick a cipher suite that is supported.

But if you are in development (and know what you are doing) you can, for testing, remove this restriction by editing your JDK's jre\lib\security\java.security file.

Search for jdk.tls.disabledAlgorithms and remove or edit the restrictions

# previously:
# jdk.tls.disabledAlgorithms=SSLv3, RC4, MD5withRSA, DH keySize < 768
jdk.tls.disabledAlgorithms=MD5withRSA, DH keySize < 768


问:
CMD does not work with folders containing spaces
I would like to run the cmd from VB.NEt. the problem is that it is not working with folder containing spaces

so, the code below does not work:

```<code>Process.Start("cmd", "/C Copy /b D:\TEMP 1\*.MP3 C:\TEMP\ALL.MP3
</code>```

答:
I got it

the issue could be solved by enclosing folder paths with ["]. so,

```<code>Process.Start("cmd", "/C Copy /b ""D:\TEMP 1\*.MP3"" C:\TEMP\ALL.MP3")
</code>```

will work fine

Body:
I would like to run the cmd from VB.NEt. the problem is that it is not working with folder containing spaces

so, the code below does not work:

Process.Start("cmd", "/C Copy /b D:\TEMP 1\*.MP3 C:\TEMP\ALL.MP3

Body:
I got it

the issue could be solved by enclosing folder paths with ["]. so,

Process.Start("cmd", "/C Copy /b ""D:\TEMP 1\*.MP3"" C:\TEMP\ALL.MP3")

will work fine


问:
Assigning a size to a Deque in Java
I'm having trouble assigning a limit to the size of my double ended queue (Deque). It seems that my queue never gets full and just resizes whenever I add or offer a value unto it. My simple code just accepts a string value, splits it by space " ", loops everything and adds it to the queue.

```<code>evaluate("A B C D E F");

public static int evaluate(final String input){
    final Deque<String> stack = new ArrayDeque<>(3);
    final String[] tokens = input.split(" ");

    for (String token:tokens){
        System.out.println(stack.offer(token));
    }

    System.out.println(stack.size());
 }
</code>```

returns:

```<code> true
 true
 true
 true
 true
 true
 6
</code>```

I was expecting that the queue will be full since I have not removed or read any value from it. Is there something that I'm missing here? Or am I just using the queue wrong? Thanks!

答:
I advise you to implement your own class with desired behaviour. Otherwise already exists classes that remove the excessive elements. See this answer
https://stackoverflow.com/a/21699069/228358</p>

Title: Assigning a size to a Deque in Java

Body:
I'm having trouble assigning a limit to the size of my double ended queue (Deque). It seems that my queue never gets full and just resizes whenever I add or offer a value unto it. My simple code just accepts a string value, splits it by space " ", loops everything and adds it to the queue.

evaluate("A B C D E F");

public static int evaluate(final String input){
    final Deque<String> stack = new ArrayDeque<>(3);
    final String[] tokens = input.split(" ");

    for (String token:tokens){
        System.out.println(stack.offer(token));
    }

    System.out.println(stack.size());
 }

returns:

 true
 true
 true
 true
 true
 true
 6

I was expecting that the queue will be full since I have not removed or read any value from it. Is there something that I'm missing here? Or am I just using the queue wrong? Thanks!


问:
Check app installs by keyword on Google Play
Is there any way to check by code if an app was installed from Google Play by search with keyword? For example, I have some app "My Test App", and it can be found by searching "test" in Google Play. Can I detect if user have installed my app by searching this keyword? Or if he used another keyword to find it, can I somehow learn what this keyword was?</p>

答:
You can use InstallReferrerReciver if you want to track via Referrer code
https://developers.google.com/android/reference/com/google/android/gms/tagmanager/InstallReferrerReceiver

Monitor User Acquisition Reports via Google Play Store Developer Console -> User Acquisition->Acquisition Reports. Here you can view your reports ( search keywords via google). You can use gsutil (https://cloud.google.com/storage/docs/gsutil) if you want to access this programmatically


问:
Creating a New Array in a Particular Order
Once a particular promise is resolved, i wish to loop through each of the items in the response and push them into an array in a specific order.

status-start

status-in-progress

status-completed

How can I go about doing this? Here is my code so far:

```<code>dashService.getBatches(refresh)
.then(function (response) {
  if (response.error) {
    console.log("No data received");
  } else {
    angular.forEach(response.items, function (item) {
      if (item.status === 'start') {
        currentBatches.push(job);
      }
    });
  }
});
</code>```

答:
how about this</p>

```<code>var newA=dataList.filter(x=>x.status=='status-start').concat(dataList.filter(x=>x.status=='status-in-progress')).concat(dataList.filter(x=>x.status=='status-completed'))
</code>```

Body:
Once a particular promise is resolved, i wish to loop through each of the items in the response and push them into an array in a specific order.

status-start

status-in-progress

status-completed

How can I go about doing this? Here is my code so far:

dashService.getBatches(refresh)
.then(function (response) {
  if (response.error) {
    console.log("No data received");
  } else {
    angular.forEach(response.items, function (item) {
      if (item.status === 'start') {
        currentBatches.push(job);
      }
    });
  }
});

Body:
how about this

var newA=dataList.filter(x=>x.status=='status-start').concat(dataList.filter(x=>x.status=='status-in-progress')).concat(dataList.filter(x=>x.status=='status-completed'))


问:
How to parse the respond url without actually open the webpage in python?
I am now woking on a sina weibo crawler using its api.
In order to use api, I have to access oauth2 authorizing page to retrive the code from url.

This is exactly how I do:

Use my app_key and app_secret (both known)

get the url of oauth2 webpage

copy and paste the code from Respond URL manually.

This is my code:

```<code>#call official SDK
client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL)

#get url of callback page of authorization
url = client.get_authorize_url()
print url

#open webpage in browser
webbrowser.open_new(url)

#after the webpage responding, parse the code part in the url manually
print 'parse the string after 'code=' in url：'
code = raw_input()
</code>```

My Question is exactly how to get rid of the manually parsing part?

Reference:
http://blog.csdn.net/liuxuejiang158blog/article/details/30042493

答:
To get the contents of a page using requests, you can do like this

```<code>import requests

url = "http://example.com"

r = requests.get(url)

print r.text
</code>```

You can see details of the requests library here. You can use pip to install it into your virtualenv / python dist.

For writing crawler, you can also use scrapy.

And finally, I did not understand one thing, if you have a official client then why do you need to parse the contents of an URL to get data. Doesn't the client give you data using some nice and easy to use functions?

Body:
I am now woking on a sina weibo crawler using its api.
In order to use api, I have to access oauth2 authorizing page to retrive the code from url.

This is exactly how I do:

Use my app_key and app_secret (both known)

get the url of oauth2 webpage

copy and paste the code from Respond URL manually.

This is my code:

#call official SDK
client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL)

#get url of callback page of authorization
url = client.get_authorize_url()
print url

#open webpage in browser
webbrowser.open_new(url)

#after the webpage responding, parse the code part in the url manually
print 'parse the string after 'code=' in url：'
code = raw_input()

My Question is exactly how to get rid of the manually parsing part?

Reference:
http://blog.csdn.net/liuxuejiang158blog/article/details/30042493

Body:
To get the contents of a page using requests, you can do like this

import requests

url = "http://example.com"

r = requests.get(url)

print r.text

You can see details of the requests library here. You can use pip to install it into your virtualenv / python dist.

For writing crawler, you can also use scrapy.

And finally, I did not understand one thing, if you have a official client then why do you need to parse the contents of an URL to get data. Doesn't the client give you data using some nice and easy to use functions?


问:
Same function name in javascript (Nested function and outside function )
I have a function as below.
My Problem is that I need to print function b() inside a function. Here function a() is parent function. and I have done it by taking c= new a() and console.log(b()) . I got the right value as I expected. But inside the parent function I have another function named test() and with same name there is another function outside the parent function. After printing function b() I call the function test() . But it return the value from the parent function. I need to get an alert as needed answer which is in outer function. Is there any way to get my expected result without changing the function name.? Both functions test() are needed.

Expected result:  function b() =  2 and function test() = needed answer

Current result :  function b() =  2 and function test() = 4

Any help will be appreciated. Thank You.

function a() {
 var val = 1;
 var otherval = 2;

        b = function() {
  return val + 1;
        }

        test = function() {
           qwerty = otherval + b();
           alert(qwerty);
        }

   return 'OK';
 }

function test(){
    alert('needed answer');
}

c = new a();
console.log(b()); //return 2
test(); //alert 4 but I needed alert needed answer```

答:
You need slight modification in your code. Do this and it will work as per your requirement -

function a() {
 var val = 1;
 var otherval = 2;

    b = function() {
  return val + 1;
 }

    this.test = function() {
  qwerty = otherval + b();
   alert(qwerty);
 }
   return 'OK';
}

function test(){
 alert('needed answer');
}

c = new a();
alert(this.b()); //return 2
test(); //alert 4```


问:
How to properly close a JMS connection?
I am trying to use Spring's SingleConnectionFactory, where there are 2 connection factories, and only one of them should be able to connect at a time.

```<code><bean id="connectionFactory1" class="org.springframework.jms.connection.SingleConnectionFactory102">
    <property name="targetConnectionFactory">
        <bean class="org.springframework.jms.connection.UserCredentialsConnectionFactoryAdapter">
            <property name="username" value="LOGIN" />
            <property name="password" value="PASS" />
            <property name="targetConnectionFactory">
                <bean class="com.tibco.tibjms.TibjmsQueueConnectionFactory">
                    <constructor-arg value="URL" />
                    <constructor-arg value="CLIENT_ID" />
                </bean>
            </property>
        </bean>
    </property>
    <property name="reconnectOnException" value="true" />
</bean>

<bean id="connectionFactory2" class="org.springframework.jms.connection.SingleConnectionFactory102">
    <property name="targetConnectionFactory">
        <bean class="org.springframework.jms.connection.UserCredentialsConnectionFactoryAdapter">
            <property name="username" value="LOGIN" />
            <property name="password" value="PASS" />
            <property name="targetConnectionFactory">
                <bean class="com.tibco.tibjms.TibjmsQueueConnectionFactory">
                    <constructor-arg value="URL" />
                    <constructor-arg value="CLIENT_ID" />
                </bean>
            </property>
        </bean>
    </property>
    <property name="reconnectOnException" value="true" />
</bean>
</code>```

By using the same client id in both factories(CLIENT_ID), I made sure that when I create connection from one factory, I can't create another connection from the other factory (throws InvalidClientIDException, so this is as expected). But the issue is, when I close the connection I got from first factory, and try to get connection from second factory, I'm still getting the exception.

Using the following Java code:

```<code>Connection connection1 = connectionFactory1.createConnection();
connection1.close();

Connection connection2 = connectionFactory2.createConnection();
</code>```

What is the proper way of closing first connection, so that it allows me to create connection using the second factory?

Also, note that I am not using Queues here. I have to achieve this without queues.

答:
I would not recommend the accepted answer. Let me address this and several points raised by other answers to this question.

A better approach would look something like this example (JavaEE6 JMS style) which sends an ObjectMessage to a Queue from within a stateless EJB:

```<code>@Stateless
public class SendEventsBean {

  private static final Logger log = Logger.getLogger(SendEventsBean.class);

  @Resource(mappedName = "jms/MyConnectionFactory")
  private ConnectionFactory jmsConnectionFactory;

  @Resource(mappedName = "jms/myApp/MyQueue"
  private Queue queue;

  public void sendEvent() {
    Connection jmsConnection = null;
    try {
        connection = jmsConnectionFactory.createConnection();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageProducer producer = session.createProducer(queue);
        MyObj obj = new MyObj(1, "Foo");
        ObjectMessage myObjMsg = session.createObjectMessage(obj);
        producer.send(myObjMsg);
    } catch (JMSException jmxEx) {
        log.error("Couldn't send JMS message: ", jmsEx);
    }finally{
        if (jmsConnection != null) {
            try {
                jmsConnection.close();
            }catch(JMSException ex) {
               log.warn("Couldn't close JMSConnection: ", ex);
            }
        }
    }
  }

}
</code>```

Title: How to properly close a JMS connection?

Body:
I am trying to use Spring's SingleConnectionFactory, where there are 2 connection factories, and only one of them should be able to connect at a time.

<bean id="connectionFactory1" class="org.springframework.jms.connection.SingleConnectionFactory102">
    <property name="targetConnectionFactory">
        <bean class="org.springframework.jms.connection.UserCredentialsConnectionFactoryAdapter">
            <property name="username" value="LOGIN" />
            <property name="password" value="PASS" />
            <property name="targetConnectionFactory">
                <bean class="com.tibco.tibjms.TibjmsQueueConnectionFactory">
                    <constructor-arg value="URL" />
                    <constructor-arg value="CLIENT_ID" />
                </bean>
            </property>
        </bean>
    </property>
    <property name="reconnectOnException" value="true" />
</bean>

<bean id="connectionFactory2" class="org.springframework.jms.connection.SingleConnectionFactory102">
    <property name="targetConnectionFactory">
        <bean class="org.springframework.jms.connection.UserCredentialsConnectionFactoryAdapter">
            <property name="username" value="LOGIN" />
            <property name="password" value="PASS" />
            <property name="targetConnectionFactory">
                <bean class="com.tibco.tibjms.TibjmsQueueConnectionFactory">
                    <constructor-arg value="URL" />
                    <constructor-arg value="CLIENT_ID" />
                </bean>
            </property>
        </bean>
    </property>
    <property name="reconnectOnException" value="true" />
</bean>

By using the same client id in both factories(CLIENT_ID), I made sure that when I create connection from one factory, I can't create another connection from the other factory (throws InvalidClientIDException, so this is as expected). But the issue is, when I close the connection I got from first factory, and try to get connection from second factory, I'm still getting the exception.

Using the following Java code:

Connection connection1 = connectionFactory1.createConnection();
connection1.close();

Connection connection2 = connectionFactory2.createConnection();

What is the proper way of closing first connection, so that it allows me to create connection using the second factory?

Also, note that I am not using Queues here. I have to achieve this without queues.

Body:
I would not recommend the accepted answer. Let me address this and several points raised by other answers to this question.

A better approach would look something like this example (JavaEE6 JMS style) which sends an ObjectMessage to a Queue from within a stateless EJB:

@Stateless
public class SendEventsBean {

  private static final Logger log = Logger.getLogger(SendEventsBean.class);

  @Resource(mappedName = "jms/MyConnectionFactory")
  private ConnectionFactory jmsConnectionFactory;

  @Resource(mappedName = "jms/myApp/MyQueue"
  private Queue queue;

  public void sendEvent() {
    Connection jmsConnection = null;
    try {
        connection = jmsConnectionFactory.createConnection();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageProducer producer = session.createProducer(queue);
        MyObj obj = new MyObj(1, "Foo");
        ObjectMessage myObjMsg = session.createObjectMessage(obj);
        producer.send(myObjMsg);
    } catch (JMSException jmxEx) {
        log.error("Couldn't send JMS message: ", jmsEx);
    }finally{
        if (jmsConnection != null) {
            try {
                jmsConnection.close();
            }catch(JMSException ex) {
               log.warn("Couldn't close JMSConnection: ", ex);
            }
        }
    }
  }

}