问:
How to get the Firebase download url of the image being uploaded?
I'm using this code below to upload an image to firebase storage but when the image is uploaded I would like to be able to recall the image using the download url. Is this possible?

ViewUserMapActivity

```<code>package uk.co.jaunt_app.jaunt;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MapStyleOptions;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;

import java.util.UUID;

import static uk.co.jaunt_app.jaunt.R.id.MapDistance;
import static uk.co.jaunt_app.jaunt.R.id.map;

public class ViewUserMapActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    Button HomeButt;
    TextView MapName;
    TextView MapStartLocLat;
    TextView MapStartLocLong;
    TextView MapEndLocLat;
    TextView MapEndLocLong;
    TextView mapDistance;
    Button chooseImg, uploadImg;
    ImageView imgView;
    int PICK_IMAGE_REQUEST = 111;
    Uri filePath;
    ProgressDialog pd;
    TextView imgUrl;

    FirebaseStorage storage = FirebaseStorage.getInstance();
    StorageReference storageRef = storage.getReferenceFromUrl("gs://jaunt-ddc86.appspot.com/");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_user_map);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(map);
        mapFragment.getMapAsync(this);

        HomeButt = (Button) findViewById(R.id.backHome);
        MapName = (TextView) findViewById(R.id.MapName);
        MapStartLocLat = (TextView) findViewById(R.id.MapStartLocLat);
        MapStartLocLong = (TextView) findViewById(R.id.MapStartLocLong);
        MapEndLocLat = (TextView) findViewById(R.id.MapEndLocLat);
        MapEndLocLong = (TextView) findViewById(R.id.MapEndLocLong);
        mapDistance = (TextView) findViewById(MapDistance);
        imgUrl = (TextView) findViewById(R.id.imgurl);

        Intent intent = getIntent();
        final String mapName = intent.getStringExtra("mapName");
        String mapStartLat = intent.getStringExtra("mapStartLat");
        String mapStartLong = intent.getStringExtra("mapStartLong");
        String mapEndLat = intent.getStringExtra("mapEndLat");
        String mapEndLong = intent.getStringExtra("mapEndLong");
        MapName.setText(mapName);
        MapStartLocLat.setText(mapStartLat);
        MapStartLocLong.setText(mapStartLong);
        MapEndLocLat.setText(mapEndLat);
        MapEndLocLong.setText(mapEndLong);

        chooseImg = (Button)findViewById(R.id.chooseImg);
        uploadImg = (Button)findViewById(R.id.uploadImg);
        imgView = (ImageView)findViewById(R.id.imgView);

        pd = new ProgressDialog(this);
        pd.setMessage("Uploading....");

        chooseImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_PICK);
                startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE_REQUEST);
            }
        });

        uploadImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(filePath != null) {
                    pd.show();
                    String imageID = UUID.randomUUID().toString();
                    StorageReference childRef = storageRef.child(imageID);

                    //uploading the image
                    UploadTask uploadTask = childRef.putFile(filePath);

                    uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            pd.dismiss();
                            Toast.makeText(ViewUserMapActivity.this, "Image Uploaded Successfully", Toast.LENGTH_LONG).show();
                        }

                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            pd.dismiss();
                            Toast.makeText(ViewUserMapActivity.this, "Upload Failed -> " + e, Toast.LENGTH_LONG).show();
                        }
                    });

                }
                else {
                    Toast.makeText(ViewUserMapActivity.this, "Select An Image", Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            filePath = data.getData();

            try {
                //getting image from gallery
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                //Setting image to ImageView
                imgView.setImageBitmap(bitmap);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        googleMap.setMapStyle(MapStyleOptions.loadRawResourceStyle(this, R.raw.style_json));

        String mapstartlat = MapStartLocLat.getText().toString().trim();
        String mapstartlong = MapStartLocLong.getText().toString().trim();
        String mapendlat = MapEndLocLat.getText().toString().trim();
        String mapendlong = MapEndLocLong.getText().toString().trim();

        double startlat = Double.valueOf(mapstartlat);
        double startlong = Double.valueOf(mapstartlong);
        double endlat = Double.valueOf(mapendlat);
        double endlong = Double.valueOf(mapendlong);

        LatLng Start = new LatLng(startlat, startlong);
        LatLng End = new LatLng(endlat, endlong);
        mMap.addMarker(new MarkerOptions().position(Start)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.mappin)));
        mMap.addMarker(new MarkerOptions().position(End)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.mappin)));
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(End, 6 ));

        Location loc1 = new Location("");
        loc1.setLatitude(startlat);
        loc1.setLongitude(startlong);

        Location loc2 = new Location("");
        loc2.setLatitude(endlat);
        loc2.setLongitude(endlong);

        float distanceInMeters = loc1.distanceTo(loc2);
        Double value = 0.00062137;
        Double distanceValue = (distanceInMeters)*value;
        mapDistance.setText(String.format("%.1f mi", distanceValue));

        HomeButt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ViewUserMapActivity.this, MainActivity.class);
                startActivity(intent);
            }
        });

    }

}
</code>```

答:
Use getDownloadUrl() in your success callback. It's populated once the upload is complete.

More info here.

Body:
I'm using this code below to upload an image to firebase storage but when the image is uploaded I would like to be able to recall the image using the download url. Is this possible?

ViewUserMapActivity

package uk.co.jaunt_app.jaunt;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MapStyleOptions;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;

import java.util.UUID;

import static uk.co.jaunt_app.jaunt.R.id.MapDistance;
import static uk.co.jaunt_app.jaunt.R.id.map;

public class ViewUserMapActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    Button HomeButt;
    TextView MapName;
    TextView MapStartLocLat;
    TextView MapStartLocLong;
    TextView MapEndLocLat;
    TextView MapEndLocLong;
    TextView mapDistance;
    Button chooseImg, uploadImg;
    ImageView imgView;
    int PICK_IMAGE_REQUEST = 111;
    Uri filePath;
    ProgressDialog pd;
    TextView imgUrl;

    FirebaseStorage storage = FirebaseStorage.getInstance();
    StorageReference storageRef = storage.getReferenceFromUrl("gs://jaunt-ddc86.appspot.com/");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_user_map);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(map);
        mapFragment.getMapAsync(this);

        HomeButt = (Button) findViewById(R.id.backHome);
        MapName = (TextView) findViewById(R.id.MapName);
        MapStartLocLat = (TextView) findViewById(R.id.MapStartLocLat);
        MapStartLocLong = (TextView) findViewById(R.id.MapStartLocLong);
        MapEndLocLat = (TextView) findViewById(R.id.MapEndLocLat);
        MapEndLocLong = (TextView) findViewById(R.id.MapEndLocLong);
        mapDistance = (TextView) findViewById(MapDistance);
        imgUrl = (TextView) findViewById(R.id.imgurl);

        Intent intent = getIntent();
        final String mapName = intent.getStringExtra("mapName");
        String mapStartLat = intent.getStringExtra("mapStartLat");
        String mapStartLong = intent.getStringExtra("mapStartLong");
        String mapEndLat = intent.getStringExtra("mapEndLat");
        String mapEndLong = intent.getStringExtra("mapEndLong");
        MapName.setText(mapName);
        MapStartLocLat.setText(mapStartLat);
        MapStartLocLong.setText(mapStartLong);
        MapEndLocLat.setText(mapEndLat);
        MapEndLocLong.setText(mapEndLong);

        chooseImg = (Button)findViewById(R.id.chooseImg);
        uploadImg = (Button)findViewById(R.id.uploadImg);
        imgView = (ImageView)findViewById(R.id.imgView);

        pd = new ProgressDialog(this);
        pd.setMessage("Uploading....");

        chooseImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_PICK);
                startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE_REQUEST);
            }
        });

        uploadImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(filePath != null) {
                    pd.show();
                    String imageID = UUID.randomUUID().toString();
                    StorageReference childRef = storageRef.child(imageID);

                    //uploading the image
                    UploadTask uploadTask = childRef.putFile(filePath);

                    uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            pd.dismiss();
                            Toast.makeText(ViewUserMapActivity.this, "Image Uploaded Successfully", Toast.LENGTH_LONG).show();
                        }

                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            pd.dismiss();
                            Toast.makeText(ViewUserMapActivity.this, "Upload Failed -> " + e, Toast.LENGTH_LONG).show();
                        }
                    });

                }
                else {
                    Toast.makeText(ViewUserMapActivity.this, "Select An Image", Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            filePath = data.getData();

            try {
                //getting image from gallery
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                //Setting image to ImageView
                imgView.setImageBitmap(bitmap);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        googleMap.setMapStyle(MapStyleOptions.loadRawResourceStyle(this, R.raw.style_json));

        String mapstartlat = MapStartLocLat.getText().toString().trim();
        String mapstartlong = MapStartLocLong.getText().toString().trim();
        String mapendlat = MapEndLocLat.getText().toString().trim();
        String mapendlong = MapEndLocLong.getText().toString().trim();

        double startlat = Double.valueOf(mapstartlat);
        double startlong = Double.valueOf(mapstartlong);
        double endlat = Double.valueOf(mapendlat);
        double endlong = Double.valueOf(mapendlong);

        LatLng Start = new LatLng(startlat, startlong);
        LatLng End = new LatLng(endlat, endlong);
        mMap.addMarker(new MarkerOptions().position(Start)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.mappin)));
        mMap.addMarker(new MarkerOptions().position(End)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.mappin)));
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(End, 6 ));

        Location loc1 = new Location("");
        loc1.setLatitude(startlat);
        loc1.setLongitude(startlong);

        Location loc2 = new Location("");
        loc2.setLatitude(endlat);
        loc2.setLongitude(endlong);

        float distanceInMeters = loc1.distanceTo(loc2);
        Double value = 0.00062137;
        Double distanceValue = (distanceInMeters)*value;
        mapDistance.setText(String.format("%.1f mi", distanceValue));

        HomeButt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ViewUserMapActivity.this, MainActivity.class);
                startActivity(intent);
            }
        });

    }

}


来源: stackexchange

问:
Python - how to use few times the same next iteration?
I would like to search a list:

```<code>[0, 0, 1, 0, 1, 1, 1, 0, 1, 1]
</code>```

and replace/edit items different from the previous item and next item. For xxample: I want to get rid of/edit 1 at index 2 in the list above.

Take a look at my code below and please continue reading my core question beneath my code:

!Update: Result should be: [0, 0, 0, 0, 1, 1, 1, 1, 1, 1]

```<code>x = [0, 0, 1, 0, 1, 1, 1, 0, 1, 1]
print(x)
hiter = iter(x)
next(hiter)
prev = None

for i in x:
    try:
        print('prev %s - CURRENT %s - next %s' % (prev, i, next(hiter)))
        prev = i

        #if i != prev and i != next(hiter):
        #   x[i] = prev

    except StopIteration:
        break

print(x)
</code>```

We know the previous item, the next item and the current item.

But everytime I use:

```
if i != prev and <b>i != next(hiter)</b>...
```

the next(hiter) destroys order. In other words, if I use next(hiter) more than 1 time in my loop, Python reads the next item as double, because I used next(hiter) two times in a loop.

I tried also declare seperate variable like y = next(hiter) - but still it didn't work (obviously won't work but I was desperate to check it anyway xD).

I have no clues, in addition, hiter.__next__() does the same as next(hiter).

答:
There's a itertools.tee function that allows to "clone" iterators.

```<code>iter1, iter2 = itertools.tee(iter(<iterable>))
</code>```

Your case seem too trivial - unless it's just the example, to use it

EDIT
In that case

```<code>for index, val in enumerate(x[1:-1], 1)
    if val != x[index-1] and val != x[index+1]:
        x[index] = x[index-1]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I would like to search a list:

[0, 0, 1, 0, 1, 1, 1, 0, 1, 1]

and replace/edit items different from the previous item and next item. For xxample: I want to get rid of/edit 1 at index 2 in the list above.

Take a look at my code below and please continue reading my core question beneath my code:

!Update: Result should be: [0, 0, 0, 0, 1, 1, 1, 1, 1, 1]

x = [0, 0, 1, 0, 1, 1, 1, 0, 1, 1]
print(x)
hiter = iter(x)
next(hiter)
prev = None

for i in x:
    try:
        print('prev %s - CURRENT %s - next %s' % (prev, i, next(hiter)))
        prev = i

        #if i != prev and i != next(hiter):
        #   x[i] = prev

    except StopIteration:
        break

print(x)

We know the previous item, the next item and the current item.

But everytime I use:

if i != prev and i != next(hiter)...

the next(hiter) destroys order. In other words, if I use next(hiter) more than 1 time in my loop, Python reads the next item as double, because I used next(hiter) two times in a loop.

I tried also declare seperate variable like y = next(hiter) - but still it didn't work (obviously won't work but I was desperate to check it anyway xD).

I have no clues, in addition, hiter.__next__() does the same as next(hiter).

Body:
There's a itertools.tee function that allows to "clone" iterators.

iter1, iter2 = itertools.tee(iter(<iterable>))

Your case seem too trivial - unless it's just the example, to use it

EDIT
In that case

for index, val in enumerate(x[1:-1], 1)
    if val != x[index-1] and val != x[index+1]:
        x[index] = x[index-1]


问:
scala reflection get class of enumaration value
Assume we have

```<code>class User(val name: String, val role: UserRole.Value)

class UserRole extends Enumeration {
    val Admin, User = Value
}

val u = new User("root", UserRole.Admin)
</code>```

how to get Class[_] "class UserRole" when

```<code>u.role.getClass
</code>```

return "scala.Enumeration.Value"

答:
Neither new User("root", UserRole.Admin) nor role: UserRole.Value make sense, because UserRole is not a value. Normally, Enumeration is extended by objects, not classes.

Something like

```<code>val field = classOf[Enumeration#Value].getDeclaredField("outerEnum")
field.setAccessible(true)
val enum = field.get(u.role)
enum.getClass // if you want specifically the class
</code>```

should work (at least for the current versions; outerEnum is not part of the API!)

Body:
Assume we have

class User(val name: String, val role: UserRole.Value)

class UserRole extends Enumeration {
    val Admin, User = Value
}

val u = new User("root", UserRole.Admin)

how to get Class[_] "class UserRole" when

u.role.getClass

return "scala.Enumeration.Value"

Body:
Neither new User("root", UserRole.Admin) nor role: UserRole.Value make sense, because UserRole is not a value. Normally, Enumeration is extended by objects, not classes.

Something like

val field = classOf[Enumeration#Value].getDeclaredField("outerEnum")
field.setAccessible(true)
val enum = field.get(u.role)
enum.getClass // if you want specifically the class

should work (at least for the current versions; outerEnum is not part of the API!)


问:
When i try to run my cucumber scripts i get an error how to solve it?
I am new to testing . I am trying to learn cucumber automation tool . I got this error when i try to run a script . enter image description here</p>

答: You just need to update your gecko driver </p>


问:
custom renderer or conditional styling in handsontable
Using the official handsontable react wrapper I'm having a hard time figuring out how to register a custom renderer, the goal is to render some rows with a different style. I attempted to write a custom renderer and it was throwing an error saying that the renderer was not registered this could have been because I was trying to register it following the docs https://docs.handsontable.com/0.32.0/demo-conditional-formatting.html where they attach it to Handsontable </p>

答:
```<code>function groupingRenderer(instance, td, row, col, prop, value,
cellProperties) {
  Handsontable.renderers.TextRenderer.apply(this, arguments);
  td.className = 'group';
}
</code>```

And then to call that function in the settings object that you pass in as a prop to HotTable

```<code>cells(row, col, prop) {
    const cellProperties = {};
    if((tableData.rows[row]).total) {
      cellProperties.renderer = groupingRenderer;
    }

    return cellProperties;
  },
</code>```

notice im not registering the "renderer" instead I call it directly.

Body:
function groupingRenderer(instance, td, row, col, prop, value,
cellProperties) {
  Handsontable.renderers.TextRenderer.apply(this, arguments);
  td.className = 'group';
}

And then to call that function in the settings object that you pass in as a prop to HotTable

cells(row, col, prop) {
    const cellProperties = {};
    if((tableData.rows[row]).total) {
      cellProperties.renderer = groupingRenderer;
    }

    return cellProperties;
  },

notice im not registering the "renderer" instead I call it directly.


问:
How to select first # rows from album and album details
I'm currently developing a photoalbum page for a website I'm working on, and my idea was to create an overview of all photoalbums, showing the 5 most recently added pictures. The photoalbum uses two MySQL tables, one containing the album details (eg: album name, album id) and one containing the pictures (I store them into the database as blobs) along with the corresponding album id.

However, I sofar haven't been able to figure out a query which allows me to fetch all of the album details and the id's for the 5 most recent pictures corresponding to the album. I hope you can help me out a bit.

The tables look like this:

Table: photoalbums

```<code>id | album_name | album_created
-------------------------------------
1  | testalbum  | 2010-11-07 19:33:20
2  | some more  | 2010-11-15 18:48:29
</code>```

Table: pictures

```<code>id | file   | thumbnail | name  | album_id
------------------------------------------
1  | binary | binary    | test1 | 1
2  | binary | binary    | test2 | 1
3  | binary | binary    | test3 | 2
4  | binary | binary    | test4 | 2
5  | binary | binary    | test5 | 1
</code>```

It looks to me like I'm going to need a subquery, or performing a separate query per album. I would rather avoid using multiple queries..

Can anybody help me finding the right way to do this? Thanks in advance.

答:
To do this in a single pass you need to relate in some way with the parent field as the query is running. To do this you need to use a variable. Here, I have used the variable x to hold the current count as the query runs. As each record is selected, it decides if it is currently dealing with a record that belongs to the current parent. If it does it simply adds 0.5 to the running total. (I originally tried 1, but it seems that 1 is added twice).

Here is the final query. Let me know if it helps. :-)

SELECT
  album_id,
  id,
  @x := if(@album_id = album_id, @x + 0.5, 1) cnt,
  @album_id := album_id
FROM
  pictures
GROUP BY
  album_id, id, cnt
HAVING
  cnt <= 5;

ContentLicense: CC BY-SA 2.5

Body:
I'm currently developing a photoalbum page for a website I'm working on, and my idea was to create an overview of all photoalbums, showing the 5 most recently added pictures. The photoalbum uses two MySQL tables, one containing the album details (eg: album name, album id) and one containing the pictures (I store them into the database as blobs) along with the corresponding album id.

However, I sofar haven't been able to figure out a query which allows me to fetch all of the album details and the id's for the 5 most recent pictures corresponding to the album. I hope you can help me out a bit.

The tables look like this:

Table: photoalbums

id | album_name | album_created
-------------------------------------
1  | testalbum  | 2010-11-07 19:33:20
2  | some more  | 2010-11-15 18:48:29

Table: pictures

id | file   | thumbnail | name  | album_id
------------------------------------------
1  | binary | binary    | test1 | 1
2  | binary | binary    | test2 | 1
3  | binary | binary    | test3 | 2
4  | binary | binary    | test4 | 2
5  | binary | binary    | test5 | 1

It looks to me like I'm going to need a subquery, or performing a separate query per album. I would rather avoid using multiple queries..

Can anybody help me finding the right way to do this? Thanks in advance.


问:
ONVIF GetStreamUri returns internal IP Address
I am trying to connect to an IP camera using Onvif. This camera is not in my network and has been made available to me through an external IP address. When using the 'GetStreamUri' function I get a RTSP link with the internal IP address of the camera, this will not work. When I replace the IP manually it works just fine.

Does anybody have any other suggestions on how to handle this? Replacing the IP manually works but is not a very nice solution.

答:
A camera behind NAT and with RTSP streaming in general cannot be viewed from Internet, because you'll end up with all the classic problems related to NAT and VOIP (voip uses RTSP as well as ONVIF).

But you have a possible solution: configure the camera so that it streams over HTTP. At this point you should get a URI that should be accessible from Internet. In fact, if you invoke GetStreamUri, the camera will still return you an internal IP address, since it does not know that the router is configured for NAT. If you are lucky enough, the URI will be on port 80, thus by replacing the internal IP address with the external IP address of the gateway you should be able get the video.


问:
Convert a list of lists of tuples to pandas dataframe
I'm trying to transform a list of lists of tuples to a pandas dataframe but can't figure out how to do so. My addresses are structured like so:

```<code>addresses = [
 [('the vicars inn', 'house'), ('68', 'house_number'), ('church lane', 'road'), ('arlesey', 'city'), ('beds', 'house')],
 [('the old oak', 'house'), ('85', 'house_number'), ('church lane', 'road'), ('arlesey', 'city'), ('beds', 'house')],
 [('adj', 'road'), ('85', 'house_number'), ('high street', 'road'), ('arlesey', 'city'), ('beds', 'house')],
 [('arlesey community centre', 'house'), ('high street', 'road'), ('arlesey', 'city'), ('beds', 'house')],
 [('arlesey community centre', 'house'), ('high street', 'road'), ('arlesey', 'city'), ('beds', 'house')]
]
</code>```

Ideally, I need to return a dataframe like:

```<code>      city           house             house_number       road
0     arlesey        the vicars inn    68                 church lane
1     arlesey        the old oak       85                 church lane
</code>```

What I've tried so far is to pivot the table but it is not producing the intended outcome:

```<code>pd.DataFrame.from_records(addresses[0]).pivot(columns=1, values=0)
</code>```

Does anyone have any guidance on methods I should be looking at to achieve my ideal dataframe?

Sam

答:
You can convert each record to a dictionary and then use DataFrame.from_records:

```<code>pd.DataFrame.from_records([{k: v for v, k in row} for row in addresses])

#      city house   house_number    road
#0  arlesey beds              68    church lane
#1  arlesey beds              85    church lane
#2  arlesey beds              85    high street
#3  arlesey beds             NaN    high street
#4  arlesey beds             NaN    high street
</code>```

Body:
I'm trying to transform a list of lists of tuples to a pandas dataframe but can't figure out how to do so. My addresses are structured like so:

addresses = [
 [('the vicars inn', 'house'), ('68', 'house_number'), ('church lane', 'road'), ('arlesey', 'city'), ('beds', 'house')],
 [('the old oak', 'house'), ('85', 'house_number'), ('church lane', 'road'), ('arlesey', 'city'), ('beds', 'house')],
 [('adj', 'road'), ('85', 'house_number'), ('high street', 'road'), ('arlesey', 'city'), ('beds', 'house')],
 [('arlesey community centre', 'house'), ('high street', 'road'), ('arlesey', 'city'), ('beds', 'house')],
 [('arlesey community centre', 'house'), ('high street', 'road'), ('arlesey', 'city'), ('beds', 'house')]
]

Ideally, I need to return a dataframe like:

      city           house             house_number       road
0     arlesey        the vicars inn    68                 church lane
1     arlesey        the old oak       85                 church lane

What I've tried so far is to pivot the table but it is not producing the intended outcome:

pd.DataFrame.from_records(addresses[0]).pivot(columns=1, values=0)

Does anyone have any guidance on methods I should be looking at to achieve my ideal dataframe?

Sam

Body:
You can convert each record to a dictionary and then use DataFrame.from_records:

pd.DataFrame.from_records([{k: v for v, k in row} for row in addresses])

#      city house   house_number    road
#0  arlesey beds              68    church lane
#1  arlesey beds              85    church lane
#2  arlesey beds              85    high street
#3  arlesey beds             NaN    high street
#4  arlesey beds             NaN    high street


问:
Validate @Value-annotated fields during application startup
How can I check that values in a property file conform to my expectations during application startup? Annotating fields directly doesn't work.
I'm using spring boot 1.5.3.RELEASE, spring 4.3.8.RELEASE

Service:

```<code>@Service
@Validated
public class ConfigService {
    @URL
    @Value("${checkout.url}")
    private String checkoutUrl;
    @Size(max = 26)
    @Value("${checkout.payment-method}")
    private String paymentMethod;
}
</code>```

Property file (application.properties):

```<code>checkout.url=not-a-url-at-all
checkout.payment-method=CreditCardButMuchTooLongToQualifyForSizeValidator
</code>```

答:
You can use this getter methods style in your class for validate String length:

```<code>@Size(min = Number, max = Number)
public String getField() {
    return field;
}
</code>```

and for validate numbers:

```<code>@Max(Number) or @Min(Number)
</code>```

When Number is equal to int value

if the fields dont have this limitations it will throw a java.lang.IllegalStateException

dont forget to add this dependency to your pom if you dont have:

```<code><dependency>
    <groupId>org.glassfish.web</groupId>
    <artifactId>el-impl</artifactId>
    <version>2.2</version>
</dependency>
</code>```

Body:
How can I check that values in a property file conform to my expectations during application startup? Annotating fields directly doesn't work.
I'm using spring boot 1.5.3.RELEASE, spring 4.3.8.RELEASE

Service:

@Service
@Validated
public class ConfigService {
    @URL
    @Value("${checkout.url}")
    private String checkoutUrl;
    @Size(max = 26)
    @Value("${checkout.payment-method}")
    private String paymentMethod;
}

Property file (application.properties):

checkout.url=not-a-url-at-all
checkout.payment-method=CreditCardButMuchTooLongToQualifyForSizeValidator

Body:
You can use this getter methods style in your class for validate String length:

@Size(min = Number, max = Number)
public String getField() {
    return field;
}

and for validate numbers:

@Max(Number) or @Min(Number)

When Number is equal to int value

if the fields dont have this limitations it will throw a java.lang.IllegalStateException

dont forget to add this dependency to your pom if you dont have:

<dependency>
    <groupId>org.glassfish.web</groupId>
    <artifactId>el-impl</artifactId>
    <version>2.2</version>
</dependency>


问:
please explain javascript called on form element
Please explain this code

```<code>"<form action='' onkeypress =if ( event.keyCode == 13){
 $('#validate').click(); return false; }>"
</code>```

this event is called on form element

答:
Each time a key is pressed within the form it checks which key (based on the ASCII table. If the key is a carriage return (ASCII character 13) it calls the validate() method.

I'm not sure if the form tag supports the onkeypress event though

Body:
Please explain this code

"<form action='' onkeypress =if ( event.keyCode == 13){
 $('#validate').click(); return false; }>"

this event is called on form element


问:
Angular route not resolving from observable
I'm trying to resolve a route in Angular and cannot get it to resolve. Whilst the resolver works when I return a value it does not continue to the intended route. My router is defined as follows...

```<code>{
    path: 'sortation',
    component: SortationComponent,
    resolve: {
        cage: 'cageResolveService'
    }
}
</code>```

... which I call using a simple link

```<code>        <a class="btn btn-block btn-danger btn-sm" routerLink="/sortation" routerLinkActive="menu-active">
            Sortation
        </a>
</code>```

... and my cageResolveService reads

```<code>import { Injectable, Inject, OnDestroy } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot } from '@angular/router';
import { Observable } from "rxjs/Observable";
import { Cage } from '../_models/cage';

@Injectable()
export class CageResolveService implements Resolve<any> {

cage;

constructor(
    @Inject('cageService') private cageService,
    @Inject('appUtilityService') private appUtilityService,
    @Inject('flashService') private flashService
) {}

ngOnDestroy() {
    this.cage.unsubscribe();
}

resolve(route: ActivatedRouteSnapshot): any {

    let criteria = {
        "limit": 3,
        "orderBy": "createdAt",
        "state": "PICKED"
    }

    // Subscribe to the observable
    this.cage = this.cageService.load( this.appUtilityService.encode( criteria ) )
    .subscribe();

    return this.cageService.cages$
    .map( cages => {

        if( cages && cages.length )
        {
            let c = cages.find( cage => cage.state === 'PICKED' );
            return c;
        }
        else
        {
            this.flashService.command.next({message: 'Error : No ready cages at this time', type: 'danger'});
            return false;
        }
    });
}
}
</code>```

Can anybody please advise? If I remove the resolver the route works fine. It's a silly issue that is driving me nuts.

答:
```<code> [routerLink]="['sortation']  I think routerlink declaraion is mistake
</code>```

Body:
I'm trying to resolve a route in Angular and cannot get it to resolve. Whilst the resolver works when I return a value it does not continue to the intended route. My router is defined as follows...

{
    path: 'sortation',
    component: SortationComponent,
    resolve: {
        cage: 'cageResolveService'
    }
}

... which I call using a simple link

            Sortation

... and my cageResolveService reads

import { Injectable, Inject, OnDestroy } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot } from '@angular/router';
import { Observable } from "rxjs/Observable";
import { Cage } from '../_models/cage';

@Injectable()
export class CageResolveService implements Resolve<any> {

cage;

constructor(
    @Inject('cageService') private cageService,
    @Inject('appUtilityService') private appUtilityService,
    @Inject('flashService') private flashService
) {}

ngOnDestroy() {
    this.cage.unsubscribe();
}

resolve(route: ActivatedRouteSnapshot): any {

    let criteria = {
        "limit": 3,
        "orderBy": "createdAt",
        "state": "PICKED"
    }

    // Subscribe to the observable
    this.cage = this.cageService.load( this.appUtilityService.encode( criteria ) )
    .subscribe();

    return this.cageService.cages$
    .map( cages => {

        if( cages && cages.length )
        {
            let c = cages.find( cage => cage.state === 'PICKED' );
            return c;
        }
        else
        {
            this.flashService.command.next({message: 'Error : No ready cages at this time', type: 'danger'});
            return false;
        }
    });
}
}

Can anybody please advise? If I remove the resolver the route works fine. It's a silly issue that is driving me nuts.


问:
jQuery DataTable Not a Function
I've done a lot of searching and everyone says it is caused by including the DataTable script before jQuery, or double-including jQuery.

However, this is not the case for my code.

I keep getting $(...).DataTable is not a function.

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Example of Employee Table with twitter bootstrap</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>

    <script type="text/javascript">
        $(document).ready(function(){
            $('#myTable').DataTable();
        });
    </script>
</head>
<body style="margin:20px auto">
    <table id="myTable" class="table table-striped" >
        <thead>
          <tr>
            <th>ENO</th>
            <th>EMPName</th>
            <th>Country</th>
            <th>Salary</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>001</td>
            <td>Anusha</td>
            <td>India</td>
            <td>10000</td>
          </tr>
          <tr>
        <td>002</td>
        <td>Charles</td>
        <td>United Kingdom</td>
        <td>28000</td>
      </tr>
      <tr>
        <td>003</td>
        <td>Sravani</td>
        <td>Australia</td>
        <td>7000</td>
      </tr>
       <tr>
        <td>004</td>
        <td>Amar</td>
        <td>India</td>
        <td>18000</td>
      </tr>
      <tr>
        <td>005</td>
        <td>Lakshmi</td>
        <td>India</td>
        <td>12000</td>
      </tr>
      <tr>
        <td>006</td>
        <td>James</td>
        <td>Canada</td>
        <td>50000</td>
      </tr>

       <tr>
        <td>007</td>
        <td>Ronald</td>
        <td>US</td>
        <td>75000</td>
      </tr>
      <tr>
        <td>008</td>
        <td>Mike</td>
        <td>Belgium</td>
        <td>100000</td>
      </tr>
    </tbody>
  </table>
  </div>
</body>

</html>
</code>```

答:
https is secured connection.In your case you are using http in http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js which may be the source of the problem

$(document).ready(function() {
  $('#myTable').DataTable();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>

<body style="margin:20px auto">
  <table id="myTable" class="table table-striped">
    <thead>
      <tr>
        <th>ENO</th>
        <th>EMPName</th>
        <th>Country</th>
        <th>Salary</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>001</td>
        <td>Anusha</td>
        <td>India</td>
        <td>10000</td>
      </tr>
      <tr>
        <td>002</td>
        <td>Charles</td>
        <td>United Kingdom</td>
        <td>28000</td>
      </tr>
      <tr>
        <td>003</td>
        <td>Sravani</td>
        <td>Australia</td>
        <td>7000</td>
      </tr>
      <tr>
        <td>004</td>
        <td>Amar</td>
        <td>India</td>
        <td>18000</td>
      </tr>
      <tr>
        <td>005</td>
        <td>Lakshmi</td>
        <td>India</td>
        <td>12000</td>
      </tr>
      <tr>
        <td>006</td>
        <td>James</td>
        <td>Canada</td>
        <td>50000</td>
      </tr>

      <tr>
        <td>007</td>
        <td>Ronald</td>
        <td>US</td>
        <td>75000</td>
      </tr>
      <tr>
        <td>008</td>
        <td>Mike</td>
        <td>Belgium</td>
        <td>100000</td>
      </tr>
    </tbody>
  </table>
  </div></code>```

Title: jQuery DataTable Not a Function

Body:
I've done a lot of searching and everyone says it is caused by including the DataTable script before jQuery, or double-including jQuery.

However, this is not the case for my code.

I keep getting $(...).DataTable is not a function.

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Example of Employee Table with twitter bootstrap</title>

            ENO
            EMPName
            Country
            Salary

            001
            Anusha
            India
            10000

        002
        Charles
        United Kingdom
        28000

        003
        Sravani
        Australia
        7000

        004
        Amar
        India
        18000

        005
        Lakshmi
        India
        12000

        006
        James
        Canada
        50000

        007
        Ronald
        US
        75000

        008
        Mike
        Belgium
        100000

Body:
https is secured connection.In your case you are using http in http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js which may be the source of the problem

$(document).ready(function() {
  $('#myTable').DataTable();
});

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>

<body style="margin:20px auto">
  <table id="myTable" class="table table-striped">
    <thead>
      <tr>
        <th>ENO</th>
        <th>EMPName</th>
        <th>Country</th>
        <th>Salary</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>001</td>
        <td>Anusha</td>
        <td>India</td>
        <td>10000</td>
      </tr>
      <tr>
        <td>002</td>
        <td>Charles</td>
        <td>United Kingdom</td>
        <td>28000</td>
      </tr>
      <tr>
        <td>003</td>
        <td>Sravani</td>
        <td>Australia</td>
        <td>7000</td>
      </tr>
      <tr>
        <td>004</td>
        <td>Amar</td>
        <td>India</td>
        <td>18000</td>
      </tr>
      <tr>
        <td>005</td>
        <td>Lakshmi</td>
        <td>India</td>
        <td>12000</td>
      </tr>
      <tr>
        <td>006</td>
        <td>James</td>
        <td>Canada</td>
        <td>50000</td>
      </tr>

      <tr>
        <td>007</td>
        <td>Ronald</td>
        <td>US</td>
        <td>75000</td>
      </tr>
      <tr>
        <td>008</td>
        <td>Mike</td>
        <td>Belgium</td>
        <td>100000</td>
      </tr>
    </tbody>
  </table>
  </div>


问:
Divide rows with date in SQL Server 2014
I have a problem with SQL. I have the following table:

```<code>declare @t table (START_DATE datetime,
                  END_DATE datetime,
                  GROSS_SALES_PRICE decimal(10,2)
                 );

insert into @t
values ('2014-08-06 00:00:00.000', '2014-10-06 23:59:59.000', 29.99),
       ('2014-09-06 00:00:00.000', '2014-09-09 23:59:59.000', 32.99),
       ('2014-09-10 00:00:00.000', '2014-09-30 23:59:59.000', 32.99),
       ('2014-10-07 00:00:00.000', '2049-12-31 23:59:59.000', 34.99)
</code>```

I would like to separate the dates which overlaps. For example I have in the first row START_DATE 2014-08-06 and END_DATE 2014-10-06. We can see that the dates from the second and the third row are inside this period of time from first row.

So I would like to separate them as follows:

```<code>declare @t2 table (START_DATE datetime,
                   END_DATE datetime,
                   GROSS_SALES_PRICE decimal(10,2)
                  );

insert into @t2
values ('2014-08-06 00:00:00.000', '2014-09-05 23:59:59.000', 29.99),
       ('2014-09-06 00:00:00.000', '2014-09-09 23:59:59.000', 32.99),
       ('2014-09-10 00:00:00.000', '2014-09-30 23:59:59.000', 32.99),
       ('2014-10-01 00:00:00.000', '2014-10-06 23:59:59.000', 29.99),
       ('2014-10-07 00:00:00.000', '2049-12-31 23:59:59.000', 34.99)
</code>```

So the second and the third rows remained unchanged. The first row should have new END_DATE. We also have new row. The GROSS_SALES_PRICE should remain as it is in internal period. Thanks for help. I am using SQL Server 2014

答:
How about using Lead to find the value from the next row:

```<code>SELECT START_DATE,
    CASE
        WHEN LEAD(Start_Date) OVER (ORDER BY Start_Date) < END_DATE
        THEN COALESCE(DATEADD(s, -1, LEAD(Start_Date) OVER (ORDER BY Start_Date)), END_Date)
        ELSE END_DATE END AS End_Date,
    GROSS_SALES_PRICE
 FROM @t
</code>```

Or using a common table expression:

```<code>;WITH CTE
 AS
 (
    SELECT Start_date,
           End_Date,
           LEAD(Start_Date) OVER (ORDER BY Start_Date) AS NextStartDate,
           GROSS_SALES_PRICE
    FROM @t
)
SELECT START_DATE,
        CASE WHEN NextStartDate < END_DATE
            THEN Coalesce(DATEADD(s, -1, NextStartDate), End_Date)
            ELSE End_date END As End_Date,
        GROSS_SALES_PRICE
FROM CTE
</code>```

Updated to add missing row:

```<code>;WITH CTE
 AS
 (
    SELECT Start_date,
           End_Date,
           LAG(END_Date) OVER (ORDER BY Start_Date) AS PreviousEndDate,
           LEAD(Start_Date) OVER (ORDER BY Start_Date) AS NextStartDate,
           GROSS_SALES_PRICE
    FROM @t
)
SELECT START_DATE,
        CASE WHEN NextStartDate < END_DATE
            THEN Coalesce(DATEADD(s, -1, NextStartDate), End_Date)
            ELSE End_date END As End_Date,
        GROSS_SALES_PRICE
FROM CTE
UNION ALL
SELECT DATEADD(s, 1, PreviousEndDate), DATEADD(s, -1, Start_Date), GROSS_SALES_PRICE
FROM CTE
WHERE DATEDIFF(s, PreviousEndDate,Start_Date) > 1
ORDER BY 1
</code>```

Body:
I have a problem with SQL. I have the following table:

declare @t table (START_DATE datetime,
                  END_DATE datetime,
                  GROSS_SALES_PRICE decimal(10,2)
                 );

insert into @t
values ('2014-08-06 00:00:00.000', '2014-10-06 23:59:59.000', 29.99),
       ('2014-09-06 00:00:00.000', '2014-09-09 23:59:59.000', 32.99),
       ('2014-09-10 00:00:00.000', '2014-09-30 23:59:59.000', 32.99),
       ('2014-10-07 00:00:00.000', '2049-12-31 23:59:59.000', 34.99)

I would like to separate the dates which overlaps. For example I have in the first row START_DATE 2014-08-06 and END_DATE 2014-10-06. We can see that the dates from the second and the third row are inside this period of time from first row.

So I would like to separate them as follows:

declare @t2 table (START_DATE datetime,
                   END_DATE datetime,
                   GROSS_SALES_PRICE decimal(10,2)
                  );

insert into @t2
values ('2014-08-06 00:00:00.000', '2014-09-05 23:59:59.000', 29.99),
       ('2014-09-06 00:00:00.000', '2014-09-09 23:59:59.000', 32.99),
       ('2014-09-10 00:00:00.000', '2014-09-30 23:59:59.000', 32.99),
       ('2014-10-01 00:00:00.000', '2014-10-06 23:59:59.000', 29.99),
       ('2014-10-07 00:00:00.000', '2049-12-31 23:59:59.000', 34.99)

So the second and the third rows remained unchanged. The first row should have new END_DATE. We also have new row. The GROSS_SALES_PRICE should remain as it is in internal period. Thanks for help. I am using SQL Server 2014

Body:
How about using Lead to find the value from the next row:

SELECT START_DATE,
    CASE
        WHEN LEAD(Start_Date) OVER (ORDER BY Start_Date) < END_DATE
        THEN COALESCE(DATEADD(s, -1, LEAD(Start_Date) OVER (ORDER BY Start_Date)), END_Date)
        ELSE END_DATE END AS End_Date,
    GROSS_SALES_PRICE
 FROM @t

Or using a common table expression:

;WITH CTE
 AS
 (
    SELECT Start_date,
           End_Date,
           LEAD(Start_Date) OVER (ORDER BY Start_Date) AS NextStartDate,
           GROSS_SALES_PRICE
    FROM @t
)
SELECT START_DATE,
        CASE WHEN NextStartDate < END_DATE
            THEN Coalesce(DATEADD(s, -1, NextStartDate), End_Date)
            ELSE End_date END As End_Date,
        GROSS_SALES_PRICE
FROM CTE

Updated to add missing row:

;WITH CTE
 AS
 (
    SELECT Start_date,
           End_Date,
           LAG(END_Date) OVER (ORDER BY Start_Date) AS PreviousEndDate,
           LEAD(Start_Date) OVER (ORDER BY Start_Date) AS NextStartDate,
           GROSS_SALES_PRICE
    FROM @t
)
SELECT START_DATE,
        CASE WHEN NextStartDate < END_DATE
            THEN Coalesce(DATEADD(s, -1, NextStartDate), End_Date)
            ELSE End_date END As End_Date,
        GROSS_SALES_PRICE
FROM CTE
UNION ALL
SELECT DATEADD(s, 1, PreviousEndDate), DATEADD(s, -1, Start_Date), GROSS_SALES_PRICE
FROM CTE
WHERE DATEDIFF(s, PreviousEndDate,Start_Date) > 1
ORDER BY 1


问:
Microsoft Graph Schema Registration
I am working on creating a simple calendar app to track the user's Outlook.com calendar. In order to add some custom information I am needing to use Schema Extension as this information must be filterable and to my knowledge there is no filterable on Open Extension data.

I have followed the RegisterSchemaExtension() from the following sample: https://github.com/microsoftgraph/uwp-csharp-snippets-rest-sample/blob/master/O365-UWP-Unified-API-Snippets/Extensions/ExtensionSnippets.cs

and have added the proper scope to my application. I have also added the Directory.AccessAsUser.All permission to my app through the app registration portal at: https://apps.dev.microsoft.com/portal/register-app

Despite this, I am unable to register the schema and get error saying: MethodNotAllowed. I am not sure where to go from here as I haven't been able to find useful resources on the web. Apologies for the English! It is not perfect yet but I am learning!

答: With how complicated the Schema Extension turned out I decided to use Open Extension and do filtering manually.</p>

Title: Microsoft Graph Schema Registration


问:
Good bootstrap UI for selecting multiple boxes
I have a state dropdown with 50 states and I want to be able to select multiple states (it's like a UI component to select multiple states to blacklist). What's a good UI component in bootstrap for this?

I was looking at this and at the multiselect, but it seems like selecting 25 states might be a bit clunky looking. Is there anything better?

答: Group the states as per region (E, W, N, S). And you could have a dropdown with the regions, and depending upon this selection, populate the states dropdown. </p>


问:
ef4 poco,how get id after insert?
I am inserting a document and i want references id of document to a part of this
document...but the code is autoincrement, and i am using poco. how i can get
back the code of insert file?</p>

```<code>            ArquivoDTO file = new ArquivoDTO();
            file.NomeArquivo = fileName;
            file.TipoArquivo = fileType;

            file.TamanhoArquivo = fileSize;
            var context = new PROGISContext();
            ArquivoRepository arquivoRepository = new ArquivoRepository(context);
            arquivoRepository.IncluirArquivo(file); //insert file
            ParteArquivoDTO part = new ParteArquivoDTO(); //create a part

            part.CodArquivo = file.CodArquivo; // here id of inserted file
</code>```

答:
It's kind of hard to say what's the problem with this code sample alone, but are you calling SubmitChanges() on your DataContext in arquivoRepository.IncluirArquivo(file)?

If you are, and the CodArquivo property of your ArquivoDTO class it correctly configured to be an auto increment ID, then the property should get updated automatically after SubmitChanges().

Title: ef4 poco,how get id after insert?

Body:
I am inserting a document and i want references id of document to a part of this
document...but the code is autoincrement, and i am using poco. how i can get
back the code of insert file?

            ArquivoDTO file = new ArquivoDTO();
            file.NomeArquivo = fileName;
            file.TipoArquivo = fileType;

            file.TamanhoArquivo = fileSize;
            var context = new PROGISContext();
            ArquivoRepository arquivoRepository = new ArquivoRepository(context);
            arquivoRepository.IncluirArquivo(file); //insert file
            ParteArquivoDTO part = new ParteArquivoDTO(); //create a part

            part.CodArquivo = file.CodArquivo; // here id of inserted file


问:
Difference in including the .cpp file and .h file (with the same content in cpp)?
I've recently started learning cpp from basics and was very much confused with the folowing:

Lets say I have a header( test.h which contains only declarations) with some content and some source file (source.cpp) and program produced some result.

If I have copied the same content of that header file to a .cpp file (testcpp.cpp) and included this in source.cpp

In this case, I did not understood what difference it makes?

(I'll not include this testcpp.cpp in make file)

I have seen some threads similar to this but couldn't get a clear idea!!!

I learnt the usage of header and cpp files and have used it correctly in projects till now, Please answer specific to this scenario (I know doing this way adds confusion but just want to know). Will there be any difference doing so or it's just a common practice everyone follows ?

答:
It changes nothing. It's just a convention whether you use a *.h or *.cpp or *.asdasd suffix, as long as it doesn't get compiled by itself.

Some projects use the .hxx extension for header files and .cc for source file.

Please, for the good of fellow programmers you'll work with, stick to common conventions and don't put header code in .cpp files.


问:
CORS response for request with unsupported methods
I am wondering how server should respond for CORS request that asks for unsupported method.

I have server endpoint, lets say server.com/endpoint which supports only GET. But client is sending CORS OPTIONS request with headers:

```<code>Origin: another.com
Access-Control-Request-Method: POST
</code>```

How proper response should look? Should it return some error message about unsupported POST method, or just return 200 OK with typical CORS response  headers like:

```<code>Access-Control-Allow-Methods: GET
Access-Control-Allow-Origin: another.com
</code>```

Or maybe I should treat it as request without CORS headers?

Also what should be returned in case of some random origin in request? Should i reveal which origins are allowed or keep it hidden and return no "Allow" headers?

答:
I am wondering how server should respond for CORS request that asks for unsupported method.

I have server endpoint, lets say server.com/endpoint which supports only GET. But client is sending CORS OPTIONS request with headers:

```<code>Origin: another.com
Access-Control-Request-Method: POST
</code>```

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests explains what’s happening: That OPTIONS is an expected request that browsers on their own automatically send as part of the CORS protocol.

How proper response should look? Should it return some error message about unsupported POST method

No, supporting the CORS protocol as expected on your server side doesn’t require you to send any special error response for this case. The browser just interprets the lack of "Allow" headers in the normal response as meaning that the server doesn’t allow the type of request it’s received.

or just return 200 OK with typical CORS response  headers like:

```<code>Access-Control-Allow-Methods: GET
Access-Control-Allow-Origin: another.com
</code>```

That would be the right way to respond to it as far as supporting CORS as expected for the case where you get a request from the allowed origin another.com but for an unsupported method (e.g., POST, if you don’t support that). That enables the browser to log a specific CORS error on the client side to let the developer know the non-allowed method is the problem, not the origin.

Also what should be returned in case of some random origin in request? Should I reveal which origins are allowed or keep it hidden and return no "Allow" headers?

You can just return no "Allow" headers in the case of a non-allowed origin. There’s never any need to reveal what origins are allowed, except to allowed origins. (Anyway, the Access-Control-Allow-Origin value is always just going to contain either a single origin, or else the * wildcard, so no random origin making a request is going to be able to sniff out all the allowed origins.)

And to be clear, the CORS protocol in no way requires servers to respond to random non-allowed origins with any CORS headers at all. The semantics of the protocol are such that to a browser, a response with no "Allow" headers at all means, “This server does not allow cross-origin requests from your origin”. A random non-allowed origin doesn’t need any more information than just that.

Body:
I am wondering how server should respond for CORS request that asks for unsupported method.

I have server endpoint, lets say server.com/endpoint which supports only GET. But client is sending CORS OPTIONS request with headers:

Origin: another.com
Access-Control-Request-Method: POST

How proper response should look? Should it return some error message about unsupported POST method, or just return 200 OK with typical CORS response  headers like:

Access-Control-Allow-Methods: GET
Access-Control-Allow-Origin: another.com

Or maybe I should treat it as request without CORS headers?

Also what should be returned in case of some random origin in request? Should i reveal which origins are allowed or keep it hidden and return no "Allow" headers?

Body:
I am wondering how server should respond for CORS request that asks for unsupported method.

I have server endpoint, lets say server.com/endpoint which supports only GET. But client is sending CORS OPTIONS request with headers:

Origin: another.com
Access-Control-Request-Method: POST

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests explains what’s happening: That OPTIONS is an expected request that browsers on their own automatically send as part of the CORS protocol.

How proper response should look? Should it return some error message about unsupported POST method

No, supporting the CORS protocol as expected on your server side doesn’t require you to send any special error response for this case. The browser just interprets the lack of "Allow" headers in the normal response as meaning that the server doesn’t allow the type of request it’s received.

or just return 200 OK with typical CORS response  headers like:

Access-Control-Allow-Methods: GET
Access-Control-Allow-Origin: another.com

That would be the right way to respond to it as far as supporting CORS as expected for the case where you get a request from the allowed origin another.com but for an unsupported method (e.g., POST, if you don’t support that). That enables the browser to log a specific CORS error on the client side to let the developer know the non-allowed method is the problem, not the origin.

Also what should be returned in case of some random origin in request? Should I reveal which origins are allowed or keep it hidden and return no "Allow" headers?

You can just return no "Allow" headers in the case of a non-allowed origin. There’s never any need to reveal what origins are allowed, except to allowed origins. (Anyway, the Access-Control-Allow-Origin value is always just going to contain either a single origin, or else the * wildcard, so no random origin making a request is going to be able to sniff out all the allowed origins.)

And to be clear, the CORS protocol in no way requires servers to respond to random non-allowed origins with any CORS headers at all. The semantics of the protocol are such that to a browser, a response with no "Allow" headers at all means, “This server does not allow cross-origin requests from your origin”. A random non-allowed origin doesn’t need any more information than just that.


问:
C# for loop to delete strings containing 'TJ' deletes only one of the Strings containing it
I am trying to create a method that deletes all Sales objects if they have a material description that includes "TJ" somewhere in the string. My problem is that when I create a List with four Sales, two of which include "TJ" in their description, only one is deleted. The one being deleted is not unique to the first one. if I delete the "TJ" from the first Sale the second Sale is then deleted correctly. Why does this occur? My method, along with the TestCase is below. </p>

```<code>/// <summary>
/// This method deletes all sales with a 'TJ' material.
/// </summary>
public void deleteTJ()
{
    for (int i = 0; i < salesList.Count; i++)
    {
        if (salesList[i].material.Contains("TJ"))
        {
            salesList.Remove(salesList[i]);
            Console.WriteLine("FOUND IT");
        }
        else
        {
            Console.WriteLine("Not this time");
        }
    }
}

    [TestMethod]
    public void TestDeleteTJ()
    {
        sale1.material = "ABJFSJTJ"; // Contains TJ
        sale2.material = "KTJANDKFH"; // Contains TJ
        sale3.material = "SADVUAWDJ"; // No TJ
        sale4.material = "JTNDBAYK"; // No TJ

        testList.Add(sale1);
        testList.Add(sale2);
        testList.Add(sale3);
        testList.Add(sale4);

        Modifier modifier = new Modifier(testList);

        Assert.IsTrue(testList.Count == 4);

        modifier.deleteTJ();

        Assert.IsTrue(testList.Count == 2);
        Assert.AreEqual("SADVUAWDJ", testList[0]);
        Assert.AreEqual("JTNDBAYK", testList[1]);
    }
</code>```

答:
When you remove an item from the list all subsequent indexes are decremented.

```<code>0: ABJFSJTJ
1: KTJANDKFH
2: SADVUAWDJ
3: JTNDBAYK
</code>```

When you remove the first index the list now looks like this:

```<code>0: KTJANDKFH
1: SADVUAWDJ
2: JTNDBAYK
</code>```

The loop then increments i to 1, effectively skipping what was previously at index 1.

Body:
I am trying to create a method that deletes all Sales objects if they have a material description that includes "TJ" somewhere in the string. My problem is that when I create a List with four Sales, two of which include "TJ" in their description, only one is deleted. The one being deleted is not unique to the first one. if I delete the "TJ" from the first Sale the second Sale is then deleted correctly. Why does this occur? My method, along with the TestCase is below.

///
/// This method deletes all sales with a 'TJ' material.
///
public void deleteTJ()
{
    for (int i = 0; i < salesList.Count; i++)
    {
        if (salesList[i].material.Contains("TJ"))
        {
            salesList.Remove(salesList[i]);
            Console.WriteLine("FOUND IT");
        }
        else
        {
            Console.WriteLine("Not this time");
        }
    }
}

    [TestMethod]
    public void TestDeleteTJ()
    {
        sale1.material = "ABJFSJTJ"; // Contains TJ
        sale2.material = "KTJANDKFH"; // Contains TJ
        sale3.material = "SADVUAWDJ"; // No TJ
        sale4.material = "JTNDBAYK"; // No TJ

        testList.Add(sale1);
        testList.Add(sale2);
        testList.Add(sale3);
        testList.Add(sale4);

        Modifier modifier = new Modifier(testList);

        Assert.IsTrue(testList.Count == 4);

        modifier.deleteTJ();

        Assert.IsTrue(testList.Count == 2);
        Assert.AreEqual("SADVUAWDJ", testList[0]);
        Assert.AreEqual("JTNDBAYK", testList[1]);
    }

Body:
When you remove an item from the list all subsequent indexes are decremented.

0: ABJFSJTJ
1: KTJANDKFH
2: SADVUAWDJ
3: JTNDBAYK

When you remove the first index the list now looks like this:

0: KTJANDKFH
1: SADVUAWDJ
2: JTNDBAYK

The loop then increments i to 1, effectively skipping what was previously at index 1.


问:
How to install curl on python 3.x in Windows 7?
Can you please tell how to install curl for python 3.x to Windows 7. Ease_install only for the 2 version of the sort.</p>

答:
There is no module called "curl", so it's unclear what you mean?

PycURL?

friendly_curl?

pylibcurl?

curlwrapper?

pyparallelcurl?

In any case, as far as I can gather, none of them are ported to Python 3, so the answer on how to install them on Python 3 is: Talk to the authors and help port them! It's fun!


问:
Is there an elegant way to extract individual words from variable names into an array?
Basically I want to do this:

I get a string "myVariableName" and turn it into: ["my", "variable", "name"]

I tried doing this using regex, but I get a lot of undefineds in my ending array it seems. The two possible cases for variable names are camel-case and upper snake-case in this situation.

```<code>const matchVariableNames =  /(\b[a-z]+)|([A-Z][a-z]+)|(\b[A-Z]+)|(_[A-Z]+)/g;
const variableName = 'myVariable';
let words = [];
let regexMatches;

while (regexMatches = matchVariableNames.exec(variableName)) {
  regexMatches.forEach((match) => {
    words.push(match);
  });
};
</code>```

outputs:

```<code>["my", "my", undefined, undefined, undefined, "Variable", undefined, "Variable", undefined, undefined]
undefined
</code>```

答:
I don't think a regular expression is a good fit for this. (I don't accept Regular expression to identify CamelCased words with leading uppercase letter as a duplicate since the question does not ask for a regular expression persé).

The way I read it you want to parse words written in camelcase. Immediately I imagine special cases such as "DOMElement and "PDFParser". I would expect the output to be [ "DOM", "Element" ] and [ "PDF", "Parser" ]. I think we can write a function that works like that.

function parseWordsFromCamelCaseString(string) {
  var i, words, last_word_char, last_case, current_case;
  words = [];
  last_word_start = 0;
  last_case = null; // false=lower, true=upper

  for (i = 0; i < string.length; i += 1) {
    current_case = string[i].toUpperCase() === string[i];
    if (last_case !== null && current_case !== last_case) {
      if (current_case === true) { // lowercase to uppercase transition
        words.push(string.substring(last_word_start, i));
        last_word_start = i;
      } else { // uppercase to lowercase transition
        if (last_word_start < i - 1) {
          words.push(string.substring(last_word_start, i - 1));
        }
        last_word_start = i - 1;
      }
    }
    last_case = current_case;
  }
  if (last_word_start < i - 1) {
    words.push(string.substring(last_word_start, i));
  }
  return words;
}

console.log(parseWordsFromCamelCaseString("fooBar"));
console.log(parseWordsFromCamelCaseString("parseWordsFromCamelCaseString"));
console.log(parseWordsFromCamelCaseString("DOMElement"));
console.log(parseWordsFromCamelCaseString("fooDOMElement"));```
</div>
</div>
</p>

<p>Output</p>

```["foo", "Bar"]
["parse", "Words", "From", "Camel", "Case", "String"]
["DOM", "Element"]
["foo", "DOM", "Element"]
```

It also works for "foo" (no case transition) and "" (empty string).

Body:
Basically I want to do this:

I get a string "myVariableName" and turn it into: ["my", "variable", "name"]

I tried doing this using regex, but I get a lot of undefineds in my ending array it seems. The two possible cases for variable names are camel-case and upper snake-case in this situation.

const matchVariableNames =  /(\b[a-z]+)|([A-Z][a-z]+)|(\b[A-Z]+)|(_[A-Z]+)/g;
const variableName = 'myVariable';
let words = [];
let regexMatches;

while (regexMatches = matchVariableNames.exec(variableName)) {
  regexMatches.forEach((match) => {
    words.push(match);
  });
};

outputs:

["my", "my", undefined, undefined, undefined, "Variable", undefined, "Variable", undefined, undefined]
undefined

Body:
I don't think a regular expression is a good fit for this. (I don't accept Regular expression to identify CamelCased words with leading uppercase letter as a duplicate since the question does not ask for a regular expression persé).

The way I read it you want to parse words written in camelcase. Immediately I imagine special cases such as "DOMElement and "PDFParser". I would expect the output to be [ "DOM", "Element" ] and [ "PDF", "Parser" ]. I think we can write a function that works like that.

function parseWordsFromCamelCaseString(string) {
  var i, words, last_word_char, last_case, current_case;
  words = [];
  last_word_start = 0;
  last_case = null; // false=lower, true=upper

  for (i = 0; i < string.length; i += 1) {
    current_case = string[i].toUpperCase() === string[i];
    if (last_case !== null && current_case !== last_case) {
      if (current_case === true) { // lowercase to uppercase transition
        words.push(string.substring(last_word_start, i));
        last_word_start = i;
      } else { // uppercase to lowercase transition
        if (last_word_start < i - 1) {
          words.push(string.substring(last_word_start, i - 1));
        }
        last_word_start = i - 1;
      }
    }
    last_case = current_case;
  }
  if (last_word_start < i - 1) {
    words.push(string.substring(last_word_start, i));
  }
  return words;
}

console.log(parseWordsFromCamelCaseString("fooBar"));
console.log(parseWordsFromCamelCaseString("parseWordsFromCamelCaseString"));
console.log(parseWordsFromCamelCaseString("DOMElement"));
console.log(parseWordsFromCamelCaseString("fooDOMElement"));

Output

["foo", "Bar"]
["parse", "Words", "From", "Camel", "Case", "String"]
["DOM", "Element"]
["foo", "DOM", "Element"]

It also works for "foo" (no case transition) and "" (empty string).


问:
Git init with symlinks
I am attempting to run Atlassian BitKeeper within the context of a Docker container (Windows Nano). The home directory is stored outside the context of the container. As a result, this is presented as a symlink inside it.

Running git init with the repository contained in the symlink'ed directory results in an error:

```<code>Invalid path '/ContainerMappedDirectories': No such file or directory.
</code>```

This is the root directory listing portion with respect to the symlink:

```<code>03/09/2017  02:22 PM    <SYMLINKD>     host [\\?\ContainerMappedDirectories\06928B3D-65E2-4BA6-AADB-7851FD273002]
</code>```

答:
I am suffering the same issue running Jenkins (which uses Git) inside a Docker container. This used to work for me but it stopped after some Git update so I compared few version and I noticed that last version that worked inside a container was 2.11.1.

Here is the proof - C:\temp is mounted from docker host:

```<code>06/06/2017  04:44 PM    <SYMLINKD>     temp [\\?\ContainerMappedDirectories\3090B08B-4EA2-49CB-8C30-227E982EC311]
</code>```

Attempt with 2.11.1:

```<code>PS C:\Program Files\git\bin> .\git.exe --version
git version 2.11.1.windows.1
PS C:\Program Files\git\bin> .\git.exe init C:\temp\git11.1\
Initialized empty Git repository in C:/temp/git11.1/.git/
</code>```

Attempt with 2.12.1:

```<code>PS C:\Program Files\Git\bin> .\git.exe --version
git version 2.12.1.windows.1
PS C:\Program Files\Git\bin> .\git.exe init C:\temp\git12.1\
fatal: Invalid path '/ContainerMappedDirectories': No such file or directory
</code>```

Same with MinGit:

```<code>PS C:\> .\Min\MinGit-2.13.0-64-bit\cmd\git.exe init C:\temp\MinGitRepo\
fatal: Invalid path '/ContainerMappedDirectories': No such file or directory

PS C:\> .\Min\MinGit-2.11.1-64-bit\cmd\git.exe init C:\temp\MinGitRepo\
Initialized empty Git repository in C:/temp/MinGitRepo/.git/
</code>```

Hard to say what changed, I'll take a deep dive into Git changelog, as for now using 2.11.1 seems like a decent workaround for me. Let me know if it worked for you.

Title: Git init with symlinks

Body:
I am attempting to run Atlassian BitKeeper within the context of a Docker container (Windows Nano). The home directory is stored outside the context of the container. As a result, this is presented as a symlink inside it.

Running git init with the repository contained in the symlink'ed directory results in an error:

Invalid path '/ContainerMappedDirectories': No such file or directory.

This is the root directory listing portion with respect to the symlink:

03/09/2017  02:22 PM    <SYMLINKD>     host [\\?\ContainerMappedDirectories\06928B3D-65E2-4BA6-AADB-7851FD273002]

Body:
I am suffering the same issue running Jenkins (which uses Git) inside a Docker container. This used to work for me but it stopped after some Git update so I compared few version and I noticed that last version that worked inside a container was 2.11.1.

Here is the proof - C:\temp is mounted from docker host:

06/06/2017  04:44 PM    <SYMLINKD>     temp [\\?\ContainerMappedDirectories\3090B08B-4EA2-49CB-8C30-227E982EC311]

Attempt with 2.11.1:

PS C:\Program Files\git\bin> .\git.exe --version
git version 2.11.1.windows.1
PS C:\Program Files\git\bin> .\git.exe init C:\temp\git11.1\
Initialized empty Git repository in C:/temp/git11.1/.git/

Attempt with 2.12.1:

PS C:\Program Files\Git\bin> .\git.exe --version
git version 2.12.1.windows.1
PS C:\Program Files\Git\bin> .\git.exe init C:\temp\git12.1\
fatal: Invalid path '/ContainerMappedDirectories': No such file or directory

Same with MinGit:

PS C:\> .\Min\MinGit-2.13.0-64-bit\cmd\git.exe init C:\temp\MinGitRepo\
fatal: Invalid path '/ContainerMappedDirectories': No such file or directory

PS C:\> .\Min\MinGit-2.11.1-64-bit\cmd\git.exe init C:\temp\MinGitRepo\
Initialized empty Git repository in C:/temp/MinGitRepo/.git/

Hard to say what changed, I'll take a deep dive into Git changelog, as for now using 2.11.1 seems like a decent workaround for me. Let me know if it worked for you.


问:
Subscribing within constructor of extended class does not work correctly
I've built an abstract class called CoreButtonService which every ButtonService will extend. For example there are UserButtonService, MessageButtonService and so on. Those services are going to be injected into the respective component like UserComponent, MessageComponent and so on. In the constructor of the CoreButtonService I subscribed to another service called ButtonsService which is responsible for firing an event when any button within the ButtonModule has been clicked.

CoreButtonService:

```<code>export abstract class CoreButtonService<T extends CoreModel> extends CoreService {

    private backSource = new Subject<string>();
    private submitSource = new Subject<string>();
    back$ = this.backSource.asObservable();
    submit$ = this.submitSource.asObservable();

    constructor(
        private coreButtonsService: ButtonsService,
        private coreLanguageService: LanguageService,
        private coreLocation: Location) {
        super(coreLanguageService);
        this.coreButtonsService
            .buttonClicked$
            .subscribe(button => console.log(button)); // !!!!!!
    }

    // Buttons are going to be built down here ...

}
</code>```

ButtonsService:

```<code>@Injectable()
export class ButtonsService {
    private button = new Subject<ButtonBase<any>>();
    buttonClicked$ = this.button.asObservable();
    constructor(private formService: FormService) { }

    clickButton(button: ButtonBase<any>): void {
        if (button.controlType === 'submit')
            this.formService.submitForm(button.parent);
        this.button.next(button);
    }
}
</code>```

Let's assume I visit the page that includes the UserComponent, click a button and then do the same on the page of the MessageComponent. Technically there should be logged 2 buttons within the console. The button of the UserComponent and the button of the MessageComponent which I can identify by button.parent. But I get 2 buttons of MessageComponent.

When I save the sent parent within CoreButtonService and log it like the button, I get the expected values: 'MessageForm' for MessageComponent and 'UserForm' for UserComponent. But the values of button.parent are both the same. How is that possible?

I don't see the problem. May be it is because every ButtonService is doing the same subscription within the CoreButtonService and that's why each subscription / button is related to each other?

UPDATE

This is the plunkr with the basic concept.

答:
To explain @user289520's solution in more detail:

Subscriptions: Represents a disposable resource, such as the execution of an Observable. A Subscription has one important method, unsubscribe, that takes no argument and just disposes the resource held by the subscription.

You can collect subscriptions that you want to unsubscribe at once in ngOnDestroy().

ngOnDestroy(): Cleanup just before Angular destroys the directive/component. Unsubscribe observables and detach event handlers to avoid memory leaks.

However apart from this.subscription.unsubscribe; you can also do this in a foreach loop shown as below:

```<code>this.subscriptions.forEach(s => s.unsubscribe());
</code>```

Why should you not forget to unsubscribe() in angular.js?

Promises are eager and are executed immediately. Observables are not eager and are only executed when subscribed to.

Promises are asynchronous. Observables can be either synchronous or asynchronous.

Promises are expected to return only a single value (like a function). Observables can return zero, one or more (infinitely) values.

Body:
I've built an abstract class called CoreButtonService which every ButtonService will extend. For example there are UserButtonService, MessageButtonService and so on. Those services are going to be injected into the respective component like UserComponent, MessageComponent and so on. In the constructor of the CoreButtonService I subscribed to another service called ButtonsService which is responsible for firing an event when any button within the ButtonModule has been clicked.

CoreButtonService:

export abstract class CoreButtonService<T extends CoreModel> extends CoreService {

    private backSource = new Subject<string>();
    private submitSource = new Subject<string>();
    back$ = this.backSource.asObservable();
    submit$ = this.submitSource.asObservable();

    constructor(
        private coreButtonsService: ButtonsService,
        private coreLanguageService: LanguageService,
        private coreLocation: Location) {
        super(coreLanguageService);
        this.coreButtonsService
            .buttonClicked$
            .subscribe(button => console.log(button)); // !!!!!!
    }

    // Buttons are going to be built down here ...

}

ButtonsService:

@Injectable()
export class ButtonsService {
    private button = new Subject<ButtonBase<any>>();
    buttonClicked$ = this.button.asObservable();
    constructor(private formService: FormService) { }

    clickButton(button: ButtonBase<any>): void {
        if (button.controlType === 'submit')
            this.formService.submitForm(button.parent);
        this.button.next(button);
    }
}

Let's assume I visit the page that includes the UserComponent, click a button and then do the same on the page of the MessageComponent. Technically there should be logged 2 buttons within the console. The button of the UserComponent and the button of the MessageComponent which I can identify by button.parent. But I get 2 buttons of MessageComponent.

When I save the sent parent within CoreButtonService and log it like the button, I get the expected values: 'MessageForm' for MessageComponent and 'UserForm' for UserComponent. But the values of button.parent are both the same. How is that possible?

I don't see the problem. May be it is because every ButtonService is doing the same subscription within the CoreButtonService and that's why each subscription / button is related to each other?

UPDATE

This is the plunkr with the basic concept.

Body:
To explain @user289520's solution in more detail:

Subscriptions: Represents a disposable resource, such as the execution of an Observable. A Subscription has one important method, unsubscribe, that takes no argument and just disposes the resource held by the subscription.

You can collect subscriptions that you want to unsubscribe at once in ngOnDestroy().

ngOnDestroy(): Cleanup just before Angular destroys the directive/component. Unsubscribe observables and detach event handlers to avoid memory leaks.

However apart from this.subscription.unsubscribe; you can also do this in a foreach loop shown as below:

this.subscriptions.forEach(s => s.unsubscribe());

Why should you not forget to unsubscribe() in angular.js?

Promises are eager and are executed immediately. Observables are not eager and are only executed when subscribed to.

Promises are asynchronous. Observables can be either synchronous or asynchronous.

Promises are expected to return only a single value (like a function). Observables can return zero, one or more (infinitely) values.


答:
This is because you edit the list during the loop. As soon as you remove one item the count gets changed.

There are two ways out of it - use one of of those:

Looping in reverse order (List.Count-1 to 0):

```<code>for (int i = salesList.Count - 1; i >= 0; i--)
{
}
</code>```

Removing values with Lambdas

```<code>salesList.RemoveAll(s => s.material.Contains("TJ"));
</code>```

Title: C# for loop to delete strings containing 'TJ' deletes only one of the Strings containing it

Body:
This is because you edit the list during the loop. As soon as you remove one item the count gets changed.

There are two ways out of it - use one of of those:

Looping in reverse order (List.Count-1 to 0):

for (int i = salesList.Count - 1; i >= 0; i--)
{
}

Removing values with Lambdas

salesList.RemoveAll(s => s.material.Contains("TJ"));


问:
Cannot resolve symbol 'Theme.AppCompat.Light.DarkActionBar' in styles.xml
Theme.AppCompat.Light.DarkActionBar is not compiling in styles.xml. I have added compile 'com.android.support:appcompat-v7:25.1.0' in app module's
build.gradle.

I have searched for solution in google. A lot of them are about changing the classpath in Project's build.gradle.Still its showing the same error.

```<code>build.gradle

dependencies {
    compile 'com.android.support:appcompat-v7:25.1.0'
    compile 'com.android.support:design:25.1.0'
    compile 'com.android.support:support-annotations:25.1.0'
    compile 'com.android.support:cardview-v7:25.1.0'
    compile 'com.android.support:recyclerview-v7:25.1.0'
    //    compile 'ch.acra:acra:4.5.0'

    testCompile 'junit:junit:4.12'
}

android {
    compileSdkVersion 25
    buildToolsVersion '25.0.2'

    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 25
        versionCode = 146
        versionName = "0.6.65"
    }
</code>```

答:
I had the exact same problem, what fixed it for me was retrograding gradle plugin:

```<code>buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        //classpath 'com.android.tools.build:gradle:2.3.1'
        classpath 'com.android.tools.build:gradle:2.2.3'
    }
}
</code>```

Followed by a project sync with gradle files to clear the problem.

Body:
Theme.AppCompat.Light.DarkActionBar is not compiling in styles.xml. I have added compile 'com.android.support:appcompat-v7:25.1.0' in app module's
build.gradle.

I have searched for solution in google. A lot of them are about changing the classpath in Project's build.gradle.Still its showing the same error.

build.gradle

dependencies {
    compile 'com.android.support:appcompat-v7:25.1.0'
    compile 'com.android.support:design:25.1.0'
    compile 'com.android.support:support-annotations:25.1.0'
    compile 'com.android.support:cardview-v7:25.1.0'
    compile 'com.android.support:recyclerview-v7:25.1.0'
    //    compile 'ch.acra:acra:4.5.0'

    testCompile 'junit:junit:4.12'
}

android {
    compileSdkVersion 25
    buildToolsVersion '25.0.2'

    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 25
        versionCode = 146
        versionName = "0.6.65"
    }

Body:
I had the exact same problem, what fixed it for me was retrograding gradle plugin:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        //classpath 'com.android.tools.build:gradle:2.3.1'
        classpath 'com.android.tools.build:gradle:2.2.3'
    }
}

Followed by a project sync with gradle files to clear the problem.


问:
How do I protect phone number from bots
I want a phone number which display on public page will be protected. Example converts phone number characters to HTML entities and bots can't grab the number in plain text. Let me know the trick.</p>

答:
some ideas

display the phone number as an image

use javascript to create and display the phone number

throw in html tags in between the numbers (e.g. [span]) that visually makes no difference but makes it more difficult for the bot to recognize the phone number

Title: How do I protect phone number from bots


问:
Python: Sending email with attachment only with the stdlib?
I want to send an email with attachment (for example a text file) with python. Is this possible with the stdlib or do I have to download and install other packages?

I would like to do this with the stdlib.

thx. :)

答:
You can try this:</p>

```<code># Import smtplib for the actual sending function
import smtplib

# Import the email modules we'll need
from email.mime.text import MIMEText

# Open a plain text file for reading.  For this example, assume that
# the text file contains only ASCII characters.
fp = open(textfile, 'rb')
# Create a text/plain message
msg = MIMEText(fp.read())
fp.close()

# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = me
msg['To'] = you

# Send the message via our own SMTP server.
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()
</code>```

Body:
You can try this:

# Import smtplib for the actual sending function
import smtplib

# Import the email modules we'll need
from email.mime.text import MIMEText

# Open a plain text file for reading.  For this example, assume that
# the text file contains only ASCII characters.
fp = open(textfile, 'rb')
# Create a text/plain message
msg = MIMEText(fp.read())
fp.close()

# me == the sender's email address
# you == the recipient's email address
msg['Subject'] = 'The contents of %s' % textfile
msg['From'] = me
msg['To'] = you

# Send the message via our own SMTP server.
s = smtplib.SMTP('localhost')
s.send_message(msg)
s.quit()


问:
Changing css dynamically without reloading page in Angular2
I have a side navigation bar, wherein there is progress bar in each nav.
This is modular structure-

```<code>MainFile
   -Children1
       -children1.html
       -children1.component.ts
  -Children2
       -children2.html
       -children2.component.ts
  -Children3
       -children3.html
       -children3.component.ts
  -ProgressIndicator
       -progressIndicator.html
       -progressIndicator.component.ts
  -main.html
  -main.component.ts
</code>```

Inside progressIndicator.html, I have this code,

```<code> <div class="progress">
    <div [ngStyle]="{'width':getProgress()}" class="progress-bar" role="progressbar" aria-
       valuenow="70" aria-valuemin="0" aria-valuemax="100">
       <span class="sr-only">70% Complete</span>
   </div>
</code>```

And my progressIndicator.component.ts

```<code>currentPage = '';
progressBar = '';
//getting current route name using 'this.route.url' and updating 'currentPage' property in
constructor.
getProgress(){
   if(currentPage  === 'children1'){
         return progressBar = '25%';
     }
   if(currentPage  === 'children2'){
        return progressBar = '50%';
    }
}
</code>```

I am successfully getting the current page, as 'children1.html' or 'children2.html', based on the current page I want to change the width of div with class 'progress-bar', I used

```<code>[ngStyle]="{width:getProgress()}"
</code>```

but it takes effect ONLY if page reloads, which angular2 being SPA doesn't happen.
Do help me in finding a better way that when I move from 'children1' to 'children2', the 'getProgress()' takes effect and changes the style.

答:
Return the full key:value pair in your call. Also bring the assigning of currentPage into your function.

HTML

```<code>[ngStyle] = "getProgress()"
</code>```

TS

```<code>getProgress(){
   let currentPage = this.router.url;
   let progressBar;
   if(currentPage  === 'children1'){
         progressBar = {'width' : '25%'};
     }
   if(currentPage  === 'children2'){
         progressBar = {'width' : '50%'};
    }
   return progressBar
}
</code>```

Here is a good write up on ngStyle use.

Body:
I have a side navigation bar, wherein there is progress bar in each nav.
This is modular structure-

MainFile
   -Children1
       -children1.html
       -children1.component.ts
  -Children2
       -children2.html
       -children2.component.ts
  -Children3
       -children3.html
       -children3.component.ts
  -ProgressIndicator
       -progressIndicator.html
       -progressIndicator.component.ts
  -main.html
  -main.component.ts

Inside progressIndicator.html, I have this code,

       70% Complete

And my progressIndicator.component.ts

currentPage = '';
progressBar = '';
//getting current route name using 'this.route.url' and updating 'currentPage' property in
constructor.
getProgress(){
   if(currentPage  === 'children1'){
         return progressBar = '25%';
     }
   if(currentPage  === 'children2'){
        return progressBar = '50%';
    }
}

I am successfully getting the current page, as 'children1.html' or 'children2.html', based on the current page I want to change the width of div with class 'progress-bar', I used

[ngStyle]="{width:getProgress()}"

but it takes effect ONLY if page reloads, which angular2 being SPA doesn't happen.
Do help me in finding a better way that when I move from 'children1' to 'children2', the 'getProgress()' takes effect and changes the style.

Body:
Return the full key:value pair in your call. Also bring the assigning of currentPage into your function.

HTML

[ngStyle] = "getProgress()"

TS

getProgress(){
   let currentPage = this.router.url;
   let progressBar;
   if(currentPage  === 'children1'){
         progressBar = {'width' : '25%'};
     }
   if(currentPage  === 'children2'){
         progressBar = {'width' : '50%'};
    }
   return progressBar
}

Here is a good write up on ngStyle use.