问:
Retrofti Json RecyclerView: No adapter attached;
I put on my json data in this URL= http://api.myjson.com/bins/1fblzn

it contains location data and has 5 fields, three of them are Strings and two of them are Doubles.

I want to show it in recyclerview.

but I keep getting this error.

I searched a lot but I couldn't get an answer.

Here's my code:

MainActivityRecyc

```<code>    public class MainActivityRecyc extends AppCompatActivity {
    private static final String TAG = MainActivityRecyc.class.getSimpleName();

    private RecyclerView recyclerView;
    private ArrayList<Locations> data;
    private DataAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_recyc);
        final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.card_recycler_view);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        RequestInterface requestInterface =
                JsonClient.getClient().create(RequestInterface.class);
        Call<JSONResponse> call = requestInterface.getJson();
        call.enqueue(new Callback<JSONResponse>() {
            @Override
            public void onResponse(Call<JSONResponse> call,
                                   Response<JSONResponse> response) {
                int statusCode = response.code();
                List<Locations> data = response.body().getData();
                recyclerView.setAdapter(new DataAdapter(data, R.layout.card_row, getApplicationContext()));            }
            @Override
            public void onFailure(Call<JSONResponse> call, Throwable t) {
            }        });    }     }
</code>```

Locations

```<code>      public class Locations {
    private String name;
    private String pname;
    private String bicycleno;
    private Double lat;
    private Double lang;
            public Locations(String name, String pname, String bicycleno,
                             Double lat, Double lang){
                this.name= name;
                this.pname= pname;
                this.bicycleno= bicycleno;
                this.lat= lat;
                this.lang= lang;
            }
   public String getName() {
        return name;
    }
    public void  setName (String name){
        this.name=name;
    }
    public String getPname() {
        return pname;
    }
    public void  setPname(String pname){
        this.pname=pname;
    }
    public String getBicycleno() {
        return bicycleno;
    }
    public void setBicycleno (String bicycleno){
        this.bicycleno=bicycleno;
    }
    public Double getLat() {
        return lat;
    }
    public void setLat (Double lat){
        this.lat=lat;
    }
    public Double getLang() {
        return lang;
    }
    public void setLang (Double lang){
        this.lang=lang;
    }    }
</code>```

RequestInterface

```<code>     public interface RequestInterface {
    @Headers("Content-Type:application/json")
    @GET("/bins/1fblzn/")
    Call<JSONResponse> getJson();
    }
</code>```

DataAdapter

```<code>      public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder>{
    private List<Locations> data=new ArrayList<>();
    private int rowLayout;
    private Context context;
    public DataAdapter(List<Locations> data ,int rowLayout, Context context){
        this.data = data;
        this.rowLayout = rowLayout;
        this.context = context;
    }
    @Override
    public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(rowLayout, viewGroup, false);
        return new ViewHolder(view);
    }
    @Override
    public void onBindViewHolder(ViewHolder viewHolder, final int i) {
        Locations locations= data.get(i);
        viewHolder.name.setText(data.get(i).getName());
        viewHolder.pname.setText(data.get(i).getPname());
        viewHolder.bicycleno.setText(data.get(i).getBicycleno());
        viewHolder.lat.setText(data.get(i).getLat().toString());
        viewHolder.lang.setText(data.get(i).getLang().toString());
    }
    @Override
    public int getItemCount() {

        return data.size();
    }
    public class ViewHolder extends RecyclerView.ViewHolder{
        private TextView name,pname,bicycleno, lat, lang;
        public ViewHolder(View view) {
            super(view);
            name = (TextView)view.findViewById(R.id.name);
            pname = (TextView)view.findViewById(R.id.pname);
            bicycleno = (TextView)view.findViewById(R.id.bicycleno);
            lat = (TextView)view.findViewById(R.id.lat);
            lang = (TextView)view.findViewById(R.id.lang);
        }   } }
</code>```

JSONResponse

```<code>public class JSONResponse {

@SerializedName("data")
@Expose
private List<Locations> data =new ArrayList<>();

public List<Locations> getData() {
    return data;
}
</code>```

JsonClient

```<code> public class JsonClient {

public static final String BASE_URL = "https://api.myjson.com/";
private static Retrofit retrofit = null;

public static Retrofit getClient() {
    if (retrofit==null) {
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
}}
</code>```

答:
The problem is in the fourth line of your onCreate:

recyclerView.setAdapter(adapter);

The adapter you're passing here is just null because you've never assigned a value to the field private DataAdapter adapter;. Right before the aforementioned 4th line, add code to instantiate the adapter. Since you don't have any data at that point, just pass empty data:

adapter = new DataAdapter(Collections.EMPTY_LIST, R.layout.card_row, getApplicationContext())

Then later when you get the data from the request, just update the data of the adapter and call notifyDataChanged();

Body:
I put on my json data in this URL= http://api.myjson.com/bins/1fblzn

it contains location data and has 5 fields, three of them are Strings and two of them are Doubles.

I want to show it in recyclerview.

but I keep getting this error.

I searched a lot but I couldn't get an answer.

Here's my code:

MainActivityRecyc

    public class MainActivityRecyc extends AppCompatActivity {
    private static final String TAG = MainActivityRecyc.class.getSimpleName();

    private RecyclerView recyclerView;
    private ArrayList<Locations> data;
    private DataAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_recyc);
        final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.card_recycler_view);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        RequestInterface requestInterface =
                JsonClient.getClient().create(RequestInterface.class);
        Call<JSONResponse> call = requestInterface.getJson();
        call.enqueue(new Callback<JSONResponse>() {
            @Override
            public void onResponse(Call<JSONResponse> call,
                                   Response<JSONResponse> response) {
                int statusCode = response.code();
                List<Locations> data = response.body().getData();
                recyclerView.setAdapter(new DataAdapter(data, R.layout.card_row, getApplicationContext()));            }
            @Override
            public void onFailure(Call<JSONResponse> call, Throwable t) {
            }        });    }     }

Locations

      public class Locations {
    private String name;
    private String pname;
    private String bicycleno;
    private Double lat;
    private Double lang;
            public Locations(String name, String pname, String bicycleno,
                             Double lat, Double lang){
                this.name= name;
                this.pname= pname;
                this.bicycleno= bicycleno;
                this.lat= lat;
                this.lang= lang;
            }
   public String getName() {
        return name;
    }
    public void  setName (String name){
        this.name=name;
    }
    public String getPname() {
        return pname;
    }
    public void  setPname(String pname){
        this.pname=pname;
    }
    public String getBicycleno() {
        return bicycleno;
    }
    public void setBicycleno (String bicycleno){
        this.bicycleno=bicycleno;
    }
    public Double getLat() {
        return lat;
    }
    public void setLat (Double lat){
        this.lat=lat;
    }
    public Double getLang() {
        return lang;
    }
    public void setLang (Double lang){
        this.lang=lang;
    }    }

RequestInterface

     public interface RequestInterface {
    @Headers("Content-Type:application/json")
    @GET("/bins/1fblzn/")
    Call<JSONResponse> getJson();
    }

DataAdapter

      public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder>{
    private List<Locations> data=new ArrayList<>();
    private int rowLayout;
    private Context context;
    public DataAdapter(List<Locations> data ,int rowLayout, Context context){
        this.data = data;
        this.rowLayout = rowLayout;
        this.context = context;
    }
    @Override
    public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(rowLayout, viewGroup, false);
        return new ViewHolder(view);
    }
    @Override
    public void onBindViewHolder(ViewHolder viewHolder, final int i) {
        Locations locations= data.get(i);
        viewHolder.name.setText(data.get(i).getName());
        viewHolder.pname.setText(data.get(i).getPname());
        viewHolder.bicycleno.setText(data.get(i).getBicycleno());
        viewHolder.lat.setText(data.get(i).getLat().toString());
        viewHolder.lang.setText(data.get(i).getLang().toString());
    }
    @Override
    public int getItemCount() {

        return data.size();
    }
    public class ViewHolder extends RecyclerView.ViewHolder{
        private TextView name,pname,bicycleno, lat, lang;
        public ViewHolder(View view) {
            super(view);
            name = (TextView)view.findViewById(R.id.name);
            pname = (TextView)view.findViewById(R.id.pname);
            bicycleno = (TextView)view.findViewById(R.id.bicycleno);
            lat = (TextView)view.findViewById(R.id.lat);
            lang = (TextView)view.findViewById(R.id.lang);
        }   } }

JSONResponse

public class JSONResponse {

@SerializedName("data")
@Expose
private List<Locations> data =new ArrayList<>();

public List<Locations> getData() {
    return data;
}

JsonClient

 public class JsonClient {

public static final String BASE_URL = "https://api.myjson.com/";
private static Retrofit retrofit = null;

public static Retrofit getClient() {
    if (retrofit==null) {
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    return retrofit;
}}


来源: stackexchange

问:
How to add the websites logo in html?
Basically, this is a part of a bookmark app that I am making with html,css,javascript. In the below code I wanted to get the websites logo along with the bookmark how could I do this in the code.</p>

```<code>for(var i=0;i<bookmarks.length;i++)
{
var name=bookmarks[i].name;
var url=bookmarks[i].url;
bookmarksresults.innerHTML+='<div class="well">'+
                            '<h3>'+name+
                            '<a class="btn btn-default" target="_blank"
                             href="'+url+'">Visit</a> '+
                            '<a onclick="deleteBookmark(\''+url+'\')" +
                            class="btn btn-danger" href="#">Delete</a> '+
                            '</h3>' +
                            '</div>';
}
</code>```

答:
You could just add in

```<code><img src=" +logo.png+ " />
</code>```

After the h3 tag, and just make sure to replace the logo.png with the correct naem for the image.

But, the question was a little vague, let me know if this is what you wanted.

ContentLicense: CC BY-SA 3.0

Title: How to add the websites logo in html?

Body:
Basically, this is a part of a bookmark app that I am making with html,css,javascript. In the below code I wanted to get the websites logo along with the bookmark how could I do this in the code.

for(var i=0;i<bookmarks.length;i++)
{
var name=bookmarks[i].name;
var url=bookmarks[i].url;
bookmarksresults.innerHTML+='
'+
                            '
'+name+
                            'Visit '+
                            'Delete '+
                            '
' +
                            '
';
}

Body:
You could just add in

<img src=" +logo.png+ " />

After the h3 tag, and just make sure to replace the logo.png with the correct naem for the image.

But, the question was a little vague, let me know if this is what you wanted.


问:
How to undo "svn upgrade"
So I am at work and installed the subversion packages on cygwin to keep my local checkouts of work files up to date. However, we use an older subversion at work and I accidentally did an svn upgrade locally. I didn't realize this caused an upgrade to the entire directory, so I am trying to undo these changes. I wanted to simply update my checkout, but it seems as though I used the wrong command from the recommendation list. Is there a way to undo the changes I just made?</p>

答:
There is no corresponding "downgrade" command.

Your only option is to downgrade the Subversion packages you installed to whatever version your workplace uses, and then checkout your files from the repository again.

Title: How to undo "svn upgrade"


答:
Use the  tag

```<code>bookmarksresults.innerHTML+='<div class="well">'+
                            '<h3>'+name+
                            '<a class="btn btn-default" target="_blank"
                             href="'+url+'">Visit <img src="logo.png" alt="Logo" height="42" width="42"></a> '+
                            '<a onclick="deleteBookmark(\''+url+'\')" +
                            class="btn btn-danger" href="#">Delete</a> '+
                            '</h3>' +
                            '</div>';
</code>```

If you want to put the favicon: see https://stackoverflow.com/a/10283308/1914034

```<code>var getFavicon = function(){
    var favicon = undefined;
    var nodeList = document.getElementsByTagName("link");
    for (var i = 0; i < nodeList.length; i++)
    {
        if((nodeList[i].getAttribute("rel") == "icon")||(nodeList[i].getAttribute("rel") == "shortcut icon"))
        {
            favicon = nodeList[i].getAttribute("href");
        }
    }
    return favicon;
}

bookmarksresults.innerHTML+='<div class="well">'+
                                '<h3>'+name+
                                '<a class="btn btn-default" target="_blank"
                                 href="'+url+'">Visit <img src="'+ getFavicon() +'" alt="Logo" height="42" width="42"></a> '+
                                '<a onclick="deleteBookmark(\''+url+'\')" +
                                class="btn btn-danger" href="#">Delete</a> '+
                                '</h3>' +
                                '</div>';
</code>```

Title: How to add the websites logo in html?

Body:
Use the <img> tag

bookmarksresults.innerHTML+='<div class="well">'+
                            '<h3>'+name+
                            '<a class="btn btn-default" target="_blank"
                             href="'+url+'">Visit&nbsp;<img src="logo.png" alt="Logo" height="42" width="42"></a> '+
                            '<a onclick="deleteBookmark(\''+url+'\')" +
                            class="btn btn-danger" href="#">Delete</a> '+
                            '</h3>' +
                            '</div>';

If you want to put the favicon: see https://stackoverflow.com/a/10283308/1914034

var getFavicon = function(){
    var favicon = undefined;
    var nodeList = document.getElementsByTagName("link");
    for (var i = 0; i < nodeList.length; i++)
    {
        if((nodeList[i].getAttribute("rel") == "icon")||(nodeList[i].getAttribute("rel") == "shortcut icon"))
        {
            favicon = nodeList[i].getAttribute("href");
        }
    }
    return favicon;
}

bookmarksresults.innerHTML+='<div class="well">'+
                                '<h3>'+name+
                                '<a class="btn btn-default" target="_blank"
                                 href="'+url+'">Visit&nbsp;<img src="'+ getFavicon() +'" alt="Logo" height="42" width="42"></a> '+
                                '<a onclick="deleteBookmark(\''+url+'\')" +
                                class="btn btn-danger" href="#">Delete</a> '+
                                '</h3>' +
                                '</div>';


问:
discard qualifiers -fpermissive
Hi guys I take an error which I cant understand.in my main class on void GPSPathList::print() const
I got this error.

```<code>[Error] passing 'const GPSPathList' as 'this' argument of 'void GPSPathList::print_item(const GPSPathList::GPSCoordNode*)' discards qualifiers [-fpermissive]
</code>```

Can you help out

MY header

```<code>#ifndef GPSPATHLIST_H
#define GPSPATHLIST_H

class GPSPathList {
     public:
        GPSPathList(){ m_size = 0; m_item_list = 0; }
         int size() const{return m_size;}

    void add_from_user();
    void print() const;
    double total_distance();

    private:
        struct GPSCoordNode{

            double longtitude;

            double lattitude;
            GPSCoordNode *next;
        };
    void print_item(const GPSCoordNode *item);
    void addpoint(const double& lattitude, const double& longtitude);

     int m_size;
    GPSCoordNode *m_item_list;

};
#endif
</code>```

my main

```<code>#include "gpspathlist.h"
#include <iostream>
#include <cmath>

using std::ifstream;
using std::cout;
using std::cin;
using std::endl;
using std::string;

void GPSPathList::print_item(const GPSCoordNode *item){

cout<< "<"<<item->lattitude<<","<<item->longtitude<<">"<<endl;
}
void GPSPathList::addpoint(const double& lattitude , const double& longtitude){

     GPSCoordNode *new_point = new GPSCoordNode;
        new_point->lattitude = lattitude;
        new_point->longtitude = longtitude;

        if (m_item_list == 0 ) {

                new_point->next = m_item_list;
                m_item_list = new_point;
                    }
                    else {

                GPSCoordNode *p = m_item_list;
                while (p->next != 0)
                        p = p->next;

                new_point->next = p->next;
                p->next = new_point;
        }
        m_size++;
}
void GPSPathList::add_from_user(){

string a;
double lattitude,longtitude;

    while(true){

    cout << "Enter lattıtude : " <<endl;
                cin >> lattitude;
                cout << "Enter longtıtude : " <<endl;
                cin >> longtitude;
                 addpoint(lattitude,longtitude) ;
                    cout <<"if exit press no to ";
                 cin >>a;
                 if(a=="no"){
                    break;
                 }
                 }
                 }

void GPSPathList::print() const
{
        const GPSCoordNode *d = m_item_list;
        while (d != 0) {
                print_item(d);//my problem is in here
                d=d->next;

        }
}
double GPSPathList::total_distance(){

double a,b,c,d,longtitude,lattitude,longtitude2,lattitude2,R,S;

 GPSCoordNode *v = m_item_list;
  for (int i =0; i<m_size; i++){

    a=v->lattitude;
    b=v->longtitude;

    v=v->next;
      c=v->lattitude;
      d=v->longtitude;
        v=v->next;
      i++;
         R = 6371.8;
    longtitude= (3.141593/180.0) * b;
    lattitude = (3.141593/180.0) * a;
    longtitude2=(3.141593/180.0) * d;
    lattitude2=(3.141593/180.0) * c;
    double  Lat =lattitude2-lattitude;
   double   Lon = longtitude2-longtitude;

    double w = sin(Lat / 2);
    double x=sin(Lon / 2);

     double q= R * asin(sqrt((w*w)+(cos(lattitude) * cos(lattitude2)*x*x)));

i++;
return S=q*1.609;

 cout<<" distance: "<< S;
 }
}
int main(int argc, char** argv){

GPSPathList a;
 a.add_from_user();
 a.print();
 a.size();
 a.total_distance();

}
</code>```

Hi guys I take an error which I cant understand.in my main class on void GPSPathList::print() const
I got this error.

答: You are not able to call non-const methods from const ones. Consider making print_item a const method.

Title: discard qualifiers -fpermissive

Body:
Hi guys I take an error which I cant understand.in my main class on void GPSPathList::print() const
I got this error.

[Error] passing 'const GPSPathList' as 'this' argument of 'void GPSPathList::print_item(const GPSPathList::GPSCoordNode*)' discards qualifiers [-fpermissive]

Can you help out

MY header

#ifndef GPSPATHLIST_H
#define GPSPATHLIST_H

class GPSPathList {
     public:
        GPSPathList(){ m_size = 0; m_item_list = 0; }
         int size() const{return m_size;}

    void add_from_user();
    void print() const;
    double total_distance();

    private:
        struct GPSCoordNode{

            double longtitude;

            double lattitude;
            GPSCoordNode *next;
        };
    void print_item(const GPSCoordNode *item);
    void addpoint(const double& lattitude, const double& longtitude);

     int m_size;
    GPSCoordNode *m_item_list;

};
#endif

my main

#include "gpspathlist.h"
#include <iostream>
#include <cmath>

using std::ifstream;
using std::cout;
using std::cin;
using std::endl;
using std::string;

void GPSPathList::print_item(const GPSCoordNode *item){

cout<< "<"<<item->lattitude<<","<<item->longtitude<<">"<<endl;
}
void GPSPathList::addpoint(const double& lattitude , const double& longtitude){

     GPSCoordNode *new_point = new GPSCoordNode;
        new_point->lattitude = lattitude;
        new_point->longtitude = longtitude;

        if (m_item_list == 0 ) {

                new_point->next = m_item_list;
                m_item_list = new_point;
                    }
                    else {

                GPSCoordNode *p = m_item_list;
                while (p->next != 0)
                        p = p->next;

                new_point->next = p->next;
                p->next = new_point;
        }
        m_size++;
}
void GPSPathList::add_from_user(){

string a;
double lattitude,longtitude;

    while(true){

    cout << "Enter lattıtude : " <<endl;
                cin >> lattitude;
                cout << "Enter longtıtude : " <<endl;
                cin >> longtitude;
                 addpoint(lattitude,longtitude) ;
                    cout <<"if exit press no to ";
                 cin >>a;
                 if(a=="no"){
                    break;
                 }
                 }
                 }

void GPSPathList::print() const
{
        const GPSCoordNode *d = m_item_list;
        while (d != 0) {
                print_item(d);//my problem is in here
                d=d->next;

        }
}
double GPSPathList::total_distance(){

double a,b,c,d,longtitude,lattitude,longtitude2,lattitude2,R,S;

 GPSCoordNode *v = m_item_list;
  for (int i =0; i<m_size; i++){

    a=v->lattitude;
    b=v->longtitude;

    v=v->next;
      c=v->lattitude;
      d=v->longtitude;
        v=v->next;
      i++;
         R = 6371.8;
    longtitude= (3.141593/180.0) * b;
    lattitude = (3.141593/180.0) * a;
    longtitude2=(3.141593/180.0) * d;
    lattitude2=(3.141593/180.0) * c;
    double  Lat =lattitude2-lattitude;
   double   Lon = longtitude2-longtitude;

    double w = sin(Lat / 2);
    double x=sin(Lon / 2);

     double q= R * asin(sqrt((w*w)+(cos(lattitude) * cos(lattitude2)*x*x)));

i++;
return S=q*1.609;

 cout<<" distance: "<< S;
 }
}
int main(int argc, char** argv){

GPSPathList a;
 a.add_from_user();
 a.print();
 a.size();
 a.total_distance();

}

Hi guys I take an error which I cant understand.in my main class on void GPSPathList::print() const
I got this error.


问:
Reading in Erlang the body of a HTTP request as it is received
I've been looking into Mochiweb, but I can't find a way to read the body while I'm receiving the request through the socket.

I'm not limited to Mochiweb, any other HTTP library would be good for me.

I also tried gen_tcp:listen(Port, [{packet, http}]), this way I can read the body/headers while I'm receiving the HTTP request, but I must handle manually the responses and keeping the socket open for more requests, so I prefer not to use this solution.

My intention is to receive request with large bodies and not to wait to receive the full body in order to start reading/processing them.

答:
With mochiweb you can fold over chunks of the request body using Req:stream_body/3.
It expects a chunk handler function as the second argument. This handler is called with
{ChunkSize, BinaryData} and your state for every chunk, as it is received from the socket.

Example (retrieving a [reversed] list of chunks):

```<code>MaxChunkSize = 100,
InitialState = [],
ChunkHandler = fun ({_Size, Bin}, State) -> [Bin | State] end,
List = Req:stream_body(MaxChunkSize, ChunkHandler, InitialState),
...
</code>```

ContentLicense: CC BY-SA 2.5

Body:
With mochiweb you can fold over chunks of the request body using Req:stream_body/3.
It expects a chunk handler function as the second argument. This handler is called with
{ChunkSize, BinaryData} and your state for every chunk, as it is received from the socket.

Example (retrieving a [reversed] list of chunks):

MaxChunkSize = 100,
InitialState = [],
ChunkHandler = fun ({_Size, Bin}, State) -> [Bin | State] end,
List = Req:stream_body(MaxChunkSize, ChunkHandler, InitialState),
...


问:
PHP mail() funciton: replace sendmail using python or php script to support SMTP
It seemed the default php mail() function is not easy to configure, and it just call the OS configured sendmail function to send an email.

Though installing an alternative sendmail do the trick, but configuring such a program also depends on the OS and the its self version, hard to control about.

So I think if there is a way to write a lightweight script of python or php, and make it as an executable, then replace the sendmail path in php.ini

```<code>; For Unix only.  You may supply arguments as well (default: "sendmail -t -
; http://php.net/sendmail-path
sendmail_path = /some/script/pymail.py
</code>```

And it supports setting any SMTP account on it.

Sending mail using python is not difficult, but is there a way to adapt the input parameters to the same or compatible with the sendmail command?

Is it possible or some exisiting work on this approach?

答:
Finally found some library to do the job.

https://github.com/chupikov/sendmail.py

Wiki: https://github.com/chupikov/sendmail.py/wiki

The final config term looks like below:

```<code>sendmail_path = /home/user/bin/sendmail.py/sendmail.py -c /home/user/bin/sendmail.py/php-apache2.json
</code>```

Body:
It seemed the default php mail() function is not easy to configure, and it just call the OS configured sendmail function to send an email.

Though installing an alternative sendmail do the trick, but configuring such a program also depends on the OS and the its self version, hard to control about.

So I think if there is a way to write a lightweight script of python or php, and make it as an executable, then replace the sendmail path in php.ini

; For Unix only.  You may supply arguments as well (default: "sendmail -t -
; http://php.net/sendmail-path
sendmail_path = /some/script/pymail.py

And it supports setting any SMTP account on it.

Sending mail using python is not difficult, but is there a way to adapt the input parameters to the same or compatible with the sendmail command?

Is it possible or some exisiting work on this approach?

Body:
Finally found some library to do the job.

https://github.com/chupikov/sendmail.py

Wiki: https://github.com/chupikov/sendmail.py/wiki

The final config term looks like below:

sendmail_path = /home/user/bin/sendmail.py/sendmail.py -c /home/user/bin/sendmail.py/php-apache2.json


问:
Get latitude/longitude from address
How can I get latitude and longitude from a full address (street, city, etc.) input by the user, using the iPhone SDK 3.x?</p>

答:
```<code>func geoCodeUsingAddress(address: NSString) -> CLLocationCoordinate2D {
    var latitude: Double = 0
    var longitude: Double = 0
    let addressstr : NSString = "http://maps.google.com/maps/api/geocode/json?sensor=false&address=\(address)" as NSString
    let urlStr  = addressstr.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
    let searchURL: NSURL = NSURL(string: urlStr! as String)!
    do {
        let newdata = try Data(contentsOf: searchURL as URL)
        if let responseDictionary = try JSONSerialization.jsonObject(with: newdata, options: []) as? NSDictionary {
            print(responseDictionary)
            let array = responseDictionary.object(forKey: "results") as! NSArray
            let dic = array[0] as! NSDictionary
            let locationDic = (dic.object(forKey: "geometry") as! NSDictionary).object(forKey: "location") as! NSDictionary
            latitude = locationDic.object(forKey: "lat") as! Double
            longitude = locationDic.object(forKey: "lng") as! Double
        }} catch {
    }
    var center = CLLocationCoordinate2D()
    center.latitude = latitude
    center.longitude = longitude
    return center
}
</code>```

Title: Get latitude/longitude from address


问:
how to pass array of model from one actvtiy to another in android
```<code>public class DataModel implements Serializable, Parcelable {

    /**  */
    private static final long serialVersionUID = 4861597073026532544L;

    private String cid;
    private String name;

    /**
     * @return the cid
     */
    public String getCid() {
        return cid;
    }

    /**
     * @param cid
     *            the cid to set
     */
    public void setCid(String cid) {
        this.cid = cid;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name
     *            the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    public DataModel(Parcel in) {
        super();
        readFromParcel(in);
    }

    public static final Parcelable.Creator<DataModel> CREATOR = new Parcelable.Creator<DataModel>() {
        public DataModel createFromParcel(Parcel in) {
            return new DataModel(in);
        }

        public DataModel[] newArray(int size) {

            return new DataModel[size];
        }

    };

    public void readFromParcel(Parcel in) {
        String[] result = new String[23];
        in.readStringArray(result);

        this.cid = result[0];
        this.name = result[1];

    }

    public int describeContents() {
        return 0;
    }

    public void writeToParcel(Parcel dest, int flags) {
        dest.writeStringArray(new String[] { this.cid,
                this.name});

    }}
</code>```

this is my Datamodel:

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

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

        DataModel _modeDataModel=new DataModel(MainActivity.this);
        _modeDataModel.setCid("1");
        _modeDataModel.setName("Anil");

        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList("channel",(ArrayList<DataModel>) model);
        Intent intent = new Intent(MainActivity.this,SecondActivity.class);
        intent.putExtras(bundle);
        startActivity(intent);

    }

}
</code>```

main activtiy

```<code>public class SecondActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Bundle getBundle = this.getIntent().getExtras();
        List<DataModel> channelsList = getBundle.getParcelableArrayList("channel");
    }
}
</code>```

second actvity

i want to pass data between one activity to another activity from One List but i am unable to set value  model also unable to send one activity to another there is compile time Error is coming please suggest me where am doing mistake and ho to send data from one activity to another ,

答:
You can pass ArrayList of model object using Serializable try with below model class:

```<code>import java.io.Serializable;

    public class DataModel implements Serializable {

        /**  */
        private static final long serialVersionUID = 4861597073026532544L;

        private String cid;
        private String name;

        public String getCid() {
            return cid;
        }

        public void setCid(String cid) {
            this.cid = cid;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
</code>```

Start Acivity:

```<code> DataModel dataModel = new DataModel();
 dataModel.setCid("1");
 dataModel.setName("User");
 ArrayList<DataModel> models = new ArrayList<>();
 models.add(dataModel);

 Intent intent=new new  Intent(MainActivity.this,SecondActivity.class);
  intent.putExtra("data",models);
  startActivity(intent);
</code>```

Second Activity:

```<code>  ArrayList<DataModel> data = new ArrayList<>();
  data.addAll((ArrayList<DataModel>)  getIntent().getSerializableExtra("data"));
</code>```

Body:
public class DataModel implements Serializable, Parcelable {

    /**  */
    private static final long serialVersionUID = 4861597073026532544L;

    private String cid;
    private String name;

    /**
     * @return the cid
     */
    public String getCid() {
        return cid;
    }

    /**
     * @param cid
     *            the cid to set
     */
    public void setCid(String cid) {
        this.cid = cid;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name
     *            the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    public DataModel(Parcel in) {
        super();
        readFromParcel(in);
    }

    public static final Parcelable.Creator<DataModel> CREATOR = new Parcelable.Creator<DataModel>() {
        public DataModel createFromParcel(Parcel in) {
            return new DataModel(in);
        }

        public DataModel[] newArray(int size) {

            return new DataModel[size];
        }

    };

    public void readFromParcel(Parcel in) {
        String[] result = new String[23];
        in.readStringArray(result);

        this.cid = result[0];
        this.name = result[1];

    }

    public int describeContents() {
        return 0;
    }

    public void writeToParcel(Parcel dest, int flags) {
        dest.writeStringArray(new String[] { this.cid,
                this.name});

    }}

this is my Datamodel:

public class MainActivity extends AppCompatActivity {

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

        DataModel _modeDataModel=new DataModel(MainActivity.this);
        _modeDataModel.setCid("1");
        _modeDataModel.setName("Anil");

        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList("channel",(ArrayList<DataModel>) model);
        Intent intent = new Intent(MainActivity.this,SecondActivity.class);
        intent.putExtras(bundle);
        startActivity(intent);

    }

}

main activtiy

public class SecondActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Bundle getBundle = this.getIntent().getExtras();
        List<DataModel> channelsList = getBundle.getParcelableArrayList("channel");
    }
}

second actvity

i want to pass data between one activity to another activity from One List but i am unable to set value  model also unable to send one activity to another there is compile time Error is coming please suggest me where am doing mistake and ho to send data from one activity to another ,

Body:
You can pass ArrayList of model object using Serializable try with below model class:

import java.io.Serializable;

    public class DataModel implements Serializable {

        /**  */
        private static final long serialVersionUID = 4861597073026532544L;

        private String cid;
        private String name;

        public String getCid() {
            return cid;
        }

        public void setCid(String cid) {
            this.cid = cid;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

Start Acivity:

 DataModel dataModel = new DataModel();
 dataModel.setCid("1");
 dataModel.setName("User");
 ArrayList<DataModel> models = new ArrayList<>();
 models.add(dataModel);

 Intent intent=new new  Intent(MainActivity.this,SecondActivity.class);
  intent.putExtra("data",models);
  startActivity(intent);

Second Activity:

  ArrayList<DataModel> data = new ArrayList<>();
  data.addAll((ArrayList<DataModel>)  getIntent().getSerializableExtra("data"));


问:
Use index of summation as the order of derivation
Given some function f, I want to compute the following sum using sympy:

In general I want to use the index of summation as the order of differentiation of the function but I could not find out how to do it with sympy.

答:
Given n is an int you know in advance, you can construct a function:

```<code><b>from sympy import diff</b>

def sum_diff_order(f,x,n):
    g = 0
    for i in range(n+1):
        g <b>+= diff(f,x,i)</b>
    return g</code>```

So if you take f to be x**10 and n=5, we get:

```<code>>>> x = symbols('x')
>>> f = x**10
>>> sum_diff_order(f,x,5)
x**10 + 10*x**9 + 90*x**8 + 720*x**7 + 5040*x**6 + 30240*x**5
</code>```

Body:
Given n is an int you know in advance, you can construct a function:

from sympy import diff

def sum_diff_order(f,x,n):
    g = 0
    for i in range(n+1):
        g += diff(f,x,i)
    return g

So if you take f to be x**10 and n=5, we get:

>>> x = symbols('x')
>>> f = x**10
>>> sum_diff_order(f,x,5)
x**10 + 10*x**9 + 90*x**8 + 720*x**7 + 5040*x**6 + 30240*x**5


问:
Is there any console available to view UGC on ASRP?
We are implementing communities site using AEM 6.2 and hosting UGC content onto ASRP.
I am able to validate that this works coz the test connection is pass and UGC content is getting loaded onto my communities pages with a path like

Now is there any console or backdoor available OTB to view ugc on cloud; other than creating components, pages and viewing them from front end. Reason are:

I am doing migration using the UGC Migration tool. How to validate migration was successfully complete 100%?

If I want to administer the cloud UGC content directly say when site is down for maintenance, how todo?

答:
Apparently I found a useful tool in GitHub catering my purpose: SRP Browser
This is bringing all UGC content of a page in a little gui screen they provided + has a json representation of the ugc content as well.</p>


问:
SQL Exclude Zero from Case Column
I have a query inserting values into a table and am using CASE to determine the value for each row. I was wondering if it is possible at the end of it to then exclude null or zero from the calculated column?

```<code>   CASE
       WHEN Value = 0 THEN Value2
       WHEN Value2 < Value1 THEN Value3
       WHEN Value2 > Value1 THEN Value4
   END AS Final_Value
</code>```

This produces a few hundred thousand rows, of which a good few thousand are now zero or null. Can I exclude these in the same piece of code?

Thanks

答:
Review the CASE WHEN so it won't result in 0 or NULL

For example:

```<code>CASE
WHEN Value = 0 THEN Value2
WHEN Value2 <= Value1 THEN Value3
WHEN Value2 > Value1 THEN Value4
ELSE Value2
END AS Final_Value
</code>```

Of course, this one assumes that Value2, Value3 and Value4 are NOT NULL and not 0.

Title: SQL Exclude Zero from Case Column

Body:
I have a query inserting values into a table and am using CASE to determine the value for each row. I was wondering if it is possible at the end of it to then exclude null or zero from the calculated column?

   CASE
       WHEN Value = 0 THEN Value2
       WHEN Value2 < Value1 THEN Value3
       WHEN Value2 > Value1 THEN Value4
   END AS Final_Value

This produces a few hundred thousand rows, of which a good few thousand are now zero or null. Can I exclude these in the same piece of code?

Thanks

Body:
Review the CASE WHEN so it won't result in 0 or NULL

For example:

CASE
WHEN Value = 0 THEN Value2
WHEN Value2 <= Value1 THEN Value3
WHEN Value2 > Value1 THEN Value4
ELSE Value2
END AS Final_Value

Of course, this one assumes that Value2, Value3 and Value4 are NOT NULL and not 0.


问:
How to conciliate the best Object Oriented Programming practices in getters and setters with the needs of ORMs frameworks?
In many of systems I have worked in, the class that represents a model is a POJO, and we map their fields to columns (in relational databases) or attributes (in some NoSQL databases). So, em many ORMs, it is mandatory to have accessors methods to take and bring data from/to database.
However, the best practices in Object Oriented Programming say that we should not expose the intern structure of our objects. Instead, we must expose operations that change the internal state of objects e maintain the state consistency of this object

Let's give an example. Let's say we have a class Client. This class has an ID, the customer's name e its date of last change. We cannot change this data directly, but we want to persist them. If we want to modify the client's name, we must also change the ID and the last change date.

The ORM needs of following getters and setters methods, so that we have:

```<code>@Entity
public class Client {

  @Id
  private Long id;

  @Index
  private String name;

  private Date lastChange;

  public Long getId() {
    return this.id;
  }

  public String getName() {
    return this.name;
  }

  public Date lastChange() {
    return this.lastChange;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public void setString(String name) {
    this.name = name;
  }

  public void setLastChange() {
    this.lastChange = latChange;
  }

}
</code>```

The way it is, anyone, besides the ORM, could change the ID and last change date, causing unwanted effects on the rest of the system.

Instead, if we wanted to respect the Oriented Object rules, we have something like this:

```<code>@Entity
public class Client {

  @Id
  private Long id;

  @Index
  private String name;

  private Date lastChange;

  public Client(Long id, String name) {
    this.id = id;
    this.name = name;
    this.lastChange = new Date();
  }

  public Long getId() {
    return this.id;
  }

  public String getName() {
    return this.name;
  }

  public void changeName(String name) {
    this.name = name;
    this.id = newIdFromClient();
    this.lastChange = new Date();
  }

  private Long getNewIdFromClient() {
    return (new Random()).nextLong();
  }

}
</code>```

So, my question is: how we conciliate the best practices of Object Oriented Programming with the needs of getters and setters in ORMs frameworks?

答:
Off Topic:

In many of systems I have worked in, the class that represents a model is a POJO,

A POJO is a Java class that does not implement interfaces or extend other (abstract) classes in order to fulfill the needs of a framework. What you most likely refer to is a data transfer object (DTO) or bean (which usually are POJOs).

On topic:

However, the best practices in Object Oriented Programming say that we should not expose the intern structure of our objects. Instead, we must expose operations that change the internal state of objects e maintain the state consistency of this object

DTOs/beans are pure data structure and not objects by means of OOP. Unfortunately in Java we have to use the same class-concept to create them (unlike e.g. Kotlin, where we have a special keyword for data classes).

Therefore it is OK for datastructure to expose their inner structure because that's what they are all about.

However, in classes that build your business logic working on DTOs/beans you should strictly follow the information hiding principle tough and avoid getters/setters.

Body:
In many of systems I have worked in, the class that represents a model is a POJO, and we map their fields to columns (in relational databases) or attributes (in some NoSQL databases). So, em many ORMs, it is mandatory to have accessors methods to take and bring data from/to database.
However, the best practices in Object Oriented Programming say that we should not expose the intern structure of our objects. Instead, we must expose operations that change the internal state of objects e maintain the state consistency of this object

Let's give an example. Let's say we have a class Client. This class has an ID, the customer's name e its date of last change. We cannot change this data directly, but we want to persist them. If we want to modify the client's name, we must also change the ID and the last change date.

The ORM needs of following getters and setters methods, so that we have:

@Entity
public class Client {

  @Id
  private Long id;

  @Index
  private String name;

  private Date lastChange;

  public Long getId() {
    return this.id;
  }

  public String getName() {
    return this.name;
  }

  public Date lastChange() {
    return this.lastChange;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public void setString(String name) {
    this.name = name;
  }

  public void setLastChange() {
    this.lastChange = latChange;
  }

}

The way it is, anyone, besides the ORM, could change the ID and last change date, causing unwanted effects on the rest of the system.

Instead, if we wanted to respect the Oriented Object rules, we have something like this:

@Entity
public class Client {

  @Id
  private Long id;

  @Index
  private String name;

  private Date lastChange;

  public Client(Long id, String name) {
    this.id = id;
    this.name = name;
    this.lastChange = new Date();
  }

  public Long getId() {
    return this.id;
  }

  public String getName() {
    return this.name;
  }

  public void changeName(String name) {
    this.name = name;
    this.id = newIdFromClient();
    this.lastChange = new Date();
  }

  private Long getNewIdFromClient() {
    return (new Random()).nextLong();
  }

}

So, my question is: how we conciliate the best practices of Object Oriented Programming with the needs of getters and setters in ORMs frameworks?


问:
TcpListener send heartbeat every 5 seconds and read message from client async
I'm writing a TcpListener service that runs as a Windows Service that a vendor software client will connect to. I can't change the client's implementation and must adhere to their spec.

I have the part that receives messages and returns a response working. The problem I have is the clients expect a heartbeat message (S0000E) to be sent every 5 seconds, to which it replies with the same message. I'm not sure how to add that functionality in among the async/await stuff I'm doing to handle the real messages received from the clients.

OnStart

```<code>_serverListenerTask = Task.Run(() => AcceptClientsAsync(_listener, _cancellationToken.Token));
</code>```

AcceptClientsAsync

```<code>static async Task AcceptClientsAsync(TcpListener listener, CancellationToken ct)
{
    var clientCounter = 0;
    while (!ct.IsCancellationRequested)
    {
        TcpClient client = await listener.AcceptTcpClientAsync()
                                         .ConfigureAwait(false);
        clientCounter++;
        await ReceiveMessageAsync(client, clientCounter, ct);
    }
}
</code>```

ReceiveMessageAsync

```<code>static async Task ReceiveMessageAsync(TcpClient client, int clientIndex, CancellationToken ct)
{
    Log.Info("New client ({0}) connected", clientIndex);
    using (client)
    {
        var buffer = new byte[4096];
        var stream = client.GetStream();
        while (!ct.IsCancellationRequested)
        {
            var timeoutTask = Task.Delay(TimeSpan.FromSeconds(15));
            var amountReadTask = stream.ReadAsync(buffer, 0, buffer.Length, ct);

            var completedTask = await Task.WhenAny(timeoutTask, amountReadTask)
                                          .ConfigureAwait(false);

            if (completedTask == timeoutTask)
            {
                var msg = Encoding.ASCII.GetBytes("Client timed out");
                await stream.WriteAsync(msg, 0, msg.Length);
                break;
            }

            var bytesRead = amountReadTask.Result;
            if (bytesRead == 0)
            {
                // Nothing was read
                break;
            }

            // Snip... Handle message from buffer here

            await stream.WriteAsync(responseBuffer, 0, responseBuffer.Length, ct)
                        .ConfigureAwait(false);
        }
    }
    Log.Info("Client ({0}) disconnected", clientIndex);
}
</code>```

I thought I could add a heartbeat task to the Task.WhenAny, but that caused the heartbeat to always fire and I could never read the response. I also tried sending the heartbeat before the timeout and read tasks, which worked for sending, but then I was either reading the heartbeat response and not the next message in line or the timeout task would complete and disconnect the client. Essentially, if the heartbeat exchange is successful then the client shouldn't be disconnected after that 15 second delay.

答:
Implementing TCP server-client is not a simple task. However, the following way of implementation, if you improve it to be more efficient in resources, can be a practical solution:

Server:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Server
{
    public class Program
    {
        static List<SocketBuffer> clients = new List<SocketBuffer>();
        public static void Main(string[] args)
        {
            //Receive from any IP, listen on port 65000 in this machine
            var listener = new TcpListener(IPAddress.Any, 65000);
            var t = Task.Run(() =>
            {
                while (true)
                {
                    listener.Start();
                    var task = listener.AcceptTcpClientAsync();
                    task.Wait();
                    clients.Add(new SocketBuffer(task.Result, new byte[4096]));
                }
            });
            t.Wait();    //It will remain here, do in a better way if you like !
        }
    }

    /// <summary>
    /// We need this class because each TcpClient will have its own buffer
    /// </summary>
    class SocketBuffer
    {
        public SocketBuffer(TcpClient client, byte[] buffer)
        {
            this.client = client;
            stream = client.GetStream();
            this.buffer = buffer;

            receiveData(null);
        }

        private TcpClient client;
        private NetworkStream stream;
        private byte[] buffer;

        private object _lock = new object();
        private async void receiveData(Task<int> result)
        {
            if (result != null)
            {
                lock (_lock)
                {
                    int numberOfBytesRead = result.Result;
                    //If no data read, it means we are here to be notified that the tcp client has been disconnected
                    if (numberOfBytesRead == 0)
                    {
                        onDisconnected();
                        return;
                    }
                    //We need a part of this array, you can do it in more efficient way if you like
                    var segmentedArr = new ArraySegment<byte>(buffer, 0, numberOfBytesRead).ToArray();
                    OnDataReceived(segmentedArr);
                }

            }
            var task = stream.ReadAsync(buffer, 0, buffer.Length);
            //This is not recursion in any sense because the current
            //thread will be free and the call to receiveData will be from a new thread
            await task.ContinueWith(receiveData);
        }

        private void onDisconnected()
        {
            //Add your code here if you want this event
        }

        private void OnDataReceived(byte[] dat)
        {
            //Do anything with the data, you can reply here. I will just pring the received data from the demo client
            string receivedTxt = Encoding.ASCII.GetString(dat);
            Console.WriteLine(receivedTxt);
        }
    }
}
</code>```

Demo client:

```<code>using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace Client
{
    public class Program
    {
        public static void Main(string[] args)
        {
            TcpClient client = new TcpClient();
            var task = client.ConnectAsync("localhost", 65000);
            task.Wait();
            if(client.Connected)
            {
                Console.WriteLine("Client connected");
                var stream = client.GetStream();
                var data = Encoding.ASCII.GetBytes("test");
                stream.Write(data, 0, data.Length);
            }
            else
            {
                Console.WriteLine("Client NOT connected");
            }
            Thread.Sleep(60000);
        }
    }
}
</code>```

Body:
I'm writing a TcpListener service that runs as a Windows Service that a vendor software client will connect to. I can't change the client's implementation and must adhere to their spec.

I have the part that receives messages and returns a response working. The problem I have is the clients expect a heartbeat message (S0000E) to be sent every 5 seconds, to which it replies with the same message. I'm not sure how to add that functionality in among the async/await stuff I'm doing to handle the real messages received from the clients.

OnStart

_serverListenerTask = Task.Run(() => AcceptClientsAsync(_listener, _cancellationToken.Token));

AcceptClientsAsync

static async Task AcceptClientsAsync(TcpListener listener, CancellationToken ct)
{
    var clientCounter = 0;
    while (!ct.IsCancellationRequested)
    {
        TcpClient client = await listener.AcceptTcpClientAsync()
                                         .ConfigureAwait(false);
        clientCounter++;
        await ReceiveMessageAsync(client, clientCounter, ct);
    }
}

ReceiveMessageAsync

static async Task ReceiveMessageAsync(TcpClient client, int clientIndex, CancellationToken ct)
{
    Log.Info("New client ({0}) connected", clientIndex);
    using (client)
    {
        var buffer = new byte[4096];
        var stream = client.GetStream();
        while (!ct.IsCancellationRequested)
        {
            var timeoutTask = Task.Delay(TimeSpan.FromSeconds(15));
            var amountReadTask = stream.ReadAsync(buffer, 0, buffer.Length, ct);

            var completedTask = await Task.WhenAny(timeoutTask, amountReadTask)
                                          .ConfigureAwait(false);

            if (completedTask == timeoutTask)
            {
                var msg = Encoding.ASCII.GetBytes("Client timed out");
                await stream.WriteAsync(msg, 0, msg.Length);
                break;
            }

            var bytesRead = amountReadTask.Result;
            if (bytesRead == 0)
            {
                // Nothing was read
                break;
            }

            // Snip... Handle message from buffer here

            await stream.WriteAsync(responseBuffer, 0, responseBuffer.Length, ct)
                        .ConfigureAwait(false);
        }
    }
    Log.Info("Client ({0}) disconnected", clientIndex);
}

I thought I could add a heartbeat task to the Task.WhenAny, but that caused the heartbeat to always fire and I could never read the response. I also tried sending the heartbeat before the timeout and read tasks, which worked for sending, but then I was either reading the heartbeat response and not the next message in line or the timeout task would complete and disconnect the client. Essentially, if the heartbeat exchange is successful then the client shouldn't be disconnected after that 15 second delay.

Body:
Implementing TCP server-client is not a simple task. However, the following way of implementation, if you improve it to be more efficient in resources, can be a practical solution:

Server:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Server
{
    public class Program
    {
        static List<SocketBuffer> clients = new List<SocketBuffer>();
        public static void Main(string[] args)
        {
            //Receive from any IP, listen on port 65000 in this machine
            var listener = new TcpListener(IPAddress.Any, 65000);
            var t = Task.Run(() =>
            {
                while (true)
                {
                    listener.Start();
                    var task = listener.AcceptTcpClientAsync();
                    task.Wait();
                    clients.Add(new SocketBuffer(task.Result, new byte[4096]));
                }
            });
            t.Wait();    //It will remain here, do in a better way if you like !
        }
    }

    /// <summary>
    /// We need this class because each TcpClient will have its own buffer
    /// </summary>
    class SocketBuffer
    {
        public SocketBuffer(TcpClient client, byte[] buffer)
        {
            this.client = client;
            stream = client.GetStream();
            this.buffer = buffer;

            receiveData(null);
        }

        private TcpClient client;
        private NetworkStream stream;
        private byte[] buffer;

        private object _lock = new object();
        private async void receiveData(Task<int> result)
        {
            if (result != null)
            {
                lock (_lock)
                {
                    int numberOfBytesRead = result.Result;
                    //If no data read, it means we are here to be notified that the tcp client has been disconnected
                    if (numberOfBytesRead == 0)
                    {
                        onDisconnected();
                        return;
                    }
                    //We need a part of this array, you can do it in more efficient way if you like
                    var segmentedArr = new ArraySegment<byte>(buffer, 0, numberOfBytesRead).ToArray();
                    OnDataReceived(segmentedArr);
                }

            }
            var task = stream.ReadAsync(buffer, 0, buffer.Length);
            //This is not recursion in any sense because the current
            //thread will be free and the call to receiveData will be from a new thread
            await task.ContinueWith(receiveData);
        }

        private void onDisconnected()
        {
            //Add your code here if you want this event
        }

        private void OnDataReceived(byte[] dat)
        {
            //Do anything with the data, you can reply here. I will just pring the received data from the demo client
            string receivedTxt = Encoding.ASCII.GetString(dat);
            Console.WriteLine(receivedTxt);
        }
    }
}

Demo client:

using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace Client
{
    public class Program
    {
        public static void Main(string[] args)
        {
            TcpClient client = new TcpClient();
            var task = client.ConnectAsync("localhost", 65000);
            task.Wait();
            if(client.Connected)
            {
                Console.WriteLine("Client connected");
                var stream = client.GetStream();
                var data = Encoding.ASCII.GetBytes("test");
                stream.Write(data, 0, data.Length);
            }
            else
            {
                Console.WriteLine("Client NOT connected");
            }
            Thread.Sleep(60000);
        }
    }
}


问:
Thousand separator in pie chart of charts.js
I 'm using Chart.js to draw pie chart.

To draw graph I used

```<code>var ctx = document.getElementById("myChart").getContext('2d');
      var myChart = new Chart(ctx, {
        type: 'pie',
        data: {
          labels: #{raw @labels.to_json},
          datasets: [{
          backgroundColor: #{raw @colors.to_json},
            data: #{@followers}
          }]
        }
      });
</code>```

To clarify this data thing is like this

```<code>data: {
      labels: ["FAISAL","muhammadfaisali","faisaliqbal3699"],
      datasets: [{
      backgroundColor: ["#00b638","#efaa30","#50c8ea"],
        data: [500000, 75000, 100000]
      }]
    }
</code>```

I need to show these data: [500000, 75000, 100000] as thousand separator like ["500,000", "75,000", "100,000"]

I tried different

things including writing this method

```<code>function separator(numbers)
      { data = []
        for (i = 0; i < numbers.length; ++i) {
          data.push(numbers[i].toLocaleString())
        }
        data
      }
</code>```

and tried to use it like this

```<code>data: separator(#{@followers})
</code>```

it format data as I want but gives error like Cannot read property 'custom' of undefined

What is the way to show data in thousand separator here

答:
In order to do this in chart.js, you need to use the tooltips.callbacks.label callback property.  The value returned from this callback is what is used to generate the tooltip text.

Here is your chart configured with a tooltip callback that uses the local string representation for your data value.

```<code>var ctx = document.getElementById("chart-area").getContext("2d");
var myPie = new Chart(ctx, {
  type: 'pie',
  data: {
    labels: ["FAISAL","muhammadfaisali","faisaliqbal3699"],
    datasets: [{
      backgroundColor: ["#00b638","#efaa30","#50c8ea"],
      data: [500000, 75000, 100000]
    }],
  },
  options: {
    title: {
      display: true,
      text: 'Employee Overview',
      fontStyle: 'bold',
      fontSize: 20
    },
    tooltips: {
      callbacks: {
        // this callback is used to create the tooltip label
        label: function(tooltipItem, data) {
          // get the data label and data value to display
          // convert the data value to local string so it uses a comma seperated number
          var dataLabel = data.labels[tooltipItem.index];
          var value = ': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index].toLocaleString();

          // make this isn't a multi-line label (e.g. [["label 1 - line 1, "line 2, ], [etc...]])
          if (Chart.helpers.isArray(dataLabel)) {
            // show value on first line of multiline label
            // need to clone because we are changing the value
            dataLabel = dataLabel.slice();
            dataLabel[0] += value;
          } else {
            dataLabel += value;
          }

          // return the text to display on the tooltip
          return dataLabel;
        }
      }
    }
  }
});
</code>```

You can see it in action at this codepen.

Body:
I 'm using Chart.js to draw pie chart.

To draw graph I used

var ctx = document.getElementById("myChart").getContext('2d');
      var myChart = new Chart(ctx, {
        type: 'pie',
        data: {
          labels: #{raw @labels.to_json},
          datasets: [{
          backgroundColor: #{raw @colors.to_json},
            data: #{@followers}
          }]
        }
      });

To clarify this data thing is like this

data: {
      labels: ["FAISAL","muhammadfaisali","faisaliqbal3699"],
      datasets: [{
      backgroundColor: ["#00b638","#efaa30","#50c8ea"],
        data: [500000, 75000, 100000]
      }]
    }

I need to show these data: [500000, 75000, 100000] as thousand separator like ["500,000", "75,000", "100,000"]

I tried different

things including writing this method

function separator(numbers)
      { data = []
        for (i = 0; i < numbers.length; ++i) {
          data.push(numbers[i].toLocaleString())
        }
        data
      }

and tried to use it like this

data: separator(#{@followers})

it format data as I want but gives error like Cannot read property 'custom' of undefined

What is the way to show data in thousand separator here

Body:
In order to do this in chart.js, you need to use the tooltips.callbacks.label callback property.  The value returned from this callback is what is used to generate the tooltip text.

Here is your chart configured with a tooltip callback that uses the local string representation for your data value.

var ctx = document.getElementById("chart-area").getContext("2d");
var myPie = new Chart(ctx, {
  type: 'pie',
  data: {
    labels: ["FAISAL","muhammadfaisali","faisaliqbal3699"],
    datasets: [{
      backgroundColor: ["#00b638","#efaa30","#50c8ea"],
      data: [500000, 75000, 100000]
    }],
  },
  options: {
    title: {
      display: true,
      text: 'Employee Overview',
      fontStyle: 'bold',
      fontSize: 20
    },
    tooltips: {
      callbacks: {
        // this callback is used to create the tooltip label
        label: function(tooltipItem, data) {
          // get the data label and data value to display
          // convert the data value to local string so it uses a comma seperated number
          var dataLabel = data.labels[tooltipItem.index];
          var value = ': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index].toLocaleString();

          // make this isn't a multi-line label (e.g. [["label 1 - line 1, "line 2, ], [etc...]])
          if (Chart.helpers.isArray(dataLabel)) {
            // show value on first line of multiline label
            // need to clone because we are changing the value
            dataLabel = dataLabel.slice();
            dataLabel[0] += value;
          } else {
            dataLabel += value;
          }

          // return the text to display on the tooltip
          return dataLabel;
        }
      }
    }
  }
});

You can see it in action at this codepen.


问:
How to make an icon open in javascript
I am creating a website and in the navigation bar in the header I have the logo on the left and the links to the other pages on the right, and when the browser is resized to less than 600px all the links are supposed to go into an icon but the logo remains.

When I click the icon the formatting of the links and the icon changes to the default settings and I want the links to display one after the other below each other like this (example taken from www.W3Schools.com).

I hope someone could help me with this error.

Thank you.

```<code><div class="slideshow_nav">
          <div class="navbar-wlogo">
            <img src="/Users/yanikwick/Documents/canvas_website/logo.png" alt="logo" class="logo "width = "175px">
            <nav class="topnav" id="myTopnav">
              <a href="/html/contact">CONTACT</a>
              <a href="/html/about">ABOUT</a>
              <a href="/html/portfolio">PORTFOLIO</a>
              <a href="/html/">HOME</a>
              <a href="javascript:void(0);" style="font-size:30px;" class="icon" onclick="myFunction()">☰</a>
            </nav>
          </div>
</code>```

This is the html for the navigation bar.

```<code>function myFunction() {
    var x = document.getElementById("myTopnav");
    if (x.className === "topnav") {
      x.className += " responsive";
      } else {
        x.className = "topnav";
      }
  }
</code>```

This is the javascript.

```<code>header .logo{

float: left;
  margin: 0px;
  padding: 10px 10px 5px 10px;
}

header .topnav{
  overflow: hidden;
  margin-right: 20px;
}

header .topnav a{
  float: right;
  display: block;
  color: #f2f2f2;
  text-align: center;
  margin-top: 2%;
  margin-bottom: 2%;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

.topnav .icon {
  display: none;
}

.topnav a:hover {
  background-color: #ddd;
  color: black;
}

@media screen and (max-width: 600px){
  .topnav a:not(:last-child) {display: none;}
  .topnav a.icon {
    display: inline-block;
      float: right;
    }

@media screen and (max-width: 600px) {
  .topnav .responsive {
    position: relative;
  }
  .topnav .responsive .icon {
    float: right;
  }
  .topnav .responsive a{
    float: none;
    display: block;
    text-align: left;
  }
}
</code>```

The CSS

I would appreciate it if you help me with this. Thank you.

答:
The issue is, that you don't set the visibility of the links if .topnav gets responsive applied...

so something like:

```<code>.topnav.responsive a {
  display:block;
}
</code>```

inside:

```<code>@media screen and (max-width: 600px){
...
}
</code>```

here a working jsbin ;)
http://jsbin.com/vupizuyeji/edit?html,css,js,output

Cheerio :)

Title: How to make an icon open in javascript

Body:
I am creating a website and in the navigation bar in the header I have the logo on the left and the links to the other pages on the right, and when the browser is resized to less than 600px all the links are supposed to go into an icon but the logo remains.

When I click the icon the formatting of the links and the icon changes to the default settings and I want the links to display one after the other below each other like this (example taken from www.W3Schools.com).

I hope someone could help me with this error.

Thank you.

              CONTACT
              ABOUT
              PORTFOLIO
              HOME
              ☰

This is the html for the navigation bar.

function myFunction() {
    var x = document.getElementById("myTopnav");
    if (x.className === "topnav") {
      x.className += " responsive";
      } else {
        x.className = "topnav";
      }
  }

This is the javascript.

header .logo{

float: left;
  margin: 0px;
  padding: 10px 10px 5px 10px;
}

header .topnav{
  overflow: hidden;
  margin-right: 20px;
}

header .topnav a{
  float: right;
  display: block;
  color: #f2f2f2;
  text-align: center;
  margin-top: 2%;
  margin-bottom: 2%;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

.topnav .icon {
  display: none;
}

.topnav a:hover {
  background-color: #ddd;
  color: black;
}

@media screen and (max-width: 600px){
  .topnav a:not(:last-child) {display: none;}
  .topnav a.icon {
    display: inline-block;
      float: right;
    }

@media screen and (max-width: 600px) {
  .topnav .responsive {
    position: relative;
  }
  .topnav .responsive .icon {
    float: right;
  }
  .topnav .responsive a{
    float: none;
    display: block;
    text-align: left;
  }
}

The CSS

I would appreciate it if you help me with this. Thank you.

Body:
The issue is, that you don't set the visibility of the links if .topnav gets responsive applied...

so something like:

.topnav.responsive a {
  display:block;
}

inside:

@media screen and (max-width: 600px){
...
}

here a working jsbin ;)
http://jsbin.com/vupizuyeji/edit?html,css,js,output

Cheerio :)


问:
Using Regexkitlite in iPhone,iPad
Can any one tell how can we set the regular expression in regexkitlite for validating float numbers,email,web address..etc....or can any one say what is the rules for using the expression ?</p>

答:
The RegexKitLite homepage has a bunch of examples on how to do the common things you ask. Check out the RegexKitLite Cookbook. Among other things you will find examples on how to do:

floating point: [+\-]?(?:[0-9]*\.[0-9]+|[0-9]+\.)

email: \b([a-zA-Z0-9%_.+\-]+)@([a-zA-Z0-9.\-]+?\.[a-zA-Z]{2,6})\b

But you should really take a look at those examples. There are many good examples on how to solve common tasks.

Title: Using Regexkitlite in iPhone,iPad


问:
ZPL code printing differently in 2 printers
I have the following ZPL code:

```<code>^XA^LH30,20^MD15^PW609
^FO0,20^AD^FD            Pull Sample Post-Login^FS
^FO0,45^AD^FDStudy ID :      ^FS
^FO0,70^AD^FDLIMS No :       3216665-TIME_FACT-STOR_COND^FS
^FO0,95^AD^FB590,2,,^FDMaterial Name : 2187- Abatacept (CTLA4g) for Injection 250mg/Vial^FS
^FO0,140^AD^FDBatch No :      ^FS
^FO0,165^AD^FDTime Point :    ^FS
^FO0,190^AD^FDStorage Conditions :^FS
^FO0,215^AD^FDRemoved By :    ^FS
^FO0,240^AD^FDRemoval Date :
^FS^XZ
</code>```

On a GX430T, the label width is 2x3 inch. It prints out field "Material Name:" fine by wrapping it to the 2nd line.

When try the same code in production, using ZM400 printer with a label width of (1x3 inch). It prints all the fields, except the Material Name field, you just see a blank line where the Material Name field should be.

I suspect that it's a issue with label width. How do I change the ZPL code that it takes into account the label width of the production ZM400 printer?

答:
The combination of these three commands might mess things up.

```<code>^LH30,20
^PW609
^FB590,2,,
</code>```

^PW609 is print width of the label.

^LH30,20 sets home position at 30

^FB590 would create a field block that exceeds the print width of the label (30+590=620, which is > 609)

So maybe when you tweak these a bit, it might print it correctly?

Body:
I have the following ZPL code:

^XA^LH30,20^MD15^PW609
^FO0,20^AD^FD            Pull Sample Post-Login^FS
^FO0,45^AD^FDStudy ID :      ^FS
^FO0,70^AD^FDLIMS No :       3216665-TIME_FACT-STOR_COND^FS
^FO0,95^AD^FB590,2,,^FDMaterial Name : 2187- Abatacept (CTLA4g) for Injection 250mg/Vial^FS
^FO0,140^AD^FDBatch No :      ^FS
^FO0,165^AD^FDTime Point :    ^FS
^FO0,190^AD^FDStorage Conditions :^FS
^FO0,215^AD^FDRemoved By :    ^FS
^FO0,240^AD^FDRemoval Date :
^FS^XZ

On a GX430T, the label width is 2x3 inch. It prints out field "Material Name:" fine by wrapping it to the 2nd line.

When try the same code in production, using ZM400 printer with a label width of (1x3 inch). It prints all the fields, except the Material Name field, you just see a blank line where the Material Name field should be.

I suspect that it's a issue with label width. How do I change the ZPL code that it takes into account the label width of the production ZM400 printer?

Body:
The combination of these three commands might mess things up.

^LH30,20
^PW609
^FB590,2,,

^PW609 is print width of the label.

^LH30,20 sets home position at 30

^FB590 would create a field block that exceeds the print width of the label (30+590=620, which is > 609)

So maybe when you tweak these a bit, it might print it correctly?


问:
How to change the proguard mapping file name in gradle for Android project
I have android project based on gradle and I want to change mapping.txt file name after it's generated for my build. How can it be done?

upd

How it can be done in build.gradle? Since I have access there to my flavors and other stiff, I would like to create mapping file name based on flavor/build variant version.

答:
This is a variation of igorpst's answer but renames mapping.txt to match the apk's name exactly including the app version name. I've combined this with code to name the APK with a version number as described in this answer. I had to snoop through the gradle source code to find $variant.baseName

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"
    defaultConfig {
        applicationId "com.company.app"
        minSdkVersion 13
        targetSdkVersion 21
        versionCode 14       // increment with every release
        versionName '1.4.8'   // change with every release
        archivesBaseName = "MyCompany-MyAppName-$versionName"
    }
    applicationVariants.all { variant ->
        if (variant.getBuildType().isMinifyEnabled()) {
            variant.assemble.doLast {
                (new File(variant.mappingFile.parent, "$archivesBaseName-$variant.baseName-mapping.txt")).delete();
                variant.mappingFile.renameTo(variant.mappingFile.parent +
                        "/$archivesBaseName-$variant.baseName-mapping.txt")
            }
        }
    }
}
</code>```

Body:
This is a variation of igorpst's answer but renames mapping.txt to match the apk's name exactly including the app version name. I've combined this with code to name the APK with a version number as described in this answer. I had to snoop through the gradle source code to find $variant.baseName

apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"
    defaultConfig {
        applicationId "com.company.app"
        minSdkVersion 13
        targetSdkVersion 21
        versionCode 14       // increment with every release
        versionName '1.4.8'   // change with every release
        archivesBaseName = "MyCompany-MyAppName-$versionName"
    }
    applicationVariants.all { variant ->
        if (variant.getBuildType().isMinifyEnabled()) {
            variant.assemble.doLast {
                (new File(variant.mappingFile.parent, "$archivesBaseName-$variant.baseName-mapping.txt")).delete();
                variant.mappingFile.renameTo(variant.mappingFile.parent +
                        "/$archivesBaseName-$variant.baseName-mapping.txt")
            }
        }
    }
}


问:
Given values for p, q and e, but gcd(e,phi) is not 1, then how to find n & d in RSA? Or is it even possible?
The values are: p = 19, q = 23, and e = 3.
Calculating as per the algorithm: n = 437 & phi = 396.
But I don't think RSA is valid here becasue GCD(e, phi) is not 1 in this case, as GCD(3, 396) = 3.
So, that means RSA algorithm isn't satisfied and can't be proceeded further to calculate d, right?

I'd like to ask if I am correct in assuming that there is no solution for those given values of p, q and e due to GCD(e,phi) = 1 not being satisfied.

Or am I doing something wrong here?
This is the original question which appeared in a previous examination paper that I'm solving: (word by word)

```<code>In RSA, given p=19, q=23 and e=3, find n and d.
</code>```

I'm willing to assume its a tricky question which checks whether one knows the algorithm(and its steps) or not. Please let me know if my assumption is right or not, thanks in advance! :)

答:
You are correct.  Running the Extended Euclidean Algorithm to compute ModInv(3, 396) we get

```<code>ModInverse(3, 396)
  r=396, newR=3, t=0, newT=   1
  r=  3, newR=0, t=1, newT=-132

  newR == 0 && r > 0: Not Invertible.
</code>```

Therefore there's no value for d.  (Computing it against lambda(n) instead of phi(n) also produces "Not invertible", since lambda is just phi/2 and 3 is the prime factor that broke things.)

Body:
The values are: p = 19, q = 23, and e = 3.
Calculating as per the algorithm: n = 437 & phi = 396.
But I don't think RSA is valid here becasue GCD(e, phi) is not 1 in this case, as GCD(3, 396) = 3.
So, that means RSA algorithm isn't satisfied and can't be proceeded further to calculate d, right?

I'd like to ask if I am correct in assuming that there is no solution for those given values of p, q and e due to GCD(e,phi) = 1 not being satisfied.

Or am I doing something wrong here?
This is the original question which appeared in a previous examination paper that I'm solving: (word by word)

In RSA, given p=19, q=23 and e=3, find n and d.

I'm willing to assume its a tricky question which checks whether one knows the algorithm(and its steps) or not. Please let me know if my assumption is right or not, thanks in advance! :)

Body:
You are correct.  Running the Extended Euclidean Algorithm to compute ModInv(3, 396) we get

ModInverse(3, 396)
  r=396, newR=3, t=0, newT=   1
  r=  3, newR=0, t=1, newT=-132

  newR == 0 && r > 0: Not Invertible.

Therefore there's no value for d.  (Computing it against lambda(n) instead of phi(n) also produces "Not invertible", since lambda is just phi/2 and 3 is the prime factor that broke things.)


问:
How to assign values to Nested Json array
I am using C#. I want the Json array in the below structure

```<code>"bed_configurations": [
           [{
             "type": "standard",
             "code": 3,
             "count": 1
             },
             {
              "type": "custom",
              "name": "Loft",
              "count": 1
             }]
        ]
</code>```

Please any one can help me..

答:
You have to create class for desired json. Also you have to use using Newtonsoft.Json; for json converter. I've created an example, please check this.

CODE:

```<code>public class Header
{
    public List<List<Item>> bed_configurations { get; set; }
}

public class Item
{
    public string type { get; set; }
    public int code { get; set; }
    public string name { get; set; }
    public int count { get; set; }
}

private static void getJSON()
{
    List<Item> items = new List<Item>();
    items.Add(new Item() { type = "standard", code = 3, count = 1 });
    items.Add(new Item() { type = "custom", name = "Loft", count = 1 });

    Header ob = new Header();
    ob.bed_configurations = new List<List<Item>>() { items };

    string output = JsonConvert.SerializeObject(ob);
}
</code>```

Output:

Body:
I am using C#. I want the Json array in the below structure

"bed_configurations": [
           [{
             "type": "standard",
             "code": 3,
             "count": 1
             },
             {
              "type": "custom",
              "name": "Loft",
              "count": 1
             }]
        ]

Please any one can help me..

Body:
You have to create class for desired json. Also you have to use using Newtonsoft.Json; for json converter. I've created an example, please check this.

CODE:

public class Header
{
    public List<List<Item>> bed_configurations { get; set; }
}

public class Item
{
    public string type { get; set; }
    public int code { get; set; }
    public string name { get; set; }
    public int count { get; set; }
}

private static void getJSON()
{
    List<Item> items = new List<Item>();
    items.Add(new Item() { type = "standard", code = 3, count = 1 });
    items.Add(new Item() { type = "custom", name = "Loft", count = 1 });

    Header ob = new Header();
    ob.bed_configurations = new List<List<Item>>() { items };

    string output = JsonConvert.SerializeObject(ob);
}

Output:


问:
get variable outside curly braces in Ruby
I have this code:

```<code>def foo( condy )
   ['<','>'].each{ | char|
      ret = condy.split( char ).reject{ |x| x.empty?() }
      break if ret.length > 2
   }
   return ret
end
</code>```

This code errors out, because ret is not recognized
However, this code does work:

```<code>def foo( condy )
   ret = []
   ['<','>'].each{ | char|
      ret = condy.split( char ).reject{ |x| x.empty?() }
      break if ret.length > 2
   }
   return ret
end
</code>```

My question is simple:
How does one get the ret variable to persist outside the curly braces, w/o defining it first outside it. It's nit-picking, I know.

答: Unless you declare it outside of the function, it's not possible to return it after the fact. As soon as you escape the braces, the variable goes out of scope, and is therefore unusable. Not a Ruby developer, but I know this is the case In other languages.</p>

Body:
I have this code:

def foo( condy )
   ['<','>'].each{ | char|
      ret = condy.split( char ).reject{ |x| x.empty?() }
      break if ret.length > 2
   }
   return ret
end

This code errors out, because ret is not recognized
However, this code does work:

def foo( condy )
   ret = []
   ['<','>'].each{ | char|
      ret = condy.split( char ).reject{ |x| x.empty?() }
      break if ret.length > 2
   }
   return ret
end

My question is simple:
How does one get the ret variable to persist outside the curly braces, w/o defining it first outside it. It's nit-picking, I know.


问:
Angular 2 : Remove class if root route not active
I only understood how to remove a whole element with *ngIf , for a specific route that is.

Lets say I have a class applied to an element of my app (header) only for routerLink="/", meaning if I switch to "/other-page", I need the header to lose that class.

How can I achieve this?

How can I link [ngClass] to the route change?

Code:

```<code>import { Component, ElementRef, ViewChild, Renderer, AfterViewInit, Input } from '@angular/core';

import { LayoutService } from 'app/core/services/layout.service';

@Component({
    moduleId: module.id,
    selector: 'header-main',
    template: `

    <header class="header-main"
        [ngClass]="{'transparent' : isMenuShown}" #header>

        <div class="wrapper">
            <a routerLink="/" routerLinkActive="active" routerLinkActiveOptions="{exact: true}" class="logo">
                <img src="../../../assets/images/logo_dark.svg" alt="{{logoAlt}}" title="{{logoAlt}}">
            </a>
            <a (click)="menuToggle($event)" class="nav-trigger" #navTrigger>
                <i class="icon icon-menu" (click)="isMenuShown = !isMenuShown;"></i>
            </a>
        </div>

        <nav class="sub-nav" [ngClass]="{'shown' : isMenuShown}">
            <a href="#" class="nav-item">about us</a>
            <a href="#" class="nav-item">team</a>
            <a href="#" class="nav-item">work</a>
        </nav>

        <div class="lets-talk" [ngClass]="{'white' : isMenuShown}">
            <a href="#" class="talk-link">
            <i class="icon icon-talk"></i>
            <p class="link-text">let's talk</p>
            </a>
        </div>

    </header>

    <main-menu (click)="onMenuSelect()" [ngClass]="{'menuShown': isMenuShown}" #mainMenu></main-menu>
`
})

export class HeaderMainComponent {

    @Input() logoAlt: string;
    @Input() logoTitle: string;

    @ViewChild('navTrigger') navTrigger: ElementRef;

    isMenuShown: false;

    constructor(private layoutService: LayoutService, private renderer: Renderer) { }

    menuToggle(event: any) {
          if (this.navTrigger.nativeElement.classList.contains('opened')) {
        this.navTrigger.nativeElement.classList.remove('opened');
        } else {
            this.navTrigger.nativeElement.classList.add('opened');
        }
    }

    onMenuSelect(event: any) {
       this.isMenuShown = false;
       this.menuToggle(event);
    }

}
</code>```

答:
try something like this:

```<code><a [routerLink]="['/home']" [routerLinkActive]="['is-active']">Home</a>
</code>```

you could add [routerLinkActive]="['your-class-name']" attribute to your link with Angular Route

Body:
I only understood how to remove a whole element with *ngIf , for a specific route that is.

Lets say I have a class applied to an element of my app (header) only for routerLink="/", meaning if I switch to "/other-page", I need the header to lose that class.

How can I achieve this?

How can I link [ngClass] to the route change?

Code:

import { Component, ElementRef, ViewChild, Renderer, AfterViewInit, Input } from '@angular/core';

import { LayoutService } from 'app/core/services/layout.service';

@Component({
    moduleId: module.id,
    selector: 'header-main',
    template: `

            about us
            team
            work

let's talk

`
})

export class HeaderMainComponent {

    @Input() logoAlt: string;
    @Input() logoTitle: string;

    @ViewChild('navTrigger') navTrigger: ElementRef;

    isMenuShown: false;

    constructor(private layoutService: LayoutService, private renderer: Renderer) { }

    menuToggle(event: any) {
          if (this.navTrigger.nativeElement.classList.contains('opened')) {
        this.navTrigger.nativeElement.classList.remove('opened');
        } else {
            this.navTrigger.nativeElement.classList.add('opened');
        }
    }

    onMenuSelect(event: any) {
       this.isMenuShown = false;
       this.menuToggle(event);
    }

}

Body:
try something like this:

<a [routerLink]="['/home']" [routerLinkActive]="['is-active']">Home</a>

you could add [routerLinkActive]="['your-class-name']" attribute to your link with Angular Route


问:
How to associate list with each enum item in c#
I have website to perform match action. I am writing code to restrict some of the action based on current match stage. For example, If first half is current stage then I should restrict direct end match without second half. For each stage, I have multiple restrict stages. Below is my stage enum.

```<code>public enum MatchStage
    {
        FirstHalfAssumedStartTime = 1,
        FirstHalfAssumedEndTime = 2,
        SecondHalfAssumedStartTime = 3,
        SecondHalfAssumedEndTime = 4,
        ExtraFirstHalfAssumedStartTime = 5,
        ExtraFirstHalfAssumedEndTime = 6,
        ExtraSecondHalfAssumedStartTime = 7,
        ExtraSecondHalfAssumedEndTime = 8,
        PauseStartTime = 9,
        PauseEndTime = 10,
        EndMatchTime = 11
    }
</code>```

I would like to make below method work. I want to call something like currentSiteCoreStage.RestrictedStages which returns List of restricted stages. How can I achieve this?

```<code>public static bool IsProposedStageValid(MatchStage currentSiteCoreStage, MatchStage proposedStage )
        {
            if (currentSiteCoreStage.RestrictedStages.Contains(proposedStage)) // I am hoping to make this work
                return false;
        }
</code>```

答:
Maybe consider something like this:
1: Your enum

2:

```<code>public class Stage
{
    public MatchStage MathStage { get; set; }
    public List<MatchStage> PossibleStages { get; set; }
}
</code>```

3.

```<code>public static bool IsProposedStageValid(Stage currentSiteCoreStage, MatchStage proposedStage)
{
     if (currentSiteCoreStage.PossibleStages.Contains(proposedStage)) // I am hoping to make this work
     return false;

     return true;
}
</code>```

Example:

```<code>Stage st1 = new Stage
{
      MathStage = MatchStage.FirstHalfAssumedStartTime,
      PossibleStages = new List<MatchStage> { MatchStage.FirstHalfAssumedEndTime }
};

bool res = IsProposedStageValid(st1, MatchStage.PauseEndTime);
</code>```

Body:
I have website to perform match action. I am writing code to restrict some of the action based on current match stage. For example, If first half is current stage then I should restrict direct end match without second half. For each stage, I have multiple restrict stages. Below is my stage enum.

public enum MatchStage
    {
        FirstHalfAssumedStartTime = 1,
        FirstHalfAssumedEndTime = 2,
        SecondHalfAssumedStartTime = 3,
        SecondHalfAssumedEndTime = 4,
        ExtraFirstHalfAssumedStartTime = 5,
        ExtraFirstHalfAssumedEndTime = 6,
        ExtraSecondHalfAssumedStartTime = 7,
        ExtraSecondHalfAssumedEndTime = 8,
        PauseStartTime = 9,
        PauseEndTime = 10,
        EndMatchTime = 11
    }

I would like to make below method work. I want to call something like currentSiteCoreStage.RestrictedStages which returns List of restricted stages. How can I achieve this?

public static bool IsProposedStageValid(MatchStage currentSiteCoreStage, MatchStage proposedStage )
        {
            if (currentSiteCoreStage.RestrictedStages.Contains(proposedStage)) // I am hoping to make this work
                return false;
        }

Body:
Maybe consider something like this:
1: Your enum

2:

public class Stage
{
    public MatchStage MathStage { get; set; }
    public List<MatchStage> PossibleStages { get; set; }
}

3.

public static bool IsProposedStageValid(Stage currentSiteCoreStage, MatchStage proposedStage)
{
     if (currentSiteCoreStage.PossibleStages.Contains(proposedStage)) // I am hoping to make this work
     return false;

     return true;
}

Example:

Stage st1 = new Stage
{
      MathStage = MatchStage.FirstHalfAssumedStartTime,
      PossibleStages = new List<MatchStage> { MatchStage.FirstHalfAssumedEndTime }
};

bool res = IsProposedStageValid(st1, MatchStage.PauseEndTime);


问:
COUNT(1) OVER () with Linq to Sql
Can I do this with Linq to SQL?

```<code>select top 10 count(1) over(), * from product
</code>```

Today I do 2 selects, one to count and another to select the page:

select count(1) from product

select top 10 * from product

The select with count(1) over() is much better since return total count together the page. I profile the queries and putting count(1) over() dont add any millisecond to original

答:
How about something like this:</p>

```<code>ctx.Products.Take(10).Select(p => new {Total = ctx.Products.Count, Product = p})
</code>```

Title: COUNT(1) OVER () with Linq to Sql

Body:
Can I do this with Linq to SQL?

select top 10 count(1) over(), * from product

Today I do 2 selects, one to count and another to select the page:

select count(1) from product

select top 10 * from product

The select with count(1) over() is much better since return total count together the page. I profile the queries and putting count(1) over() dont add any millisecond to original

Body:
How about something like this:

ctx.Products.Take(10).Select(p => new {Total = ctx.Products.Count, Product = p})


问:
how i can get the sheet in excel by number in c# and how to close Excel applicatin after open it
```<code>    var excelApp = new Excel.Application();
    var excelWorkbook = excelApp.Workbooks.Open(Program.FileName);
    var excelSheets1 = excelWorkbook.Worksheets;
    var excelWorksheet1 = (Excel.Worksheet)excelSheets1.Item["Sheet1"];
    for (var i = 2; i <= 62; i++)
    {

        for (var j = 2; j <= 5; j++)
        {
            var iRow = _dtCode1.NewRow();
            var cellValue = Convert.ToString(((Excel.Range)excelWorksheet1.Cells[i, j]).Value);
            var codeValue = Convert.ToString(((Excel.Range)excelWorksheet1.Cells[i + 1, j]).Value);
            iRow[0] = cellValue; iRow[1] = codeValue;
            _dtCode1.Rows.Add(iRow);
        }
        i = i + 1;
    }
</code>```

this code above in

```<code>var excelWorksheet1 = (Excel.Worksheet)excelSheets1.Item["Sheet1"];
</code>```

i wanna change Sheet1 by ID like the number of sheet in the woorkbook
the second thing is there any way to close the excel file after open it

```<code>var excelWorkbook = excelApp.Workbooks.Open(Program.FileName);
</code>```

答:
To select a sheet using its index use:

```<code>Excel.Worksheet xlWorkSheetFocus = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheetFocus.Activate();
</code>```

To close the workbook use

```<code>excelWorkbook.Close();
</code>```

To quit Excel app:

```<code>excelApp.Quit();
</code>```

Body:
    var excelApp = new Excel.Application();
    var excelWorkbook = excelApp.Workbooks.Open(Program.FileName);
    var excelSheets1 = excelWorkbook.Worksheets;
    var excelWorksheet1 = (Excel.Worksheet)excelSheets1.Item["Sheet1"];
    for (var i = 2; i <= 62; i++)
    {

        for (var j = 2; j <= 5; j++)
        {
            var iRow = _dtCode1.NewRow();
            var cellValue = Convert.ToString(((Excel.Range)excelWorksheet1.Cells[i, j]).Value);
            var codeValue = Convert.ToString(((Excel.Range)excelWorksheet1.Cells[i + 1, j]).Value);
            iRow[0] = cellValue; iRow[1] = codeValue;
            _dtCode1.Rows.Add(iRow);
        }
        i = i + 1;
    }

this code above in

var excelWorksheet1 = (Excel.Worksheet)excelSheets1.Item["Sheet1"];

i wanna change Sheet1 by ID like the number of sheet in the woorkbook
the second thing is there any way to close the excel file after open it

var excelWorkbook = excelApp.Workbooks.Open(Program.FileName);

Body:
To select a sheet using its index use:

Excel.Worksheet xlWorkSheetFocus = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheetFocus.Activate();

To close the workbook use

excelWorkbook.Close();

To quit Excel app:

excelApp.Quit();


问:
SAP Web Service throwing "Error during access to the ref node"
Using transaction code SRT_UTIL a web service call is reporting :

Error during access to the ref node 'ITEM'. The ref node is not defined or does not have the necessary type

ITEM is the name of a structure in the call.

Additionally it says the error type is CX_ST_REF_ACCESS and provides the following:

```<code><ERROR_CATEGORY>XML-Conversion</ERROR_CATEGORY>
<T100_AREA>SRT_CORE</T100_AREA>
<T100_MSGNO>143</T100_MSGNO>
</code>```

I'm able to communicate with other SAP web services (in the same interface and in others) without an issue. Using both VB .NET and PHP (using wsdl2phpgenerator).

答: I'm certain there are other reasons this error may appear, but in this case it turned out the BAPI structure name was 30 characters, which translated to 26 characters in the WSDL (sans the underscores). Decreasing the length of the names by 10 characters has resolved the issue.</p>

Body:
Using transaction code SRT_UTIL a web service call is reporting :

Error during access to the ref node 'ITEM'. The ref node is not defined or does not have the necessary type

ITEM is the name of a structure in the call.

Additionally it says the error type is CX_ST_REF_ACCESS and provides the following:

<ERROR_CATEGORY>XML-Conversion</ERROR_CATEGORY>
<T100_AREA>SRT_CORE</T100_AREA>
<T100_MSGNO>143</T100_MSGNO>

I'm able to communicate with other SAP web services (in the same interface and in others) without an issue. Using both VB .NET and PHP (using wsdl2phpgenerator).