问:
Google Sheets How to find the Top 3 closest columns to a given column
I have a table in google sheets like this one,

```<code>-------------------
   | A | B | C | D |
-------------------
1  |C1 |C2 |C3 |C4 |
2  | 1 | 2 | 1 | 2 |
3  | 2 | 3 | 4 | 3 |
4  | 5 | 7 | 1 | 6 |
-------------------
</code>```

My goal is to find which 2 columns C1,C2,C3 are closest to C4,

by calculate the average difference bewteen each column and column C4,

e,g Column C1 will have an averyage of abs( (  (1-2)+(2-3)+(5-6)  )  /3 )

which is , abs( (  (A2-D2)+(A3-D3)+(A4-D4) )/(number of rows) )

I'm using ARRYFORMULA to get the average differece for one column and then I drag it horizontally so As will increase to Bs and so on

=ArrayFormula({A1;abs(average(  (checks if there is empty cell)  ,$D2:$D-(A2:A) )))})

if I use it in cell Z1, Z1 will show 'C1', and Z2 will show the average difference for column C1

but i'm not sure how to use a single nested formula to do it for all columns A:C  at once, with out having to drag it

like I if I type =FORMULA(...) in Z1, and a table will show up

Thank you

答:
Try the formula:

=QUERY(ARRAYFORMULA(ABS((ROW(A2:C)*COLUMN(A2:C))^0*D2:D26-A2:C26)),
"select avg(Col"&JOIN("), avg(Col",ArrayFormula(row(INDIRECT("A1:A"&COLUMNS(A2:C)))))&")")

Explanation

(ROW(A2:C)*COLUMN(A2:C))^0*D2:D26 -- copy C4 to compare it with others

"select avg(Col"&JOIN("), avg(Col"... -- compose query to get the average for each column.

Note: in your formula abs(average( must be replaced → average(abs( in order to complete abs function first.

Body:
I have a table in google sheets like this one,

-------------------
   | A | B | C | D |
-------------------
1  |C1 |C2 |C3 |C4 |
2  | 1 | 2 | 1 | 2 |
3  | 2 | 3 | 4 | 3 |
4  | 5 | 7 | 1 | 6 |
-------------------

My goal is to find which 2 columns C1,C2,C3 are closest to C4,

by calculate the average difference bewteen each column and column C4,

e,g Column C1 will have an averyage of abs( (  (1-2)+(2-3)+(5-6)  )  /3 )

which is , abs( (  (A2-D2)+(A3-D3)+(A4-D4) )/(number of rows) )

I'm using ARRYFORMULA to get the average differece for one column and then I drag it horizontally so As will increase to Bs and so on

=ArrayFormula({A1;abs(average(  (checks if there is empty cell)  ,$D2:$D-(A2:A) )))})

if I use it in cell Z1, Z1 will show 'C1', and Z2 will show the average difference for column C1

but i'm not sure how to use a single nested formula to do it for all columns A:C  at once, with out having to drag it

like I if I type =FORMULA(...) in Z1, and a table will show up

Thank you


来源: stackexchange

问:
How to handle a wait() method call in JUnit test case?
I have a method that has another method call whose definition has a SomeIntegerObject.wait() call. Now when I run my test case, due to this wait method, the test case keeps waiting and doesn't execute.

I tried adding a timeout at @Test annotation but that causes an exception like "test timed out".

The test method:

```<code>private PastingResult result;
public PastingResult pasteImages(IIOImage[] images, byte pasteProcessType){
     result = new PastingResult();
     _reprocessingProvider.setListLogicHandler(this);
     //--some more method calls--
    waitForResult(); //causes my test case to wait forever and pauses execution
    return result;
}
</code>```

Test case:

```<code>@Test
    public void testPasteImagesIIOImageArrayByte() throws Exception
    {
        ReprocessManager _reprocessingProvider1=Mockito.mock(ReprocessManager.class);
        Whitebox.setInternalState(imagePasterIfImpl, "_reprocessingProvider", _reprocessingProvider1);

        IIOImage[] images=new IIOImage[]{Mockito.mock(IIOImage.class),Mockito.mock(IIOImage.class)};
        byte pasteProcessType = 02;

        PastingResult result= imagePasterIfImpl.pasteImages(images, pasteProcessType);
        Mockito.verify(_reprocessingProvider1).setListLogicHandler(imagePasterIfImpl);
        System.out.println(result+"is the result");
    }
</code>```

Definition of waitForResult();

```<code>private Integer processingWaitMonitor = new Integer(0);
private void waitForResult() {
       // synchronize to wait on the Monitor..
       synchronized(processingWaitMonitor) {
           try {
               processingWaitMonitor.wait();
           }
           catch(Exception e) {
               System.out.println("Exception during Wait !"+e);
           }
       }
   }
</code>```

答:
There are two answers here:

On a first level: if you need to control something "inside" an object under test; you can either turn to Mockito Spys or PowerMock or JMockit; as those frameworks allow for "mocking" (aka gaining control) on such aspects. But that is not really good practice in most cases; if at all, you should "outsource" the required functionality into another class; and then you use dependency injection in order provide a mocked object of that class for your test setup. And instead of real waiting, you just call some wait method on a mocked object that simply does nothing.

Beyond that: you could step back and consider to re-design your whole approach. You see, using those "low level" primitives such as wait/notify is again not good practice any more. There are abstractions such as ExecutorService, Futures, Promises. The point is: using ExecutorService, you might be able to rewrite your code to use a Same-Thread-Executor-Service for your tests. Meaning: it is possible to rewrite multi-threaded code so that just by providing a different executor for tests, all things happe on a single thread. No more waiting, guaranteed, reliable results.

Regarding your comment; your code says:

```<code>private Integer processingWaitMonitor = new Integer(0);
private void waitForResult() {
</code>```

Meaning: you have a field+private method within your class under test. Assume that you create

```<code>public interface<E> WaitService {
   public E waitForResult();
}
</code>```

or something like that. And then; instead of having a lock object, and that wait method inside your production class, you only keep "some" instance of that service there. But of course, that again requires you to change your production code.

If you really can't change that code (which is kind of a shame - what is the point of testing code when you can't change it ? ) ... then Mockito/PowerMock/JMockit are your only options get there.

ContentLicense: CC BY-SA 3.0

Body:
I have a method that has another method call whose definition has a SomeIntegerObject.wait() call. Now when I run my test case, due to this wait method, the test case keeps waiting and doesn't execute.

I tried adding a timeout at @Test annotation but that causes an exception like "test timed out".

The test method:

private PastingResult result;
public PastingResult pasteImages(IIOImage[] images, byte pasteProcessType){
     result = new PastingResult();
     _reprocessingProvider.setListLogicHandler(this);
     //--some more method calls--
    waitForResult(); //causes my test case to wait forever and pauses execution
    return result;
}

Test case:

@Test
    public void testPasteImagesIIOImageArrayByte() throws Exception
    {
        ReprocessManager _reprocessingProvider1=Mockito.mock(ReprocessManager.class);
        Whitebox.setInternalState(imagePasterIfImpl, "_reprocessingProvider", _reprocessingProvider1);

        IIOImage[] images=new IIOImage[]{Mockito.mock(IIOImage.class),Mockito.mock(IIOImage.class)};
        byte pasteProcessType = 02;

        PastingResult result= imagePasterIfImpl.pasteImages(images, pasteProcessType);
        Mockito.verify(_reprocessingProvider1).setListLogicHandler(imagePasterIfImpl);
        System.out.println(result+"is the result");
    }

Definition of waitForResult();

private Integer processingWaitMonitor = new Integer(0);
private void waitForResult() {
       // synchronize to wait on the Monitor..
       synchronized(processingWaitMonitor) {
           try {
               processingWaitMonitor.wait();
           }
           catch(Exception e) {
               System.out.println("Exception during Wait !"+e);
           }
       }
   }

Body:
There are two answers here:

On a first level: if you need to control something "inside" an object under test; you can either turn to Mockito Spys or PowerMock or JMockit; as those frameworks allow for "mocking" (aka gaining control) on such aspects. But that is not really good practice in most cases; if at all, you should "outsource" the required functionality into another class; and then you use dependency injection in order provide a mocked object of that class for your test setup. And instead of real waiting, you just call some wait method on a mocked object that simply does nothing.

Beyond that: you could step back and consider to re-design your whole approach. You see, using those "low level" primitives such as wait/notify is again not good practice any more. There are abstractions such as ExecutorService, Futures, Promises. The point is: using ExecutorService, you might be able to rewrite your code to use a Same-Thread-Executor-Service for your tests. Meaning: it is possible to rewrite multi-threaded code so that just by providing a different executor for tests, all things happe on a single thread. No more waiting, guaranteed, reliable results.

Regarding your comment; your code says:

private Integer processingWaitMonitor = new Integer(0);
private void waitForResult() {

Meaning: you have a field+private method within your class under test. Assume that you create

public interface<E> WaitService {
   public E waitForResult();
}

or something like that. And then; instead of having a lock object, and that wait method inside your production class, you only keep "some" instance of that service there. But of course, that again requires you to change your production code.

If you really can't change that code (which is kind of a shame - what is the point of testing code when you can't change it ? ) ... then Mockito/PowerMock/JMockit are your only options get there.


问:
Chart not being displayed using DotNet.HighCharts and WebForms
I'm following this tutorial that discusses databinding to a sql server with WebForms. I've entered raw data to show the charts are working before adding the databinding. However, no chart is being displayed when I run the project. I added DotNet.HighCharts using NuGet in VS2012. Any idea why the chart is not being rendered?
Here's the code for my Default.aspx.cs

```<code>namespace HighChartsWebForms
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Render_Chart();
        }

        protected void Render_Chart()
        {
            Object[] chartValues = new Object[8]; // declare an object for the chart rendering

            DotNet.Highcharts.Highcharts chart = new DotNet.Highcharts.Highcharts("chart")
                .InitChart(new Chart { DefaultSeriesType = ChartTypes.Line })
                .SetTitle(new Title
                {
                    Text = "Data",
                    X = -20
                })
                .SetSubtitle(new Subtitle
                {
                    Text = "Source: Static data",
                    X = -20
                })
                .SetXAxis(new XAxis
                {
                    Categories = new[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug" }
                })
                .SetSeries(new[]
                {
                    new Series
                    {
                        Name = "# Pizza",
                        Data = new Data(new object[] { 2, 3, 5, 7, 6, 6, 7, 8 }),
                    },
                });

    ltChart1.Text = chart.ToHtmlString();
        }
    }
}
</code>```

Here's my Default.aspx:

```<code><%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="HighChartsWebForms._Default" %>

<asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">
    <section class="featured">
        <div class="content-wrapper">
            <hgroup class="title">
                <h1><%: Title %>.</h1>
                <h2>Testing HighCharts with ASP.NET</h2>
            </hgroup>
        </div>
    </section>
</asp:Content>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
    <h3>This should show a chart:</h3>
    <asp:Literal id="ltChart1" runat="server"></asp:Literal>
</asp:Content>
</code>```

答:
If you are using Site.Master file to add path of the JavaScript files, then make sure you have added path of these three JavaScript files.

```<code>    <asp:ScriptManager runat="server">
        <Scripts>
            <asp:ScriptReference Path="~/Scripts/highcharts.js" />
            <asp:ScriptReference Path="~/Scripts/jquery-1.5.1.min.js" />
            <asp:ScriptReference Path="~/Scripts/exporting.js" />
        </Scripts>
    </asp:ScriptManager>
</code>```

Check out this tutorial: http://dotnethighcharts.codeplex.com/
Here it is explained for both MVC and Web Forms.

Body:
I'm following this tutorial that discusses databinding to a sql server with WebForms. I've entered raw data to show the charts are working before adding the databinding. However, no chart is being displayed when I run the project. I added DotNet.HighCharts using NuGet in VS2012. Any idea why the chart is not being rendered?
Here's the code for my Default.aspx.cs

namespace HighChartsWebForms
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Render_Chart();
        }

        protected void Render_Chart()
        {
            Object[] chartValues = new Object[8]; // declare an object for the chart rendering

            DotNet.Highcharts.Highcharts chart = new DotNet.Highcharts.Highcharts("chart")
                .InitChart(new Chart { DefaultSeriesType = ChartTypes.Line })
                .SetTitle(new Title
                {
                    Text = "Data",
                    X = -20
                })
                .SetSubtitle(new Subtitle
                {
                    Text = "Source: Static data",
                    X = -20
                })
                .SetXAxis(new XAxis
                {
                    Categories = new[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug" }
                })
                .SetSeries(new[]
                {
                    new Series
                    {
                        Name = "# Pizza",
                        Data = new Data(new object[] { 2, 3, 5, 7, 6, 6, 7, 8 }),
                    },
                });

    ltChart1.Text = chart.ToHtmlString();
        }
    }
}

Here's my Default.aspx:

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="HighChartsWebForms._Default" %>

<asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">

            <hgroup class="title">

<%: Title %>.

Testing HighCharts with ASP.NET

            </hgroup>

</asp:Content>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">

This should show a chart:

    <asp:Literal id="ltChart1" runat="server"></asp:Literal>
</asp:Content>

Body:
If you are using Site.Master file to add path of the JavaScript files, then make sure you have added path of these three JavaScript files.

    <asp:ScriptManager runat="server">
        <Scripts>
            <asp:ScriptReference Path="~/Scripts/highcharts.js" />
            <asp:ScriptReference Path="~/Scripts/jquery-1.5.1.min.js" />
            <asp:ScriptReference Path="~/Scripts/exporting.js" />
        </Scripts>
    </asp:ScriptManager>

Check out this tutorial: http://dotnethighcharts.codeplex.com/
Here it is explained for both MVC and Web Forms.


问:
Changing value of a variable on OnClick Android
I have 2 buttons in my layout when user presses button 1 the value of 'number' should change to '2' and when the user presses button 2 the value of 'number' should change to '1'.But the value does not change.
Here is my code :

```<code>public class test extends AppCompatActivity{

public  int number ;

private Button btn1;
private Button btn2;
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.testing);

    btn1=(Button)findViewById(R.id.btn1);
    btn2=(Button)findViewById(R.id.btn2);

    test();
}

void test()
{

  if(number<1) {
    number = 1;
    }

        Log.e("number value : ",String.valueOf(number));

    if(number==1)
    {

         btn1.setOnClickListener(new View.OnClickListener() {

         @Override
         public void onClick(View arg0) {
          number=2;

             Log.e("number value : ",String.valueOf(number));

         }

    });

    }

     if(number==2)
    {
     btn2.setOnClickListener(new View.OnClickListener() {

         @Override
        public void onClick(View arg0) {
             number=1;
             Log.e("number value : ",String.valueOf(number));

    }

    });

    }

    }
</code>```

Log.e outputs ``` E/number value :: 2``` when I press btn1 but when i press btn2 nothing happens and only btn1 works

答:
This part of your code doesn't gets called at all:

```<code>if(number==2)
    {
     btn2.setOnClickListener(new View.OnClickListener() {

         @Override
        public void onClick(View arg0) {
             number=1;
             Log.e("number value : ",String.valueOf(number));

    }

    });
</code>```

The reason is the condition if(number==2) because number is actually 1 so this block of code doesn't get called, so there is no click listener added to the btn2.

set the click listener in onCreate and it will work perfectly.

Body:
I have 2 buttons in my layout when user presses button 1 the value of 'number' should change to '2' and when the user presses button 2 the value of 'number' should change to '1'.But the value does not change.
Here is my code :

public class test extends AppCompatActivity{

public  int number ;

private Button btn1;
private Button btn2;
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.testing);

    btn1=(Button)findViewById(R.id.btn1);
    btn2=(Button)findViewById(R.id.btn2);

    test();
}

void test()
{

  if(number<1) {
    number = 1;
    }

        Log.e("number value : ",String.valueOf(number));

    if(number==1)
    {

         btn1.setOnClickListener(new View.OnClickListener() {

         @Override
         public void onClick(View arg0) {
          number=2;

             Log.e("number value : ",String.valueOf(number));

         }

    });

    }

     if(number==2)
    {
     btn2.setOnClickListener(new View.OnClickListener() {

         @Override
        public void onClick(View arg0) {
             number=1;
             Log.e("number value : ",String.valueOf(number));

    }

    });

    }

    }

Log.e outputs
 E/number value :: 2
 when I press btn1 but when i press btn2 nothing happens and only btn1 works

Body:
This part of your code doesn't gets called at all:

if(number==2)
    {
     btn2.setOnClickListener(new View.OnClickListener() {

         @Override
        public void onClick(View arg0) {
             number=1;
             Log.e("number value : ",String.valueOf(number));

    }

    });

The reason is the condition if(number==2) because number is actually 1 so this block of code doesn't get called, so there is no click listener added to the btn2.

set the click listener in onCreate and it will work perfectly.


Title: Cassandra COPY FROM loses lots of rows

Body:
I'm trying to figure out why I'm losing data when I load from a CSV file using COPY FROM.  Here's my setup:

% cat /tmp/data
2-54-2014,"2014-01-01T01:00:00Z","1588.6960767"
2-54-2014,"2014-01-01T01:10:00Z","1587.64072333"
2-54-2014,"2014-01-01T01:20:00Z","1590.48448448"
2-54-2014,"2014-01-01T01:30:00Z","1590.72830295"
2-54-2014,"2014-01-01T01:40:00Z","1582.58896162"
2-54-2014,"2014-01-01T01:50:00Z","1569.62739561"
2-54-2014,"2014-01-01T02:00:00Z","1560.63714579"
2-54-2014,"2014-01-01T02:10:00Z","1551.97991093"
2-54-2014,"2014-01-01T02:20:00Z","1576.29093944"
2-54-2014,"2014-01-01T02:30:00Z","1584.34574486"

% cqlsh -k hats
Connected to Test Cluster at 127.0.0.1:9042.
[cqlsh 5.0.1 | Cassandra 3.10 | CQL spec 3.4.4 | Native protocol v4]
Use HELP for help.
cqlsh:hats> CREATE TABLE power_1turb (
            id TEXT, ts TIMESTAMP, value DOUBLE, PRIMARY KEY ((id), ts));

Now I try to load the data file into Cassandra:

cqlsh:hats> COPY power_1turb (id, ts, value) FROM '/tmp/data';
Using 7 child processes

Starting copy of hats.power_1turb with columns [id, ts, value].
Processed: 10 rows; Rate:      16 rows/s; Avg. rate:      24 rows/s
10 rows imported from 1 files in 0.412 seconds (0 skipped).

cqlsh:hats> select * from power_1turb ;

 id        | ts                              | value
-----------+---------------------------------+------------
 2-54-2014 | 2013-12-31 18:00:00.000000+0000 | 1560.63715

(1 rows)

Why is it only loading 1 row, and why is it always this same row in the middle of the data?  If I run a few queries like insert into power_1turb (id, ts, value) values ('2-54-2014','2014-01-01T01:30:00Z',1590.72830295);, they do populate to the database just fine.

Body:
Define datetimeformat along with copy command

Because your datetime format is not matching with cqlsh default datetime format

For your case use the below copy command :

COPY power_1turb (id, ts, value) FROM 'data' WITH DATETIMEFORMAT = '%Y-%m-%dT%H:%M:%SZ';

Tested with Cqlsh of Cassandra 2.2.5

cassandra@cqlsh:test> SELECT * FROM power_1turb ;

 id        | ts                       | value
-----------+--------------------------+------------
 2-54-2014 | 2014-01-01 01:00:00+0000 | 1588.69608
 2-54-2014 | 2014-01-01 01:10:00+0000 | 1587.64072
 2-54-2014 | 2014-01-01 01:20:00+0000 | 1590.48448
 2-54-2014 | 2014-01-01 01:30:00+0000 |  1590.7283
 2-54-2014 | 2014-01-01 01:40:00+0000 | 1582.58896
 2-54-2014 | 2014-01-01 01:50:00+0000 |  1569.6274
 2-54-2014 | 2014-01-01 02:00:00+0000 | 1560.63715
 2-54-2014 | 2014-01-01 02:10:00+0000 | 1551.97991
 2-54-2014 | 2014-01-01 02:20:00+0000 | 1576.29094
 2-54-2014 | 2014-01-01 02:30:00+0000 | 1584.34574

(10 rows)

Related doc For cassandra 2.2.5 cqlsh

DATETIMEFORMAT, which used to be called TIMEFORMAT, a string containing the Python strftime format for date and time values, such as ‘%Y-%m-%d %H:%M:%S%z’. It defaults to the time_format value in cqlshrc.


问:
Swift 3: UILabel not showing in custom UITableViewCell
I have a custom UITableViewCell called CCLineupTableViewCell that looks like this:

```<code>@IBOutlet weak var artistNameLabel: UILabel!
@IBOutlet weak var artistValuationLabel: UILabel!

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code

}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}
</code>```

I access the cell in the cellForRowAt indexPath: IndexPath method like so:

```<code>let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCell", for: indexPath) as! CCLineupTableViewCell
</code>```

My custom cell setup is like so:

As you can see it's setup right in the IB and in the code. The weird thing is that the first label, artistNameLabel, is accessible through cellForRowAt indexPath: IndexPath and works perfectly. The artistValuationLabel, however, never even shows up despite having default text via the storyboard.

Edit:

I've added a picture of the constraints from the nib. It's anchored to the right side, top, and bottom of the cell (as well as the aspect ratio).

答: Due to improper width constraint this thing is happened. Either You need to add proportional width or you should run in that device for which you have designed.</p>

Body:
I have a custom UITableViewCell called CCLineupTableViewCell that looks like this:

@IBOutlet weak var artistNameLabel: UILabel!
@IBOutlet weak var artistValuationLabel: UILabel!

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code

}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

I access the cell in the cellForRowAt indexPath: IndexPath method like so:

let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCell", for: indexPath) as! CCLineupTableViewCell

My custom cell setup is like so:

As you can see it's setup right in the IB and in the code. The weird thing is that the first label, artistNameLabel, is accessible through cellForRowAt indexPath: IndexPath and works perfectly. The artistValuationLabel, however, never even shows up despite having default text via the storyboard.

Edit:

I've added a picture of the constraints from the nib. It's anchored to the right side, top, and bottom of the cell (as well as the aspect ratio).


问:
how to pass data from view to controller in angularjs by defining a multi-dimension array using ng-init in view
```<code><body>

<div ng-app="myapp"ng-model="user"ng-init="user=[{'name':'A','email':'a@gmail.com','mobile':'9494563132','city':'banglore'},
{'name':'B','email':'B@gmail.com','mobile':'9494563132','city':'pune'},
{'name':'C','email':'C@gmail.com','mobile':'9494563132','city':'hyderebad'}] "ng-init="fuser='hello'">
<div  ng-controller="myctrl" >
<table align="left">
<tr>

<td><ul>
    <h1>City</h1>

    <li ng-repeat="x in user">{{x.city}}</li>
</ul></td>
</tr>
</table>

<table align="center">
<tr>
<th>Select User</th>
<td>

<select ng-model="u" ng-change="getuser(name,email,mobile,city)">
    <option value="">Choose name</option>
    <option  ng-repeat="x in user" value="{{x.name}}">{{x.name}}</option>

</select></td>

</tr>

<tr>

    <table align="center" cellpadding="5" ng-model="table" bgcolor='skyblue'>
    <caption><h2>User info</h2></caption>
        <tr>
        <th>Name</th>
        <th>email</th>
        <th>mobile</th>
        <th>city</th>
        </tr>

        <tr ng-repeat="row in user|filter:fuser">
        <td>{{row.name}}</td>
        <td>{{row.email}}</td>
        <td>{{row.mobile}}</td>
        <td>{{row.city}}</td>
        </tr>

</table>
<tr>
</table>

</div>

</div>
<script>
var obj = angular.module("myapp",[]);
        obj.controller("myctrl",function($scope)
            {

                    $scope.u=this.response;}

                $scope.getuser=function(uname)
                {

                    $scope.fuser=uname;

                }

            });
</code>```

please help me to extract the data from array into table by filtering the data using dropdown option and diplay the relevant data.i can not use $http event and i dont want to initializa my array in the controller

答:
I remembered your requirement that you dont want to put your data in controller,but i dont know how to do that so i followed the regular procedure....Hope this will helps you

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.user=[{'name':'A','email':'a@gmail.com','mobile':'9494563132','city':'banglore'},
{'name':'B','email':'B@gmail.com','mobile':'9494563132','city':'pune'},
{'name':'C','email':'C@gmail.com','mobile':'9494563132','city':'hyderebad'}];

 $scope.getuser=function(uname){
for(var i=0;i<$scope.user.length;i++){
  if($scope.user[i].name==uname){
    $scope.e=$scope.user[i];

}
}
}
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
   <table align="left">
<tr>

<td><ul>
    <h1>City</h1>

    <li ng-repeat="x in user">{{x.city}}</li>
</ul></td>
</tr>
</table>

<table align="center">
<tr>
<th>Select User</th>
<td>

<select ng-model="x" ng-change="getuser(x)">
    <option value="">Choose name</option>
    <option  ng-repeat="x in user" value="{{x.name}}">{{x.name}}</option>

</select></td>

</tr>

<tr>

    <table align="center" cellpadding="5" ng-model="table" bgcolor='skyblue'>
    <caption><h2>User info</h2></caption>
        <tr>
        <th>Name</th>
        <th>email</th>
        <th>mobile</th>
        <th>city</th>
        </tr>

        <tr >
        <td>{{e.name}}</td>
        <td>{{e.email}}</td>
        <td>{{e.mobile}}</td>
        <td>{{e.city}}</td>
        </tr>

</table>
</tr>
</table>
  </body>

</html></code>```

Body:
City

{{x.city}}

Select User

<select ng-model="u" ng-change="getuser(name,email,mobile,city)">
    <option value="">Choose name</option>
    <option  ng-repeat="x in user" value="{{x.name}}">{{x.name}}</option>

</select>

User info

        Name
        email
        mobile
        city

        {{row.name}}
        {{row.email}}
        {{row.mobile}}
        {{row.city}}

Body:
I remembered your requirement that you dont want to put your data in controller,but i dont know how to do that so i followed the regular procedure....Hope this will helps you

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.user=[{'name':'A','email':'a@gmail.com','mobile':'9494563132','city':'banglore'},
{'name':'B','email':'B@gmail.com','mobile':'9494563132','city':'pune'},
{'name':'C','email':'C@gmail.com','mobile':'9494563132','city':'hyderebad'}];

 $scope.getuser=function(uname){
for(var i=0;i<$scope.user.length;i++){
  if($scope.user[i].name==uname){
    $scope.e=$scope.user[i];

}
}
}
});

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
   <table align="left">
<tr>

<td><ul>
    <h1>City</h1>

    <li ng-repeat="x in user">{{x.city}}</li>
</ul></td>
</tr>
</table>

<table align="center">
<tr>
<th>Select User</th>
<td>

<select ng-model="x" ng-change="getuser(x)">
    <option value="">Choose name</option>
    <option  ng-repeat="x in user" value="{{x.name}}">{{x.name}}</option>

</select></td>

</tr>

<tr>

    <table align="center" cellpadding="5" ng-model="table" bgcolor='skyblue'>
    <caption><h2>User info</h2></caption>
        <tr>
        <th>Name</th>
        <th>email</th>
        <th>mobile</th>
        <th>city</th>
        </tr>

        <tr >
        <td>{{e.name}}</td>
        <td>{{e.email}}</td>
        <td>{{e.mobile}}</td>
        <td>{{e.city}}</td>
        </tr>

</table>
</tr>
</table>
  </body>

</html>


问:
How do you query the EclipseLink version at runtime (plus JPA meta data)?
Question pretty much says it all.

Is there an equivalent for org.hibernate.Version.getVersionString() in EclipseLink?

Why isn't there a portable (JPA) way to query provider information in general?

答:
There is a static class and static method to get this information.

Example: How to print in java code

```<code>AbstractSessionLog.getLog().log(SessionLog.INFO, DatabaseLogin.getVersion());
</code>```

Body:
There is a static class and static method to get this information.

Example: How to print in java code

AbstractSessionLog.getLog().log(SessionLog.INFO, DatabaseLogin.getVersion());


问:
ReactJS FixedDataTable sorting and filtering example not working
I am trying to follow this ReactJS tutorial :

Part 1 : http://4dev.tech/2015/12/reactjs-datatable-with-sort-filter-and-pagination-example-part-1/

Part 2 : http://4dev.tech/2016/03/tutorial-sorting-and-filtering-a-reactjs-datatable/

I finished part 1 successfully and I need some help to finish part 2.

This is my code for part 2 :

```<code>import React from 'react';
import {Table, Column, Cell} from 'fixed-data-table';

class MyTable extends React.Component {

  constructor(props) {
    super(props);
      this.rows = [{"id":1,"first_name":"William","last_name":"Elliott","email":"welliott0@wisc.edu",
             "country":"Argentina","ip_address":"247.180.226.89"},
              {"id":2,"first_name":"Carl","last_name":"Ross","email":"cross1@mlb.com",
             "country":"South Africa","ip_address":"27.146.70.36"},
              {"id":3,"first_name":"Jeremy","last_name":"Scott","email":"jscott2@cbsnews.com",
             "country":"Colombia","ip_address":"103.52.74.225"},
             ]
    this.state = {
      filteredDataList: this.rows
    };
  }

_renderHeader(label, cellDataKey) {
  return <div>
        <span>{label}</span>
          <div>
            <br />
            <input style={{width:90+'%'}} onChange={this._onFilterChange.bind(this, cellDataKey)}/>
          </div>
      </div>;
}

_onFilterChange(cellDataKey, event) {
  if (!event.target.value) {
    this.setState({
      filteredDataList: this.rows,
    });
  }
  var filterBy = event.target.value.toString().toLowerCase();
  var size = this.rows.length;
  var filteredList = [];
  for (var index = 0; index < size; index++) {
    var v = this.rows[index][cellDataKey];
    if (v.toString().toLowerCase().indexOf(filterBy) !== -1) {
      filteredList.push(this.rows[index]);
    }
  }
  this.setState({
    filteredDataList: filteredList,
  });
}

  render() {
      return <Table
        height={40+((this.rows.length+1) * 30)}
        width={1150}
        rowsCount={this.rows.length}
        rowHeight={30}
        headerHeight={30}
        rowGetter={function(rowIndex) {return this.rows[rowIndex]; }.bind(this)}>
        <Column dataKey="id" width={50} label="Id"
            headerRenderer={this._renderHeader.bind(this)}/>
        <Column dataKey="first_name" width={200} label="First Name" />
        <Column  dataKey="last_name" width={200} label="Last Name" />
        <Column  dataKey="email" width={400} label="e-mail" />
        <Column  dataKey="country" width={300} label="Country" />
      </Table>;
  }
}

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

The datatable is showing but not the input fields which are used to filter the rows.

The browser console is not showing any errors except few warnings :

```<code>`rowGetter` will be DEPRECATED in version 0.7.0 of FixedDataTable and beyond.
Please use the cell API in Column to fetch data for your cells.
Read the docs at: https://fburl.com/FixedDataTable-v0.6
`label` will be DEPRECATED in version 0.7.0 of FixedDataTable and beyond.
Please use `header` instead.
Read the docs at: https://fburl.com/FixedDataTable-v0.6
`dataKey` will be DEPRECATED in version 0.7.0 of FixedDataTable and beyond.
Please use the `cell` API to pass in a dataKey
Read the docs at: https://fburl.com/FixedDataTable-v0.6
`headerRenderer` will be DEPRECATED in version 0.7.0 of FixedDataTable and beyond.
Please use the `header` API to pass in a React Element instead.
Read the docs at: https://fburl.com/FixedDataTable-v0.6
</code>```

I have no clue what the problem is.
Thanks for your time.

答: This problem is about your fixed data table version. Please check this v0.6 API Migration at here: https://facebook.github.io/fixed-data-table/v6-migration.html</p>

Body:
I am trying to follow this ReactJS tutorial :

Part 1 : http://4dev.tech/2015/12/reactjs-datatable-with-sort-filter-and-pagination-example-part-1/

Part 2 : http://4dev.tech/2016/03/tutorial-sorting-and-filtering-a-reactjs-datatable/

I finished part 1 successfully and I need some help to finish part 2.

This is my code for part 2 :

import React from 'react';
import {Table, Column, Cell} from 'fixed-data-table';

class MyTable extends React.Component {

  constructor(props) {
    super(props);
      this.rows = [{"id":1,"first_name":"William","last_name":"Elliott","email":"welliott0@wisc.edu",
             "country":"Argentina","ip_address":"247.180.226.89"},
              {"id":2,"first_name":"Carl","last_name":"Ross","email":"cross1@mlb.com",
             "country":"South Africa","ip_address":"27.146.70.36"},
              {"id":3,"first_name":"Jeremy","last_name":"Scott","email":"jscott2@cbsnews.com",
             "country":"Colombia","ip_address":"103.52.74.225"},
             ]
    this.state = {
      filteredDataList: this.rows
    };
  }

_renderHeader(label, cellDataKey) {
  return

        {label}

            <input style={{width:90+'%'}} onChange={this._onFilterChange.bind(this, cellDataKey)}/>

;
}

_onFilterChange(cellDataKey, event) {
  if (!event.target.value) {
    this.setState({
      filteredDataList: this.rows,
    });
  }
  var filterBy = event.target.value.toString().toLowerCase();
  var size = this.rows.length;
  var filteredList = [];
  for (var index = 0; index < size; index++) {
    var v = this.rows[index][cellDataKey];
    if (v.toString().toLowerCase().indexOf(filterBy) !== -1) {
      filteredList.push(this.rows[index]);
    }
  }
  this.setState({
    filteredDataList: filteredList,
  });
}

  render() {
      return

        <Column dataKey="id" width={50} label="Id"
            headerRenderer={this._renderHeader.bind(this)}/>
        <Column dataKey="first_name" width={200} label="First Name" />
        <Column  dataKey="last_name" width={200} label="Last Name" />
        <Column  dataKey="email" width={400} label="e-mail" />
        <Column  dataKey="country" width={300} label="Country" />

;
  }
}

module.exports = MyTable;

The datatable is showing but not the input fields which are used to filter the rows.

The browser console is not showing any errors except few warnings :

`rowGetter` will be DEPRECATED in version 0.7.0 of FixedDataTable and beyond.
Please use the cell API in Column to fetch data for your cells.
Read the docs at: https://fburl.com/FixedDataTable-v0.6
`label` will be DEPRECATED in version 0.7.0 of FixedDataTable and beyond.
Please use `header` instead.
Read the docs at: https://fburl.com/FixedDataTable-v0.6
`dataKey` will be DEPRECATED in version 0.7.0 of FixedDataTable and beyond.
Please use the `cell` API to pass in a dataKey
Read the docs at: https://fburl.com/FixedDataTable-v0.6
`headerRenderer` will be DEPRECATED in version 0.7.0 of FixedDataTable and beyond.
Please use the `header` API to pass in a React Element instead.
Read the docs at: https://fburl.com/FixedDataTable-v0.6

I have no clue what the problem is.
Thanks for your time.


问:
jQuery datetimepicker not initializing in ASP.NET
I am trying to initialize a datetimepicker but I am always getting an error:

```<code> $(...).timepicker not a function
</code>```

My code is as follow:

```<code> //REFERENCES:

 <link href="/CSS/jquery-ui-timepicker-addon.css" rel="stylesheet"  type="text/css" />
  <script type="text/javascript" src="/JS/jquery-ui-timepicker-addon.js"></script>
  <script type="text/javascript" src="/JS/jquery-1.10.2.js"></script>
  <script type="text/javascript" src="/JS/jquery-1.9.1.js"></script>
  <script type="text/javascript" src="/JS/jquery.min.js"></script>
  <script type="text/javascript" src="/JS/jquery-ui.js"></script>
  <script type="text/javascript" src="/JS/jquery-1.9.1.min.js"></script>

  //JAVASCRIPT

  <script type="text/javascript">
  $('"[id*=tb_input]"').timepicker();

  function tpicker() {
    $('"[id*=tb_input]"').timepicker();
  }
  Sys.WebForms.PageRequestManager.getInstance().add_endRequest(tpicker);
  </script>

  //HTML
  <asp:TextBox ID="tb_input" style="text-align:center" runat="server"
   CssClass="font2" Width="226px" onfocus="disableautocompletion(this.id);"
   Height="24px"></asp:TextBox>
</code>```

Any ideas? Thank you!

答:
You just need to reorder the scripts.

```<code><script type="text/javascript" src="/JS/jquery-1.10.2.js"></script>
<script type="text/javascript" src="/JS/jquery-ui.js"></script>
<script type="text/javascript" src="/JS/jquery-ui-timepicker-addon.js"></script>
</code>```

Remove following :

```<code><script type="text/javascript" src="/JS/jquery.min.js"></script>
<script type="text/javascript" src="/JS/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="/JS/jquery-1.9.1.min.js"></script>
</code>```

It will just you cost extra page load time .

and Init your datepicker in like this:

```<code> $(document).ready(function () {
       InitTimePicker();
    });
</code>```

If you are using updatepanel :

```<code>function InitTimePicker(){
     $('"[id*=tb_input]"').timepicker();
}
</code>```

and add thi function to end reuqest:)

Body:
I am trying to initialize a datetimepicker but I am always getting an error:

 $(...).timepicker not a function

My code is as follow:

 //REFERENCES:

 <link href="/CSS/jquery-ui-timepicker-addon.css" rel="stylesheet"  type="text/css" />

  //JAVASCRIPT

  //HTML
  <asp:TextBox ID="tb_input" style="text-align:center" runat="server"
   CssClass="font2" Width="226px" onfocus="disableautocompletion(this.id);"
   Height="24px"></asp:TextBox>

Any ideas? Thank you!

Body:
You just need to reorder the scripts.

<script type="text/javascript" src="/JS/jquery-1.10.2.js"></script>
<script type="text/javascript" src="/JS/jquery-ui.js"></script>
<script type="text/javascript" src="/JS/jquery-ui-timepicker-addon.js"></script>

Remove following :

<script type="text/javascript" src="/JS/jquery.min.js"></script>
<script type="text/javascript" src="/JS/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="/JS/jquery-1.9.1.min.js"></script>

It will just you cost extra page load time .

and Init your datepicker in like this:

 $(document).ready(function () {
       InitTimePicker();
    });

If you are using updatepanel :

function InitTimePicker(){
     $('"[id*=tb_input]"').timepicker();
}

and add thi function to end reuqest:)


问:
http to https into subfolder (.htaccess)
I have a Wordpress running on an Apache Server. Now I want to configure the following using .htaccess:

Force http to https

Redirect requests from (www.)domain.com to domain.com/domaincom/web

So if a user types: http://www.domain.com he will be directed to https://domain.com/domaincom/web but in the browser navigation he will see https://domain.com.

I already have the following:

```<code>RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www\.)?domain.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteCond %{HTTPS} =off
RewriteRule ^ https://%{HTTP_HOST}/domaincom/web/%{REQUEST_URI} [QSA,L,R=301]
</code>```

But this does not replace the URL. Can you help me?

答:
Web sites behind load balancers or reverse proxies that support HTTP_X_FORWARDED_PROTO can be fixed by adding the following code to the wp-config.php file, above the require_once call:

if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')
    $_SERVER['HTTPS'] = 'on';

OR by plugin

Add into WordPress plugins folder on your website, then activate it in the Plugins admin

https://gist.github.com/krunalsojitra/b975043933bca9183f57581e45858949

It is working like

http://www.exmaple.com/blog/ **to **  https://www.exmaple.com/blog/

http://www.exmaple.com/ **to **  https://www.exmaple.com/

Body:
I have a Wordpress running on an Apache Server. Now I want to configure the following using .htaccess:

Force http to https

Redirect requests from (www.)domain.com to domain.com/domaincom/web

So if a user types: http://www.domain.com he will be directed to https://domain.com/domaincom/web but in the browser navigation he will see https://domain.com.

I already have the following:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www\.)?domain.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteCond %{HTTPS} =off
RewriteRule ^ https://%{HTTP_HOST}/domaincom/web/%{REQUEST_URI} [QSA,L,R=301]

But this does not replace the URL. Can you help me?


问:
Return mulitple string is not working
I want to return multiple string from the below function. How to do that</p>

```<code>public static string GETSTATE_SAP(string SAP)
    {
        string strState = "";
        string strSiteAdd = "";
        string strLatitude = "";
        string strLongtiude = "";
        try
        {
            OracleConnection Oraconn = new OracleConnection(ConfigurationManager.ConnectionStrings["ConnectionStringAPPSAPID"].ConnectionString);
            Oraconn.Open();
            OracleCommand cmd = new OracleCommand("Select STATE, SITE_NAME, SITE_ADDRESS, latitude, longitude from R4G_OSP.UBR where SAP_ID = '" + SAP + "'", Oraconn);
            OracleDataAdapter da = new OracleDataAdapter(cmd);
            DataTable dtSap = new DataTable();
            da.Fill(dtSap);
            strState = Convert.ToString(dtSap.Rows[0][0]);
            strSiteAdd = Convert.ToString(dtSap.Rows[0][0]);
            strLatitude = Convert.ToString(dtSap.Rows[0][0]);
            strLongtiude = Convert.ToString(dtSap.Rows[0][0]);
        }
        catch (Exception)
        {
        }
        return strState, strSiteAdd, strLatitude, strLongtiude;
    }
</code>```

答:
You can create a custom class with those fields and return it,</p>

```<code> public MyClass string GETSTATE_SAP(string SAP)
    {
        MyClass myObj = new MyClass();
        try
        {
            OracleConnection Oraconn = new OracleConnection(ConfigurationManager.ConnectionStrings["ConnectionStringAPPSAPID"].ConnectionString);
            Oraconn.Open();
            OracleCommand cmd = new OracleCommand("Select STATE, SITE_NAME, SITE_ADDRESS, latitude, longitude from R4G_OSP.UBR where SAP_ID = '" + SAP + "'", Oraconn);
            OracleDataAdapter da = new OracleDataAdapter(cmd);
            DataTable dtSap = new DataTable();
            da.Fill(dtSap);

            myObj.strState = Convert.ToString(dtSap.Rows[0][0]);
            myObj.strSiteAdd = Convert.ToString(dtSap.Rows[0][0]);
            myObj.strLatitude = Convert.ToString(dtSap.Rows[0][0]);
            myObj.strLongtiude = Convert.ToString(dtSap.Rows[0][0]);
        }
        catch (Exception)
        {
        }
        return myObj;
    }
    public class MyClass
    {
        public string strState { get; set; }
        public string strSiteAdd { get; set; }
        public string strLatitude { get; set; }
        public string strLongtiude { get; set; }

    }
</code>```

Title: Return mulitple string is not working

Body:
I want to return multiple string from the below function. How to do that

public static string GETSTATE_SAP(string SAP)
    {
        string strState = "";
        string strSiteAdd = "";
        string strLatitude = "";
        string strLongtiude = "";
        try
        {
            OracleConnection Oraconn = new OracleConnection(ConfigurationManager.ConnectionStrings["ConnectionStringAPPSAPID"].ConnectionString);
            Oraconn.Open();
            OracleCommand cmd = new OracleCommand("Select STATE, SITE_NAME, SITE_ADDRESS, latitude, longitude from R4G_OSP.UBR where SAP_ID = '" + SAP + "'", Oraconn);
            OracleDataAdapter da = new OracleDataAdapter(cmd);
            DataTable dtSap = new DataTable();
            da.Fill(dtSap);
            strState = Convert.ToString(dtSap.Rows[0][0]);
            strSiteAdd = Convert.ToString(dtSap.Rows[0][0]);
            strLatitude = Convert.ToString(dtSap.Rows[0][0]);
            strLongtiude = Convert.ToString(dtSap.Rows[0][0]);
        }
        catch (Exception)
        {
        }
        return strState, strSiteAdd, strLatitude, strLongtiude;
    }

Body:
You can create a custom class with those fields and return it,

 public MyClass string GETSTATE_SAP(string SAP)
    {
        MyClass myObj = new MyClass();
        try
        {
            OracleConnection Oraconn = new OracleConnection(ConfigurationManager.ConnectionStrings["ConnectionStringAPPSAPID"].ConnectionString);
            Oraconn.Open();
            OracleCommand cmd = new OracleCommand("Select STATE, SITE_NAME, SITE_ADDRESS, latitude, longitude from R4G_OSP.UBR where SAP_ID = '" + SAP + "'", Oraconn);
            OracleDataAdapter da = new OracleDataAdapter(cmd);
            DataTable dtSap = new DataTable();
            da.Fill(dtSap);

            myObj.strState = Convert.ToString(dtSap.Rows[0][0]);
            myObj.strSiteAdd = Convert.ToString(dtSap.Rows[0][0]);
            myObj.strLatitude = Convert.ToString(dtSap.Rows[0][0]);
            myObj.strLongtiude = Convert.ToString(dtSap.Rows[0][0]);
        }
        catch (Exception)
        {
        }
        return myObj;
    }
    public class MyClass
    {
        public string strState { get; set; }
        public string strSiteAdd { get; set; }
        public string strLatitude { get; set; }
        public string strLongtiude { get; set; }

    }


问:
Fuzzy logic vs AI vs Machine learning vs Deep learning
How do these four subjects differ from one another? From what I understand, they learn from numerous input data and output an estimated output. My understanding is very lacking thus me questioning these. It made no sense to me about the examples given by people such as the spam email, apple orange cat dog identification, neural network examples.

Is there a better representation of these four subjects in a more simpler example with coding to show the concept? I really appreciate that a lot.

Links to example you think that is very simple with code is more than welcome. I need something relate-able to get the code writing concept better.

Many thanks!

答:
Fuzzy logic is a form of many-valued logic in which the truth values of variables may be any real number between 0 and 1. By contrast, in Boolean logic, the truth values of variables may only be the integer values 0 or 1. Fuzzy logic has been employed to handle the concept of partial truth, where the truth value may range between completely true and completely false.1 Furthermore, when linguistic variables are used, these degrees may be managed by specific (membership) functions.

The field of AI research defines itself as the study of "intelligent agents": any device that perceives its environment and takes actions that maximize its chance of success at some goal. Colloquially, the term "artificial intelligence" is applied when a machine mimics "cognitive" functions that humans associate with other human minds, such as "learning" and "problem solving" (known as Machine Learning).

Machine Learning by Tom Mitchell:

A computer program is said to learn from experience E with respect to some class of tasks T and performance measure P if its performance at tasks in T, as measured by P, improves with experience E.

Deep learning is machine learning with deep neural networks.

Hence: AI is a superset of Machine Learning. Machine Learning is a superset of Deep learning. AI includes fuzzy logic:

Resources

Fuzzy logic lecture notes (German)

Computerphile: Fuzzy logic

IEEE: Fuzzy logic

Tom Mitchel: Machine Learning

Michael Nielsen: Deep Learning


问:
Create a KeyValuePair<byte, string[]> with Linq
I'm developing a C# library with .NET Framework 4.6.2, Entity Framework 6.1.3 and Repository pattern.

I want to create a KeyValuePair<byte, string[]> in a select as follows:

```<code>Dictionary<string, byte> dict =
    GetAggregationLevelsNameId(arvatoConnectionString, productionOrderId);

KeyValuePair<byte, string[]>[] codes = null;

List<Data.Code> aCodes =
    repo.SearchFor(c => c.ProductionOrderId == productionOrderId).ToList();

if ((aCodes != null) && (aCodes.Count > 0))
{
    codes =
        aCodes
            .Select(ac => new { ac.Level, ac.Serial })
            .AsEnumerable()
            .Select(ac => new KeyValuePair<byte, string[]>(dict[ac.Level], ac.Serial))
            .ToArray();
}
</code>```

But here .Select(ac => new KeyValuePair<byte, string[]>(dict[ac.Level], ac.Serial)) I get the following error:

Cannot convert string to string[].

How can I create a KeyValuePair<byte, string[]> in that select?

I want to group all the ac.Serial with the same ac.Level into a KeyValuePair.

ac is a struct that I haven't declare it anywhere. I create it here Select(ac => new { ac.Level, ac.Serial }).

ac.Level is a string.

ac.Serial is a string.

UPDATE:

I have this code that works converting the select into a Dictionary (note that the following dictionary has its key as a string, not as a byte that the one I want to create now):

```<code>GenericRepository<Data.Code> repo =
    new GenericRepository<Data.Code>(context);

codes =
    repo
        .SearchFor(c => c.ProductionOrderId == productionOrderId)
        .GroupBy(c => c.Level)
        .ToDictionary(dic => dic.Key, dic => dic.Select(c => c.Serial).ToList());
</code>```

UPDATE 2:

The Data.Code is a POCO object that represents a Database table where there are a lot of Serial with the same Level.

答:
Try this

```<code>codes =
    aCodes
        .AsEnumerable()
        .GroupBy(ac => dict[ac.Level])
        .Select(ac => new KeyValuePair<byte, string[]>(ac.Key, ac.Select(a => a.Serial).ToArray()))
        .ToArray();
</code>```

Or to a dictionary:

```<code>codes =
    aCodes
        .AsEnumerable()
        .GroupBy(ac => dict[ac.Level])
        .ToDictionary(ac => ac.Key, ac.ToArray());
</code>```

Body:
I'm developing a C# library with .NET Framework 4.6.2, Entity Framework 6.1.3 and Repository pattern.

I want to create a KeyValuePair<byte, string[]> in a select as follows:

Dictionary<string, byte> dict =
    GetAggregationLevelsNameId(arvatoConnectionString, productionOrderId);

KeyValuePair<byte, string[]>[] codes = null;

List<Data.Code> aCodes =
    repo.SearchFor(c => c.ProductionOrderId == productionOrderId).ToList();

if ((aCodes != null) && (aCodes.Count > 0))
{
    codes =
        aCodes
            .Select(ac => new { ac.Level, ac.Serial })
            .AsEnumerable()
            .Select(ac => new KeyValuePair<byte, string[]>(dict[ac.Level], ac.Serial))
            .ToArray();
}

But here .Select(ac => new KeyValuePair<byte, string[]>(dict[ac.Level], ac.Serial)) I get the following error:

Cannot convert string to string[].

How can I create a KeyValuePair<byte, string[]> in that select?

I want to group all the ac.Serial with the same ac.Level into a KeyValuePair.

ac is a struct that I haven't declare it anywhere. I create it here Select(ac => new { ac.Level, ac.Serial }).

ac.Level is a string.

ac.Serial is a string.

UPDATE:

I have this code that works converting the select into a Dictionary (note that the following dictionary has its key as a string, not as a byte that the one I want to create now):

GenericRepository<Data.Code> repo =
    new GenericRepository<Data.Code>(context);

codes =
    repo
        .SearchFor(c => c.ProductionOrderId == productionOrderId)
        .GroupBy(c => c.Level)
        .ToDictionary(dic => dic.Key, dic => dic.Select(c => c.Serial).ToList());

UPDATE 2:

The Data.Code is a POCO object that represents a Database table where there are a lot of Serial with the same Level.

Body:
Try this

codes =
    aCodes
        .AsEnumerable()
        .GroupBy(ac => dict[ac.Level])
        .Select(ac => new KeyValuePair<byte, string[]>(ac.Key, ac.Select(a => a.Serial).ToArray()))
        .ToArray();

Or to a dictionary:

codes =
    aCodes
        .AsEnumerable()
        .GroupBy(ac => dict[ac.Level])
        .ToDictionary(ac => ac.Key, ac.ToArray());


问:
How to Recovering mysql database from data folder backup from uninstalled xamp to newly installed xamp
I have uninstalled the old XAMPP and deleted all of the content of d:\xampp folder and installed the new one. When I copy my backup folder (with the name of my database, containing all .frm and .opt files) to the D:\xampp\mysql\data, the database shows in the list in phpmyadmin but it has no tables and data. What I've done wrong?

tables are show in the database but while clicking on table its saying file doesn't exist..

答:
Probably you have not deleted the main file phpmyadmin
You should to search phpmyadmin in xampp file and delete phpmyadmin and past you're file in xampp again
before you past phpmyadmin be sure you've delete it completely


问:
Why this jquery else if statements are not working?
Could you please take a look at this? It does not work. I can not figure out why.

$(document).ready(function() {
  var result = parseInt($('#kmi').text());
  if (result < 18, 5) {
    $("#line1").css("background-color", "#eee");
  } else if (result >= 18, 5 && result < 24, 9) {
    $("#line2").css("background-color", "#eee");
  } else if (result >= 25 && result = < 29, 9) {
    $("#line3").css("background-color", "#eee");
  } else if (result >= 30 && result = < 34.9) {
    $("#line4").css("background-color", "#eee");
  } else if (result >= 35 && result = < 39.9) {
    $("#line5").css("background-color", "#eee");
  } else if (result >= 40) {
    $("#line6").css("background-color", "#eee");
  } else {
    $("#line1").css("background-color", "#fff");
  }
}
});
```

答:
You wrote => instead of <= where the former one will be considered as an assignment operator and there was an extra } closing braces.

$(document).ready(function() {
  var result = parseInt($('#kmi').text());
  if (result < 18, 5) {
    $("#line1").css("background-color", "#eee");
  } else if (result >= 18.5 && result < 24.9) {
    $("#line2").css("background-color", "#eee");
  } else if (result >= 25 && result <= 29.9) {
    $("#line3").css("background-color", "#eee");
  } else if (result >= 30 && result <= 34.9) {
    $("#line4").css("background-color", "#eee");
  } else if (result >= 35 && result <= 39.9) {
    $("#line5").css("background-color", "#eee");
  } else if (result >= 40) {
    $("#line6").css("background-color", "#eee");
  } else {
    $("#line1").css("background-color", "#fff");
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Body:
You wrote => instead of <= where the former one will be considered as an assignment operator and there was an extra } closing braces.

$(document).ready(function() {
  var result = parseInt($('#kmi').text());
  if (result < 18, 5) {
    $("#line1").css("background-color", "#eee");
  } else if (result >= 18.5 && result < 24.9) {
    $("#line2").css("background-color", "#eee");
  } else if (result >= 25 && result <= 29.9) {
    $("#line3").css("background-color", "#eee");
  } else if (result >= 30 && result <= 34.9) {
    $("#line4").css("background-color", "#eee");
  } else if (result >= 35 && result <= 39.9) {
    $("#line5").css("background-color", "#eee");
  } else if (result >= 40) {
    $("#line6").css("background-color", "#eee");
  } else {
    $("#line1").css("background-color", "#fff");
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
Django Token Authorization based on IP
I am looking for some help with respect to token based authorization. We have a client server model. The client contacts the server for the first time and gets a token. This token has to then utilized whenever a new message is sent to the server. I don't have any users as such. The messages are triggers from the system.Can someone please suggest on how to proceed?
I came across this link
   http://www.tomchristie.com/rest-framework-2-docs/api-guide/authentication

but I am confused when it comes to saving it against a user as I have request from a machine as such.

答:
You can have middleware layer where you can check if the request is from certain IP. If so, then you can program to either allow or deny the request to go through. If a request is allowed, then you can authenticate using Django token authentication. Here I assume you are using something like DRF, Tastypie

```<code>class MiddleWare2CheckIP(object):
    def process_request(self, request):
        ip = request.META['REMOTE_ADDR']
        ### if ip is in list:
           ...
</code>```

and then add the middleware path to MIDDLEWARE_CLASSES

```<code> MIDDLEWARE_CLASSES = (
     ...,
     'path-to-middleware-MiddleWare2CheckIP',
     ...
 )
</code>```

OR

You can have a decorator that you can use with all apis, to check if the request is from certain IPs

Title: Django Token Authorization based on IP

Body:
You can have middleware layer where you can check if the request is from certain IP. If so, then you can program to either allow or deny the request to go through. If a request is allowed, then you can authenticate using Django token authentication. Here I assume you are using something like DRF, Tastypie

class MiddleWare2CheckIP(object):
    def process_request(self, request):
        ip = request.META['REMOTE_ADDR']
        ### if ip is in list:
           ...

and then add the middleware path to MIDDLEWARE_CLASSES

 MIDDLEWARE_CLASSES = (
     ...,
     'path-to-middleware-MiddleWare2CheckIP',
     ...
 )

OR

You can have a decorator that you can use with all apis, to check if the request is from certain IPs


问:
SQLAlchemy Model Django like Save Method?
I am using sqlalchemy for a project. However, I am more accustomed to Django's ORM.

I would like to know if, in the sqlachemy ORM, there is anything similar to a Django models' save() method that I can overrride to implement actions automatically upon a 'commit' / 'save.'

答:
Good news for you!

I created package for that. It implements Active Record pattern for SQLAlchemy.

See https://github.com/absent1706/sqlalchemy-mixins#active-record

It also has many very useful features such as Django lookups that span relationship, declarative eager load and readable print for SQAlchemy.


问:
Bitwise NOT of Java BigInteger is Negative
I am trying to perform a bitwise not on a 128 bit BigInteger in Java. I have a 128 bit number which has the first 64 bits set to 1 and the last 64 bits set to 0 (I am playing with IPv6 masks).

```<code>BigInteger b = new BigInteger(2).pow(64).subtract(BigInteger.ONE).shiftLeft(64);
System.out.println(b.toString(2));
</code>```

This results in the following, if I output it using base 2:

11111111111111111111111111111111111111111111111111111111111111110000000000000000000000000000000000000000000000000000000000000000

I am trying to flip/reverse all the bits using a bitwise not.

```<code>System.out.println(b.not().toString(2));
</code>```

From my understanding of a bitwise not, I was expecting all the 1's to change to 0's and all the 0's to change to 1's, but I get the following instead:

-11111111111111111111111111111111111111111111111111111111111111110000000000000000000000000000000000000000000000000000000000000000

This also seems to match the documentation of the not() function:

This method returns a negative value if and only if this BigInteger is non-negative

Is it a case of looping through all 128 bits and performing a bitwise not on each separate bit instead?

UPDATE
It probably helps if I try and explain what I was trying to achieve to give some context. I am manipulating IPv6 addresses and was trying to determine if a given IPv6 address was within a subnet or not based on an IPv6 mask.

Based on the responses, I think the following should work:

E.g.
Is 2001:db8:0:0:8:800:200c:417b within 2001:db8::/64?

```<code>BigInteger n = new BigInteger(1, InetAddress.getByName("2001:db8::").getAddress());
BigInteger b = BigInteger.ONE.shiftLeft(64).subtract(BigInteger.ONE).shiftLeft(64);

// First Address in Subnet
BigInteger first = n.and(b);

// Last Address in Subnet (this is where I was having a problem as it was returning a negative number)
BigInteger MASK_128 = BigInteger.ONE.shiftLeft(128).subtract(BigInteger.ONE);
BigInteger last = first.add(b.xor(MASK_128));

// Convert our test IP into BigInteger
BigInteger ip = new BigInteger(1, InetAddress.getByName("2001:db8:0:0:8:800:200c:417b").getAddress());

// Check if IP is >= first and <= last
if ((first.compareTo(ip) <= 0) && (last.compareTo(ip) >= 0)) {
  // in subnet
}
</code>```

答:
Your answer is perfectly correct ,In java everything is in two's compliment:

Convert Decimal to Two's Complement

Convert the number to binary (ignore the sign for now) e.g. 5 is 0101 and -5 is 0101

If the number is a positive number then you are done. e.g. 5 is 0101 in binary using twos complement notation.

Here goes your solution.

```<code>If the number is negative then

3.1 find the complement (invert 0's and 1's) e.g. -5 is 0101 so finding the complement is 1010

3.2 Add 1 to the complement 1010 + 1 = 1011. Therefore, -5 in two's complement is 1011.
</code>```

So, what if you wanted to do 2 + (-3) in binary? 2 + (-3) is -1. What would you have to do if you were using sign magnitude to add these numbers? 0010 + 1101 = ?

Using two's complement consider how easy it would be.

2  =  0010

-3 =  1101

+

-1 =  1111

Converting Two's Complement to Decimal

Converting 1111 to decimal:

The number starts with 1, so it's negative, so we find the complement of 1111, which is 0000.

Add 1 to 0000, and we obtain 0001.

Convert 0001 to decimal, which is 1.

Apply the sign = -1.

In your case

when you do b.not().toString(2) , you will get the response :

```<code>-11111111111111111111111111111111111111111111111111111111111111110000000000000000000000000000000000000000000000000000000000000001
</code>```

with 1 at the last bit.

Now do the two's compliment and you will get the right answer.

e.g; Flip all the 1's by 0's and vice-versa. after doing that add one to the solution and you will get the solution that you are seeking.

Final solution

```<code>00000000000000000000000000000000000000000000000000000000000000001111111111111111111111111111111111111111111111111111111111111111
</code>```

Body:
I am trying to perform a bitwise not on a 128 bit BigInteger in Java. I have a 128 bit number which has the first 64 bits set to 1 and the last 64 bits set to 0 (I am playing with IPv6 masks).

BigInteger b = new BigInteger(2).pow(64).subtract(BigInteger.ONE).shiftLeft(64);
System.out.println(b.toString(2));

This results in the following, if I output it using base 2:

11111111111111111111111111111111111111111111111111111111111111110000000000000000000000000000000000000000000000000000000000000000

I am trying to flip/reverse all the bits using a bitwise not.

System.out.println(b.not().toString(2));

From my understanding of a bitwise not, I was expecting all the 1's to change to 0's and all the 0's to change to 1's, but I get the following instead:

-11111111111111111111111111111111111111111111111111111111111111110000000000000000000000000000000000000000000000000000000000000000

This also seems to match the documentation of the not() function:

This method returns a negative value if and only if this BigInteger is non-negative

Is it a case of looping through all 128 bits and performing a bitwise not on each separate bit instead?

UPDATE
It probably helps if I try and explain what I was trying to achieve to give some context. I am manipulating IPv6 addresses and was trying to determine if a given IPv6 address was within a subnet or not based on an IPv6 mask.

Based on the responses, I think the following should work:

E.g.
Is 2001:db8:0:0:8:800:200c:417b within 2001:db8::/64?

BigInteger n = new BigInteger(1, InetAddress.getByName("2001:db8::").getAddress());
BigInteger b = BigInteger.ONE.shiftLeft(64).subtract(BigInteger.ONE).shiftLeft(64);

// First Address in Subnet
BigInteger first = n.and(b);

// Last Address in Subnet (this is where I was having a problem as it was returning a negative number)
BigInteger MASK_128 = BigInteger.ONE.shiftLeft(128).subtract(BigInteger.ONE);
BigInteger last = first.add(b.xor(MASK_128));

// Convert our test IP into BigInteger
BigInteger ip = new BigInteger(1, InetAddress.getByName("2001:db8:0:0:8:800:200c:417b").getAddress());

// Check if IP is >= first and <= last
if ((first.compareTo(ip) <= 0) && (last.compareTo(ip) >= 0)) {
  // in subnet
}

Body:
Your answer is perfectly correct ,In java everything is in two's compliment:

Convert Decimal to Two's Complement

Convert the number to binary (ignore the sign for now) e.g. 5 is 0101 and -5 is 0101

If the number is a positive number then you are done. e.g. 5 is 0101 in binary using twos complement notation.

Here goes your solution.

If the number is negative then

3.1 find the complement (invert 0's and 1's) e.g. -5 is 0101 so finding the complement is 1010

3.2 Add 1 to the complement 1010 + 1 = 1011. Therefore, -5 in two's complement is 1011.

So, what if you wanted to do 2 + (-3) in binary? 2 + (-3) is -1. What would you have to do if you were using sign magnitude to add these numbers? 0010 + 1101 = ?

Using two's complement consider how easy it would be.

2  =  0010

-3 =  1101

+

-1 =  1111

Converting Two's Complement to Decimal

Converting 1111 to decimal:

The number starts with 1, so it's negative, so we find the complement of 1111, which is 0000.

Add 1 to 0000, and we obtain 0001.

Convert 0001 to decimal, which is 1.

Apply the sign = -1.

In your case

when you do b.not().toString(2) , you will get the response :

-11111111111111111111111111111111111111111111111111111111111111110000000000000000000000000000000000000000000000000000000000000001

with 1 at the last bit.

Now do the two's compliment and you will get the right answer.

e.g; Flip all the 1's by 0's and vice-versa. after doing that add one to the solution and you will get the solution that you are seeking.

Final solution

00000000000000000000000000000000000000000000000000000000000000001111111111111111111111111111111111111111111111111111111111111111


问:
trimmingCharacters not work on iOS 10.3 Xcode8.3
Please help me, I use Xcode 8.3(swift 3.1), the function trimmingCharacters not work. My code as below:

```<code>    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if var searchStr = textField.text{
       let _searchStr = searchStr.trimmingCharacters(in: .whitespaces)
       print("After trimming:\(_searchStr)")
   }
}
</code>```

The input in textfield is 409 huỳnh and the print result is 409 huỳnh not as expected: 409huỳnh .

答:
In Swift 3 you can use below code to solve the problem

```<code>let _searchStr = searchStr.replacingOccurrences(of: " ", with: "")
</code>```

Body:
Please help me, I use Xcode 8.3(swift 3.1), the function trimmingCharacters not work. My code as below:

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if var searchStr = textField.text{
       let _searchStr = searchStr.trimmingCharacters(in: .whitespaces)
       print("After trimming:\(_searchStr)")
   }
}

The input in textfield is 409 huỳnh and the print result is 409 huỳnh not as expected: 409huỳnh .

Body:
In Swift 3 you can use below code to solve the problem

let _searchStr = searchStr.replacingOccurrences(of: " ", with: "")


问:
Java 8 - Xmx and XX:MaxHeapSize do not match
I have set the Xmx parameter for JVM to 5120 but when the java process(tomcat) runs, I see that the MaxHeapSize does not match the Xmx value, it is stuck at 2570, which is strange to me, any thoughts on this are much appreciated!!

Output of ps:

/usr/bin/java -Dnop -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Xms1536m -Xmx5120 -Dorg.apache.catalina.STRICT_SERVLET_COMPLIANCE=true -Djava.net.preferIPv4Stack=true -DSHUTDOWN_PORT=8005 -DHTTP_PORT=8080 -DHTTPS_PORT=8443 -DAJP_PORT=8009 -XX:InitialHeapSize=2570m -XX:MaxHeapSize=2570m -XX:MetaspaceSize=256m -XX:MaxMetaspaceSize=512m -XX:+DisableExplicitGC -Djava.endorsed.dirs=/usr/local/tomcat/endorsed -classpath /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar -Dcatalina.base=/app/tomcat/default -Dcatalina.home=/usr/local/tomcat -Djava.io.tmpdir=/app/tomcat/default/temp org.apache.catalina.

答:
Problems in your config:

-Xms1536m -Xmx5120

If you don't specify the unit of this config, it will be parsed as bytes,  which means your Xmx is less than your Xms, if this config applies JVM will failed to launch:

```<code> ~/ java -Xms1536m -Xmx5120 -XX:+PrintFlagsFinal -version
Error occurred during initialization of VM
Initial heap size set to a larger value than the maximum heap size
</code>```

Your JVM did not aborted because you have following configs:

-XX:InitialHeapSize=2570m -XX:MaxHeapSize=2570m

-Xms is -XX:InitialHeapSize and -Xmx is -XX:MaxHeapSize, so your previous wrong config of -Xms1536m -Xmx5120 is replaced by the later ones, which specified Xmx to be 2570M.

Body:
Problems in your config:

-Xms1536m -Xmx5120

If you don't specify the unit of this config, it will be parsed as bytes,  which means your Xmx is less than your Xms, if this config applies JVM will failed to launch:

 ~/ java -Xms1536m -Xmx5120 -XX:+PrintFlagsFinal -version
Error occurred during initialization of VM
Initial heap size set to a larger value than the maximum heap size

Your JVM did not aborted because you have following configs:

-XX:InitialHeapSize=2570m -XX:MaxHeapSize=2570m

-Xms is -XX:InitialHeapSize and -Xmx is -XX:MaxHeapSize, so your previous wrong config of -Xms1536m -Xmx5120 is replaced by the later ones, which specified Xmx to be 2570M.


问:
Changing value of a variable on OnClick Android
I have 2 buttons in my layout when user presses button 1 the value of 'number' should change to '2' and when the user presses button 2 the value of 'number' should change to '1'.But the value does not change.
Here is my code :

```<code>public class test extends AppCompatActivity{

public  int number ;

private Button btn1;
private Button btn2;
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.testing);

    btn1=(Button)findViewById(R.id.btn1);
    btn2=(Button)findViewById(R.id.btn2);

    test();
}

void test()
{

  if(number<1) {
    number = 1;
    }

        Log.e("number value : ",String.valueOf(number));

    if(number==1)
    {

         btn1.setOnClickListener(new View.OnClickListener() {

         @Override
         public void onClick(View arg0) {
          number=2;

             Log.e("number value : ",String.valueOf(number));

         }

    });

    }

     if(number==2)
    {
     btn2.setOnClickListener(new View.OnClickListener() {

         @Override
        public void onClick(View arg0) {
             number=1;
             Log.e("number value : ",String.valueOf(number));

    }

    });

    }

    }
</code>```

Log.e outputs ``` E/number value :: 2``` when I press btn1 but when i press btn2 nothing happens and only btn1 works

答:
Try This</p>

```<code>void test()
{

  if(number<1) { number = 1; }

  Log.e("number value : ",String.valueOf(number));

  btn1.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View arg0)  {
       if(number == 1)
       {
         number=2;
         Log.e("Button 1 number value : ",String.valueOf(number));
       }
     }
  });

  btn2.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View arg0)  {
       if(number == 2)
       {
         number=1;
         Log.e("Button 2 number value : ",String.valueOf(number));
       }
     }
  });

}
</code>```

Body:
I have 2 buttons in my layout when user presses button 1 the value of 'number' should change to '2' and when the user presses button 2 the value of 'number' should change to '1'.But the value does not change.
Here is my code :

public class test extends AppCompatActivity{

public  int number ;

private Button btn1;
private Button btn2;
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.testing);

    btn1=(Button)findViewById(R.id.btn1);
    btn2=(Button)findViewById(R.id.btn2);

    test();
}

void test()
{

  if(number<1) {
    number = 1;
    }

        Log.e("number value : ",String.valueOf(number));

    if(number==1)
    {

         btn1.setOnClickListener(new View.OnClickListener() {

         @Override
         public void onClick(View arg0) {
          number=2;

             Log.e("number value : ",String.valueOf(number));

         }

    });

    }

     if(number==2)
    {
     btn2.setOnClickListener(new View.OnClickListener() {

         @Override
        public void onClick(View arg0) {
             number=1;
             Log.e("number value : ",String.valueOf(number));

    }

    });

    }

    }

Log.e outputs
 E/number value :: 2
 when I press btn1 but when i press btn2 nothing happens and only btn1 works

Body:
Try This

void test()
{

  if(number<1) { number = 1; }

  Log.e("number value : ",String.valueOf(number));

  btn1.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View arg0)  {
       if(number == 1)
       {
         number=2;
         Log.e("Button 1 number value : ",String.valueOf(number));
       }
     }
  });

  btn2.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View arg0)  {
       if(number == 2)
       {
         number=1;
         Log.e("Button 2 number value : ",String.valueOf(number));
       }
     }
  });

}


问:
intellij plugin development show input dialog with multiple text boxes
I'm creating intelliJ plugin and registering my action , inside my action i want to show an input dialog with multiple text boxes, how do I do that ?
I have an example of showing only one text box -</p>

```<code> String txt= Messages.showInputDialog(project, "What is your name?",
                                     "Input your name", Messages.getQuestionIcon());
</code>```

答:
Create a new GUI Form (form + class). Class should extend DialogWrapper and override methods.

Inside createCenterPanel() return your root JPanel. You can set any default values, add event listeners to text box, etc., before returning JPanel.

Implement an Action interface where you want to get the value when OK button is clicked. Pass this action to your form class.

getOKAction() should return this action.

Following code is from a plugin i'm currently working on. Hopefully this will give you some idea but will have to adapt it to your need.

```<code>public class ReleaseNoteDialog extends DialogWrapper implements Action {
    private JTextArea txtReleaseNote;
    private JPanel panelWrapper;

    .......
    protected JComponent createCenterPanel() {
        ......
        return panelWrapper;
    }
    ......
    @Override
    protected Action getOKAction() {
         return this;
    }
    .......
   @Override
   public void actionPerformed(ActionEvent e) {
        // save value to project state
        super.doOKAction();
   }
</code>```

Body:
I'm creating intelliJ plugin and registering my action , inside my action i want to show an input dialog with multiple text boxes, how do I do that ?
I have an example of showing only one text box -

 String txt= Messages.showInputDialog(project, "What is your name?",
                                     "Input your name", Messages.getQuestionIcon());

Body:
Create a new GUI Form (form + class). Class should extend DialogWrapper and override methods.

Inside createCenterPanel() return your root JPanel. You can set any default values, add event listeners to text box, etc., before returning JPanel.

Implement an Action interface where you want to get the value when OK button is clicked. Pass this action to your form class.

getOKAction() should return this action.

Following code is from a plugin i'm currently working on. Hopefully this will give you some idea but will have to adapt it to your need.

public class ReleaseNoteDialog extends DialogWrapper implements Action {
    private JTextArea txtReleaseNote;
    private JPanel panelWrapper;

    .......
    protected JComponent createCenterPanel() {
        ......
        return panelWrapper;
    }
    ......
    @Override
    protected Action getOKAction() {
         return this;
    }
    .......
   @Override
   public void actionPerformed(ActionEvent e) {
        // save value to project state
        super.doOKAction();
   }


问:
List of Map.Entry<String,String>
how to convert a list of Map.Entry<String, String> to a String?

```<code>List<Map.Entry<String, String>> : [AREA_DS_ID=1,5,9,13,17,21,25,29,33, PROJECTS_ID=13,78,267,18,28,33,55,99, SIGNAL_NAME=a, ASSESSMENTNAME=a]
// these are the values which I need to convert into String.
</code>```

答:
Just as an answer to your comment: I just tried it and there is no exception at all:</p>

```<code>Map<String, String> map = new LinkedHashMap<>();
map.put("AREA_DS_ID", "1,5,9,13,17,21,25,29,33");
map.put("PROJECTS_ID", "13,78,267,18,28,33,55,99");
map.put("SIGNAL_NAME", "a");
map.put("ASSESSMENTNAME", "a");

List<String> entryList = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for (Entry<String, String> entry : map.entrySet()) {
    String value = entry.getKey() + '=' + entry.getValue();
    entryList.add(value);
    sb.append(value);
}
String[] entries = entryList.toArray(new String[entryList.size()]);
String mapAsString = sb.toString();
</code>```

Title: List of Map.Entry<String,String>

Body:
how to convert a list of Map.Entry<String, String> to a String?

List<Map.Entry<String, String>> : [AREA_DS_ID=1,5,9,13,17,21,25,29,33, PROJECTS_ID=13,78,267,18,28,33,55,99, SIGNAL_NAME=a, ASSESSMENTNAME=a]
// these are the values which I need to convert into String.

Body:
Just as an answer to your comment: I just tried it and there is no exception at all:

Map<String, String> map = new LinkedHashMap<>();
map.put("AREA_DS_ID", "1,5,9,13,17,21,25,29,33");
map.put("PROJECTS_ID", "13,78,267,18,28,33,55,99");
map.put("SIGNAL_NAME", "a");
map.put("ASSESSMENTNAME", "a");

List<String> entryList = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for (Entry<String, String> entry : map.entrySet()) {
    String value = entry.getKey() + '=' + entry.getValue();
    entryList.add(value);
    sb.append(value);
}
String[] entries = entryList.toArray(new String[entryList.size()]);
String mapAsString = sb.toString();


问:
vTiger Custom Field Validation beforesave
I have created a custom module on vTiger 6.5.

I have made an event handler for the module but I am wondering how I could perform some sort of validation on this field. So fat I have done this but I am unable to get it work, I have tested the handler just echoing a sting and it works fine.

Please see my code below. Thanks!

```<code>    <?php
/*+***********************************************************************************
 * The contents of this file are subject to the vtiger CRM Public License Version 1.0
 * ("License"); You may not use this file except in compliance with the License
 * The Original Code is:  vtiger CRM Open Source
 * The Initial Developer of the Original Code is vtiger.
 * Portions created by vtiger are Copyright (C) vtiger.
 * All Rights Reserved.
 *************************************************************************************/
# getModuleName : Returns the module name of the entity.
# getId : Returns id of the entity, this will return null if the id has not been saved yet.
# getData : Returns the fields of the entity as an array where the field name is the key and the fields value is the value.
# isNew : Returns true if new record is being created, false otherwise.
# 'vtiger.entity.beforesave.modifiable' : Setting values : $data->set('simple_field', 'value');

class isaHandler extends VTEventHandler {
    function handleEvent($eventName, $entityData) {
        global $adb;
        $moduleName = $entityData->getModuleName();
        if($moduleName=='isa'){
            if($eventName == 'vtiger.entity.beforesave.modifiable') {}
            if($eventName == 'vtiger.entity.beforesave') {
                if('currentamount' > 20000){
                    echo "Please go back and enter less than 20000";
                exit;
                }

            }
            if($eventName == 'vtiger.entity.beforesave.final') {}
            if($eventName == 'vtiger.entity.aftersave') {
            }
        }
    }

}
?>
</code>```

答:
In my opinion you should use the recordPreSave function.
It's allow you to display an information/error message before to save data on the database

Here is an example:

In your Edit.js:

```<code>donCache : {},
    checkDon : function(details) {
        // alert("checkOverlap");
        var aDeferred = jQuery.Deferred();

        var params = {
            'module' : 'Affectations',
            'action' : "checkAffectAmount",
            'mode': 'CtrlAffectAmount',
            'recordId' : details.don,
            'montant' : details.montant
        }
        AppConnector.request(params).then(
            function(data) {
                if (data.success == true) {
                    // console.log(data.result);
                    var statut = data.result.statut;
                    var reste = data.result.reste;

                    if(statut == "error"){
                        aDeferred.reject(data);
                    }else {
                        aDeferred.resolve(data);
                    }
                }
            },
            function(error,err){
                aDeferred.reject();
            }
        );
        return aDeferred.promise();
    },

    registerRecordPreSaveEvent : function(form) {
        var thisInstance = this;
        if (typeof form == 'undefined') {
            form = this.getForm();
        }
        form.on(Vtiger_Edit_Js.recordPreSave, function(e, data) {
            var check = false;
            var recordId = jQuery('input[name="record"]').val();

            if (!recordId || recordId) {

                var montant_affectation = jQuery("input[name='affectations_montant']").val();
                var don_id = jQuery("input[name='affectations_potentialid']").val();

                var params = {};
                if (!(check in thisInstance.donCache)) {
                    thisInstance.checkDon({
                        'montant' : montant_affectation,
                        'don': don_id
                    }).then(
                        function(data){
                            thisInstance.donCache[check] = data['success'];
                            form.submit();
                        },
                        function(data, err){
                            thisInstance.donCache[check] = data['success'];
                            var reste = data.result.reste;
                            var msg = app.vtranslate("<strong>Attention!</strong> La somme des affectations est supérieure  de ")+ reste +app.vtranslate(" Euros au montant du don");
                            Vtiger_Helper_Js.showPnotify(msg);
                            delete thisInstance.donCache[check];
                        }
                    );
                } else {
                    delete thisInstance.donCache[check];
                    return true;
                }
                e.preventDefault();
            }
        })
    },
</code>```

The PHP part in modules/isa/actions:

```<code><?php

/***********************************
** DEBUT ALTAIR - JPR 15/06/2016 ***
***********************************/

class Affectations_checkAffectAmount_Action extends Vtiger_Action_Controller {

    function __construct() {
        $this->exposeMethod('CtrlAffectAmount');
    }

    public function checkPermission(Vtiger_Request $request) {
        $moduleName = $request->getModule();
        $moduleModel = Vtiger_Module_Model::getInstance($moduleName);

        $userPrivilegesModel = Users_Privileges_Model::getCurrentUserPrivilegesModel();
        $permission = $userPrivilegesModel->hasModulePermission($moduleModel->getId());

        if(!$permission) {
            throw new AppException('LBL_PERMISSION_DENIED');
        }
    }

    public function process(Vtiger_Request $request) {
        $mode = $request->getMode();
        if(!empty($mode) && $this->isMethodExposed($mode)) {
            $this->invokeExposedMethod($mode, $request);
            return;
        }
    }

    function CtrlAffectAmount(Vtiger_Request $request){
        global $adb,$log;

        $log->debug("ALTAIR CtrlAffectAmount OK");

        $recordId = $request->get('recordId');
        $montant = $request->get('montant');

        // $query = $adb->pquery("SELECT SUM(unit_price) AS sommeaffectation FROM vtiger_products INNER JOIN vtiger_crmentity ON vtiger_products.productid = vtiger_crmentity.crmid WHERE don_affecte = ? AND vtiger_crmentity.deleted=0",array($recordId));
        $query = $adb->pquery("SELECT SUM(affectations_montant) AS sommeaffectation FROM vtiger_affectations INNER JOIN vtiger_crmentity ON vtiger_affectations.affectationsid = vtiger_crmentity.crmid WHERE vtiger_affectations.affectations_potentialid = ? AND vtiger_crmentity.deleted=0",array($recordId));
        $sommeAffectation = $adb->query_result($query,0,"sommeaffectation");

        $query = $adb->pquery("SELECT amount FROM vtiger_potential INNER JOIN vtiger_crmentity ON vtiger_potential.potentialid = vtiger_crmentity.crmid WHERE potentialid = ? AND vtiger_crmentity.deleted = 0", array($recordId));
        $montantDon = $adb->query_result($query,0,"amount");

        if ( ($sommeAffectation + $montant) == $montantDon) {
            $statut = "ok";
            $reste = "";
        } else if( ($sommeAffectation + $montant) > $montantDon) {
            $statut = "error";
            $reste = ($sommeAffectation + $montant) - $montantDon;

        }

        $value = array('statut'=>$statut, 'reste'=>$reste);

        $response = new Vtiger_Response();
        $response->setEmitType(Vtiger_Response::$EMIT_JSON);
        $response->setResult($value);
        $response->emit();
    }
}
</code>```

Body:
I have created a custom module on vTiger 6.5.

I have made an event handler for the module but I am wondering how I could perform some sort of validation on this field. So fat I have done this but I am unable to get it work, I have tested the handler just echoing a sting and it works fine.

Please see my code below. Thanks!

    <?php
/*+***********************************************************************************
 * The contents of this file are subject to the vtiger CRM Public License Version 1.0
 * ("License"); You may not use this file except in compliance with the License
 * The Original Code is:  vtiger CRM Open Source
 * The Initial Developer of the Original Code is vtiger.
 * Portions created by vtiger are Copyright (C) vtiger.
 * All Rights Reserved.
 *************************************************************************************/
# getModuleName : Returns the module name of the entity.
# getId : Returns id of the entity, this will return null if the id has not been saved yet.
# getData : Returns the fields of the entity as an array where the field name is the key and the fields value is the value.
# isNew : Returns true if new record is being created, false otherwise.
# 'vtiger.entity.beforesave.modifiable' : Setting values : $data->set('simple_field', 'value');

class isaHandler extends VTEventHandler {
    function handleEvent($eventName, $entityData) {
        global $adb;
        $moduleName = $entityData->getModuleName();
        if($moduleName=='isa'){
            if($eventName == 'vtiger.entity.beforesave.modifiable') {}
            if($eventName == 'vtiger.entity.beforesave') {
                if('currentamount' > 20000){
                    echo "Please go back and enter less than 20000";
                exit;
                }

            }
            if($eventName == 'vtiger.entity.beforesave.final') {}
            if($eventName == 'vtiger.entity.aftersave') {
            }
        }
    }

}
?>

Body:
In my opinion you should use the recordPreSave function.
It's allow you to display an information/error message before to save data on the database

Here is an example:

In your Edit.js:

donCache : {},
    checkDon : function(details) {
        // alert("checkOverlap");
        var aDeferred = jQuery.Deferred();

        var params = {
            'module' : 'Affectations',
            'action' : "checkAffectAmount",
            'mode': 'CtrlAffectAmount',
            'recordId' : details.don,
            'montant' : details.montant
        }
        AppConnector.request(params).then(
            function(data) {
                if (data.success == true) {
                    // console.log(data.result);
                    var statut = data.result.statut;
                    var reste = data.result.reste;

                    if(statut == "error"){
                        aDeferred.reject(data);
                    }else {
                        aDeferred.resolve(data);
                    }
                }
            },
            function(error,err){
                aDeferred.reject();
            }
        );
        return aDeferred.promise();
    },

    registerRecordPreSaveEvent : function(form) {
        var thisInstance = this;
        if (typeof form == 'undefined') {
            form = this.getForm();
        }
        form.on(Vtiger_Edit_Js.recordPreSave, function(e, data) {
            var check = false;
            var recordId = jQuery('input[name="record"]').val();

            if (!recordId || recordId) {

                var montant_affectation = jQuery("input[name='affectations_montant']").val();
                var don_id = jQuery("input[name='affectations_potentialid']").val();

                var params = {};
                if (!(check in thisInstance.donCache)) {
                    thisInstance.checkDon({
                        'montant' : montant_affectation,
                        'don': don_id
                    }).then(
                        function(data){
                            thisInstance.donCache[check] = data['success'];
                            form.submit();
                        },
                        function(data, err){
                            thisInstance.donCache[check] = data['success'];
                            var reste = data.result.reste;
                            var msg = app.vtranslate("<strong>Attention!</strong> La somme des affectations est supérieure  de ")+ reste +app.vtranslate(" Euros au montant du don");
                            Vtiger_Helper_Js.showPnotify(msg);
                            delete thisInstance.donCache[check];
                        }
                    );
                } else {
                    delete thisInstance.donCache[check];
                    return true;
                }
                e.preventDefault();
            }
        })
    },

The PHP part in modules/isa/actions:

<?php

/***********************************
** DEBUT ALTAIR - JPR 15/06/2016 ***
***********************************/

class Affectations_checkAffectAmount_Action extends Vtiger_Action_Controller {

    function __construct() {
        $this->exposeMethod('CtrlAffectAmount');
    }

    public function checkPermission(Vtiger_Request $request) {
        $moduleName = $request->getModule();
        $moduleModel = Vtiger_Module_Model::getInstance($moduleName);

        $userPrivilegesModel = Users_Privileges_Model::getCurrentUserPrivilegesModel();
        $permission = $userPrivilegesModel->hasModulePermission($moduleModel->getId());

        if(!$permission) {
            throw new AppException('LBL_PERMISSION_DENIED');
        }
    }

    public function process(Vtiger_Request $request) {
        $mode = $request->getMode();
        if(!empty($mode) && $this->isMethodExposed($mode)) {
            $this->invokeExposedMethod($mode, $request);
            return;
        }
    }

    function CtrlAffectAmount(Vtiger_Request $request){
        global $adb,$log;

        $log->debug("ALTAIR CtrlAffectAmount OK");

        $recordId = $request->get('recordId');
        $montant = $request->get('montant');

        // $query = $adb->pquery("SELECT SUM(unit_price) AS sommeaffectation FROM vtiger_products INNER JOIN vtiger_crmentity ON vtiger_products.productid = vtiger_crmentity.crmid WHERE don_affecte = ? AND vtiger_crmentity.deleted=0",array($recordId));
        $query = $adb->pquery("SELECT SUM(affectations_montant) AS sommeaffectation FROM vtiger_affectations INNER JOIN vtiger_crmentity ON vtiger_affectations.affectationsid = vtiger_crmentity.crmid WHERE vtiger_affectations.affectations_potentialid = ? AND vtiger_crmentity.deleted=0",array($recordId));
        $sommeAffectation = $adb->query_result($query,0,"sommeaffectation");

        $query = $adb->pquery("SELECT amount FROM vtiger_potential INNER JOIN vtiger_crmentity ON vtiger_potential.potentialid = vtiger_crmentity.crmid WHERE potentialid = ? AND vtiger_crmentity.deleted = 0", array($recordId));
        $montantDon = $adb->query_result($query,0,"amount");

        if ( ($sommeAffectation + $montant) == $montantDon) {
            $statut = "ok";
            $reste = "";
        } else if( ($sommeAffectation + $montant) > $montantDon) {
            $statut = "error";
            $reste = ($sommeAffectation + $montant) - $montantDon;

        }

        $value = array('statut'=>$statut, 'reste'=>$reste);

        $response = new Vtiger_Response();
        $response->setEmitType(Vtiger_Response::$EMIT_JSON);
        $response->setResult($value);
        $response->emit();
    }
}