问:
How to retrieve snapshot of map from place-picker activity?
I'm creating an app which picks places from the Google maps and stores the address in the database. I also want to store the snapshot of the picked place in the storage, so I can display the data with corresponding snapshot.

When I select a place from the map, the place-picker activity shows the following dialog:

Here in the dialog, the address, latitude and longitude and also the snapshot is shown. I know how to get address and latLng. but don't know how to store that displayed snapshot.

Here is my method which retrieves everything other than that image:

```<code>  //opening place picker activity.
protected void onActivityResult(int requestCode,
                                int resultCode, Intent data) {

    if (requestCode == PLACE_PICKER_REQUEST
            && resultCode == Activity.RESULT_OK) {

        final Place place = PlacePicker.getPlace(this, data);
        final CharSequence name = place.getName();
        final CharSequence address = place.getAddress();

        String attributions = (String) place.getAttributions();
        if (attributions == null) {
            attributions = "";
        }
        tv4.setText(place.getLatLng().toString()+"\n"+name+"\n"+address+"\n"+attributions);

    } else {
        super.onActivityResult(requestCode, resultCode, data);
    }
}
</code>```

I don't know how to get the image and store it in external or internal storage. Is it possible?  I've to take snapshot as explained in this link?

EDIT

I have the following activity, which is calling activity of place-picker:

Main2Activity.java:

```<code>import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
 import android.os.Environment;
import android.support.v4.app.NavUtils;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import  com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlacePicker;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import android.database.Cursor;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.maps.OnMapReadyCallback;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;

public class Main2Activity extends AppCompatActivity implements OnMapReadyCallback{
private static final int PLACE_PICKER_REQUEST = 1;
private TextView mName;
private TextView mAddress;
private TextView mAttributions;
private GoogleApiClient mGoogleApiClient;
public TextView tv4;
private static final LatLngBounds BOUNDS_MOUNTAIN_VIEW = new LatLngBounds(
        new LatLng(37.398160, -122.180831), new LatLng(37.430610, -121.972090));

private Toolbar toolbar;
private GoogleMap mMap;
private boolean flag = false;
DatabaseHelper myDb;
EditText newevent;
Button submit;
Button viewremainders;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);

    MapFragment mapFragment = (MapFragment) getFragmentManager() .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    myDb =new DatabaseHelper(this);
    newevent=(EditText)findViewById(R.id.newEvent);
    submit=(Button)findViewById(R.id.submit);
    viewremainders=(Button)findViewById(R.id.view);

    toolbar = (Toolbar)findViewById(R.id.app_bar0);
    setSupportActionBar(toolbar);

    getSupportActionBar().setHomeButtonEnabled(true);          //for back button to main activity.
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    Button pickerButton = (Button) findViewById(R.id.pickerButton);
    tv4 = (TextView)findViewById(R.id.textView4);
    pickerButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                PlacePicker.IntentBuilder intentBuilder =
                        new PlacePicker.IntentBuilder();
                intentBuilder.setLatLngBounds(BOUNDS_MOUNTAIN_VIEW);
                Intent intent = intentBuilder.build(Main2Activity.this);
                startActivityForResult(intent, PLACE_PICKER_REQUEST);

            } catch (GooglePlayServicesRepairableException
                    | GooglePlayServicesNotAvailableException e) {
                e.printStackTrace();
            }
        }
    });

    AddData();
    viewremainders();
}

@Override
public void onMapReady(GoogleMap map) {

    mMap = map;
}

//method for adding data in Database.
public void AddData(){
    submit.setOnClickListener(
            new View.OnClickListener(){
                @Override
                public void onClick(View v){
                    boolean isInserted =myDb.insertData(newevent.getText().toString(),tv4.getText().toString());
                    if(isInserted==true)
                        Toast.makeText(Main2Activity.this,"Data Inserted",Toast.LENGTH_LONG).show();
                    else
                        Toast.makeText(Main2Activity.this,"Data not Inserted",Toast.LENGTH_LONG).show();

                }
            }
    );
}

//Method for view all data from database.
public void viewremainders(){
    viewremainders.setOnClickListener(
            new View.OnClickListener(){
                @Override
                public void onClick(View v){
                    Cursor res= myDb.getAllData();
                    if(res.getCount()==0)
                    {
                        Showmessage("Error","No remainders found");
                        return;
                    }
                    StringBuffer buffer=new StringBuffer();
                    while(res.moveToNext())
                    {
                        buffer.append("Id : " +res.getString(0)+"\n");
                        buffer.append("Event : " +res.getString(1)+"\n");
                        buffer.append("Location : " +res.getString(2)+"\n");
                    }
                    Showmessage("Data",buffer.toString());

                }

            }
    );
}

public void Showmessage(String title,String message)
{
    AlertDialog.Builder builder=new AlertDialog.Builder(this);
    builder.setCancelable(true);
    builder.setTitle(title);
    builder.setMessage(message);
    builder.show();
}

//opening place picker activity.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == PLACE_PICKER_REQUEST
            && resultCode == Activity.RESULT_OK) {

        final Place place = PlacePicker.getPlace(this, data);
        final CharSequence name = place.getName();
        final CharSequence address = place.getAddress();

        String attributions = (String) place.getAttributions();
        if (attributions == null) {
            attributions = "";
        }
     //   tv4.setText(place.getLatLng().toString()+"\n"+name+"\n"+address+"\n"+attributions);  To get latitide and longitudes.
        tv4.setText(address+"\n"+attributions);

   /*     LatLngBounds selectedPlaceBounds = PlacePicker.getLatLngBounds(data);
        // move camera to selected bounds
        CameraUpdate camera = CameraUpdateFactory.newLatLngBounds(selectedPlaceBounds,0);
        mMap.moveCamera(camera);

        // take snapshot and implement the snapshot ready callback
        mMap.snapshot(new GoogleMap.SnapshotReadyCallback() {
            Bitmap bitmap=null;
            public void onSnapshotReady(Bitmap snapshot) {
                // handle snapshot here
                bitmap = snapshot;
                try {
                    FileOutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory().toString()+"/ing.png");
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
                    Toast.makeText(Main2Activity.this,"dsfds",Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                    Toast.makeText(Main2Activity.this,e.toString(),Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                }
            }
        });*/

    } else {
        super.onActivityResult(requestCode, resultCode, data);
    }
}

private void capture(){
    try {
        // image naming and path  to include sd card  appending name you choose for file
        String mPath = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_MOVIES).toString();

        // create bitmap screen capture
        View v1 = getWindow().getDecorView().getRootView();
        v1.setDrawingCacheEnabled(true);
        Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
        v1.setDrawingCacheEnabled(false);

        File imageFile = new File(Environment.getExternalStorageDirectory().toString()+"/"+"lllll.jpg");

        FileOutputStream outputStream = new FileOutputStream(imageFile);
        int quality = 100;
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
        outputStream.flush();
        outputStream.close();

        openScreenshot(imageFile);
    } catch (Throwable e) {
        // Several error may come out with file handling or OOM
        e.printStackTrace();
    }
}

private void openScreenshot(File imageFile) {
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    Uri uri = Uri.fromFile(imageFile);
    intent.setDataAndType(uri, "image/*");
    startActivity(intent);
}

//Methods for toolbar

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main2, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    if(id == android.R.id.home){
        NavUtils.navigateUpFromSameTask(this);
    }

    return super.onOptionsItemSelected(item);
}
}
</code>```

答: I faced same issue. I've tried with API key and Server key in both case I faced same error like "The Google Maps API server rejected your request... ". Finally I noticed that "Google Static Maps API" was disable from console. I just enable  and everything works fine.

Body:
I'm creating an app which picks places from the Google maps and stores the address in the database. I also want to store the snapshot of the picked place in the storage, so I can display the data with corresponding snapshot.

When I select a place from the map, the place-picker activity shows the following dialog:

Here in the dialog, the address, latitude and longitude and also the snapshot is shown. I know how to get address and latLng. but don't know how to store that displayed snapshot.

Here is my method which retrieves everything other than that image:

  //opening place picker activity.
protected void onActivityResult(int requestCode,
                                int resultCode, Intent data) {

    if (requestCode == PLACE_PICKER_REQUEST
            && resultCode == Activity.RESULT_OK) {

        final Place place = PlacePicker.getPlace(this, data);
        final CharSequence name = place.getName();
        final CharSequence address = place.getAddress();

        String attributions = (String) place.getAttributions();
        if (attributions == null) {
            attributions = "";
        }
        tv4.setText(place.getLatLng().toString()+"\n"+name+"\n"+address+"\n"+attributions);

    } else {
        super.onActivityResult(requestCode, resultCode, data);
    }
}

I don't know how to get the image and store it in external or internal storage. Is it possible?  I've to take snapshot as explained in this link?

EDIT

I have the following activity, which is calling activity of place-picker:

Main2Activity.java:

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
 import android.os.Environment;
import android.support.v4.app.NavUtils;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import  com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlacePicker;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import android.database.Cursor;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.maps.OnMapReadyCallback;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;

public class Main2Activity extends AppCompatActivity implements OnMapReadyCallback{
private static final int PLACE_PICKER_REQUEST = 1;
private TextView mName;
private TextView mAddress;
private TextView mAttributions;
private GoogleApiClient mGoogleApiClient;
public TextView tv4;
private static final LatLngBounds BOUNDS_MOUNTAIN_VIEW = new LatLngBounds(
        new LatLng(37.398160, -122.180831), new LatLng(37.430610, -121.972090));

private Toolbar toolbar;
private GoogleMap mMap;
private boolean flag = false;
DatabaseHelper myDb;
EditText newevent;
Button submit;
Button viewremainders;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);

    MapFragment mapFragment = (MapFragment) getFragmentManager() .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    myDb =new DatabaseHelper(this);
    newevent=(EditText)findViewById(R.id.newEvent);
    submit=(Button)findViewById(R.id.submit);
    viewremainders=(Button)findViewById(R.id.view);

    toolbar = (Toolbar)findViewById(R.id.app_bar0);
    setSupportActionBar(toolbar);

    getSupportActionBar().setHomeButtonEnabled(true);          //for back button to main activity.
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    Button pickerButton = (Button) findViewById(R.id.pickerButton);
    tv4 = (TextView)findViewById(R.id.textView4);
    pickerButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                PlacePicker.IntentBuilder intentBuilder =
                        new PlacePicker.IntentBuilder();
                intentBuilder.setLatLngBounds(BOUNDS_MOUNTAIN_VIEW);
                Intent intent = intentBuilder.build(Main2Activity.this);
                startActivityForResult(intent, PLACE_PICKER_REQUEST);

            } catch (GooglePlayServicesRepairableException
                    | GooglePlayServicesNotAvailableException e) {
                e.printStackTrace();
            }
        }
    });

    AddData();
    viewremainders();
}

@Override
public void onMapReady(GoogleMap map) {

    mMap = map;
}

//method for adding data in Database.
public void AddData(){
    submit.setOnClickListener(
            new View.OnClickListener(){
                @Override
                public void onClick(View v){
                    boolean isInserted =myDb.insertData(newevent.getText().toString(),tv4.getText().toString());
                    if(isInserted==true)
                        Toast.makeText(Main2Activity.this,"Data Inserted",Toast.LENGTH_LONG).show();
                    else
                        Toast.makeText(Main2Activity.this,"Data not Inserted",Toast.LENGTH_LONG).show();

                }
            }
    );
}

//Method for view all data from database.
public void viewremainders(){
    viewremainders.setOnClickListener(
            new View.OnClickListener(){
                @Override
                public void onClick(View v){
                    Cursor res= myDb.getAllData();
                    if(res.getCount()==0)
                    {
                        Showmessage("Error","No remainders found");
                        return;
                    }
                    StringBuffer buffer=new StringBuffer();
                    while(res.moveToNext())
                    {
                        buffer.append("Id : " +res.getString(0)+"\n");
                        buffer.append("Event : " +res.getString(1)+"\n");
                        buffer.append("Location : " +res.getString(2)+"\n");
                    }
                    Showmessage("Data",buffer.toString());

                }

            }
    );
}

public void Showmessage(String title,String message)
{
    AlertDialog.Builder builder=new AlertDialog.Builder(this);
    builder.setCancelable(true);
    builder.setTitle(title);
    builder.setMessage(message);
    builder.show();
}

//opening place picker activity.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == PLACE_PICKER_REQUEST
            && resultCode == Activity.RESULT_OK) {

        final Place place = PlacePicker.getPlace(this, data);
        final CharSequence name = place.getName();
        final CharSequence address = place.getAddress();

        String attributions = (String) place.getAttributions();
        if (attributions == null) {
            attributions = "";
        }
     //   tv4.setText(place.getLatLng().toString()+"\n"+name+"\n"+address+"\n"+attributions);  To get latitide and longitudes.
        tv4.setText(address+"\n"+attributions);

   /*     LatLngBounds selectedPlaceBounds = PlacePicker.getLatLngBounds(data);
        // move camera to selected bounds
        CameraUpdate camera = CameraUpdateFactory.newLatLngBounds(selectedPlaceBounds,0);
        mMap.moveCamera(camera);

        // take snapshot and implement the snapshot ready callback
        mMap.snapshot(new GoogleMap.SnapshotReadyCallback() {
            Bitmap bitmap=null;
            public void onSnapshotReady(Bitmap snapshot) {
                // handle snapshot here
                bitmap = snapshot;
                try {
                    FileOutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory().toString()+"/ing.png");
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
                    Toast.makeText(Main2Activity.this,"dsfds",Toast.LENGTH_LONG).show();
                } catch (Exception e) {
                    Toast.makeText(Main2Activity.this,e.toString(),Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                }
            }
        });*/

    } else {
        super.onActivityResult(requestCode, resultCode, data);
    }
}

private void capture(){
    try {
        // image naming and path  to include sd card  appending name you choose for file
        String mPath = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_MOVIES).toString();

        // create bitmap screen capture
        View v1 = getWindow().getDecorView().getRootView();
        v1.setDrawingCacheEnabled(true);
        Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
        v1.setDrawingCacheEnabled(false);

        File imageFile = new File(Environment.getExternalStorageDirectory().toString()+"/"+"lllll.jpg");

        FileOutputStream outputStream = new FileOutputStream(imageFile);
        int quality = 100;
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
        outputStream.flush();
        outputStream.close();

        openScreenshot(imageFile);
    } catch (Throwable e) {
        // Several error may come out with file handling or OOM
        e.printStackTrace();
    }
}

private void openScreenshot(File imageFile) {
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    Uri uri = Uri.fromFile(imageFile);
    intent.setDataAndType(uri, "image/*");
    startActivity(intent);
}

//Methods for toolbar

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main2, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    if(id == android.R.id.home){
        NavUtils.navigateUpFromSameTask(this);
    }

    return super.onOptionsItemSelected(item);
}
}


来源: stackexchange

问:
Howto reconnect to a server which does not answer to close()
I am using the C++ REST SDK ("Casablanca") to receive feed from websocket servers.

Sometimes, I need to close the connection and reconnect. The library does not have a reconnect function, so I close the old connection and simply open a new one. The problem is that the server on the other side does, as it seems, not answer to my close message.

This is the code:

```<code>web::websockets::client::websocket_callback_client*  m_clClient;

///...

void Connection::reconnect()
{
    std::cout << "Debug 1" << std::endl;
    this->m_clClient.close().get();
    delete this->m_clClient;
    this->m_clClient = new web::websockets::client::websocket_callback_client();
    std::cout << "Debug2" << std::endl;
}
</code>```

As I said, it seems like the server does not answer to close(), so the program gets stuck at this->m_clClient.close().get(); forever.

I also tried deleting the session without sending a close(), like so:

```<code>web::websockets::client::websocket_callback_client*  m_clClient;

///...

void Connection::reconnect()
{
    std::cout << "Debug 1" << std::endl;
    delete this->m_clClient;
    this->m_clClient = new web::websockets::client::websocket_callback_client();
    std::cout << "Debug2" << std::endl;
}
</code>```

But the program still gets stuck after "Debug 1". I think the close() is called in the destructor of websocket_callback_client if it hasn't been done before.

I have searched the source code of the library and found the destructor of websocket_callback_client here: link :

```<code>    ~wspp_callback_client()
    {
        _ASSERTE(m_state < DESTROYED);
        std::unique_lock<std::mutex> lock(m_wspp_client_lock);

        // Now, what states could we be in?
        switch (m_state) {
        case DESTROYED:
            // This should be impossible
            std::abort();
        case CREATED:
            lock.unlock();
            break;
        case CLOSED:
        case CONNECTING:
        case CONNECTED:
        case CLOSING:
            // Unlock the mutex so connect/close can use it.
            lock.unlock();
            try
            {
                // This will do nothing in the already-connected case
                pplx::task<void>(m_connect_tce).get();
            }
            catch (...) {}
            try
            {
                // This will do nothing in the already-closing case
                close().wait();
            }
            catch (...) {}
            break;
        }

        // At this point, there should be no more references to me.
        m_state = DESTROYED;
}
</code>```

As you can see under case CLOSING: it waits for the connection to close.

The only possibility I can see at this point is to call close() without waiting for the answer and then overwriting the pointer with a new client, leaving the old one undeleted. This would be a very unclean solution.

What can I do to close the session and open a new one?

答: I ran into this issue as well and the reason I had the issue was due to my attempt to clean up the websocket_callback_client from the close handler. if I don't do that it seems to clean itself up marvelously.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am using the C++ REST SDK ("Casablanca") to receive feed from websocket servers.

Sometimes, I need to close the connection and reconnect. The library does not have a reconnect function, so I close the old connection and simply open a new one. The problem is that the server on the other side does, as it seems, not answer to my close message.

This is the code:

web::websockets::client::websocket_callback_client*  m_clClient;

///...

void Connection::reconnect()
{
    std::cout << "Debug 1" << std::endl;
    this->m_clClient.close().get();
    delete this->m_clClient;
    this->m_clClient = new web::websockets::client::websocket_callback_client();
    std::cout << "Debug2" << std::endl;
}

As I said, it seems like the server does not answer to close(), so the program gets stuck at this->m_clClient.close().get(); forever.

I also tried deleting the session without sending a close(), like so:

web::websockets::client::websocket_callback_client*  m_clClient;

///...

void Connection::reconnect()
{
    std::cout << "Debug 1" << std::endl;
    delete this->m_clClient;
    this->m_clClient = new web::websockets::client::websocket_callback_client();
    std::cout << "Debug2" << std::endl;
}

But the program still gets stuck after "Debug 1". I think the close() is called in the destructor of websocket_callback_client if it hasn't been done before.

I have searched the source code of the library and found the destructor of websocket_callback_client here: link :

    ~wspp_callback_client()
    {
        _ASSERTE(m_state < DESTROYED);
        std::unique_lock<std::mutex> lock(m_wspp_client_lock);

        // Now, what states could we be in?
        switch (m_state) {
        case DESTROYED:
            // This should be impossible
            std::abort();
        case CREATED:
            lock.unlock();
            break;
        case CLOSED:
        case CONNECTING:
        case CONNECTED:
        case CLOSING:
            // Unlock the mutex so connect/close can use it.
            lock.unlock();
            try
            {
                // This will do nothing in the already-connected case
                pplx::task<void>(m_connect_tce).get();
            }
            catch (...) {}
            try
            {
                // This will do nothing in the already-closing case
                close().wait();
            }
            catch (...) {}
            break;
        }

        // At this point, there should be no more references to me.
        m_state = DESTROYED;
}

As you can see under case CLOSING: it waits for the connection to close.

The only possibility I can see at this point is to call close() without waiting for the answer and then overwriting the pointer with a new client, leaving the old one undeleted. This would be a very unclean solution.

What can I do to close the session and open a new one?


问:
Golang code to get all the pod details on my setup
I have a setup where k8s is running. When i run the "curl http://< host-ip>/api/v1/pods" i get all the pod details running on my setup. I need to do something similar using the k8s client instead, using the token/certificate authentication.

I did see some code which is similar "How can I create a simple client app with the Kubernetes Go library?" but this is not helping me much.

答:
you can create your client using

```<code>rest, err := clientcmd.BuildConfigFromFlags("", "kube-config-file")
if err != nil {
    log.Fatal("Failed to load KubeConfig", err)
}

client := clientset.NewForConfigOrDie(rest)

pods, err := client.Core().Pods("").List(api.ListOptions{})
</code>```

if you running this inside the k8s cluster you can do it by

```<code>rest, err := clientcmd.BuildConfigFromFlags("", "")
</code>```

Body:
you can create your client using

rest, err := clientcmd.BuildConfigFromFlags("", "kube-config-file")
if err != nil {
    log.Fatal("Failed to load KubeConfig", err)
}

client := clientset.NewForConfigOrDie(rest)

pods, err := client.Core().Pods("").List(api.ListOptions{})

if you running this inside the k8s cluster you can do it by

rest, err := clientcmd.BuildConfigFromFlags("", "")


问:
How to fetch data from two tables based on session variable php?
Actually im trying to display data from 2 tables on database based on current session, basically, i had read many article and forum on how to solve this problem but i still facing them till now. so those are data and code that already i did:

```<code><?php
include('db.php');

$sql="SELECT*
FROM users
INNER JOIN details ON users.id= details.id LIMIT 1 WHERE users.id ='$loggedin_id' " ;

$result=mysqli_query($db,$sql);
if (!$result) {
printf("Error: %s\n", mysqli_error($db));
exit();
}
?>
</code>```

so here, i got this error:
"Error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE users.id = '16'' at line 3". so if i only use this query:

```<code> $sql="SELECT* FROM users INNER JOIN details ON users.id= details.id"
</code>```

it will display all data in my database, but i only need data from current session.

here is my session.php file:

```<code><?php
include('db.php');
session_start();
$user_check=$_SESSION['sess_username'];
$ses_sql=mysqli_query($db,"select username,id from users where username='$user_check' ");
$row=mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);
$loggedin_session=$row['username'];
$loggedin_id=$row['id'];
$role = $_SESSION['sess_userrole'];
if(!isset($loggedin_session) && $role!="user"){
  header('Location: index.php?err=2');
}
?>
</code>```

this is my tables detail:
table users
table details

hope someone can help me, im new with my sql and php. tq

答:
Change your query like that.</p>

```<code>$sql="SELECT*
FROM users
INNER JOIN details ON users.id= details.id WHERE users.id ='$loggedin_id' LIMIT 1" ;
</code>```

Body:
Actually im trying to display data from 2 tables on database based on current session, basically, i had read many article and forum on how to solve this problem but i still facing them till now. so those are data and code that already i did:

<?php
include('db.php');

$sql="SELECT*
FROM users
INNER JOIN details ON users.id= details.id LIMIT 1 WHERE users.id ='$loggedin_id' " ;

$result=mysqli_query($db,$sql);
if (!$result) {
printf("Error: %s\n", mysqli_error($db));
exit();
}
?>

so here, i got this error:
"Error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE users.id = '16'' at line 3". so if i only use this query:

 $sql="SELECT* FROM users INNER JOIN details ON users.id= details.id"

it will display all data in my database, but i only need data from current session.

here is my session.php file:

<?php
include('db.php');
session_start();
$user_check=$_SESSION['sess_username'];
$ses_sql=mysqli_query($db,"select username,id from users where username='$user_check' ");
$row=mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);
$loggedin_session=$row['username'];
$loggedin_id=$row['id'];
$role = $_SESSION['sess_userrole'];
if(!isset($loggedin_session) && $role!="user"){
  header('Location: index.php?err=2');
}
?>

this is my tables detail:
table users
table details

hope someone can help me, im new with my sql and php. tq

Body:
Change your query like that.

$sql="SELECT*
FROM users
INNER JOIN details ON users.id= details.id WHERE users.id ='$loggedin_id' LIMIT 1" ;


问:
Jquery addClass is not working?
When I click on any categories it is adding class as "active", but when I click on other, then categories it is refreshing and class is removed. how to resolve this?

Below is HTML code,

```<code><div class="flDropDiv category_fl">
                            <div class="flItems"><a class="category_filter" data-value="Fitted bed Sheet " href="http://192.168.1.156/eles/bed-linen/fitted-bed-sheet"> Fitted bed Sheet  </a> </div>
                            <div class="flItems"><a class="category_filter" data-value="Flat bed sheet " href="http://192.168.1.156/eles/bed-linen/flat-bed-sheet"> Flat bed sheet  </a> </div>
                            <div class="flItems"><a class="category_filter" data-value="Full bed sheets  " href="http://192.168.1.156/eles/bed-linen/full-bed-sheets"> Full bed sheets   </a> </div>
                            <div class="flItems"><a class="category_filter" data-value="Twin bed sheet " href="http://192.168.1.156/eles/bed-linen/twin-bed-sheet"> Twin bed sheet  </a> </div>
                            <div class="flItems"><a class="category_filter" data-value="Twinxl bed sheets  " href="http://192.168.1.156/eles/bed-linen/twinxl-bed-sheets"> Twinxl bed sheets   </a> </div>
                            <div class="flItems"><a class="category_filter" data-value="Queen bed sheet " href="http://192.168.1.156/eles/bed-linen/queen-bed-sheet"> Queen bed sheet  </a> </div>
                            <div class="flItems"><a class="category_filter" data-value="King bed sheets " href="http://192.168.1.156/eles/bed-linen/king-bed-sheets"> King bed sheets  </a> </div>
                            <div class="flItems"><a class="category_filter" data-value="Cal king bed sheets " href="http://192.168.1.156/eles/bed-linen/cal-king-bed-sheets"> Cal king bed sheets  </a> </div>
                            <div class="flItems"><a class="category_filter" data-value="Duvet covers " href="http://192.168.1.156/eles/bed-linen/duvet-covers"> Duvet covers  </a> </div>
                            <div class="flItems"><a class="category_filter" data-value="Bed skirts " href="http://192.168.1.156/eles/bed-linen/bed-skirts"> Bed skirts  </a> </div>
                            <div class="flItems"><a class="category_filter" data-value="Standard Pillow cases " href="http://192.168.1.156/eles/bed-linen/standard-pillow-cases"> Standard Pillow cases  </a> </div>
                            <div class="flItems"><a class="category_filter" data-value="King Pillow cases " href="http://192.168.1.156/eles/bed-linen/king-pillow-cases"> King Pillow cases  </a> </div>
                            <div class="flItems"><a class="category_filter" data-value="Pillow shells " href="http://192.168.1.156/eles/bed-linen/pillow-shells"> Pillow shells  </a> </div>
                        </div>
</code>```

Jquery Code,

```<code>    var localStorageIndex = "clickedLink";
$(function() {
  $(".category_filter").click(function(e) {
    if($(e.target).hasClass("active")){
    return;
    }
    var clickedLink = getActiveLinkFromLocalStorage();
    if(clickedLink !== e.target.href){
      clickedLink = e.target.href;
      $(e.target).addClass("active");
      localStorage.setItem(localStorageIndex, clickedLink);
    }
  })

  function getActiveLinkFromLocalStorage() {
    return localStorage.getItem(localStorageIndex);
  }

  function initActiveLink(){
    var clickedLink = getActiveLinkFromLocalStorage();
    if(!clickedLink){
      return;
    }
      localStorage.clear();
      $("a[href='" + clickedLink + "'].category_filter").addClass("active");
  }
  initActiveLink();
});
</code>```

答:
Please check the below code. Hope this will help you.

$(document).ready(function(){
   $(".category_filter li a").each(function() {
       $(this).click(function() {
           $(".category_filter li a").removeClass("active");
           $(this).addClass("active");
      });
});
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.active{color:red;}</code>```

Filter 1

Filter 2

Filter 3

Filter 4

                           ```

Title: Jquery addClass is not working?

Body:
When I click on any categories it is adding class as "active", but when I click on other, then categories it is refreshing and class is removed. how to resolve this?

Below is HTML code,

 Fitted bed Sheet

 Flat bed sheet

 Full bed sheets

 Twin bed sheet

 Twinxl bed sheets

 Queen bed sheet

 King bed sheets

 Cal king bed sheets

 Duvet covers

 Bed skirts

 Standard Pillow cases

 King Pillow cases

 Pillow shells

Jquery Code,

    var localStorageIndex = "clickedLink";
$(function() {
  $(".category_filter").click(function(e) {
    if($(e.target).hasClass("active")){
    return;
    }
    var clickedLink = getActiveLinkFromLocalStorage();
    if(clickedLink !== e.target.href){
      clickedLink = e.target.href;
      $(e.target).addClass("active");
      localStorage.setItem(localStorageIndex, clickedLink);
    }
  })

  function getActiveLinkFromLocalStorage() {
    return localStorage.getItem(localStorageIndex);
  }

  function initActiveLink(){
    var clickedLink = getActiveLinkFromLocalStorage();
    if(!clickedLink){
      return;
    }
      localStorage.clear();
      $("a[href='" + clickedLink + "'].category_filter").addClass("active");
  }
  initActiveLink();
});

Body:
Please check the below code. Hope this will help you.

$(document).ready(function(){
   $(".category_filter li a").each(function() {
       $(this).click(function() {
           $(".category_filter li a").removeClass("active");
           $(this).addClass("active");
      });
});
});

.active{color:red;}

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

<div class="categories-filters">
<ul class="category_filter">
<li><a href="#">Filter 1 </a></li>
<li><a href="#">Filter 2 </a></li>
<li><a href="#">Filter 3 </a></li>
<li><a href="#">Filter 4 </a></li>
</ul>
</div>


问:
Best way add a new column with sequential numbering in an existing data table
I have a non empty datatable . What is the best way to add another column to it that has sequential numbering starting from 1.

I tried the following code. But did not work.

```<code>DataColumn dc = new DataColumn("Col1");
dc.AutoIncrement = true;
dc.AutoIncrementSeed = 1;
dc.AutoIncrementStep = 1;
dc.DataType = typeof(Int32);
dt.Columns.Add(dc);
</code>```

Will setting any expression help in this scenario ?

Thanks in Advance

答:
I think you could achieve that by using a 2nd "helper" data table that would contain just an auto-increment field and then you populate/merge it with the existing data, something like this:

```<code>DataTable dtIncremented  = new DataTable(dt.TableName);
DataColumn dc            = new DataColumn("Col1");
dc.AutoIncrement         = true;
dc.AutoIncrementSeed     = 1;
dc.AutoIncrementStep     = 1;
dc.DataType              = typeof(Int32);
dtIncremented.Columns.Add(dc);

dtIncremented.BeginLoadData();

DataTableReader dtReader = new DataTableReader(dt);
dtIncremented.Load(dtReader);

dtIncremented.EndLoadData();
</code>```

And then you would just return dtIncremented table instead of the original dt. Not an elegant solution but should work.

ContentLicense: CC BY-SA 2.5

Body:
I have a non empty datatable . What is the best way to add another column to it that has sequential numbering starting from 1.

I tried the following code. But did not work.

DataColumn dc = new DataColumn("Col1");
dc.AutoIncrement = true;
dc.AutoIncrementSeed = 1;
dc.AutoIncrementStep = 1;
dc.DataType = typeof(Int32);
dt.Columns.Add(dc);

Will setting any expression help in this scenario ?

Thanks in Advance

Body:
I think you could achieve that by using a 2nd "helper" data table that would contain just an auto-increment field and then you populate/merge it with the existing data, something like this:

DataTable dtIncremented  = new DataTable(dt.TableName);
DataColumn dc            = new DataColumn("Col1");
dc.AutoIncrement         = true;
dc.AutoIncrementSeed     = 1;
dc.AutoIncrementStep     = 1;
dc.DataType              = typeof(Int32);
dtIncremented.Columns.Add(dc);

dtIncremented.BeginLoadData();

DataTableReader dtReader = new DataTableReader(dt);
dtIncremented.Load(dtReader);

dtIncremented.EndLoadData();

And then you would just return dtIncremented table instead of the original dt. Not an elegant solution but should work.


问:
Calculate slope and intercept value for logarithmic trendline as excel
I am generating Logarithmic trendlines and used Excel formula for this. But i can't calculate slope and intercept value as calculated in Excel. I think, i did some mistakes in my formula.

This is my code

```<code> var X= [10, 25, 30, 40]; Y= [5, 4, 7, 12];

 var Slope, Intercept, SX = 0, SY = 0,
            SXX = 0, SXY = 0, SYY = 0,
            SumProduct = 0, N = X.length;

            for (var i = 0; i < N; i++) {
                SX = SX + X[i];
                SY = SY + Y[i];
                SXY = SXY + X[i] * Y[i];
                SXX = SXX + X[i] * X[i];
                SYY = SYY + Y[i] * Y[i];
            }

            Slope = ((N * SXY) - (SX * SY)) / ((N * SXX) - (SX * SX));

            Intercept = (SY - (Slope * SX)) / N;
</code>```

Fiddle link

Excel Formula:

Logarithmic Equation: y=(c*LN(x))+b

where:

```<code>c = INDEX(LINEST(y,LN(x)),1)
b = INDEX(LINEST(y,LN(x)),1,2)
</code>```

Screenshot for Excel output

Please suggest how to derive the Excel formula in JavaScript.

答:
You missed Math.log() for ln() in Excel. Edit for parts like this.

```<code>for (var i = 0; i < N; i++) {
    SX = SX + Math.log(X[i]);
    SY = SY + Y[i];
    SXY = SXY + Math.log(X[i]) * Y[i];
    SXX = SXX + Math.log(X[i]) * Math.log(X[i]);
    SYY = SYY + Y[i] * Y[i];
}
</code>```

I've verified the output is the sams as Excel.

```<code>> Slope
3.8860409979365333
> Intercept
-5.252238189415747
</code>```

Body:
I am generating Logarithmic trendlines and used Excel formula for this. But i can't calculate slope and intercept value as calculated in Excel. I think, i did some mistakes in my formula.

This is my code

 var X= [10, 25, 30, 40]; Y= [5, 4, 7, 12];

 var Slope, Intercept, SX = 0, SY = 0,
            SXX = 0, SXY = 0, SYY = 0,
            SumProduct = 0, N = X.length;

            for (var i = 0; i < N; i++) {
                SX = SX + X[i];
                SY = SY + Y[i];
                SXY = SXY + X[i] * Y[i];
                SXX = SXX + X[i] * X[i];
                SYY = SYY + Y[i] * Y[i];
            }

            Slope = ((N * SXY) - (SX * SY)) / ((N * SXX) - (SX * SX));

            Intercept = (SY - (Slope * SX)) / N;

Fiddle link

Excel Formula:

Logarithmic Equation: y=(c*LN(x))+b

where:

c = INDEX(LINEST(y,LN(x)),1)
b = INDEX(LINEST(y,LN(x)),1,2)

Screenshot for Excel output

Please suggest how to derive the Excel formula in JavaScript.

Body:
You missed Math.log() for ln() in Excel. Edit for parts like this.

for (var i = 0; i < N; i++) {
    SX = SX + Math.log(X[i]);
    SY = SY + Y[i];
    SXY = SXY + Math.log(X[i]) * Y[i];
    SXX = SXX + Math.log(X[i]) * Math.log(X[i]);
    SYY = SYY + Y[i] * Y[i];
}

I've verified the output is the sams as Excel.

> Slope
3.8860409979365333
> Intercept
-5.252238189415747


问:
Failed to resolve 'kafka:9092': Name or service not known - docker / php-rdkafka
I am trying to get php connecting to kafka all within a docker container.

kafka php lib - https://github.com/arnaud-lb/php-rdkafka/

kafka docker container - https://hub.docker.com/r/wurstmeister/kafka/

Everything is building and running ok, but when I try to connect with the PHP producer, I get the following:

```<code>httpd_1   | %3|1490816385.542|FAIL|rdkafka#producer-1| [thrd:kafka:9092/bootstrap]: kafka:9092/bootstrap: Failed to resolve 'kafka:9092': Name or service not known
httpd_1   | %3|1490816385.543|ERROR|rdkafka#producer-1| [thrd:kafka:9092/bootstrap]: kafka:9092/bootstrap: Failed to resolve 'kafka:9092': Name or service not known
httpd_1   | %3|1490816385.543|ERROR|rdkafka#producer-1| [thrd:kafka:9092/bootstrap]: 1/1 brokers are down
</code>```

I am using the following in PHP

```<code>    $rk = new RdKafka\Producer();
    $rk->setLogLevel(LOG_DEBUG);
    $rk->addBrokers("kafka");

    $topicConf = new RdKafka\TopicConf();
    $topicConf->set("message.timeout.ms", 1000);
    $topic = $rk->newTopic("DEV", $topicConf);

    $topic->produce(RD_KAFKA_PARTITION_UA, 0, "Message");

    $rk->poll(1000);
    $kafkaConf = new RdKafka\Conf();
    $kafkaConf->setErrorCb(function ($rk, $err, $reason) {
        printf("Kafka error: %s (reason: %s)\n", rd_kafka_err2str($err), $reason);
    });
    $kafkaConf->setDrMsgCb(function ($rk, $message) {
        if ($message->err) {
            print_r($message);
        } else {
            print_r("ok");
        }
    });
</code>```

I've played around, trying to set the host IP in both the docker-compose.yml and the PHP code, but no joy. I also had connection refused but I don't know if thats better or worse?

If it helps, my docker-compose.yml

```<code>httpd:
  build: .
  ports:
  - 8180:80
  volumes:
  - ~/www:/var/www/html
zookeeper:
  image: wurstmeister/zookeeper
  ports:
  - "2181:2181"
kafka:
  build: ~/kafka-docker/.
  links:
  - zookeeper
  ports:
  - "9092:9092"
  environment:
    KAFKA_ADVERTISED_HOST_NAME: kafka
    KAFKA_ADVERTISED_PORT: 9092
    KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
  volumes:
  - /var/run/docker.sock:/var/run/docker.sock
</code>```

PHP version: 7.0.17

librdkafka version: 0.9.5.0

php-rdkafka version: 2.0.1

My question: Any idea how I can connect to kafka successfully from php?

答:
The brokers will advertise themselve using advertised.listeners (which seems to be abstracted with KAFKA_ADVERTISED_HOST_NAME in that docker image) and the clients will consequently try to connect to these advertised hosts and ports.

You will thus need to make sure the client can resolve and reach this advertised hostnames, e.g. by adding "kafka" to /etc/hosts on the client host.

Body:
I am trying to get php connecting to kafka all within a docker container.

kafka php lib - https://github.com/arnaud-lb/php-rdkafka/

kafka docker container - https://hub.docker.com/r/wurstmeister/kafka/

Everything is building and running ok, but when I try to connect with the PHP producer, I get the following:

httpd_1   | %3|1490816385.542|FAIL|rdkafka#producer-1| [thrd:kafka:9092/bootstrap]: kafka:9092/bootstrap: Failed to resolve 'kafka:9092': Name or service not known
httpd_1   | %3|1490816385.543|ERROR|rdkafka#producer-1| [thrd:kafka:9092/bootstrap]: kafka:9092/bootstrap: Failed to resolve 'kafka:9092': Name or service not known
httpd_1   | %3|1490816385.543|ERROR|rdkafka#producer-1| [thrd:kafka:9092/bootstrap]: 1/1 brokers are down

I am using the following in PHP

    $rk = new RdKafka\Producer();
    $rk->setLogLevel(LOG_DEBUG);
    $rk->addBrokers("kafka");

    $topicConf = new RdKafka\TopicConf();
    $topicConf->set("message.timeout.ms", 1000);
    $topic = $rk->newTopic("DEV", $topicConf);

    $topic->produce(RD_KAFKA_PARTITION_UA, 0, "Message");

    $rk->poll(1000);
    $kafkaConf = new RdKafka\Conf();
    $kafkaConf->setErrorCb(function ($rk, $err, $reason) {
        printf("Kafka error: %s (reason: %s)\n", rd_kafka_err2str($err), $reason);
    });
    $kafkaConf->setDrMsgCb(function ($rk, $message) {
        if ($message->err) {
            print_r($message);
        } else {
            print_r("ok");
        }
    });

I've played around, trying to set the host IP in both the docker-compose.yml and the PHP code, but no joy. I also had connection refused but I don't know if thats better or worse?

If it helps, my docker-compose.yml

httpd:
  build: .
  ports:
  - 8180:80
  volumes:
  - ~/www:/var/www/html
zookeeper:
  image: wurstmeister/zookeeper
  ports:
  - "2181:2181"
kafka:
  build: ~/kafka-docker/.
  links:
  - zookeeper
  ports:
  - "9092:9092"
  environment:
    KAFKA_ADVERTISED_HOST_NAME: kafka
    KAFKA_ADVERTISED_PORT: 9092
    KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
  volumes:
  - /var/run/docker.sock:/var/run/docker.sock

PHP version: 7.0.17

librdkafka version: 0.9.5.0

php-rdkafka version: 2.0.1

My question: Any idea how I can connect to kafka successfully from php?


问:
Adding string Array in Angular
I have created this app in Angular as a practice can't seem to add the amount to a total value... Here is the Code I need to put the total value of the amount.

```<code><body>
<div class="container" ng-app="myApp" ng-controller="namesCtrl">
<div class="col-sm-6"><br>
<button  class="btn btn-default" ng-click="myFunc()">Show me the Table</button><br>
<div ng-show="showMe">
<table  class="table"  width="80%" border="2px">

    <tr class="panel panel-default">
        <th> Names</th>
        <th>Country</th>
        <th>Amount</th>
    </tr>
    <tr ng-repeat= "x in names">
        <td class="info"> {{x.name}}</td>
        <td class="danger">{{x.country}}</td>
        <td class="default">{{x.amount}}</td>
    </tr>

</table>
</div>
</div>
</div>
<script>
    var app=angular.module("myApp", []);
    app.controller("namesCtrl", function($scope){

$scope.names = [
    {name:'Jani',country:'Norway',  amount:'321'},
    {name:'Carl',country:'Sweden',amount:'2231'},
    {name:'Margareth',country:'England',amount:'521'},
    {name:'Hege',country:'Norway',amount:'1720'},
    {name:'Joe',country:'Denmark',amount:'376'},
    {name:'Gustav',country:'Sweden',amount:'3040'},
    {name:'Birgit',country:'Denmark',amount:'1115'},
    {name:'Mary',country:'England',amount:'4501'},
    {name:'Kai',country:'Norway',amount:'4533'}
    ];

        $scope.showMe=false;
        $scope.myFunc=function(){
        $scope.showMe=!$scope.showMe;

    }

    });

</script>
</body>
</html>
</code>```

it would be help ful for me to Know how to add the amount to a total value.

答:
you can use javascript reduce method to get the sum of array

ES6 implementation

```<code>$scope.sum = $scope.names.reduce((a, b) => a + parseInt(b.amount), 0);
</code>```

ES5 implementation

```<code>$scope.sum = $scope.names.reduce(function(a,b){
  return  a + parseInt(b.amount)
},0);
</code>```

Demo

angular.module("app",[])
.controller("ctrl",function($scope){
$scope.names = [
    {name:'Jani',country:'Norway',  amount:'321'},
    {name:'Carl',country:'Sweden',amount:'2231'},
    {name:'Margareth',country:'England',amount:'521'},
    {name:'Hege',country:'Norway',amount:'1720'},
    {name:'Joe',country:'Denmark',amount:'376'},
    {name:'Gustav',country:'Sweden',amount:'3040'},
    {name:'Birgit',country:'Denmark',amount:'1115'},
    {name:'Mary',country:'England',amount:'4501'},
    {name:'Kai',country:'Norway',amount:'4533'}
    ];

      /// es6
    $scope.sum = $scope.names.reduce((a, b) => a + parseInt(b.amount), 0);

    console.log('es6 - '+$scope.sum)

    /// es5

    $scope.sum = $scope.names.reduce(function(a,b){
      return  a + parseInt(b.amount)
    },0);

    console.log("es5 - "+$scope.sum)

})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">

</div></code>```

Title: Adding string Array in Angular

Body:
I have created this app in Angular as a practice can't seem to add the amount to a total value... Here is the Code I need to put the total value of the amount.

<button  class="btn btn-default" ng-click="myFunc()">Show me the Table</button>

         Names
        Country
        Amount

         {{x.name}}
        {{x.country}}
        {{x.amount}}

it would be help ful for me to Know how to add the amount to a total value.

Body:
you can use javascript reduce method to get the sum of array

ES6 implementation

$scope.sum = $scope.names.reduce((a, b) => a + parseInt(b.amount), 0);

ES5 implementation

$scope.sum = $scope.names.reduce(function(a,b){
  return  a + parseInt(b.amount)
},0);

Demo

angular.module("app",[])
.controller("ctrl",function($scope){
$scope.names = [
    {name:'Jani',country:'Norway',  amount:'321'},
    {name:'Carl',country:'Sweden',amount:'2231'},
    {name:'Margareth',country:'England',amount:'521'},
    {name:'Hege',country:'Norway',amount:'1720'},
    {name:'Joe',country:'Denmark',amount:'376'},
    {name:'Gustav',country:'Sweden',amount:'3040'},
    {name:'Birgit',country:'Denmark',amount:'1115'},
    {name:'Mary',country:'England',amount:'4501'},
    {name:'Kai',country:'Norway',amount:'4533'}
    ];

      /// es6
    $scope.sum = $scope.names.reduce((a, b) => a + parseInt(b.amount), 0);

    console.log('es6 - '+$scope.sum)

    /// es5

    $scope.sum = $scope.names.reduce(function(a,b){
      return  a + parseInt(b.amount)
    },0);

    console.log("es5 - "+$scope.sum)

})

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">

</div>


问:
NEXT_DAY function works differently in SQL vs. PL/SQL?
Why does this SQL query work:

```<code>SELECT NEXT_DAY(SYSDATE, 7)
FROM DUAL;
</code>```

```<code>NEXT_DAY(SYSDATE,7)
-------------------
01-APR-17
1 row selected.
</code>```

...but this anonymous block of PL/SQL does not work?

```<code>DECLARE
  dteExpires DATE;
BEGIN
  dteExpires := NEXT_DAY(SYSDATE, 7);
END;
</code>```

```<code>Error at line 1
ORA-01846: not a valid day of the week
ORA-06512: at line 4
</code>```

I do not want to hard code the second parameter to the English name of a day ex. NEXT_DAY(SYSDATE, 'SATURDAY') or NEXT_DAY(SYSDATE, 'SUNDAY') etc.

For now, I will use the following work around, but I would really like to know why NEXT_DAY() behaves differently in PL/SQL than in SQL.

```<code>DECLARE
  dteExpires DATE;
BEGIN
  -- 2017-01-01 = SUNDAY
  dteExpires := NEXT_DAY(SYSDATE, TO_CHAR(TO_DATE('2017-01-01', 'YYYY-MM-DD'), 'DAY'));
END;
</code>```

This is my DEV environment:

```<code>SELECT *
FROM v$version;
</code>```

```<code>BANNER

--------------------------------------------------------------------------------
Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production
PL/SQL Release 12.1.0.2.0 - Production
CORE  12.1.0.2.0  Production
TNS for 64-bit Windows: Version 12.1.0.2.0 - Production
NLSRTL Version 12.1.0.2.0 - Production

5 rows selected.
</code>```

答:
I think the only way to make function NEXT_DAY independent from current session NLS_DATE_LANGUAGE is to workaround with ISO week where first day of week is always Monday:

```<code>SELECT NEXT_DAY(SYSDATE, TO_CHAR(TRUNC(SYSDATE, 'IW')+5, 'Day'))
from dual;
</code>```

TRUNC(SYSDATE, 'IW')+5 means "Next Saturday"

Body:
Why does this SQL query work:

SELECT NEXT_DAY(SYSDATE, 7)
FROM DUAL;

NEXT_DAY(SYSDATE,7)
-------------------
01-APR-17
1 row selected.

...but this anonymous block of PL/SQL does not work?

DECLARE
  dteExpires DATE;
BEGIN
  dteExpires := NEXT_DAY(SYSDATE, 7);
END;

Error at line 1
ORA-01846: not a valid day of the week
ORA-06512: at line 4

I do not want to hard code the second parameter to the English name of a day ex. NEXT_DAY(SYSDATE, 'SATURDAY') or NEXT_DAY(SYSDATE, 'SUNDAY') etc.

For now, I will use the following work around, but I would really like to know why NEXT_DAY() behaves differently in PL/SQL than in SQL.

DECLARE
  dteExpires DATE;
BEGIN
  -- 2017-01-01 = SUNDAY
  dteExpires := NEXT_DAY(SYSDATE, TO_CHAR(TO_DATE('2017-01-01', 'YYYY-MM-DD'), 'DAY'));
END;

This is my DEV environment:

SELECT *
FROM v$version;

BANNER

--------------------------------------------------------------------------------
Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production
PL/SQL Release 12.1.0.2.0 - Production
CORE  12.1.0.2.0  Production
TNS for 64-bit Windows: Version 12.1.0.2.0 - Production
NLSRTL Version 12.1.0.2.0 - Production

5 rows selected.

Body:
I think the only way to make function NEXT_DAY independent from current session NLS_DATE_LANGUAGE is to workaround with ISO week where first day of week is always Monday:

SELECT NEXT_DAY(SYSDATE, TO_CHAR(TRUNC(SYSDATE, 'IW')+5, 'Day'))
from dual;

TRUNC(SYSDATE, 'IW')+5 means "Next Saturday"


问:
How to remove character from last array element
I need to remove the last element comma in Javascript array

```<code>var arr =  ["AAA,","BBB,"];
</code>```

I need the result below

```<code>var arr =  ["AAA,","BBB"];
</code>```

Any help is appreciated...

答:
using JavaScript string split() method & Array splice() method.

DEMO

var arr =  ["AAA,","BBB,"];

var arrLastElement = arr[arr.length-1];

var splitStr =  arrLastElement.split(',');

var strWithoutComma = splitStr[0];

arr.splice(arr.length-1);
arr.push(strWithoutComma);

console.log(arr);```

Body:
I need to remove the last element comma in Javascript array

var arr =  ["AAA,","BBB,"];

I need the result below

var arr =  ["AAA,","BBB"];

Any help is appreciated...


问:
Making android listview layout scrollable
I have an xml file that has the layout in ASCII form:

```<code>---------------
| ImageView
--------------
| TextView
--------------
| List...
--------------

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myapp="http://schemas.android.com/apk/res/com.some.app"
 android:orientation="vertical" android:layout_width="fill_parent"
 android:layout_height="fill_parent">
<ImageView
android:id="@+id/MovieCover"
android:layout_width="100dip"
android:layout_height="100dip"
/>
 <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textSize="16sp"
    android:padding="10dp"
    android:id="@+id/TextHeader"
    android:background="#000000">
</TextView>
<ListView android:id="@+id/ListView02" android:layout_height="wrap_content"
 android:layout_width="fill_parent">
 </ListView>
 </LinearLayout>
</code>```

I'm having a problem displaying the layout when my ImageView and TextView takes up more than 3/4 of the screen. How do I make ImageView and TextView scrollable with the ListView that is being displayed? At this point of time, only the ListView to be scrolled and I want the entire layout to be scrollable as though they are one page on its own.

How can I do that?

答:
Butter to use two LinearLayout with layoutweight="1" and put ScrollView in one and listview in other

```<code><LinearLayout android:layout_weight="1"
        android:layout_height="fill_parent" android:layout_width="fill_parent">
        <ScrollView android:layout_width="fill_parent"
            android:layout_height="fill_parent">
            <LinearLayout android:orientation="vertical"
                android:layout_width="fill_parent"
                                android:layout_height="fill_parent">

                          <!-- scroll view content -->
            </LinearLayout>
        </ScrollView>
    </LinearLayout>
    <LinearLayout android:layout_weight="1"
        android:layout_height="fill_parent" android:layout_width="fill_parent">
        <ListView android:id="@+id/ListView02" android:layout_height="wrap_content"
            android:layout_width="fill_parent">
        </ListView>
    </LinearLayout>
</code>```

Body:
I have an xml file that has the layout in ASCII form:

---------------
| ImageView
--------------
| TextView
--------------
| List...
--------------

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myapp="http://schemas.android.com/apk/res/com.some.app"
 android:orientation="vertical" android:layout_width="fill_parent"
 android:layout_height="fill_parent">
<ImageView
android:id="@+id/MovieCover"
android:layout_width="100dip"
android:layout_height="100dip"
/>
 <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textSize="16sp"
    android:padding="10dp"
    android:id="@+id/TextHeader"
    android:background="#000000">
</TextView>
<ListView android:id="@+id/ListView02" android:layout_height="wrap_content"
 android:layout_width="fill_parent">
 </ListView>
 </LinearLayout>

I'm having a problem displaying the layout when my ImageView and TextView takes up more than 3/4 of the screen. How do I make ImageView and TextView scrollable with the ListView that is being displayed? At this point of time, only the ListView to be scrolled and I want the entire layout to be scrollable as though they are one page on its own.

How can I do that?

Body:
Butter to use two LinearLayout with layoutweight="1" and put ScrollView in one and listview in other

<LinearLayout android:layout_weight="1"
        android:layout_height="fill_parent" android:layout_width="fill_parent">
        <ScrollView android:layout_width="fill_parent"
            android:layout_height="fill_parent">
            <LinearLayout android:orientation="vertical"
                android:layout_width="fill_parent"
                                android:layout_height="fill_parent">

                          <!-- scroll view content -->
            </LinearLayout>
        </ScrollView>
    </LinearLayout>
    <LinearLayout android:layout_weight="1"
        android:layout_height="fill_parent" android:layout_width="fill_parent">
        <ListView android:id="@+id/ListView02" android:layout_height="wrap_content"
            android:layout_width="fill_parent">
        </ListView>
    </LinearLayout>


问:
Using Regex with netstat (Windows)
I am trying to get a single command line to display both TCP listening and established states and UDP connections.

So this would be one command line to show the following:

```<code>netstat -abfn  | findstr /r "[0-9]*[ED|ING]$"
netstat -abfn  | findstr UDP
</code>```

I tried the below command line but am not able to sanitize the *

```<code>netstat -abfn  | findstr /r "[0-9]*[ED|ING|*:*]$"
</code>```

Can anyone please post and explain the successful regex ?

答:
The command you need is:

```<code>netstat -abfn  | findstr /r "TCP.*[ING]$ TCP.*[ED]$ UDP.*$"
</code>```

That's because the findstr has limited use of regex's and doesn't support the | (OR) operator, but you can pass to it multiple patterns. In your case one for each:

TCP LISTENING TCP.*[ING]$

TCP ESTABLISHED TCP.*[ED]$

UDP UDP.*$

Also, this regex is not case sensitive to make it so you must use the /i parameter, if you like.

Title: Using Regex with netstat (Windows)

Body:
I am trying to get a single command line to display both TCP listening and established states and UDP connections.

So this would be one command line to show the following:

netstat -abfn  | findstr /r "[0-9]*[ED|ING]$"
netstat -abfn  | findstr UDP

I tried the below command line but am not able to sanitize the *

netstat -abfn  | findstr /r "[0-9]*[ED|ING|*:*]$"

Can anyone please post and explain the successful regex ?

Body:
The command you need is:

netstat -abfn  | findstr /r "TCP.*[ING]$ TCP.*[ED]$ UDP.*$"

That's because the findstr has limited use of regex's and doesn't support the | (OR) operator, but you can pass to it multiple patterns. In your case one for each:

TCP LISTENING TCP.*[ING]$

TCP ESTABLISHED TCP.*[ED]$

UDP UDP.*$

Also, this regex is not case sensitive to make it so you must use the /i parameter, if you like.


问:
Download attribute on A tag not working in IE
From the following code I'm creating a dynamic anchor tag which downloads a file. This code works well in Chrome but not in IE. How can I get this working</p>

```<code><div id="divContainer">
    <h3>Sample title</h3>
</div>
<button onclick="clicker()">Click me</button>

<script type="text/javascript">

    function clicker() {
        var anchorTag = document.createElement('a');
        anchorTag.href = "http://cdn1.dailymirror.lk/media/images/finance.jpg";
        anchorTag.download = "download";
        anchorTag.click();

        var element = document.getElementById('divContainer');
        element.appendChild(anchorTag);
    }

</script>
</code>```

答:
Old question, but thought I'd add our solution. Here is the code I used on my last project. It's not perfect, but it passed QA in all browsers and IE9+.

```<code>downloadCSV(data,fileName){
  var blob = new Blob([data], {type:  "text/plain;charset=utf-8;"});
  var anchor = angular.element('<a/>');

  if (window.navigator.msSaveBlob) { // IE
    window.navigator.msSaveOrOpenBlob(blob, fileName)
  } else if (navigator.userAgent.search("Firefox") !== -1) { // Firefox
    anchor.css({display: 'none'});
    angular.element(document.body).append(anchor);

    anchor.attr({
      href: 'data:attachment/csv;charset=utf-8,' + encodeURIComponent(data),
      target: '_blank',
      download: fileName
    })[0].click();

    anchor.remove();
  } else { // Chrome
    anchor.attr({
      href: URL.createObjectURL(blob),
      target: '_blank',
      download: fileName
    })[0].click();
  }
}
</code>```

Using the ms specific API worked best for us in IE. Also note that some browsers require the anchor to actually be in the DOM for the download attribute to work, whereas Chrome, for example, does not. Also, we found some inconsistencies with how Blobs work in various browsers. Some browsers also have an export limit. This allows the largest possible CSV export in each browser afaik.

Body:
From the following code I'm creating a dynamic anchor tag which downloads a file. This code works well in Chrome but not in IE. How can I get this working

Sample title

<button onclick="clicker()">Click me</button>

Body:
Old question, but thought I'd add our solution. Here is the code I used on my last project. It's not perfect, but it passed QA in all browsers and IE9+.

downloadCSV(data,fileName){
  var blob = new Blob([data], {type:  "text/plain;charset=utf-8;"});
  var anchor = angular.element('<a/>');

  if (window.navigator.msSaveBlob) { // IE
    window.navigator.msSaveOrOpenBlob(blob, fileName)
  } else if (navigator.userAgent.search("Firefox") !== -1) { // Firefox
    anchor.css({display: 'none'});
    angular.element(document.body).append(anchor);

    anchor.attr({
      href: 'data:attachment/csv;charset=utf-8,' + encodeURIComponent(data),
      target: '_blank',
      download: fileName
    })[0].click();

    anchor.remove();
  } else { // Chrome
    anchor.attr({
      href: URL.createObjectURL(blob),
      target: '_blank',
      download: fileName
    })[0].click();
  }
}

Using the ms specific API worked best for us in IE. Also note that some browsers require the anchor to actually be in the DOM for the download attribute to work, whereas Chrome, for example, does not. Also, we found some inconsistencies with how Blobs work in various browsers. Some browsers also have an export limit. This allows the largest possible CSV export in each browser afaik.


问:
Android Studio Corrupts Base64 String When Trying To Upload
So I am testing methods to upload an image to a php server. One of the methods was to convert the image to a Base64 String and upload it and then decode it when needed.

When I uploaded a picture I noticed that there was a difference in the Strings. Some spaces were missing and some next lines were misplaced.

Before I sent the string to the server the string is okay and then it goes through a _POST command in the php file and then it is inserted into the database using INSERT INTO.

I suspect that the header that I use changes the string when I try to upload it. the header is /x-www-form-urlencoded. I tried using /json but if the json object is converted to string it changes the original string. So what header do I need to use so the string won't change? Or is there another method to upload a picture to a MySQL database?

This is the method I use to upload the string to the server:

```<code>ImageString = getStringImage(bitmap);
String ImageUploadString="image="+ImageString;
final OkHttpClient client = new OkHttpClient();
MediaType contentType = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");

RequestBody body = RequestBody.create(contentType, imageUploadString));
Request request = new Request.Builder().url(uploadURL).post(body).build();
Response response = null;
try {
    response = client.newCall(request).execute();
} catch (IOException e) {
    e.printStackTrace();
}
try {
    String json = response.body().string();
} catch (IOException e) {
    e.printStackTrace();
}
</code>```

Edit: this is the php file that I use to insert the picture:

```<code><?php
$response = array();
if (isset($_POST['image']))
{
$image = $_POST['image'];
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$result = $db->query("INSERT INTO images(image) VALUES('$image')");
if ($result) {
$response["success"] = 1;
$response["message"] = "Product successfully created.";
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "missing fields";
echo json_encode($response);
}
?>
</code>```

答:
Problem is, the data you are sending to the server is being encoded somehow by your HttpClient.

you just need to decode it in php code -

For an example,

Here I was sending device id to the server, look how I did url decoding -

```<code>if(isset($_POST['device_id']) && !empty($_POST['device_id']))
    $data->device_id = urldecode($_POST['device_id']);
</code>```

Body:
So I am testing methods to upload an image to a php server. One of the methods was to convert the image to a Base64 String and upload it and then decode it when needed.

When I uploaded a picture I noticed that there was a difference in the Strings. Some spaces were missing and some next lines were misplaced.

Before I sent the string to the server the string is okay and then it goes through a _POST command in the php file and then it is inserted into the database using INSERT INTO.

I suspect that the header that I use changes the string when I try to upload it. the header is /x-www-form-urlencoded. I tried using /json but if the json object is converted to string it changes the original string. So what header do I need to use so the string won't change? Or is there another method to upload a picture to a MySQL database?

This is the method I use to upload the string to the server:

ImageString = getStringImage(bitmap);
String ImageUploadString="image="+ImageString;
final OkHttpClient client = new OkHttpClient();
MediaType contentType = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");

RequestBody body = RequestBody.create(contentType, imageUploadString));
Request request = new Request.Builder().url(uploadURL).post(body).build();
Response response = null;
try {
    response = client.newCall(request).execute();
} catch (IOException e) {
    e.printStackTrace();
}
try {
    String json = response.body().string();
} catch (IOException e) {
    e.printStackTrace();
}

Edit: this is the php file that I use to insert the picture:

<?php
$response = array();
if (isset($_POST['image']))
{
$image = $_POST['image'];
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$result = $db->query("INSERT INTO images(image) VALUES('$image')");
if ($result) {
$response["success"] = 1;
$response["message"] = "Product successfully created.";
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
echo json_encode($response);
}
} else {
$response["success"] = 0;
$response["message"] = "missing fields";
echo json_encode($response);
}
?>

Body:
Problem is, the data you are sending to the server is being encoded somehow by your HttpClient.

you just need to decode it in php code -

For an example,

Here I was sending device id to the server, look how I did url decoding -

if(isset($_POST['device_id']) && !empty($_POST['device_id']))
    $data->device_id = urldecode($_POST['device_id']);


问:
Pattern within a pattern?
I want to capture Alta, Utah, USA from asd Alta, Utah, USA qwe. Basically I'm trying to capture places from a text. It won't be a perfect method, but the places must start with a capital and use a comma, followed by another word with a capital.

So far, I have wrote:

```<code>\s[A-Z][a-z]+[,]?
</code>```

I want to do multiple words, not just the first word, Alta. This is my attempt to use square brackets inside other square brackets.

```<code>[\s[A-Z][a-z]+[,]?]+
</code>```

But that doesn't work, so it must be syntactically incorrect.

答:
Just joining the party:

```<code>import re
dirty = "asd Alta, Utah, USA qwe"
p = re.compile("([A-Z][a-zA-Z]+)")
re.findall(p,dirty)
</code>```

output:

```<code>['Alta', 'Utah', 'USA']
</code>```

Title: Pattern within a pattern?

Body:
I want to capture Alta, Utah, USA from asd Alta, Utah, USA qwe. Basically I'm trying to capture places from a text. It won't be a perfect method, but the places must start with a capital and use a comma, followed by another word with a capital.

So far, I have wrote:

\s[A-Z][a-z]+[,]?

I want to do multiple words, not just the first word, Alta. This is my attempt to use square brackets inside other square brackets.

[\s[A-Z][a-z]+[,]?]+

But that doesn't work, so it must be syntactically incorrect.

Body:
Just joining the party:

import re
dirty = "asd Alta, Utah, USA qwe"
p = re.compile("([A-Z][a-zA-Z]+)")
re.findall(p,dirty)

output:

['Alta', 'Utah', 'USA']


问:
C# PDF Printing Library
Are there any free libraries that would "print" to a PDF without actually having to install a PDF printer on the system.  I want something that can be completely self contained in my application.  The reason I say I want it to "print" is that I've tried and tried to find a solution for directly converting from HTML with CSS to PDF, but it does't seem very possible.  So I want to use the System.Windows.Forms.WebBrowser control to render the page first and then output that rendering to PDF.  I just don't want the user to be required to install a PDFPrinter.</p>

答: http://www.html-to-pdf.net/ - This isn't free but its preety cheap and effective. I am using it now to convert HTML with CSS to PDF. Essentially we display the page to the user and then with a click of a button they can download a PDF of the page. </p>

OwnerDisplayName: Adam Haile

Title: C# PDF Printing Library

OwnerDisplayName: Josh


问:
Releasing updates to your android application
I put out an android app last week, and wanted to release an update to it that will include additional phrases to a specific aspect of the app.  It isn't a big release that serves as a bug fix (no known bugs actually - fingers crossed ;p) but it will certainly add to the entertainment value of the app and add a lot of flexibility.

Is this poor practice, as new releases should include a lot of content or is this accepted for the most part?

Thanks!

答:
AFAIK, We can release minor updates to the applicatio as well, it is always acceptable and desirable.

I have also released the minor updates to my one of the application, they were for the solving the bug and issues raised in the application.

So you can also do the same !!

But for that You need to Change the versionCode and versionName attributes inside the AndroidManifest.xml file for releasing a udpate version of the same application.

For example:

```<code>  android:versionCode="2"
  android:versionName="1.0.2"
</code>```

Body:
AFAIK, We can release minor updates to the applicatio as well, it is always acceptable and desirable.

I have also released the minor updates to my one of the application, they were for the solving the bug and issues raised in the application.

So you can also do the same !!

But for that You need to Change the versionCode and versionName attributes inside the AndroidManifest.xml file for releasing a udpate version of the same application.

For example:

  android:versionCode="2"
  android:versionName="1.0.2"


问:
how does a static variable not get reassigned when inside the function
I have a question regarding the answer in this question but I can not comment on it because I have less than 50 rep.

I was wondering in the answer foo() is being called multiple times and the static variable is being assigned the same number of times. So why is it that the static variable is not reassigned to 10 each time?

答:
Actually static variables can get reassigned. But can't be redefined.

Once a static variable defined it can't get redefined throughout the life time of program. But we can change the value.


问:
Product of matrix and 3-way tensor in Numpy/Theano
I would like to compute the product of a matrix X with shape (a, b) and a tensor Y with shape (a, b, c) such that the result Z has shape (a, c), and row i (i = 1...a) of Z is the product of row i of X and the matrix slice (i, :, :) of Y.

Is there a convenient way to do this in NumPy and Theano, ideally using built-in functions, and without using loops or computing unnecessary matrix products?

答:
With your description, writing an einsum expression is easy:

```<code>In [428]: X=np.arange(6).reshape(2,3)
In [429]: Y=np.arange(2*3*4).reshape(2,3,4)

In [431]: np.einsum('ab,abc->ac',X,Y)
Out[431]:
array([[ 20,  23,  26,  29],
       [200, 212, 224, 236]])
In [432]: _.shape
Out[432]: (2, 4)
</code>```

np.matmul or the @ operator is a little trickier, though probably as fast:

```<code>In [438]: (X[:,None,:]@Y).squeeze()
Out[438]:
array([[ 20,  23,  26,  29],
       [200, 212, 224, 236]])
</code>```

The intermediate stage will be (a,1,c) in shape, i.e.

```<code>(a,1,b)@(a,b,c)=>(a,1,c)   # with sum on b
</code>```

Body:
With your description, writing an einsum expression is easy:

In [428]: X=np.arange(6).reshape(2,3)
In [429]: Y=np.arange(2*3*4).reshape(2,3,4)

In [431]: np.einsum('ab,abc->ac',X,Y)
Out[431]:
array([[ 20,  23,  26,  29],
       [200, 212, 224, 236]])
In [432]: _.shape
Out[432]: (2, 4)

np.matmul or the @ operator is a little trickier, though probably as fast:

In [438]: (X[:,None,:]@Y).squeeze()
Out[438]:
array([[ 20,  23,  26,  29],
       [200, 212, 224, 236]])

The intermediate stage will be (a,1,c) in shape, i.e.

(a,1,b)@(a,b,c)=>(a,1,c)   # with sum on b


问:
To run commands on different linux nide by jenkins
I want to jenkins to execute a list of commands on different linux node in a network.
What steps should I take to run a command on another linux node by adrressing its ip address</p>

答:
once you added the nodes.
in pilpeline groovy script
use :</p>

```<code>node('node1'){
//command execution
}
node('node2'){
//command execution
}
</code>```

Body:
once you added the nodes.
in pilpeline groovy script
use :

node('node1'){
//command execution
}
node('node2'){
//command execution
}


问:
Refined and existential types for runtime values
Suppose I want to map between some strings and integer identifiers, and I want my types to make it impossible to get a runtime failure because someone tried to look up an id that was out of range. Here's one straightforward API:

```<code>trait Vocab {
  def getId(value: String): Option[Int]
  def getValue(id: Int): Option[String]
}
</code>```

This is annoying, though, if users will typically be getting their ids from getId and therefore know they're valid. The following is an improvement in that sense:

```<code>trait Vocab[Id] {
  def getId(value: String): Option[Id]
  def getValue(id: Id): String
}
</code>```

Now we could have something like this:

```<code>class TagId private(val value: Int) extends AnyVal

object TagId {
  val tagCount: Int = 100

  def fromInt(id: Int): Option[TagId] =
    if (id >= 0 && id < tagCount) Some(new TagId(id)) else None
}
</code>```

And then our users can work with Vocab[TagId] and not have to worry about checking whether getValue lookups failed in the typical case, but they can still look up arbitrary integers if they need to. It's still pretty awkward, though, since we have to write a separate type for each kind of thing we want a vocabulary for.

We can also do something like this with refined:

```<code>import eu.timepit.refined.api.Refined
import eu.timepit.refined.numeric.Interval.ClosedOpen
import shapeless.Witness

class Vocab(values: Vector[String]) {
  type S <: Int
  type P = ClosedOpen[Witness.`0`.T, S]

  def size: S = values.size.asInstanceOf[S]

  def getId(value: String): Option[Refined[Int, P]] = values.indexOf(value) match {
    case -1 => None
    case i  => Some(Refined.unsafeApply[Int, P](i))
  }

  def getValue(id: Refined[Int, P]): String = values(id.value)
}
</code>```

Now even though S isn't known at compile time, the compiler is still able to keep track of the fact that the ids it gives us are between zero and S, so that we don't have to worry about the possibility of failure when we go back to values (if we're using the same vocab instance, of course).

What I want is to be able to write this:

```<code>val x = 2
val vocab = new Vocab(Vector("foo", "bar", "qux"))

eu.timepit.refined.refineV[vocab.P](x).map(vocab.getValue)
</code>```

So that users can easily look up arbitrary integers when they really need to. This doesn't compile, though:

```<code>scala> eu.timepit.refined.refineV[vocab.P](x).map(vocab.getValue)
<console>:17: error: could not find implicit value for parameter v: eu.timepit.refined.api.Validate[Int,vocab.P]
       eu.timepit.refined.refineV[vocab.P](x).map(vocab.getValue)
                                          ^
</code>```

I can make it compile by providing a Witness instance for S:

```<code>scala> implicit val witVocabS: Witness.Aux[vocab.S] = Witness.mkWitness(vocab.size)
witVocabS: shapeless.Witness.Aux[vocab.S] = shapeless.Witness$$anon$1@485aac3c

scala> eu.timepit.refined.refineV[vocab.P](x).map(vocab.getValue)
res1: scala.util.Either[String,String] = Right(qux)
</code>```

And of course it fails (at runtime but safely) when the value is out of range:

```<code>scala> val y = 3
y: Int = 3

scala> println(eu.timepit.refined.refineV[vocab.P](y).map(vocab.getValue))
Left(Right predicate of (!(3 < 0) && (3 < 3)) failed: Predicate failed: (3 < 3).)
</code>```

I could also put the witness definition inside my Vocab class and then import vocab._ to make it available when I need this, but what I really want is to be able to provide refineV support without extra imports or definitions.

I've tried various stuff like this:

```<code>object Vocab {
  implicit def witVocabS[V <: Vocab](implicit
    witV: Witness.Aux[V]
  ): Witness.Aux[V#S] = Witness.mkWitness(witV.value.size)
}
</code>```

But this still requires an explicit definition for each vocab instance:

```<code>scala> implicit val witVocabS: Witness.Aux[vocab.S] = Vocab.witVocabS
witVocabS: shapeless.Witness.Aux[vocab.S] = shapeless.Witness$$anon$1@1bde5374

scala> eu.timepit.refined.refineV[vocab.P](x).map(vocab.getValue)
res4: scala.util.Either[String,String] = Right(qux)
</code>```

I know I could implement witVocabS with a macro, but I feel like there should be a nicer way to do this kind of thing, since it seems like a pretty reasonable use case (and I'm not very familiar with refined, so it's entirely possible that I'm missing something obvious).

答:
Since the predicate you're using for refining Ints is dependant on Vocab, one solution is to add an implicit Witness.Aux[S] and an alias for refineV to this class:

```<code>import eu.timepit.refined._
import eu.timepit.refined.api.Refined
import eu.timepit.refined.numeric.Interval.ClosedOpen
import shapeless.Witness

class Vocab(values: Vector[String]) {
  type S <: Int
  type P = ClosedOpen[Witness.`0`.T, S]

  def size: S = values.size.asInstanceOf[S]

  def getId(value: String): Option[Refined[Int, P]] = values.indexOf(value) match {
    case -1 => None
    case i  => Some(Refined.unsafeApply[Int, P](i))
  }

  def getValue(id: Refined[Int, P]): String = values(id.value)

  implicit val witnessS: Witness.Aux[S] = Witness.mkWitness(size)

  def refine(i: Int): Either[String, Refined[Int, P]] =
    refineV[P](i)
}
</code>```

Using Vocab.refine now doesn't need any additional imports:

```<code>scala> val vocab = new Vocab(Vector("foo", "bar", "baz"))
vocab: Vocab = Vocab@490b83b3

scala> vocab.refine(1)
res4: Either[String,eu.timepit.refined.api.Refined[Int,vocab.P]] = Right(1)

scala> vocab.refine(3)
res5: Either[String,eu.timepit.refined.api.Refined[Int,vocab.P]] = Left(Right predicate of (!(3 < 0) && (3 < 3)) failed: Predicate failed: (3 < 3).)
</code>```

Body:
Suppose I want to map between some strings and integer identifiers, and I want my types to make it impossible to get a runtime failure because someone tried to look up an id that was out of range. Here's one straightforward API:

trait Vocab {
  def getId(value: String): Option[Int]
  def getValue(id: Int): Option[String]
}

This is annoying, though, if users will typically be getting their ids from getId and therefore know they're valid. The following is an improvement in that sense:

trait Vocab[Id] {
  def getId(value: String): Option[Id]
  def getValue(id: Id): String
}

Now we could have something like this:

class TagId private(val value: Int) extends AnyVal

object TagId {
  val tagCount: Int = 100

  def fromInt(id: Int): Option[TagId] =
    if (id >= 0 && id < tagCount) Some(new TagId(id)) else None
}

And then our users can work with Vocab[TagId] and not have to worry about checking whether getValue lookups failed in the typical case, but they can still look up arbitrary integers if they need to. It's still pretty awkward, though, since we have to write a separate type for each kind of thing we want a vocabulary for.

We can also do something like this with refined:

import eu.timepit.refined.api.Refined
import eu.timepit.refined.numeric.Interval.ClosedOpen
import shapeless.Witness

class Vocab(values: Vector[String]) {
  type S <: Int
  type P = ClosedOpen[Witness.`0`.T, S]

  def size: S = values.size.asInstanceOf[S]

  def getId(value: String): Option[Refined[Int, P]] = values.indexOf(value) match {
    case -1 => None
    case i  => Some(Refined.unsafeApply[Int, P](i))
  }

  def getValue(id: Refined[Int, P]): String = values(id.value)
}

Now even though S isn't known at compile time, the compiler is still able to keep track of the fact that the ids it gives us are between zero and S, so that we don't have to worry about the possibility of failure when we go back to values (if we're using the same vocab instance, of course).

What I want is to be able to write this:

val x = 2
val vocab = new Vocab(Vector("foo", "bar", "qux"))

eu.timepit.refined.refineV[vocab.P](x).map(vocab.getValue)

So that users can easily look up arbitrary integers when they really need to. This doesn't compile, though:

scala> eu.timepit.refined.refineV[vocab.P](x).map(vocab.getValue)
<console>:17: error: could not find implicit value for parameter v: eu.timepit.refined.api.Validate[Int,vocab.P]
       eu.timepit.refined.refineV[vocab.P](x).map(vocab.getValue)
                                          ^

I can make it compile by providing a Witness instance for S:

scala> implicit val witVocabS: Witness.Aux[vocab.S] = Witness.mkWitness(vocab.size)
witVocabS: shapeless.Witness.Aux[vocab.S] = shapeless.Witness$$anon$1@485aac3c

scala> eu.timepit.refined.refineV[vocab.P](x).map(vocab.getValue)
res1: scala.util.Either[String,String] = Right(qux)

And of course it fails (at runtime but safely) when the value is out of range:

scala> val y = 3
y: Int = 3

scala> println(eu.timepit.refined.refineV[vocab.P](y).map(vocab.getValue))
Left(Right predicate of (!(3 < 0) && (3 < 3)) failed: Predicate failed: (3 < 3).)

I could also put the witness definition inside my Vocab class and then import vocab._ to make it available when I need this, but what I really want is to be able to provide refineV support without extra imports or definitions.

I've tried various stuff like this:

object Vocab {
  implicit def witVocabS[V <: Vocab](implicit
    witV: Witness.Aux[V]
  ): Witness.Aux[V#S] = Witness.mkWitness(witV.value.size)
}

But this still requires an explicit definition for each vocab instance:

scala> implicit val witVocabS: Witness.Aux[vocab.S] = Vocab.witVocabS
witVocabS: shapeless.Witness.Aux[vocab.S] = shapeless.Witness$$anon$1@1bde5374

scala> eu.timepit.refined.refineV[vocab.P](x).map(vocab.getValue)
res4: scala.util.Either[String,String] = Right(qux)

I know I could implement witVocabS with a macro, but I feel like there should be a nicer way to do this kind of thing, since it seems like a pretty reasonable use case (and I'm not very familiar with refined, so it's entirely possible that I'm missing something obvious).

Body:
Since the predicate you're using for refining Ints is dependant on Vocab, one solution is to add an implicit Witness.Aux[S] and an alias for refineV to this class:

import eu.timepit.refined._
import eu.timepit.refined.api.Refined
import eu.timepit.refined.numeric.Interval.ClosedOpen
import shapeless.Witness

class Vocab(values: Vector[String]) {
  type S <: Int
  type P = ClosedOpen[Witness.`0`.T, S]

  def size: S = values.size.asInstanceOf[S]

  def getId(value: String): Option[Refined[Int, P]] = values.indexOf(value) match {
    case -1 => None
    case i  => Some(Refined.unsafeApply[Int, P](i))
  }

  def getValue(id: Refined[Int, P]): String = values(id.value)

  implicit val witnessS: Witness.Aux[S] = Witness.mkWitness(size)

  def refine(i: Int): Either[String, Refined[Int, P]] =
    refineV[P](i)
}

Using Vocab.refine now doesn't need any additional imports:

scala> val vocab = new Vocab(Vector("foo", "bar", "baz"))
vocab: Vocab = Vocab@490b83b3

scala> vocab.refine(1)
res4: Either[String,eu.timepit.refined.api.Refined[Int,vocab.P]] = Right(1)

scala> vocab.refine(3)
res5: Either[String,eu.timepit.refined.api.Refined[Int,vocab.P]] = Left(Right predicate of (!(3 < 0) && (3 < 3)) failed: Predicate failed: (3 < 3).)


问:
Why is my relative format looking awkward?
I'm trying to build a relative layout for my school project. The center element refuses to be the same height and distance from the top as the others. How do I fix this?

Edit: To clarify the icons are textViews using fontAwesome. Debugging a little I switched the icons of the left and center containers and the center was still higher so I believe it is an issue of formatting.

Layout:

```<code><RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="10dp"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:orientation="vertical"
            android:paddingTop="10dp">

            <TextView
                android:id="@+id/icDate"
                android:textAppearance="@color/colorPrimaryDark"
                android:text="@string/fa_calender"
                android:textSize="24sp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAlignment="center">
            </TextView>

            <TextView
                android:textAppearance="@color/colorPrimaryDark"
                android:id="@+id/tvDate"
                android:textSize="14sp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAlignment="center">
            </TextView>

        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:orientation="vertical"
            android:paddingTop="10dp">

            <TextView
                android:id="@+id/icDuration"
                android:textAppearance="@color/colorPrimaryDark"
                android:text="@string/fa_time"
                android:textSize="24sp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAlignment="center">
            </TextView>

            <TextView
                android:textAppearance="@color/colorPrimaryDark"
                android:id="@+id/tvDuration"
                android:textSize="14sp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAlignment="center">
            </TextView>

        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:orientation="vertical"
            android:paddingTop="10dp">

            <TextView
                android:id="@+id/icDistance"
                android:textAppearance="@color/colorPrimaryDark"
                android:text="@string/fa_road"
                android:textSize="24sp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAlignment="center">
            </TextView>

            <TextView
                android:textAppearance="@color/colorPrimaryDark"
                android:id="@+id/tvDistance"
                android:textSize="14sp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAlignment="center">
            </TextView>

        </LinearLayout>

    </RelativeLayout>
</code>```

with bg to highlight issue:

without bg

答:
Have you tried using android:layout_centerVertical="true" in all of your LinearLayout?

Remember that you must center the icon plus the date or whatever text is below the icon. Thus, you must center the container of both which is the LinearLayout.

Also, using theandroid:textAlignment="center" centers the text in its own borders. It doesn't center it in its parent layout.

Body:
I'm trying to build a relative layout for my school project. The center element refuses to be the same height and distance from the top as the others. How do I fix this?

Edit: To clarify the icons are textViews using fontAwesome. Debugging a little I switched the icons of the left and center containers and the center was still higher so I believe it is an issue of formatting.

Layout:

<RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="10dp"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:orientation="vertical"
            android:paddingTop="10dp">

            <TextView
                android:id="@+id/icDate"
                android:textAppearance="@color/colorPrimaryDark"
                android:text="@string/fa_calender"
                android:textSize="24sp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAlignment="center">
            </TextView>

            <TextView
                android:textAppearance="@color/colorPrimaryDark"
                android:id="@+id/tvDate"
                android:textSize="14sp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAlignment="center">
            </TextView>

        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:orientation="vertical"
            android:paddingTop="10dp">

            <TextView
                android:id="@+id/icDuration"
                android:textAppearance="@color/colorPrimaryDark"
                android:text="@string/fa_time"
                android:textSize="24sp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAlignment="center">
            </TextView>

            <TextView
                android:textAppearance="@color/colorPrimaryDark"
                android:id="@+id/tvDuration"
                android:textSize="14sp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAlignment="center">
            </TextView>

        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:orientation="vertical"
            android:paddingTop="10dp">

            <TextView
                android:id="@+id/icDistance"
                android:textAppearance="@color/colorPrimaryDark"
                android:text="@string/fa_road"
                android:textSize="24sp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAlignment="center">
            </TextView>

            <TextView
                android:textAppearance="@color/colorPrimaryDark"
                android:id="@+id/tvDistance"
                android:textSize="14sp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAlignment="center">
            </TextView>

        </LinearLayout>

    </RelativeLayout>

with bg to highlight issue:

without bg