问:
In kotlin, how to make the setter of properties in primary constructor private?
In kotlin, how to make the setter of properties in primary constructor private?

```<code>class City(val id: String, var name: String, var description: String = "") {

    fun update(name: String, description: String? = "") {
        this.name = name
        this.description = description ?: this.description
    }
}
</code>```

I  want the setter of properties name to be private, and the getter of it public, how can I do?

答:
You can try like this</p>

```<code>class Sample(var id: Int, private var name:String) {

    // Backing field
    var _name: String = ""
        get() = name
        private set

}

fun main(args: Array<String>) {
     println("Hello World")

     val sample = Sample(1, "hello")
    //    println(sample.name); It's not possible
    println(sample._name)
}
</code>```

Body:
In kotlin, how to make the setter of properties in primary constructor private?

class City(val id: String, var name: String, var description: String = "") {

    fun update(name: String, description: String? = "") {
        this.name = name
        this.description = description ?: this.description
    }
}

I  want the setter of properties name to be private, and the getter of it public, how can I do?

Body:
You can try like this

class Sample(var id: Int, private var name:String) {

    // Backing field
    var _name: String = ""
        get() = name
        private set

}

fun main(args: Array<String>) {
     println("Hello World")

     val sample = Sample(1, "hello")
    //    println(sample.name); It's not possible
    println(sample._name)
}


来源: stackexchange

问:
Angular2: Failing to load component's templateUrl file
I am getting the following Unhandled Promise rejection: Failed to load error in my Angular 2 project:

Here is my messages.component.js:

```<code>import { Component, OnInit } from "@angular/core"

@Component({
    moduleId: module.id,
    selector: 'messages',
    templateUrl: './messages.component.html',
})

export class MessagesComponent {
    messages: object[] = [{ text: "this is some text", owner: "Brad" }, { text: "this is a cool article", owner: "Fred" }];
}
</code>```

and messages.component.html:

```<code><p>This is the messages Component: {{messages.length}}</p>
<div *ngFor="let message of messages">
    {{message.text}} by {{message.owner}}
</div>
</code>```

I looked at this SO post and this this article the the path looks correct to me.

Towards the end of this post seems to indicate that the html can fail to build and thus be missing. The html file is indeed missing from the wwwroot after building, but I get no compiler errors.

I am on Windows10 using VS2017. I used this template for setting up the project.

答:
Your component seems great. I think your error is related to the module declarations.
Did you add your new component in app.module.ts file ?

You should have something like :

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
//import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { MessagesComponent } from './messages/messages.component'; // DECLARE YOUR COMPONENT HERE

@NgModule({
    imports: [
        BrowserModule,
        //FormsModule,
        HttpModule,
        //routing,
        AppRoutingModule
    ],
    declarations: [
        AppComponent,
        HomeComponent,
        MessagesComponent // INJECT YOUR COMPONENT
    ],
    bootstrap: [AppComponent],
    providers: [
    ]
})
export class AppModule { }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am getting the following Unhandled Promise rejection: Failed to load error in my Angular 2 project:

Here is my messages.component.js:

import { Component, OnInit } from "@angular/core"

@Component({
    moduleId: module.id,
    selector: 'messages',
    templateUrl: './messages.component.html',
})

export class MessagesComponent {
    messages: object[] = [{ text: "this is some text", owner: "Brad" }, { text: "this is a cool article", owner: "Fred" }];
}

and messages.component.html:

This is the messages Component: {{messages.length}}

    {{message.text}} by {{message.owner}}

I looked at this SO post and this this article the the path looks correct to me.

Towards the end of this post seems to indicate that the html can fail to build and thus be missing. The html file is indeed missing from the wwwroot after building, but I get no compiler errors.

I am on Windows10 using VS2017. I used this template for setting up the project.

Body:
Your component seems great. I think your error is related to the module declarations.
Did you add your new component in app.module.ts file ?

You should have something like :

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
//import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { MessagesComponent } from './messages/messages.component'; // DECLARE YOUR COMPONENT HERE

@NgModule({
    imports: [
        BrowserModule,
        //FormsModule,
        HttpModule,
        //routing,
        AppRoutingModule
    ],
    declarations: [
        AppComponent,
        HomeComponent,
        MessagesComponent // INJECT YOUR COMPONENT
    ],
    bootstrap: [AppComponent],
    providers: [
    ]
})
export class AppModule { }


问:
Compare two DataFrames and output their differences side-by-side
I am trying to highlight exactly what changed between two dataframes.

Suppose I have two Python Pandas dataframes:

```<code>"StudentRoster Jan-1":
id   Name   score                    isEnrolled           Comment
111  Jack   2.17                     True                 He was late to class
112  Nick   1.11                     False                Graduated
113  Zoe    4.12                     True

"StudentRoster Jan-2":
id   Name   score                    isEnrolled           Comment
111  Jack   2.17                     True                 He was late to class
112  Nick   1.21                     False                Graduated
113  Zoe    4.12                     False                On vacation
</code>```

My goal is to output an HTML table that:

Identifies rows that have changed (could be int, float, boolean, string)

Outputs rows with same, OLD and NEW values (ideally into an HTML table) so the consumer can clearly see what changed between two dataframes:

```<code>"StudentRoster Difference Jan-1 - Jan-2":
id   Name   score                    isEnrolled           Comment
112  Nick   was 1.11| now 1.21       False                Graduated
113  Zoe    4.12                     was True | now False was "" | now   "On   vacation"
</code>```

I suppose I could do a row by row and column by column comparison, but is there an easier way?

答:
Here is another way using select and merge:

```<code>In [6]: # first lets create some dummy dataframes with some column(s) different
   ...: df1 = pd.DataFrame({'a': range(-5,0), 'b': range(10,15), 'c': range(20,25)})
   ...: df2 = pd.DataFrame({'a': range(-5,0), 'b': range(10,15), 'c': [20] + list(range(101,105))})

In [7]: df1
Out[7]:
   a   b   c
0 -5  10  20
1 -4  11  21
2 -3  12  22
3 -2  13  23
4 -1  14  24

In [8]: df2
Out[8]:
   a   b    c
0 -5  10   20
1 -4  11  101
2 -3  12  102
3 -2  13  103
4 -1  14  104

In [10]: # make condition over the columns you want to comapre
    ...: condition = df1['c'] != df2['c']
    ...:
    ...: # select rows from each dataframe where the condition holds
    ...: diff1 = df1[condition]
    ...: diff2 = df2[condition]

In [11]: # merge the selected rows (dataframes) with some suffixes (optional)
    ...: diff1.merge(diff2, on=['a','b'], suffixes=('_before', '_after'))
Out[11]:
   a   b  c_before  c_after
0 -4  11        21      101
1 -3  12        22      102
2 -2  13        23      103
3 -1  14        24      104
</code>```

Here is the same thing from a Jupyter screenshot:

ContentLicense: CC BY-SA 4.0

Body:
I am trying to highlight exactly what changed between two dataframes.

Suppose I have two Python Pandas dataframes:

"StudentRoster Jan-1":
id   Name   score                    isEnrolled           Comment
111  Jack   2.17                     True                 He was late to class
112  Nick   1.11                     False                Graduated
113  Zoe    4.12                     True

"StudentRoster Jan-2":
id   Name   score                    isEnrolled           Comment
111  Jack   2.17                     True                 He was late to class
112  Nick   1.21                     False                Graduated
113  Zoe    4.12                     False                On vacation

My goal is to output an HTML table that:

Identifies rows that have changed (could be int, float, boolean, string)

Outputs rows with same, OLD and NEW values (ideally into an HTML table) so the consumer can clearly see what changed between two dataframes:

"StudentRoster Difference Jan-1 - Jan-2":
id   Name   score                    isEnrolled           Comment
112  Nick   was 1.11| now 1.21       False                Graduated
113  Zoe    4.12                     was True | now False was "" | now   "On   vacation"

I suppose I could do a row by row and column by column comparison, but is there an easier way?

Body:
Here is another way using select and merge:

In [6]: # first lets create some dummy dataframes with some column(s) different
   ...: df1 = pd.DataFrame({'a': range(-5,0), 'b': range(10,15), 'c': range(20,25)})
   ...: df2 = pd.DataFrame({'a': range(-5,0), 'b': range(10,15), 'c': [20] + list(range(101,105))})

In [7]: df1
Out[7]:
   a   b   c
0 -5  10  20
1 -4  11  21
2 -3  12  22
3 -2  13  23
4 -1  14  24

In [8]: df2
Out[8]:
   a   b    c
0 -5  10   20
1 -4  11  101
2 -3  12  102
3 -2  13  103
4 -1  14  104

In [10]: # make condition over the columns you want to comapre
    ...: condition = df1['c'] != df2['c']
    ...:
    ...: # select rows from each dataframe where the condition holds
    ...: diff1 = df1[condition]
    ...: diff2 = df2[condition]

In [11]: # merge the selected rows (dataframes) with some suffixes (optional)
    ...: diff1.merge(diff2, on=['a','b'], suffixes=('_before', '_after'))
Out[11]:
   a   b  c_before  c_after
0 -4  11        21      101
1 -3  12        22      102
2 -2  13        23      103
3 -1  14        24      104

Here is the same thing from a Jupyter screenshot:


问:
Caching policies and techniques for matrices
as explained before, I'm currently working on a small linear algebra library to use in a personal project. Matrices are implemented as C++ vectors and element assignment ( a(i,j) = v; ) is delegated to the assignment to the vector's elements. For my project I'll need to solve tons of square equation systems and, in order to do that, I implemented the LU factorization (Gaussian Elimination) for square matrices. In the current implementation I'm avoiding to recalculate each time the LU factorization by caching the L and U matrices, the problem is that since I'm delegating the element assignment to vector, I can't find a way to say if the matrix is being changed and whether to recalculate the factorization. Any ideas on how to solve this?

Thank you

答:
```<code>template<class T>
class matrix {
public:
    class accessor {
    public:
        accessor(T& dest, matrix& parent) : dest(dest), parent(parent) { }
        operator T const& () const { return dest; }
        accessor& operator=(T const& t) { dest = t; parent.invalidate_cache(); return *this; }
    private:
        T& dest;
        matrix& parent;
    };

    // replace those with actual implementation..
    accessor operator()(int x, int y) {
        static T t; return accessor(t, *this);
    }
    T const& operator()(int x, int y) const {
        static T t; return t;
    }

private:
    void invalidate_cache() { cout << "Cache invalidated !!\n"; }
    vector<T> impl;
};
</code>```

thanks go to to ##iso-c++ @ irc.freenode.net for some helpful corrections

OwnerDisplayName: Tunnuz

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Tunnuz

Body:
template<class T>
class matrix {
public:
    class accessor {
    public:
        accessor(T& dest, matrix& parent) : dest(dest), parent(parent) { }
        operator T const& () const { return dest; }
        accessor& operator=(T const& t) { dest = t; parent.invalidate_cache(); return *this; }
    private:
        T& dest;
        matrix& parent;
    };

    // replace those with actual implementation..
    accessor operator()(int x, int y) {
        static T t; return accessor(t, *this);
    }
    T const& operator()(int x, int y) const {
        static T t; return t;
    }

private:
    void invalidate_cache() { cout << "Cache invalidated !!\n"; }
    vector<T> impl;
};

thanks go to to ##iso-c++ @ irc.freenode.net for some helpful corrections

OwnerDisplayName: Iraimbilanja


问:
How can I check the calling command within RowEditEnding in WPF, to be sure I want to execute the event?
I have some validation requirements to run within my RowEditEnding event handler. However, there are certain conditions under which those do not run: if the delete button is pressed, if the user goes to a detail form to work with the record, etc.

How can I check the calling command to see if one of the "Exceptions to the rule" is in play before I try to validate the data in the row?

Currently, the pseudo-code looks something like this:

```<code>private void resultsGrid_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
{
    if (!allFieldsAreValid)
    {
        e.Cancel = true;
        return;
    }
    return;
}
</code>```

I would like it to look like this:

```<code>private void resultsGrid_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
{
    if ( CommandToDeleteRow || CommandToGoToForm )
        return;
    if (!allFieldsAreValid)
    {
        e.Cancel = true;
        return;
    }
    return;
}
</code>```

Thanks!

答:
Take a look at implementing validation within the DataGrid; which will allow you to perform the validation whenever an item changes within your model at both the cell and row level.  On top of that you can also check out IEditableObject as it will allow you to implement rolling back changes within your model.

This will move you away from making use of event handlers as well and more towards an MVVM approach; which will after the initial hurdle make your life easier.

Body:
I have some validation requirements to run within my RowEditEnding event handler. However, there are certain conditions under which those do not run: if the delete button is pressed, if the user goes to a detail form to work with the record, etc.

How can I check the calling command to see if one of the "Exceptions to the rule" is in play before I try to validate the data in the row?

Currently, the pseudo-code looks something like this:

private void resultsGrid_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
{
    if (!allFieldsAreValid)
    {
        e.Cancel = true;
        return;
    }
    return;
}

I would like it to look like this:

private void resultsGrid_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
{
    if ( CommandToDeleteRow || CommandToGoToForm )
        return;
    if (!allFieldsAreValid)
    {
        e.Cancel = true;
        return;
    }
    return;
}

Thanks!


问:
Convert IloNumVar variabale of CPLEX to double in Java
I tried to read columns values from excel using java, here a part of code:

```<code>     .....
     List<ReportRow> listOfDataFromReport = new ArrayList<ReportRow>();
     for(int x = 1; x<=sheet.getPhysicalNumberOfRows(); x++){
     ReportRow rr = new ReportRow();
     HSSFRow dataRow = sheet.getRow(x);

     int idxForColumn1 = map.get("Cost");
     int idxForColumn2 = map.get("Level");

     HSSFCell cell1 = dataRow.getCell(idxForColumn1);
     HSSFCell cell2 = dataRow.getCell(idxForColumn2);

     rr.setCost(cell1.getNumericCellValue());
     rr.setLevel(cell2.getNumericCellValue());

     .....
</code>```

So the code to read data from excel works fine, the problem I have is in setters functions, because I don't have the same type, I'm using cplex solver in another class :

```<code>    private IloNumVar Cost = new IloNumVar;

    public IloNumVar getCost() {
        return Cost;
    }
    public void setCost(IloNumVar cost) {
        Cost = cost;
    }
</code>```

So I get this error :

```<code>  The method setCost is not applicable for the arguments (double)
</code>```

so I want to know if it's possible to covert IloNumVar to double or any solution to use them both, get the value as double but use it as IloNumVar.

EDIT

To explain more, I use electrical powers values(from excel) as inputs to use them to solve problem of cost with cplex solver.

To read data from excel I can only use getNumericCellValue() method of POI to get values, so I will have variables as double, but when I use them to solve my model I must use them as IloNumVar[] because I wish to optimize the value of cost of energy during 24 hours depends of values of powers taken from excel file.

答:
IloNumVar is a CPLEX / Concert class that is used to model a variable in a CPLEX model. During the model building stage, it usually does NOT have a single value. Rather, you need to specify the range of values that the IloNumVar can take, usually a lower bound and an upper bound. However, you can set the variable to always have a single value by setting the lower and upper bound of a variable to the same value. In most cases that is rare - perhaps for forcing some known values or decisions into a model for debugging.

Once you have run and solved the model, then the variable should have a single value, because CPLEX should have chosen a value for you. Then you can get that value from an IloNumVar using something like getValue().

Now an observation - in most models,things like 'costs' are known constant values, and we want CPLEX to decide how many things to use at that known cost. Typically, the costs are the coefficients of some terms in the objective function. In such cases, it would be normal to just use a double for those known values. You say nothing about your model, so we can't tell what you are using these IloNumVars for in your model and it may be a good design decision or not.

Body:
I tried to read columns values from excel using java, here a part of code:

     .....
     List<ReportRow> listOfDataFromReport = new ArrayList<ReportRow>();
     for(int x = 1; x<=sheet.getPhysicalNumberOfRows(); x++){
     ReportRow rr = new ReportRow();
     HSSFRow dataRow = sheet.getRow(x);

     int idxForColumn1 = map.get("Cost");
     int idxForColumn2 = map.get("Level");

     HSSFCell cell1 = dataRow.getCell(idxForColumn1);
     HSSFCell cell2 = dataRow.getCell(idxForColumn2);

     rr.setCost(cell1.getNumericCellValue());
     rr.setLevel(cell2.getNumericCellValue());

     .....

So the code to read data from excel works fine, the problem I have is in setters functions, because I don't have the same type, I'm using cplex solver in another class :

    private IloNumVar Cost = new IloNumVar;

    public IloNumVar getCost() {
        return Cost;
    }
    public void setCost(IloNumVar cost) {
        Cost = cost;
    }

So I get this error :

  The method setCost is not applicable for the arguments (double)

so I want to know if it's possible to covert IloNumVar to double or any solution to use them both, get the value as double but use it as IloNumVar.

EDIT

To explain more, I use electrical powers values(from excel) as inputs to use them to solve problem of cost with cplex solver.

To read data from excel I can only use getNumericCellValue() method of POI to get values, so I will have variables as double, but when I use them to solve my model I must use them as IloNumVar[] because I wish to optimize the value of cost of energy during 24 hours depends of values of powers taken from excel file.


问:
how to turn off all vim settings for golang?
How could I turn off syntax highlighting in vim, but only for Go?  </p>

<p>I've seen a few posts about just turning off the red-highlighting for white space but that's not quite what I'm looking for. </p>

答:
Considering that the vim documentation states

The syntax and highlighting commands for one language are normally stored in
  a syntax file.

  The name convention is: "{name}.vim".  Where {name} is the
  name of the language, or an abbreviation

If you can find a go.vim file (similar to this one) and delete it (or move it), that should disable the syntax highlighting just for Go.

Body:
How could I turn off syntax highlighting in vim, but only for Go?

I've seen a few posts about just turning off the red-highlighting for white space but that's not quite what I'm looking for.


问:
Joomla. How to edit the link of the Menu in default.php?
I want to edit Menu in Joomla.

Me need to replace

```<code><li class="item-101 default"><a href="/2/index.php">Светлое</a></li>
</code>```

on

```<code><li class="item-101 default"><a href="/2/index.php"><span class="MyClass">Светлое</span></a></li>
</code>```

I think this is done in this file
nameTemplate\modules\mod_menu\tmpl\default.php

or
nameTemplate\modules\mod_menu\tmpl\default_url.php

But I can not solve the problem. Can anyone help?

Thanks

答: You can add a class label under the option tab of this menu entry. This class label will add the class Name to the link</p>

Body:
I want to edit Menu in Joomla.

Me need to replace

Светлое

on

Светлое

I think this is done in this file
nameTemplate\modules\mod_menu\tmpl\default.php

or
nameTemplate\modules\mod_menu\tmpl\default_url.php

But I can not solve the problem. Can anyone help?

Thanks


问:
how to represent members in a list of list as a list in python
I have a list of lists. How can I get a specific index members in each element as a list without using a loop and assignment. Below code snippet is an example. Actual list contains more than 3 sublists. Output should be like a list say mem_lst given below.</p>

```<code>    alst = [['abc', 1 , 2], ['cde', 2, 2], ['xyz', 2, 2]]
    o/p: mem_lst = [ 'abc', 'cde', 'xyz']
</code>```

Body:
I have a list of lists. How can I get a specific index members in each element as a list without using a loop and assignment. Below code snippet is an example. Actual list contains more than 3 sublists. Output should be like a list say mem_lst given below.

    alst = [['abc', 1 , 2], ['cde', 2, 2], ['xyz', 2, 2]]
    o/p: mem_lst = [ 'abc', 'cde', 'xyz']

Body:
Without any kind of a loop:

alst = [['abc', 1 , 2], ['cde', 2, 2], ['xyz', 2, 2]]
lst = [alst[0][0],alst[1][0],alst[2][0]]
print(lst)


答:
If you have pandas this is super easy:</p>

```<code>import pandas as pd
data = pd.read_csv("data.csv")
data_dict = {col: list(data[col]) for col in data.columns}
</code>```

Title: convert csv to dictionary

Body:
I have the following csv file(total 20000 lines)

ozone,paricullate_matter,carbon_monoxide,sulfure_dioxide,nitrogen_dioxide,longitude,latitude,timestamp,avg_measured_time,avg_speed,median_measured_time,timestamp:1,vehicle_count,lat1,long1,lat2,long2,distance_between_2_points,duration_of_measurement,ndt_in_kmh
99,99,98,116,118,10.09351660921,56.1671665604395,1407575099.99998,0,0,0,1407575099.99998,0,56.1089513576227,10.1823955595246,56.1048021343541,10.1988040846558,1124,65,62
99,99,98,116,118,10.09351660921,56.1671665604395,1407575099.99998,0,0,0,1407575099.99998,0,56.10986429895,10.1627288048935,56.1089513576227,10.1823955595246,1254,71,64
99,99,98,116,118,10.09351660921,56.1671665604395,1407575099.99998,0,0,0,1407575099.99998,0,56.1425188527673,10.1868802625656,56.1417522836526,10.1927236478157,521,62,30
99,99,98,116,118,10.09351660921,56.1671665604395,1407575099.99998,18,84,18,1407575099.99998,1,56.1395320665735,10.1772034087371,56.1384485157567,10.1791506011887,422,50,30

I want to convert this into a dictionary like

{'ozone': [99,99,99,99], 'paricullate_matter': [99,99,99,99],'carbon_monoxide': [98,98,98,98],etc....}

What i have tried

import csv

reader = csv.DictReader(open('resulttable.csv'))

output = open("finalprojdata.py","w")

result = {}
for row in reader:
    for column, value in row.iteritems():
        result.setdefault(column, []).append(float(value))
output.write(str(result))

The output am getting is consisting of only few dictionaries. Like from

{'vehicle_count': [0,0,0,1], 'lat1': etc}

The whole csv file is not getting converted to dictionary.

Body:
If you have pandas this is super easy:

import pandas as pd
data = pd.read_csv("data.csv")
data_dict = {col: list(data[col]) for col in data.columns}


问:
Adding txt file attachment to outgoing email in an Android project
I have these two files which enable the sending an email in the background of an Android app.
How can I modify the existing code to add and send an attachment?
The attachment would be just a regular .txt file.

```<code>import android.util.Log;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class GMail {

final String emailPort = "587";// gmail's smtp port
final String smtpAuth = "true";
final String starttls = "true";
final String emailHost = "smtp.gmail.com";

String fromEmail;
String fromPassword;
List<String> toEmailList;
String emailSubject;
String emailBody;

Properties emailProperties;
Session mailSession;
MimeMessage emailMessage;

public GMail() {

}

public GMail(String fromEmail, String fromPassword,
             List<String> toEmailList, String emailSubject, String
emailBody) {
    this.fromEmail = fromEmail;
    this.fromPassword = fromPassword;
    this.toEmailList = toEmailList;
    this.emailSubject = emailSubject;
    this.emailBody = emailBody;

    emailProperties = System.getProperties();
    emailProperties.put("mail.smtp.port", emailPort);
    emailProperties.put("mail.smtp.auth", smtpAuth);
    emailProperties.put("mail.smtp.starttls.enable", starttls);
    Log.i("GMail", "Mail server properties set.");
}

public MimeMessage createEmailMessage() throws AddressException,
        MessagingException, UnsupportedEncodingException {

    mailSession = Session.getDefaultInstance(emailProperties, null);
    emailMessage = new MimeMessage(mailSession);

    emailMessage.setFrom(new InternetAddress(fromEmail, fromEmail));
    for (String toEmail : toEmailList) {
        Log.i("GMail", "toEmail: " + toEmail);
        emailMessage.addRecipient(Message.RecipientType.TO,
                new InternetAddress(toEmail));
    }

    emailMessage.setSubject(emailSubject);
    emailMessage.setContent(emailBody, "text/html");// for a html email
    // emailMessage.setText(emailBody);// for a text email
    Log.i("GMail", "Email Message created.");
    return emailMessage;
}

public void sendEmail() throws AddressException, MessagingException {

    Transport transport = mailSession.getTransport("smtp");
    transport.connect(emailHost, fromEmail, fromPassword);
    Log.i("GMail", "allrecipients: " + emailMessage.getAllRecipients());
    transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
    transport.close();
    Log.i("GMail", "Email sent successfully.");
}

}
</code>```

And

```<code>import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;

public class SendMailTask extends AsyncTask {

private ProgressDialog statusDialog;
private Activity sendMailActivity;

public SendMailTask(Activity activity) {
    sendMailActivity = activity;

}

protected void onPreExecute() {
    statusDialog = new ProgressDialog(sendMailActivity);
    statusDialog.setMessage("Getting ready...");
    statusDialog.setIndeterminate(false);
    statusDialog.setCancelable(false);
    statusDialog.show();
}

@Override
protected Object doInBackground(Object... args) {
    String senderEmail = "XXXXX@gmail.com"; // XXXXXXXXXX
    String senderPassword = "XXXXXX"; // XXXXXXXXX
    String subject = args[0].toString();
    String body = args[1].toString();
    List emailRecipients = new ArrayList();
    emailRecipients.add("XXXXXXX@hotmail.com");

    try {
        Log.i("SendMailTask", "About to instantiate GMail...");
        publishProgress("Processing input....");

        GMail gMail = new GMail(
                senderEmail,
                senderPassword,
                emailRecipients,
                subject,
                body);

        publishProgress("Preparing mail message....");
        gMail.createEmailMessage();
        publishProgress("Sending email....");
        gMail.sendEmail();
        publishProgress("Email Sent.");
        Log.i("SendMailTask", "Mail Sent.");
    } catch (Exception e) {
        publishProgress(e.getMessage());
        Log.e("SendMailTask", e.getMessage(), e);
    }
    return null;
}

@Override
public void onProgressUpdate(Object... values) {
    statusDialog.setMessage(values[0].toString());

}

@Override
public void onPostExecute(Object result) {
    statusDialog.dismiss();
}

}
</code>```

答:
I figured it out, see the modified method below. Cheers!     </p>

```<code>public GMail(String fromEmail, String fromPassword,
             List<String> toEmailList, String emailSubject, String emailBody, List<String> attachmentFileNames) throws MessagingException {
    this.fromEmail = fromEmail;
    this.fromPassword = fromPassword;
    this.toEmailList = toEmailList;
    this.emailSubject = emailSubject;
    this.emailBody = emailBody;

    emailProperties = System.getProperties();
    emailProperties.put("mail.smtp.port", emailPort);
    emailProperties.put("mail.smtp.auth", smtpAuth);
    emailProperties.put("mail.smtp.starttls.enable", starttls);
    Log.i("GMail", "Mail server properties set.");

    if (attachmentFileNames != null && !attachmentFileNames.isEmpty()) {
        for (String filename : attachmentFileNames) {
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(filename);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(filename);

            attachments.add(messageBodyPart);
        }
    }
}

public MimeMessage createEmailMessage() throws AddressException,
        MessagingException, UnsupportedEncodingException {

    mailSession = Session.getDefaultInstance(emailProperties, null);
    emailMessage = new MimeMessage(mailSession);

    emailMessage.setFrom(new InternetAddress(fromEmail, fromEmail));
    for (String toEmail : toEmailList) {
        Log.i("GMail", "toEmail: " + toEmail);
        emailMessage.addRecipient(Message.RecipientType.TO,
                new InternetAddress(toEmail));
    }

    emailMessage.setSubject(emailSubject);

    if (attachments.size() > 0) {
        // Create the message part
        BodyPart messageBodyPart = new MimeBodyPart();

        // Now set the actual message
        messageBodyPart.setContent(emailBody, "text/html");

        // Create a multipart message
        Multipart multipart = new MimeMultipart();

        // Set text message part
        multipart.addBodyPart(messageBodyPart);

        // attachments
        for (MimeBodyPart att : attachments) {
            multipart.addBodyPart(att);
        }

        // Send the complete message parts
        emailMessage.setContent(multipart);
    } else {
        emailMessage.setContent(emailBody, "text/html");// for a html email
    }

    // emailMessage.setText(emailBody);// for a text email
    Log.i("GMail", "Email Message created.");
    return emailMessage;
}
</code>```

Body:
I have these two files which enable the sending an email in the background of an Android app.
How can I modify the existing code to add and send an attachment?
The attachment would be just a regular .txt file.

import android.util.Log;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class GMail {

final String emailPort = "587";// gmail's smtp port
final String smtpAuth = "true";
final String starttls = "true";
final String emailHost = "smtp.gmail.com";

String fromEmail;
String fromPassword;
List<String> toEmailList;
String emailSubject;
String emailBody;

Properties emailProperties;
Session mailSession;
MimeMessage emailMessage;

public GMail() {

}

public GMail(String fromEmail, String fromPassword,
             List<String> toEmailList, String emailSubject, String
emailBody) {
    this.fromEmail = fromEmail;
    this.fromPassword = fromPassword;
    this.toEmailList = toEmailList;
    this.emailSubject = emailSubject;
    this.emailBody = emailBody;

    emailProperties = System.getProperties();
    emailProperties.put("mail.smtp.port", emailPort);
    emailProperties.put("mail.smtp.auth", smtpAuth);
    emailProperties.put("mail.smtp.starttls.enable", starttls);
    Log.i("GMail", "Mail server properties set.");
}

public MimeMessage createEmailMessage() throws AddressException,
        MessagingException, UnsupportedEncodingException {

    mailSession = Session.getDefaultInstance(emailProperties, null);
    emailMessage = new MimeMessage(mailSession);

    emailMessage.setFrom(new InternetAddress(fromEmail, fromEmail));
    for (String toEmail : toEmailList) {
        Log.i("GMail", "toEmail: " + toEmail);
        emailMessage.addRecipient(Message.RecipientType.TO,
                new InternetAddress(toEmail));
    }

    emailMessage.setSubject(emailSubject);
    emailMessage.setContent(emailBody, "text/html");// for a html email
    // emailMessage.setText(emailBody);// for a text email
    Log.i("GMail", "Email Message created.");
    return emailMessage;
}

public void sendEmail() throws AddressException, MessagingException {

    Transport transport = mailSession.getTransport("smtp");
    transport.connect(emailHost, fromEmail, fromPassword);
    Log.i("GMail", "allrecipients: " + emailMessage.getAllRecipients());
    transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
    transport.close();
    Log.i("GMail", "Email sent successfully.");
}

}

And

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;

public class SendMailTask extends AsyncTask {

private ProgressDialog statusDialog;
private Activity sendMailActivity;

public SendMailTask(Activity activity) {
    sendMailActivity = activity;

}

protected void onPreExecute() {
    statusDialog = new ProgressDialog(sendMailActivity);
    statusDialog.setMessage("Getting ready...");
    statusDialog.setIndeterminate(false);
    statusDialog.setCancelable(false);
    statusDialog.show();
}

@Override
protected Object doInBackground(Object... args) {
    String senderEmail = "XXXXX@gmail.com"; // XXXXXXXXXX
    String senderPassword = "XXXXXX"; // XXXXXXXXX
    String subject = args[0].toString();
    String body = args[1].toString();
    List emailRecipients = new ArrayList();
    emailRecipients.add("XXXXXXX@hotmail.com");

    try {
        Log.i("SendMailTask", "About to instantiate GMail...");
        publishProgress("Processing input....");

        GMail gMail = new GMail(
                senderEmail,
                senderPassword,
                emailRecipients,
                subject,
                body);

        publishProgress("Preparing mail message....");
        gMail.createEmailMessage();
        publishProgress("Sending email....");
        gMail.sendEmail();
        publishProgress("Email Sent.");
        Log.i("SendMailTask", "Mail Sent.");
    } catch (Exception e) {
        publishProgress(e.getMessage());
        Log.e("SendMailTask", e.getMessage(), e);
    }
    return null;
}

@Override
public void onProgressUpdate(Object... values) {
    statusDialog.setMessage(values[0].toString());

}

@Override
public void onPostExecute(Object result) {
    statusDialog.dismiss();
}

}

Body:
I figured it out, see the modified method below. Cheers!

public GMail(String fromEmail, String fromPassword,
             List<String> toEmailList, String emailSubject, String emailBody, List<String> attachmentFileNames) throws MessagingException {
    this.fromEmail = fromEmail;
    this.fromPassword = fromPassword;
    this.toEmailList = toEmailList;
    this.emailSubject = emailSubject;
    this.emailBody = emailBody;

    emailProperties = System.getProperties();
    emailProperties.put("mail.smtp.port", emailPort);
    emailProperties.put("mail.smtp.auth", smtpAuth);
    emailProperties.put("mail.smtp.starttls.enable", starttls);
    Log.i("GMail", "Mail server properties set.");

    if (attachmentFileNames != null && !attachmentFileNames.isEmpty()) {
        for (String filename : attachmentFileNames) {
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(filename);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(filename);

            attachments.add(messageBodyPart);
        }
    }
}

public MimeMessage createEmailMessage() throws AddressException,
        MessagingException, UnsupportedEncodingException {

    mailSession = Session.getDefaultInstance(emailProperties, null);
    emailMessage = new MimeMessage(mailSession);

    emailMessage.setFrom(new InternetAddress(fromEmail, fromEmail));
    for (String toEmail : toEmailList) {
        Log.i("GMail", "toEmail: " + toEmail);
        emailMessage.addRecipient(Message.RecipientType.TO,
                new InternetAddress(toEmail));
    }

    emailMessage.setSubject(emailSubject);

    if (attachments.size() > 0) {
        // Create the message part
        BodyPart messageBodyPart = new MimeBodyPart();

        // Now set the actual message
        messageBodyPart.setContent(emailBody, "text/html");

        // Create a multipart message
        Multipart multipart = new MimeMultipart();

        // Set text message part
        multipart.addBodyPart(messageBodyPart);

        // attachments
        for (MimeBodyPart att : attachments) {
            multipart.addBodyPart(att);
        }

        // Send the complete message parts
        emailMessage.setContent(multipart);
    } else {
        emailMessage.setContent(emailBody, "text/html");// for a html email
    }

    // emailMessage.setText(emailBody);// for a text email
    Log.i("GMail", "Email Message created.");
    return emailMessage;
}


问:
Getting values of textfields on page
Lets just say that I have some (many many many) text fields on a page... and i enter a new value in one of them, then click a button... How can I update the database with just that new value? Or, if it would be easier... How can I update all of those textfields to the database?

Thanks :)

答:
identify textfield values: every textfield is supposed to have a "name" attribute:

```<code> <input type="text" name="firstName" value="please enter your first name"/>
</code>```

you can the access the value of the textfield "foo" with $_POST["foo"]
To know if the field was changed you must compare it with the default value.

```<code>if($_POST["firstName"]!="please enter your first name"){
   /*do databse update*/
}
</code>```

How exactly you do the database update depends on your application.

Title: Getting values of textfields on page

Body:
identify textfield values: every textfield is supposed to have a "name" attribute:

 <input type="text" name="firstName" value="please enter your first name"/>

you can the access the value of the textfield "foo" with $_POST["foo"]
To know if the field was changed you must compare it with the default value.

if($_POST["firstName"]!="please enter your first name"){
   /*do databse update*/
}

How exactly you do the database update depends on your application.


问:
npm install angular/cli error
node -v 8 and npm -v 5. Trying to install angular/cli globally from yesterday. Facing new error everytime.

Vipins-Air:~ vipingupta$ sudo npm install -g @angular/cli
      npm ERR! code ETIMEDOUT
      npm ERR! errno ETIMEDOUT
      npm ERR! network request to http://registry.npmjs.org/@angular%2fcli failed, reason: connect ETIMEDOUT 74.122.238.10:8080
      npm ERR! network This is a problem related to network connectivity.
      npm ERR! network In most cases you are behind a proxy or have bad network settings.
      npm ERR! network
      npm ERR! network If you are behind a proxy, please make sure that the
      npm ERR! network 'proxy' config is set properly.  See: 'npm help config'
      npm ERR! A complete log of this run can be found in:
      npm ERR!     /Users/vipingupta/C:Devnodejsnpm-cache/_logs/2017-06-07T06_37_13_337Z-debug.log

答:
Try to clean cache
"npm cache clean"

uninstall angular-cli
"npm uninstall -g angular-cli"

install again
"npm install -g angular-cli"

If this doesn't work, use Force flag (-f).

And also make sure your network connection is descent.

Title: npm install angular/cli error


问:
How can I polyfill Promise with webpack?
I'm using webpack to bundle up my JavaScript. I'm depending on modules like popsicle which use any-promise.

Here's my code:

```<code>var popsicle = require('popsicle');
popsicle.get('/').then(function() {
  console.log('loaded URL');
});
</code>```

This works fine in browsers where Promise is available, but IE 11 does not provide Promise. So I want to use es6-promise as a polyfill.

I tried adding an explicit ProvidePlugin to my webpack.config.js:

```<code>plugins: [
  new webpack.ProvidePlugin({
    'Promise': 'exports?global.Promise!es6-promise'
  })
]
</code>```

But I still get the error in IE 11: any-promise browser requires a polyfill or explicit registration e.g: require('any-promise/register/bluebird').

I tried explicitly attaching a global:

```<code>global.Promise = global.Promise || require('es6-promise');
</code>```

But IE 11 gives a different error: Object doesn't support this action.

I also tried explicitly registering es6-promise:

```<code>require('any-promise/register/es6-promise');
var popsicle = require('popsicle');
</code>```

This works, but I have to do it in every single file that loads popsicle. I want to just attach Promise to window.

How can I ensure window.Promise is always defined, using webpack?

Full repo demo here.

答:
babel polyfill usually works, but this time for a vuejs(webpack1) project, somehow not working.

Fortunately, core-js works as a charm.

```<code>npm install core-js --save

module.exports = {
   entry: ['core-js/fn/promise', './app/js']
};
</code>```

Body:
I'm using webpack to bundle up my JavaScript. I'm depending on modules like popsicle which use any-promise.

Here's my code:

var popsicle = require('popsicle');
popsicle.get('/').then(function() {
  console.log('loaded URL');
});

This works fine in browsers where Promise is available, but IE 11 does not provide Promise. So I want to use es6-promise as a polyfill.

I tried adding an explicit ProvidePlugin to my webpack.config.js:

plugins: [
  new webpack.ProvidePlugin({
    'Promise': 'exports?global.Promise!es6-promise'
  })
]

But I still get the error in IE 11: any-promise browser requires a polyfill or explicit registration e.g: require('any-promise/register/bluebird').

I tried explicitly attaching a global:

global.Promise = global.Promise || require('es6-promise');

But IE 11 gives a different error: Object doesn't support this action.

I also tried explicitly registering es6-promise:

require('any-promise/register/es6-promise');
var popsicle = require('popsicle');

This works, but I have to do it in every single file that loads popsicle. I want to just attach Promise to window.

How can I ensure window.Promise is always defined, using webpack?

Full repo demo here.

Body:
babel polyfill usually works, but this time for a vuejs(webpack1) project, somehow not working.

Fortunately, core-js works as a charm.

npm install core-js --save

module.exports = {
   entry: ['core-js/fn/promise', './app/js']
};


问:
Printing last name + first name - but it shows error (Java)
So I have made a code for user to enter their first and last name; then exhanging the two position.

for example. Bulota Babi becomes Babi, Bulota

this is my code

```<code>public class trial {
    public static void main(String [] args) {
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();

        String fname = input.substring(0, input.indexOf(0));
        String lname = input.substring(1, input.indexOf(input.length()));

        System.out.println(lname +","+ fname);
    }

}
</code>```

im not sure whats wrong with it, this is the error message

```<code>Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.String.substring(String.java:1967)
    at trial.main(trial.java:11)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
</code>```

答:
The problem is in substring method. It needs start and end positions of string to cut out from:

```<code>public static void main(String args[]) throws IOException {
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();

        int coma = input.indexOf(' ');
        String fname = input.substring(0, coma);
        String lname = input.substring(coma + 1, input.length());

        System.out.println(lname + "," + fname);

    }
</code>```

Body:
So I have made a code for user to enter their first and last name; then exhanging the two position.

for example. Bulota Babi becomes Babi, Bulota

this is my code

public class trial {
    public static void main(String [] args) {
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();

        String fname = input.substring(0, input.indexOf(0));
        String lname = input.substring(1, input.indexOf(input.length()));

        System.out.println(lname +","+ fname);
    }

}

im not sure whats wrong with it, this is the error message

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.String.substring(String.java:1967)
    at trial.main(trial.java:11)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

Body:
The problem is in substring method. It needs start and end positions of string to cut out from:

public static void main(String args[]) throws IOException {
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();

        int coma = input.indexOf(' ');
        String fname = input.substring(0, coma);
        String lname = input.substring(coma + 1, input.length());

        System.out.println(lname + "," + fname);

    }


问:
get_post_meta() to JSON
I have a generated data from get_post_meta which I need to convert it to JSON. The generated array are as follows:

```<code>Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => Array
                        (
                            [rate] => 5
                            [review] => Array
                                (
                                    [content] => Test Review
                                    [custom_field_1] => Azman Ishak
                                    [custom_field_2] => Selagnor
                                    [date] =>  2017-06-06  , 15:06
                                    [title] =>
                                    [status] => publish
                                    [weight] => 5
                                )

                            [user] => Array
                                (
                                    [name] => ebeneadmin
                                    [email] => azman@considerdigital.com
                                    [id] => 1
                                    [ip] => 115.135.10.5
                                )

                        )

                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [0] => Array
                        (
                            [rate] => 4
                            [review] => Array
                                (
                                    [content] => Test review 2
                                    [custom_field_1] => Azman
                                    [custom_field_2] => Beranang
                                    [date] =>  2017-06-06  , 16:01
                                    [title] =>
                                    [status] => publish
                                    [weight] => 5
                                )

                            [user] => Array
                                (
                                    [name] => Azman Ishak
                                    [email] => azmunk@gmail.com
                                    [id] =>
                                    [ip] => 115.135.10.5
                                )

                        )

                )

        )

    [2] => Array
        (
            [0] => Array
                (
                )

        )

)
</code>```

The value that I need to get from the above arrays are:

rate

content

custom_field_1

custom_field_2

date

title

status

This data need to be converted into JSON.

答:
Try this:

convert your get_post_meta result with json_encode();

it will make your result to be

```<code><?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

echo json_encode($arr);
?>
</code>```

Output:

```<code>{"a":1,"b":2,"c":3,"d":4,"e":5}
</code>```

Title: get_post_meta() to JSON

Body:
I have a generated data from get_post_meta which I need to convert it to JSON. The generated array are as follows:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => Array
                        (
                            [rate] => 5
                            [review] => Array
                                (
                                    [content] => Test Review
                                    [custom_field_1] => Azman Ishak
                                    [custom_field_2] => Selagnor
                                    [date] =>  2017-06-06  , 15:06
                                    [title] =>
                                    [status] => publish
                                    [weight] => 5
                                )

                            [user] => Array
                                (
                                    [name] => ebeneadmin
                                    [email] => azman@considerdigital.com
                                    [id] => 1
                                    [ip] => 115.135.10.5
                                )

                        )

                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [0] => Array
                        (
                            [rate] => 4
                            [review] => Array
                                (
                                    [content] => Test review 2
                                    [custom_field_1] => Azman
                                    [custom_field_2] => Beranang
                                    [date] =>  2017-06-06  , 16:01
                                    [title] =>
                                    [status] => publish
                                    [weight] => 5
                                )

                            [user] => Array
                                (
                                    [name] => Azman Ishak
                                    [email] => azmunk@gmail.com
                                    [id] =>
                                    [ip] => 115.135.10.5
                                )

                        )

                )

        )

    [2] => Array
        (
            [0] => Array
                (
                )

        )

)

The value that I need to get from the above arrays are:

rate

content

custom_field_1

custom_field_2

date

title

status

This data need to be converted into JSON.

Body:
Try this:

convert your get_post_meta result with json_encode();

it will make your result to be

<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

echo json_encode($arr);
?>

Output:

{"a":1,"b":2,"c":3,"d":4,"e":5}


问:
Android : How to get rid of weird border around progress dialog
I have made my custom style for progress dialog, however it has weird borders around it.

Here is the theme:

```<code><style name="AppTheme.Dialog" parent="Theme.AppCompat.Light.Dialog">
    <item name="colorAccent">@android:color/white</item>
    <item name="android:textColorPrimary">@android:color/white</item>
    <item name="android:background">@color/colorPrimaryDark</item>
    <item name="android:popupBackground">@null</item>
</style>
</code>```

Any ideas why there is such weird background ?

答:
I may be late to answer this question, but as I was facing same problem, I resolved it as follows:

I created 2 styles one for above lollipop and one for below it.

API Level greater than 19

```<code><style name="AppAlertTheme" parent="Theme.AppCompat.Light.Dialog">
        <item name="colorAccent">@color/white</item>
        <item name="android:textColorPrimary">@color/transparent</item>
        <item name="android:background">@color/blue</item>
        <item name="android:windowBackground">@color/transparent</item>
        <item name="android:popupBackground">@null</item>
</style>
</code>```

API Level less than 19

```<code><style name="AppAlertTheme_api19" parent="android:Theme.Holo.Dialog">
     <item name="android:alertDialogStyle">@style/CustomAlertDialogStyle</item>
    <item name="android:windowBackground">@color/nlue</item>
    <item name="android:background">@android:color/transparent</item>
    <item name="android:backgroundDimEnabled">false</item>
    <item name="android:textColor">@color/white</item>
</style>

<style name="CustomAlertDialogStyle">
        <item name="android:bottomBright">@android:color/transparent</item>
        <item name="android:bottomDark">@android:color/transparent</item>
        <item name="android:bottomMedium">@android:color/transparent</item>
        <item name="android:centerBright">@android:color/transparent</item>
        <item name="android:centerDark">@android:color/transparent</item>
        <item name="android:centerMedium">@android:color/transparent</item>
        <item name="android:fullBright">@android:color/transparent</item>
        <item name="android:fullDark">@android:color/transparent</item>
        <item name="android:topBright">@android:color/transparent</item>
        <item name="android:topDark">@android:color/transparent</item>
    </style>
</code>```

Then used this style as follows:

```<code>public int getProgressDailogStyle(){
  if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
      return R.style.AppAlertTheme;
  } else {
      return R.style.AppAlertTheme_api19;
  }
}
</code>```

and finally

```<code>   progressDialog = new ProgressDialog(context, getProgressDailogStyle());
</code>```

Hope this helps you..

Body:
I have made my custom style for progress dialog, however it has weird borders around it.

Here is the theme:

Any ideas why there is such weird background ?

Body:
I may be late to answer this question, but as I was facing same problem, I resolved it as follows:

I created 2 styles one for above lollipop and one for below it.

API Level greater than 19

<style name="AppAlertTheme" parent="Theme.AppCompat.Light.Dialog">
        <item name="colorAccent">@color/white</item>
        <item name="android:textColorPrimary">@color/transparent</item>
        <item name="android:background">@color/blue</item>
        <item name="android:windowBackground">@color/transparent</item>
        <item name="android:popupBackground">@null</item>
</style>

API Level less than 19

<style name="AppAlertTheme_api19" parent="android:Theme.Holo.Dialog">
     <item name="android:alertDialogStyle">@style/CustomAlertDialogStyle</item>
    <item name="android:windowBackground">@color/nlue</item>
    <item name="android:background">@android:color/transparent</item>
    <item name="android:backgroundDimEnabled">false</item>
    <item name="android:textColor">@color/white</item>
</style>

<style name="CustomAlertDialogStyle">
        <item name="android:bottomBright">@android:color/transparent</item>
        <item name="android:bottomDark">@android:color/transparent</item>
        <item name="android:bottomMedium">@android:color/transparent</item>
        <item name="android:centerBright">@android:color/transparent</item>
        <item name="android:centerDark">@android:color/transparent</item>
        <item name="android:centerMedium">@android:color/transparent</item>
        <item name="android:fullBright">@android:color/transparent</item>
        <item name="android:fullDark">@android:color/transparent</item>
        <item name="android:topBright">@android:color/transparent</item>
        <item name="android:topDark">@android:color/transparent</item>
    </style>

Then used this style as follows:

public int getProgressDailogStyle(){
  if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
      return R.style.AppAlertTheme;
  } else {
      return R.style.AppAlertTheme_api19;
  }
}

and finally

   progressDialog = new ProgressDialog(context, getProgressDailogStyle());

Hope this helps you..


问:
Why can we supply a Comparator to TreeSet but not something like Hasher to HashSet?
In Java 6, my understanding is that you can supply a Comparator to a TreeSet when creating it to override the "natural ordering" of the objects in the set.

Do you have any thoughts why Java doesn't support supplying a "Hasher" that overrides the "natural hashing" of objects in the set as well?

EDIT:
Getting input from you might help me when designing APIs in the future.

Thanks.

答:
Here are several likely reasons:

Simplicity - most people don't need multiple hash functions, so to keep the API simple it makes sense to rely on a single Object.hashCode() approach

Performance - In the standard library at least,
HashSets and HashMaps etc. need to be
pretty heavily optimised as they are
so widely used. It doesn't make sense
to have the overhead of calling a
separate "hasher", however small that
overhead may be.

Private fields - there is the issue that
hashCode() may rely on private
fields, it may be difficult to
create external "hashers" for some
objects.


问:
Magento Localhost only homepage is working
I have downloaded my website files and db from the live server to XAMPP.
I replaced the db details and the urls in config_core_data.
Also, mod_rewrite is on.
ONLY homepage is working.

The products links and admin as well link to my live websites links.
Here is my .htaccess file

```<code># All explanations you could find in .htaccess.sample file
  DirectoryIndex index.php
 <IfModule mod_php5.c>
  php_value memory_limit 768M
 php_value max_execution_time 18000
 php_flag session.auto_start off
 php_flag suhosin.session.cryptua off
 </IfModule>
 <IfModule mod_php7.c>
 php_value memory_limit 768M
 php_value max_execution_time 18000
 php_flag session.auto_start off
 php_flag suhosin.session.cryptua off
 </IfModule>
 <IfModule mod_security.c>
 SecFilterEngine Off
 SecFilterScanPOST Off
 </IfModule>
 <IfModule mod_ssl.c>
SSLOptions StdEnvVars
 </IfModule>
 <IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine on
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteCond %{REQUEST_METHOD} ^TRAC[EK]
RewriteRule .* - [L,R=405]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule .* index.php [L]
</IfModule>
AddDefaultCharset Off
AddType 'text/html; charset=UTF-8' html
<IfModule mod_expires.c>
ExpiresDefault "access plus 1 year"
ExpiresByType text/html A0
ExpiresByType text/plain A0
</IfModule>
RedirectMatch 403 /\.git
<Files composer.json>
    order allow,deny
    deny from all
</Files>
<Files composer.lock>
    order allow,deny
    deny from all
</Files>
<Files .gitignore>
    order allow,deny
    deny from all
</Files>
<Files .htaccess>
    order allow,deny
    deny from all
</Files>
<Files .htaccess.sample>
    order allow,deny
    deny from all
</Files>
<Files .php_cs>
    order allow,deny
    deny from all
</Files>
<Files .travis.yml>
    order allow,deny
    deny from all
</Files>
<Files CHANGELOG.md>
    order allow,deny
    deny from all
</Files>
<Files CONTRIBUTING.md>
    order allow,deny
    deny from all
</Files>
<Files COPYING.txt>
    order allow,deny
    deny from all
</Files>
<Files Gruntfile.js>
    order allow,deny
    deny from all
</Files>
<Files LICENSE.txt>
    order allow,deny
    deny from all
</Files>
<Files LICENSE_AFL.txt>
    order allow,deny
    deny from all
</Files>
<Files nginx.conf.sample>
    order allow,deny
    deny from all
</Files>
<Files package.json>
    order allow,deny
    deny from all
</Files>
<Files php.ini.sample>
    order allow,deny
    deny from all
</Files>
<Files README.md>
    order allow,deny
    deny from all
</Files>
<Files magento_umask>
    order allow,deny
    deny from all
</Files>
 ErrorDocument 404 /pub/errors/404.php
  ErrorDocument 403 /pub/errors/404.php
  <IfModule mod_headers.c>
Header set X-UA-Compatible "IE=edge"
<FilesMatch "\.(appcache|atom|bbaw|bmp|crx|css|cur|eot|f4[abpv]|flv|geojson|gif|htc|ico|jpe?g|js|json(ld)?|m4[av]|manifest|map|mp4|oex|og[agv]|opus|otf|pdf|png|rdf|rss|safariextz|svgz?|swf|topojson|tt[cf]|txt|vcard|vcf|vtt|webapp|web[mp]|webmanifest|woff2?|xloc|xml|xpi)$">
    Header unset X-UA-Compatible
</FilesMatch>
</code>```

I have tried even replacing the .htaccess with a new one, it doesn't work.
Can somebody help?

答:
Whenever we take anything from live to local machine & testing in local :-
1) We should use only plain .htaccess (means default one) not the live one.
2) In core_config_data table we need to replace 2 urls secure & unsecure
3) In local.xml please make sure DB name, Host, DB Username & DB Passwords all are correct. In Host, use only - localhost
4) Delete var folder itself.
5) Check the file permissions

Also please check whether there is a use of CDN. If live site is using CDN then in local pc please try changing the value of media urls, skin urls & js in System -> Configuration -> General -> Web to simple ones like this :

In Unsecure media url - {{unsecure_base_url}}media/
In Secure media url - {{secure_base_url}}media/

Please check var/log folder in exception.log & system.log
Please try to resolve that if possible.
If still not getting any idea then try disabling custom modules one by one & check if frontend is working fine or not.

Also make sure you must have these things in default .htaccess you use :
php_value memory_limit 768M
php_value max_execution_time 18000

Thank you.

Body:
I have downloaded my website files and db from the live server to XAMPP.
I replaced the db details and the urls in config_core_data.
Also, mod_rewrite is on.
ONLY homepage is working.

The products links and admin as well link to my live websites links.
Here is my .htaccess file

# All explanations you could find in .htaccess.sample file
  DirectoryIndex index.php
 <IfModule mod_php5.c>
  php_value memory_limit 768M
 php_value max_execution_time 18000
 php_flag session.auto_start off
 php_flag suhosin.session.cryptua off
 </IfModule>
 <IfModule mod_php7.c>
 php_value memory_limit 768M
 php_value max_execution_time 18000
 php_flag session.auto_start off
 php_flag suhosin.session.cryptua off
 </IfModule>
 <IfModule mod_security.c>
 SecFilterEngine Off
 SecFilterScanPOST Off
 </IfModule>
 <IfModule mod_ssl.c>
SSLOptions StdEnvVars
 </IfModule>
 <IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine on
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteCond %{REQUEST_METHOD} ^TRAC[EK]
RewriteRule .* - [L,R=405]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule .* index.php [L]
</IfModule>
AddDefaultCharset Off
AddType 'text/html; charset=UTF-8' html
<IfModule mod_expires.c>
ExpiresDefault "access plus 1 year"
ExpiresByType text/html A0
ExpiresByType text/plain A0
</IfModule>
RedirectMatch 403 /\.git
<Files composer.json>
    order allow,deny
    deny from all
</Files>
<Files composer.lock>
    order allow,deny
    deny from all
</Files>
<Files .gitignore>
    order allow,deny
    deny from all
</Files>
<Files .htaccess>
    order allow,deny
    deny from all
</Files>
<Files .htaccess.sample>
    order allow,deny
    deny from all
</Files>
<Files .php_cs>
    order allow,deny
    deny from all
</Files>
<Files .travis.yml>
    order allow,deny
    deny from all
</Files>
<Files CHANGELOG.md>
    order allow,deny
    deny from all
</Files>
<Files CONTRIBUTING.md>
    order allow,deny
    deny from all
</Files>
<Files COPYING.txt>
    order allow,deny
    deny from all
</Files>
<Files Gruntfile.js>
    order allow,deny
    deny from all
</Files>
<Files LICENSE.txt>
    order allow,deny
    deny from all
</Files>
<Files LICENSE_AFL.txt>
    order allow,deny
    deny from all
</Files>
<Files nginx.conf.sample>
    order allow,deny
    deny from all
</Files>
<Files package.json>
    order allow,deny
    deny from all
</Files>
<Files php.ini.sample>
    order allow,deny
    deny from all
</Files>
<Files README.md>
    order allow,deny
    deny from all
</Files>
<Files magento_umask>
    order allow,deny
    deny from all
</Files>
 ErrorDocument 404 /pub/errors/404.php
  ErrorDocument 403 /pub/errors/404.php
  <IfModule mod_headers.c>
Header set X-UA-Compatible "IE=edge"
<FilesMatch "\.(appcache|atom|bbaw|bmp|crx|css|cur|eot|f4[abpv]|flv|geojson|gif|htc|ico|jpe?g|js|json(ld)?|m4[av]|manifest|map|mp4|oex|og[agv]|opus|otf|pdf|png|rdf|rss|safariextz|svgz?|swf|topojson|tt[cf]|txt|vcard|vcf|vtt|webapp|web[mp]|webmanifest|woff2?|xloc|xml|xpi)$">
    Header unset X-UA-Compatible
</FilesMatch>

I have tried even replacing the .htaccess with a new one, it doesn't work.
Can somebody help?


问:
JDBC Connection close conecpt
I have created connection's object and stored in the hashMap. While executing query on the connection object I retrieve the object from the hashMap. In finally block I close the connection.
However, when we come for the second time I again retrieve the connection's object from the hashMap. This time while executing the query I get closed connection exception.
If I remove conn.close() from finally, it works.
what is the reason behind this? Moreover, when i print the connection's object I get the object.</p>

答:
I think you have to go for a connection  pool implementation instead of a simple Map of connections. Here when you close a connection after each transaction, the life cycle of the connection ends, and you can not reuse it from the map. </p>

<p>Think of a connection pool which can get you an already opened connection, and return/release the connection back to the pool once your usage is done. </p>

Title: JDBC Connection close conecpt

Body:
I think you have to go for a connection  pool implementation instead of a simple Map of connections. Here when you close a connection after each transaction, the life cycle of the connection ends, and you can not reuse it from the map.

Think of a connection pool which can get you an already opened connection, and return/release the connection back to the pool once your usage is done.


问:
Can Mobile Vision API detect Chinese, Japanese and Korean?
Is it possible for Mobile Vision API to detect Chinese, Japanese and Korean?
If not, is there any way to detect these language in Android?</p>

答:
You can detect Chinese, Japanese and Korean Tesseract but you will not get 100% result.

Tutorial Link :

http://imperialsoup.com/2016/04/29/simple-ocr-android-app-using-tesseract-tutorial/

other Language Data files :

https://github.com/tesseract-ocr/tessdata

Sample Links:

https://github.com/rmtheis/tess-two

https://github.com/imperialsoup/SimpleTesseractExample


问:
Zend Forms - Element ID modification to allow re-use
I have a Zend_Form object that I want to re-use several times in one page.  The problem I'm having is that each time it's rendered it has the same element IDs.  I've been unable to find a method for giving all the IDs a unique prefix or suffix each time I render the form.

Complete Solution

Subclass Zend_Form:

```<code>class My_Form extends Zend_Form
{
    protected $_idSuffix = null;

    /**
     * Set form and element ID suffix
     *
     * @param string $suffix
     * @return My_Form
     */
    public function setIdSuffix($suffix)
    {
        $this->_idSuffix = $suffix;
        return $this;
    }

    /**
     * Render form
     *
     * @param Zend_View_Interface $view
     * @return string
     */
    public function render(Zend_View_Interface $view = null)
    {
        if (!is_null($this->_idSuffix)) {
            // form
            $formId = $this->getId();
            if (0 < strlen($formId)) {
                $this->setAttrib('id', $formId . '_' . $this->_idSuffix);
            }

            // elements
            $elements = $this->getElements();
            foreach ($elements as $element) {
                $element->setAttrib('id', $element->getId() . '_' . $this->_idSuffix);
            }
        }

        return parent::render($view);
    }
}
</code>```

Loop in the view script:

```<code><?php foreach ($this->rows as $row) : ?>
    <?php echo $this->form->setDefaults($row->toArray())->setIdSuffix($row->id); ?>
<?php endforeach; ?>
</code>```

答:
You could add a static integer property (let's say  self::$counter)to your Zend_Form inherited class.
You increment it on the init() method.
For each element you create on your Zend_Form object you append that property to your element :</p>

```<code>$element->setAttrib('id', self::$counter + '_myId');
</code>```

Body:
I have a Zend_Form object that I want to re-use several times in one page.  The problem I'm having is that each time it's rendered it has the same element IDs.  I've been unable to find a method for giving all the IDs a unique prefix or suffix each time I render the form.

Complete Solution

Subclass Zend_Form:

class My_Form extends Zend_Form
{
    protected $_idSuffix = null;

    /**
     * Set form and element ID suffix
     *
     * @param string $suffix
     * @return My_Form
     */
    public function setIdSuffix($suffix)
    {
        $this->_idSuffix = $suffix;
        return $this;
    }

    /**
     * Render form
     *
     * @param Zend_View_Interface $view
     * @return string
     */
    public function render(Zend_View_Interface $view = null)
    {
        if (!is_null($this->_idSuffix)) {
            // form
            $formId = $this->getId();
            if (0 < strlen($formId)) {
                $this->setAttrib('id', $formId . '_' . $this->_idSuffix);
            }

            // elements
            $elements = $this->getElements();
            foreach ($elements as $element) {
                $element->setAttrib('id', $element->getId() . '_' . $this->_idSuffix);
            }
        }

        return parent::render($view);
    }
}

Loop in the view script:

<?php foreach ($this->rows as $row) : ?>
    <?php echo $this->form->setDefaults($row->toArray())->setIdSuffix($row->id); ?>
<?php endforeach; ?>

Body:
You could add a static integer property (let's say  self::$counter)to your Zend_Form inherited class.
You increment it on the init() method.
For each element you create on your Zend_Form object you append that property to your element :

$element->setAttrib('id', self::$counter + '_myId');


答:
Let say you have an input string "Bulota Babi".</p>

```<code>String fname = input.substring(0, input.indexOf(" "));
String lname = input.substring(input.indexOf(" "), input.length());
</code>```

Title: Printing last name + first name - but it shows error (Java)

Body:
Let say you have an input string "Bulota Babi".

String fname = input.substring(0, input.indexOf(" "));
String lname = input.substring(input.indexOf(" "), input.length());


问:
ctree() - How to get the list of splitting conditions for each terminal node?
I have an output from ctree() (party package) that looks like the following. How do I get the list of splitting conditions for each terminal node, like like sns <= 0, dta <= 1; sns <= 0, dta > 1 and so on?

```<code>1) sns <= 0; criterion = 1, statistic = 14655.021
  2) dta <= 1; criterion = 1, statistic = 3286.389
   3)*  weights = 153682
  2) dta > 1
   4)*  weights = 289415
1) sns > 0
  5) dta <= 2; criterion = 1, statistic = 1882.439
   6)*  weights = 245457
  5) dta > 2
   7) dta <= 6; criterion = 1, statistic = 1170.813
     8)*  weights = 328582
   7) dta > 6
</code>```

Thanks

答:
The CtreePathFunc function rewritten in more of a Hadley-verse (and I think more comprehensible) way. Also handling categorical variables.

```<code>library(magrittr)
readSplitter <- function(nodeSplit){
  splitPoint <- nodeSplit$splitpoint
  if("levels" %>% is_in(splitPoint %>% attributes %>% names)){
    splitPoint %>% attr("levels") %>% .[splitPoint]
  }else{
    splitPoint %>% as.numeric
  }
}

hasWeigths <- function(ct, path, terminalNode, pathNumber){
  ct %>%
    nodes(pathNumber %>% equals(path %>% length) %>% ifelse(terminalNode, path[pathNumber + 1]) ) %>%
    .[[1]] %>% use_series("weights") %>% as.logical %>% which
}

dataFilter <- function(ct, dts, path, terminalNode, pathNumber){
  whichWeights <- hasWeigths(ct, path, terminalNode, pathNumber)
  nodes(ct, path[pathNumber])[[1]][[5]] %>%
    buildDataFilter(dts, whichWeights)
}

buildDataFilter <- function(nodeSplit, ...) UseMethod("buildDataFilter")

buildDataFilter.nominalSplit <-
  function(nodeSplit, dts, whichWeights){
    varName <- nodeSplit$variableName
    includedLevels <- dts[ whichWeights
                          ,varName] %>% unique
    paste( varName, "=="
          ,includedLevels %>% paste(collapse = ", ") %>% paste0("{", ., "}"))
  }

buildDataFilter.orderedSplit <-
  function(nodeSplit, dts, whichWeights){
    varName <- nodeSplit$variableName
    splitter <- nodeSplit %>% readSplitter

    dts[ whichWeights
        ,varName] %>%
          is_weakly_less_than(splitter) %>%
          all %>%
          ifelse("<=" ,">") %>%
          paste(varName, ., splitter)
}

readTerminalNodePaths <- function (ct, dts) {

  nodeWeights <- function(Node) nodes(ct, Node)[[1]]$weights
  sgmnts <- ct %>% where %>% unique
  nodesFirstTreeWeightIsOne <- function(node) nodes(ct, node)[[1]][2][[1]] == 1

  # Take the inner nodes smaller than the selected terminal node
  innerNodes <-
    function(Node) setdiff( 1:(Node - 1)
                           ,sgmnts[sgmnts < Node])
  pathForTerminalNode <- function(terminalNode){
    innerNodes(terminalNode) %>%
      sapply(function(innerNode){
        if(any(nodeWeights(terminalNode) & nodesFirstTreeWeightIsOne(innerNode))) innerNode
       }) %>%
      unlist
  }

  # Find the splits criteria
  sgmnts %>% sapply(function(terminalNode){ #

    path <- terminalNode %>% pathForTerminalNode

    path %>% length %>% seq %>%
      sapply(function(nodeNumber){
        dataFilter(ct, dts, path, terminalNode, nodeNumber)
       }, simplify = FALSE) %>%
      unlist %>% paste(collapse = " & ") %>%
      data.frame(Node = terminalNode, Path = .)

  }, simplify = FALSE) %>%
    Reduce(f = rbind)
}
</code>```

Testing

```<code>shiftFirstPart <- function(vctr, divideBy, proportion = .5){
    vctr[vctr %>% length %>% multiply_by(proportion) %>% round %>% seq] %<>% divide_by(divideBy)
  vctr
}
set.seed(11)
n <- 13000
gdt <-
  data.frame( is_buyer = runif(n) %>% shiftFirstPart(1.5) %>% round %>% factor(labels = c("no", "yes"))
             ,age = runif(n) %>% shiftFirstPart(1.5) %>%
               cut(breaks = c(0, .3, .6, 1), include_lowest = TRUE, ordered_result = TRUE, labels = c("low", "mid", "high"))
             ,city = runif(n) %>% shiftFirstPart(1.5) %>%
               cut(breaks = c(0, .3, .6, 1), include_lowest = TRUE, labels = c("Chigaco", "Boston", "Memphis"))
             ,point = runif(n) %>% shiftFirstPart(1.2)
             )

gct <- ctree( is_buyer ~ ., data = gdt)
readTerminalNodePaths(gct, gdt)
</code>```

Body:
I have an output from ctree() (party package) that looks like the following. How do I get the list of splitting conditions for each terminal node, like like sns <= 0, dta <= 1; sns <= 0, dta > 1 and so on?

1) sns <= 0; criterion = 1, statistic = 14655.021
  2) dta <= 1; criterion = 1, statistic = 3286.389
   3)*  weights = 153682
  2) dta > 1
   4)*  weights = 289415
1) sns > 0
  5) dta <= 2; criterion = 1, statistic = 1882.439
   6)*  weights = 245457
  5) dta > 2
   7) dta <= 6; criterion = 1, statistic = 1170.813
     8)*  weights = 328582
   7) dta > 6

Thanks

Body:
The CtreePathFunc function rewritten in more of a Hadley-verse (and I think more comprehensible) way. Also handling categorical variables.

library(magrittr)
readSplitter <- function(nodeSplit){
  splitPoint <- nodeSplit$splitpoint
  if("levels" %>% is_in(splitPoint %>% attributes %>% names)){
    splitPoint %>% attr("levels") %>% .[splitPoint]
  }else{
    splitPoint %>% as.numeric
  }
}

hasWeigths <- function(ct, path, terminalNode, pathNumber){
  ct %>%
    nodes(pathNumber %>% equals(path %>% length) %>% ifelse(terminalNode, path[pathNumber + 1]) ) %>%
    .[[1]] %>% use_series("weights") %>% as.logical %>% which
}

dataFilter <- function(ct, dts, path, terminalNode, pathNumber){
  whichWeights <- hasWeigths(ct, path, terminalNode, pathNumber)
  nodes(ct, path[pathNumber])[[1]][[5]] %>%
    buildDataFilter(dts, whichWeights)
}

buildDataFilter <- function(nodeSplit, ...) UseMethod("buildDataFilter")

buildDataFilter.nominalSplit <-
  function(nodeSplit, dts, whichWeights){
    varName <- nodeSplit$variableName
    includedLevels <- dts[ whichWeights
                          ,varName] %>% unique
    paste( varName, "=="
          ,includedLevels %>% paste(collapse = ", ") %>% paste0("{", ., "}"))
  }

buildDataFilter.orderedSplit <-
  function(nodeSplit, dts, whichWeights){
    varName <- nodeSplit$variableName
    splitter <- nodeSplit %>% readSplitter

    dts[ whichWeights
        ,varName] %>%
          is_weakly_less_than(splitter) %>%
          all %>%
          ifelse("<=" ,">") %>%
          paste(varName, ., splitter)
}

readTerminalNodePaths <- function (ct, dts) {

  nodeWeights <- function(Node) nodes(ct, Node)[[1]]$weights
  sgmnts <- ct %>% where %>% unique
  nodesFirstTreeWeightIsOne <- function(node) nodes(ct, node)[[1]][2][[1]] == 1

  # Take the inner nodes smaller than the selected terminal node
  innerNodes <-
    function(Node) setdiff( 1:(Node - 1)
                           ,sgmnts[sgmnts < Node])
  pathForTerminalNode <- function(terminalNode){
    innerNodes(terminalNode) %>%
      sapply(function(innerNode){
        if(any(nodeWeights(terminalNode) & nodesFirstTreeWeightIsOne(innerNode))) innerNode
       }) %>%
      unlist
  }

  # Find the splits criteria
  sgmnts %>% sapply(function(terminalNode){ #

    path <- terminalNode %>% pathForTerminalNode

    path %>% length %>% seq %>%
      sapply(function(nodeNumber){
        dataFilter(ct, dts, path, terminalNode, nodeNumber)
       }, simplify = FALSE) %>%
      unlist %>% paste(collapse = " & ") %>%
      data.frame(Node = terminalNode, Path = .)

  }, simplify = FALSE) %>%
    Reduce(f = rbind)
}

Testing

shiftFirstPart <- function(vctr, divideBy, proportion = .5){
    vctr[vctr %>% length %>% multiply_by(proportion) %>% round %>% seq] %<>% divide_by(divideBy)
  vctr
}
set.seed(11)
n <- 13000
gdt <-
  data.frame( is_buyer = runif(n) %>% shiftFirstPart(1.5) %>% round %>% factor(labels = c("no", "yes"))
             ,age = runif(n) %>% shiftFirstPart(1.5) %>%
               cut(breaks = c(0, .3, .6, 1), include_lowest = TRUE, ordered_result = TRUE, labels = c("low", "mid", "high"))
             ,city = runif(n) %>% shiftFirstPart(1.5) %>%
               cut(breaks = c(0, .3, .6, 1), include_lowest = TRUE, labels = c("Chigaco", "Boston", "Memphis"))
             ,point = runif(n) %>% shiftFirstPart(1.2)
             )

gct <- ctree( is_buyer ~ ., data = gdt)
readTerminalNodePaths(gct, gdt)


问:
How to dynamically add textviews in a linear layout with additional constraints?
I am developing an app in which I want to add textviews in a column-wise order. Atmost 3 textviews can fill horizontally the screen width. If there are more than 3 textviews to be added, the new ones should be added in the next row, and so on. See the diagram below-

---1st---------------2nd--------------3rd

---4th----------------5th-----and so on

I know we need to use a nested linear layout with different orientation parameters. But how do I get around this "maximum 3 textviews per row constraint". I know that this has to do something with the weight parameter. The code I have written so far is-

```<code>LinearLayout out = (LinearLayout) findViewById(R.id.linear_params);
TextView mView = new TextView(this);
mView.setText("placeholder");
mView.setLayoutParams(new LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
out.addView(mView);
</code>```

And for the layout I have written-

```<code><LinearLayout
    android:id="@+id/out
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_margin="5dp">

    <LinearLayout
    android:id="@+id/in
    android:layout_width="match_parent"
    android:layout_height="10dp"
    android:layout_gravity="center_horizontal"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp"
    android:orientation="horizontal">
    <TextView ... />
    </LinearLayout>
    </LinearLayout>
</code>```

How should I modify the above xml and code so that I am able to place the views dynamically as required ?

答:
The correct way to do this will be to use a GridView Component with three columns. It will allow you to add the views as well.

If you use LinearLayout you will have to use weights and keep adding new LinearLayout per row, this will take a lot of processing for calculations and overdrawing as well.

Using GridView will help to avoid writing the code to calculate and add every row and every view and will keep the layout optimized as well.

Body:
I am developing an app in which I want to add textviews in a column-wise order. Atmost 3 textviews can fill horizontally the screen width. If there are more than 3 textviews to be added, the new ones should be added in the next row, and so on. See the diagram below-

---1st---------------2nd--------------3rd

---4th----------------5th-----and so on

I know we need to use a nested linear layout with different orientation parameters. But how do I get around this "maximum 3 textviews per row constraint". I know that this has to do something with the weight parameter. The code I have written so far is-

LinearLayout out = (LinearLayout) findViewById(R.id.linear_params);
TextView mView = new TextView(this);
mView.setText("placeholder");
mView.setLayoutParams(new LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
out.addView(mView);

And for the layout I have written-

<LinearLayout
    android:id="@+id/out
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_margin="5dp">

    <LinearLayout
    android:id="@+id/in
    android:layout_width="match_parent"
    android:layout_height="10dp"
    android:layout_gravity="center_horizontal"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp"
    android:orientation="horizontal">
    <TextView ... />
    </LinearLayout>
    </LinearLayout>

How should I modify the above xml and code so that I am able to place the views dynamically as required ?


问:
sep=";" statement breaks utf8 BOM in CSV file which is generated by XSL
I'm currently developing CSV export with XSLT. And CSV file will be used %99 percent with Excel in my case, so I have to consider Excel behavior.

My first problem was German special characters in csv. Even fact that CSV encoding is UTF8, Excel cannot open properly CSV file with UTF8. The special characters are getting weird symbols. I found a solution for this problem. I just added 3 additional bytes(EF BB BF - a.k.a BOM Header) beginning of content bytes. Because UTF8 BOM is way to say that 'hey dude, it is UTF8, open it properly' to Excel. Problem solved!

And my second problem was about separator. The default separator could be comma or semicolon depending on region. I think it is semicolon in Germany and comma in UK. So, in order to prevent this problem, I had to add the line in below:

```<code><xsl:text>sep=;</xsl:text>
</code>```

or

```<code><xsl:text>sep=,</xsl:text>
</code>```

(This separator was not implemented as hard-coded)

But my problem which I cannot find any solution is that if you add "sep=;" or "sep=," beginning of the file while the CSV file is being generated with UT8-BOM, the BOM doesn't help for showing special characters properly anymore! And I'm sure that BOM bytes are always in the beginning of byte array. This screen shot is from MS Excel in Mac OS X:

First 3 symbols belong to BOM header.

Have you ever had like this problem or do you have any suggestions? Thank you.

Edit:

I share the printscreens.

a. With BOM and <xsl:text>sep=;</xsl:text>

b. Just with BOM

The Java code:

```<code>// Write the bytes
ServletOutputStream out = resp.getOutputStream();
if(contentType.toString().equals("CSV")) {
  // The additional bytes in below is prefix indicates that the content is in UTF-8.
  out.write(239);
  out.write(187);
  out.write(191);
}
out.write(bytes); // Content bytes, in this case XSL
</code>```

The XSL code:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output method="text" version="1.0" encoding="UTF-8" indent="yes" />

    <xsl:template match="/">
    <xsl:text>sep=;</xsl:text>
    <table>
        ...
        </table>
</xsl:template>
</code>```

答:
I can't write comments yet, but I'd like to address @Pier-Luc Gendreau's solution. While it is possible to open it in European Excel (which by default uses ;as delimiter) and have full utf-16LE support, it is apparently not possible to use this technique when you specify sep=,.

The issue with solution is that while Excel interprets sep=; properly, it displays sep= (yes, it swallows the ;) in the first column of the last row.

For me it did not work if I specified a delimiter which wasn't the default one (;in my case) so I assume Excel did not interpret the last line correctly and swallowed the last delimiter because this is the default behavior.

Please correct me if I'm wrong

Body:
I'm currently developing CSV export with XSLT. And CSV file will be used %99 percent with Excel in my case, so I have to consider Excel behavior.

My first problem was German special characters in csv. Even fact that CSV encoding is UTF8, Excel cannot open properly CSV file with UTF8. The special characters are getting weird symbols. I found a solution for this problem. I just added 3 additional bytes(EF BB BF - a.k.a BOM Header) beginning of content bytes. Because UTF8 BOM is way to say that 'hey dude, it is UTF8, open it properly' to Excel. Problem solved!

And my second problem was about separator. The default separator could be comma or semicolon depending on region. I think it is semicolon in Germany and comma in UK. So, in order to prevent this problem, I had to add the line in below:

<xsl:text>sep=;</xsl:text>

or

<xsl:text>sep=,</xsl:text>

(This separator was not implemented as hard-coded)

But my problem which I cannot find any solution is that if you add "sep=;" or "sep=," beginning of the file while the CSV file is being generated with UT8-BOM, the BOM doesn't help for showing special characters properly anymore! And I'm sure that BOM bytes are always in the beginning of byte array. This screen shot is from MS Excel in Mac OS X:

First 3 symbols belong to BOM header.

Have you ever had like this problem or do you have any suggestions? Thank you.

Edit:

I share the printscreens.

a. With BOM and <xsl:text>sep=;</xsl:text>

b. Just with BOM

The Java code:

// Write the bytes
ServletOutputStream out = resp.getOutputStream();
if(contentType.toString().equals("CSV")) {
  // The additional bytes in below is prefix indicates that the content is in UTF-8.
  out.write(239);
  out.write(187);
  out.write(191);
}
out.write(bytes); // Content bytes, in this case XSL

The XSL code:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output method="text" version="1.0" encoding="UTF-8" indent="yes" />

    <xsl:template match="/">
    <xsl:text>sep=;</xsl:text>

        ...

</xsl:template>


问:
Sporadic SVN 500 Errors With CruiseControl.NET
I'm running several projects in CruiseControl.NET. Many of them have no build errors and have successful builds. They all try to pull the latest code prior to building.

I've noticed that they frequently fail building; CruiseControl reports "Exception." The exception is an SVN 500 error (internal server error). It strikes randomly but persistently (eg. in one project, every alternating build fails).

I've tried checking out some of these sporadically failing projects with the same credentials, and it works. I know the projects build, because not every build fails.

What could the problem be?

For what it's worth, here's the top line of an exemplary exception (without SVN project URL or credentials):

```<code>ThoughtWorks.CruiseControl.Core.CruiseControlException: Source control operation failed: svn: Server sent unexpected return value (500 Internal Server Error) in response to OPTIONS request for 'https://some/url/trunk'
. Process command: C:\Program Files\CollabNet Subversion Client\svn.exe log https://some/url/trunk -r "{2010-12-04T09:09:19Z}:{2010-12-07T09:08:48Z}" --verbose --xml --username ******** --password ******** --non-interactive --no-auth-cache
</code>```

Edit: Sometimes this seems to be because there's an SVN conflict in the local folder. But it's not consistent.

Bounty: I've added a bounty for a general solution to this: how can CC.NET be configured to gracefully cope with SVN errors, i.e. do not treat SVN failures triggered by a periodic update check (as opposed to scheduled daily builds) as build failures but instead gracefully back off until it's fixed or until the connection recovers.

I haven't managed to figure this out myself, although I'm not a CC.NET expert and haven't looked for a long time. Is there support for this or would it need coding up? Thanks!

To clarify,

We have a CC.NET server to set up to check for new commits and checkout + build + test all changes then report the result.

If, however, the SVN server goes down or if we lose connection to it then it treats this as if the last commit broke the build: it sets the build status to red and emails the last committer as if it was their fault.

Yes, this would be a problem for a once-a-day build job but for continuous every-commit integration I don't think this is useful behaviour.

答: One hard way of solving this problem would be to check for modifications with a batch file or a custom wrapper (instead of the source control facility of CruiseControl.NET) that calls the svn client and creates a file (or some other way of signaling changes) if the build is required. The batch or wrapper could treat the exceptions as needed. Of course, this solution might require altering the rest of the build process.</p>

Body:
I'm running several projects in CruiseControl.NET. Many of them have no build errors and have successful builds. They all try to pull the latest code prior to building.

I've noticed that they frequently fail building; CruiseControl reports "Exception." The exception is an SVN 500 error (internal server error). It strikes randomly but persistently (eg. in one project, every alternating build fails).

I've tried checking out some of these sporadically failing projects with the same credentials, and it works. I know the projects build, because not every build fails.

What could the problem be?

For what it's worth, here's the top line of an exemplary exception (without SVN project URL or credentials):

ThoughtWorks.CruiseControl.Core.CruiseControlException: Source control operation failed: svn: Server sent unexpected return value (500 Internal Server Error) in response to OPTIONS request for 'https://some/url/trunk'
. Process command: C:\Program Files\CollabNet Subversion Client\svn.exe log https://some/url/trunk -r "{2010-12-04T09:09:19Z}:{2010-12-07T09:08:48Z}" --verbose --xml --username ******** --password ******** --non-interactive --no-auth-cache

Edit: Sometimes this seems to be because there's an SVN conflict in the local folder. But it's not consistent.

Bounty: I've added a bounty for a general solution to this: how can CC.NET be configured to gracefully cope with SVN errors, i.e. do not treat SVN failures triggered by a periodic update check (as opposed to scheduled daily builds) as build failures but instead gracefully back off until it's fixed or until the connection recovers.

I haven't managed to figure this out myself, although I'm not a CC.NET expert and haven't looked for a long time. Is there support for this or would it need coding up? Thanks!

To clarify,

We have a CC.NET server to set up to check for new commits and checkout + build + test all changes then report the result.

If, however, the SVN server goes down or if we lose connection to it then it treats this as if the last commit broke the build: it sets the build status to red and emails the last committer as if it was their fault.

Yes, this would be a problem for a once-a-day build job but for continuous every-commit integration I don't think this is useful behaviour.