问:
Duplicity incremental backup taking too long
I have duplicity running an incremental daily backup to S3. About 37 GiB.

On the first month or so, it went ok. It used to finish in about 1 hour. Then it started taking too long to complete the task. Right now, as I type, it is still running the daily backup that started 7 hours ago.

I'm running two commands, first to backup and then cleanup:

```<code>duplicity --full-if-older-than 1M LOCAL.SOURCE S3.DEST --volsize 666 --verbosity 8
duplicity remove-older-than 2M S3.DEST
</code>```

The logs

```<code>Temp has 54774476800 available, backup will use approx 907857100.
</code>```

So the temp has enough space, good. Then it starts with this...

```<code>Copying duplicity-full-signatures.20161107T090303Z.sigtar.gpg to local cache.
Deleting /tmp/duplicity-ipmrKr-tempdir/mktemp-13tylb-2
Deleting /tmp/duplicity-ipmrKr-tempdir/mktemp-NanCxQ-3
[...]
Copying duplicity-inc.20161110T095624Z.to.20161111T103456Z.manifest.gpg to local cache.
Deleting /tmp/duplicity-ipmrKr-tempdir/mktemp-VQU2zx-30
Deleting /tmp/duplicity-ipmrKr-tempdir/mktemp-4Idklo-31
[...]
</code>```

This continues for each day till today, taking long minutes for each file. And continues with this...

```<code>Ignoring incremental Backupset (start_time: Thu Nov 10 09:56:24 2016; needed: Mon Nov  7 09:03:03 2016)
Ignoring incremental Backupset (start_time: Thu Nov 10 09:56:24 2016; needed: Wed Nov  9 18:09:07 2016)
Added incremental Backupset (start_time: Thu Nov 10 09:56:24 2016 / end_time: Fri Nov 11 10:34:56 2016)
</code>```

After a long time...

```<code>Warning, found incomplete backup sets, probably left from aborted session
Last full backup date: Sun Mar 12 09:54:00 2017
Collection Status
-----------------
Connecting with backend: BackendWrapper
Archive dir: /home/user/.cache/duplicity/700b5f90ee4a620e649334f96747bd08

Found 6 secondary backup chains.
Secondary chain 1 of 6:
-------------------------
Chain start time: Mon Nov  7 09:03:03 2016
Chain end time: Mon Nov  7 09:03:03 2016
Number of contained backup sets: 1
Total number of contained volumes: 2
Type of backup set:                            Time:      Num volumes:
               Full         Mon Nov  7 09:03:03 2016                 2
-------------------------
Secondary chain 2 of 6:
-------------------------
Chain start time: Wed Nov  9 18:09:07 2016
Chain end time: Wed Nov  9 18:09:07 2016
Number of contained backup sets: 1
Total number of contained volumes: 11
Type of backup set:                            Time:      Num volumes:
               Full         Wed Nov  9 18:09:07 2016                11
-------------------------

Secondary chain 3 of 6:
-------------------------
Chain start time: Thu Nov 10 09:56:24 2016
Chain end time: Sat Dec 10 09:44:31 2016
Number of contained backup sets: 31
Total number of contained volumes: 41
Type of backup set:                            Time:      Num volumes:
               Full         Thu Nov 10 09:56:24 2016                11
        Incremental         Fri Nov 11 10:34:56 2016                 1
        Incremental         Sat Nov 12 09:59:47 2016                 1
        Incremental         Sun Nov 13 09:57:15 2016                 1
        Incremental         Mon Nov 14 09:48:31 2016                 1
        [...]
</code>```

After listing all chains:

```<code>Also found 0 backup sets not part of any chain, and 1 incomplete backup set.
These may be deleted by running duplicity with the "cleanup" command.
</code>```

This was only the backup part. It takes hours doing this and only 10 minutes to upload 37 GiB to S3.

```<code>ElapsedTime 639.59 (10 minutes 39.59 seconds)
SourceFiles 288
SourceFileSize 40370795351 (37.6 GB)
</code>```

Then comes the cleanup, that gives me this:

```<code>Cleaning up
Local and Remote metadata are synchronized, no sync needed.
Warning, found incomplete backup sets, probably left from aborted session
Last full backup date: Sun Mar 12 09:54:00 2017
There are backup set(s) at time(s):
Tue Jan 10 09:58:05 2017
Wed Jan 11 09:54:03 2017
Thu Jan 12 09:56:42 2017
Fri Jan 13 10:05:05 2017
Sat Jan 14 10:24:54 2017
Sun Jan 15 09:49:31 2017
Mon Jan 16 09:39:41 2017
Tue Jan 17 09:59:05 2017
Wed Jan 18 09:59:56 2017
Thu Jan 19 10:01:51 2017
Fri Jan 20 09:35:30 2017
Sat Jan 21 09:53:26 2017
Sun Jan 22 09:48:57 2017
Mon Jan 23 09:38:45 2017
Tue Jan 24 09:54:29 2017
Which can't be deleted because newer sets depend on them.
Found old backup chains at the following times:
Mon Nov  7 09:03:03 2016
Wed Nov  9 18:09:07 2016
Sat Dec 10 09:44:31 2016
Mon Jan  9 10:04:51 2017
Rerun command with --force option to actually delete.
</code>```

答:
I found the problem. Because of an issue, I followed this answer, and added this code to my script:

```<code>rm -rf ~/.cache/deja-dup/*
rm -rf ~/.cache/duplicity/*
</code>```

This is supposed to be a one time thing because of random bug duplicity had. But the answer didn't mention this. So every day the script was removing the cache just after syncing the cache, and then, on the next day it had to download the whole thing again.

Body:
I have duplicity running an incremental daily backup to S3. About 37 GiB.

On the first month or so, it went ok. It used to finish in about 1 hour. Then it started taking too long to complete the task. Right now, as I type, it is still running the daily backup that started 7 hours ago.

I'm running two commands, first to backup and then cleanup:

duplicity --full-if-older-than 1M LOCAL.SOURCE S3.DEST --volsize 666 --verbosity 8
duplicity remove-older-than 2M S3.DEST

The logs

Temp has 54774476800 available, backup will use approx 907857100.

So the temp has enough space, good. Then it starts with this...

Copying duplicity-full-signatures.20161107T090303Z.sigtar.gpg to local cache.
Deleting /tmp/duplicity-ipmrKr-tempdir/mktemp-13tylb-2
Deleting /tmp/duplicity-ipmrKr-tempdir/mktemp-NanCxQ-3
[...]
Copying duplicity-inc.20161110T095624Z.to.20161111T103456Z.manifest.gpg to local cache.
Deleting /tmp/duplicity-ipmrKr-tempdir/mktemp-VQU2zx-30
Deleting /tmp/duplicity-ipmrKr-tempdir/mktemp-4Idklo-31
[...]

This continues for each day till today, taking long minutes for each file. And continues with this...

Ignoring incremental Backupset (start_time: Thu Nov 10 09:56:24 2016; needed: Mon Nov  7 09:03:03 2016)
Ignoring incremental Backupset (start_time: Thu Nov 10 09:56:24 2016; needed: Wed Nov  9 18:09:07 2016)
Added incremental Backupset (start_time: Thu Nov 10 09:56:24 2016 / end_time: Fri Nov 11 10:34:56 2016)

After a long time...

Warning, found incomplete backup sets, probably left from aborted session
Last full backup date: Sun Mar 12 09:54:00 2017
Collection Status
-----------------
Connecting with backend: BackendWrapper
Archive dir: /home/user/.cache/duplicity/700b5f90ee4a620e649334f96747bd08

Found 6 secondary backup chains.
Secondary chain 1 of 6:
-------------------------
Chain start time: Mon Nov  7 09:03:03 2016
Chain end time: Mon Nov  7 09:03:03 2016
Number of contained backup sets: 1
Total number of contained volumes: 2
Type of backup set:                            Time:      Num volumes:
               Full         Mon Nov  7 09:03:03 2016                 2
-------------------------
Secondary chain 2 of 6:
-------------------------
Chain start time: Wed Nov  9 18:09:07 2016
Chain end time: Wed Nov  9 18:09:07 2016
Number of contained backup sets: 1
Total number of contained volumes: 11
Type of backup set:                            Time:      Num volumes:
               Full         Wed Nov  9 18:09:07 2016                11
-------------------------

Secondary chain 3 of 6:
-------------------------
Chain start time: Thu Nov 10 09:56:24 2016
Chain end time: Sat Dec 10 09:44:31 2016
Number of contained backup sets: 31
Total number of contained volumes: 41
Type of backup set:                            Time:      Num volumes:
               Full         Thu Nov 10 09:56:24 2016                11
        Incremental         Fri Nov 11 10:34:56 2016                 1
        Incremental         Sat Nov 12 09:59:47 2016                 1
        Incremental         Sun Nov 13 09:57:15 2016                 1
        Incremental         Mon Nov 14 09:48:31 2016                 1
        [...]

After listing all chains:

Also found 0 backup sets not part of any chain, and 1 incomplete backup set.
These may be deleted by running duplicity with the "cleanup" command.

This was only the backup part. It takes hours doing this and only 10 minutes to upload 37 GiB to S3.

ElapsedTime 639.59 (10 minutes 39.59 seconds)
SourceFiles 288
SourceFileSize 40370795351 (37.6 GB)

Then comes the cleanup, that gives me this:

Cleaning up
Local and Remote metadata are synchronized, no sync needed.
Warning, found incomplete backup sets, probably left from aborted session
Last full backup date: Sun Mar 12 09:54:00 2017
There are backup set(s) at time(s):
Tue Jan 10 09:58:05 2017
Wed Jan 11 09:54:03 2017
Thu Jan 12 09:56:42 2017
Fri Jan 13 10:05:05 2017
Sat Jan 14 10:24:54 2017
Sun Jan 15 09:49:31 2017
Mon Jan 16 09:39:41 2017
Tue Jan 17 09:59:05 2017
Wed Jan 18 09:59:56 2017
Thu Jan 19 10:01:51 2017
Fri Jan 20 09:35:30 2017
Sat Jan 21 09:53:26 2017
Sun Jan 22 09:48:57 2017
Mon Jan 23 09:38:45 2017
Tue Jan 24 09:54:29 2017
Which can't be deleted because newer sets depend on them.
Found old backup chains at the following times:
Mon Nov  7 09:03:03 2016
Wed Nov  9 18:09:07 2016
Sat Dec 10 09:44:31 2016
Mon Jan  9 10:04:51 2017
Rerun command with --force option to actually delete.

Body:
I found the problem. Because of an issue, I followed this answer, and added this code to my script:

rm -rf ~/.cache/deja-dup/*
rm -rf ~/.cache/duplicity/*

This is supposed to be a one time thing because of random bug duplicity had. But the answer didn't mention this. So every day the script was removing the cache just after syncing the cache, and then, on the next day it had to download the whole thing again.


来源: stackexchange

问:
How to get Google map (map_icon, title, latitude, longitude) dynamically from webservice
This is my web service

where I want to get map_icon, longitude, latitude dynamically from given web service. I am stuck at this point. How can I do this please help me out.
In old code what is done is get longitude, latitude, post_title from web service on the basis of id and then assign image statically.

Frnt_mapActivity.java

```<code>public class Frnt_mapActivity extends Activity {

public String Shop_title;
public String Shop_address;
public String Shop_icons;
ProgressDialog mDialog;
JSONObject jsonobject3;
JSONArray jsonarray3;
// Google Map
private static GoogleMap googlemap;
public static ArrayList<SearchBeams> searchdata_list;
public static ArrayList<NormalSearchBeams> normlSearchList;
ArrayList<All_products_lat_long> venueList;

private int i;
private Intent intent;
HashMap<Marker, Integer> hashMap=new HashMap<Marker, Integer>();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.frnt_map_activity);

    googlemap=((MapFragment)getFragmentManager().findFragmentById(R.id.places_map)).getMap();
    googlemap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    googlemap.setMyLocationEnabled(true);
    googlemap.getUiSettings().setZoomControlsEnabled(true);
    googlemap.getUiSettings().setMyLocationButtonEnabled(true);
    googlemap.getUiSettings().setCompassEnabled(true);
    googlemap.getUiSettings().setRotateGesturesEnabled(true);
    googlemap.getUiSettings().setZoomGesturesEnabled(true);
    googlemap.setMyLocationEnabled(true);
    intent=new Intent(Frnt_mapActivity.this,MainActivity.class);
    googlemap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {

        @Override
        public void onInfoWindowClick(Marker arg0) {
            i=hashMap.get(arg0);
            intent.putExtra("PRODUCT_ID", venueList.get(i).getId());
            startActivity(intent);
            //overridePendingTransition( R.anim.slide_right, R.anim.slide_left );
        }
    });

    new Frnt_mIcons_Activity().execute();

}

class AddMarkerAsyncTask extends AsyncTask<String,String,String>{

    private All_products_lat_long venue;
    private int k;
    BitmapDescriptor bd=null;

    AddMarkerAsyncTask(All_products_lat_long venue,int k){
        this.venue=venue;
        this.k=k;
    }

    @Override
    protected String doInBackground(String... strings) {
        try{
            bd=BitmapDescriptorFactory.fromBitmap(Glide.
                    with(Frnt_mapActivity.this).
                    load(venue.getMap_icon()).
                    asBitmap().
                    into(100, 100). // Width and height
                    get());
        }catch (Exception e){
            bd=null;
            e.printStackTrace();

        }

        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        try{
            if(bd!=null){
                Marker marker=googlemap.addMarker(new MarkerOptions()
                        .position(new LatLng(Double.parseDouble(venue.getLatitude()), Double.parseDouble(venue.getLongitude())))
                        .title(venue.getPost_title())
                        .icon(bd));
                hashMap.put(marker, k);
            }

        }catch (Exception e){
            e.printStackTrace();
        }

    }
}

private void addMarkers() {

    for(int k=0; k<venueList.size(); k += 1){

        //nirmal
        try{
            Log.e("nirmal",venueList.get(k).getMap_icon());

            //new AddMarkerAsyncTask(venueList.get(k),k).execute();

            double ln = Double.parseDouble(venueList.get(k).getLongitude());
            double la = Double.parseDouble(venueList.get(k).getLatitude());
                /*String title=venueList.get(k).getPost_title()==null?"":venueList.get(k).getPost_title();
                URL url = new URL(venueList.get(k).getMap_icon());
                Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
                BitmapDescriptor bd=BitmapDescriptorFactory.fromBitmap(image);*/

                /*Marker marker=googlemap.addMarker(new MarkerOptions()
                        .position(new LatLng(la, ln))
                        .title(title)
                        .icon(bd));
                hashMap.put(marker, k);*/

            switch (Integer.parseInt(venueList.get(k).getId()))
            {
                case 5689 :
                    Marker marker=googlemap.addMarker(new MarkerOptions()
                            .position(new LatLng(la, ln))
                            .title(venueList.get(k).getPost_title())
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.fruitandveg)));
                    hashMap.put(marker, k);
                    break;
                case 5779 :
                    Marker marker1=googlemap.addMarker(new MarkerOptions()
                            .position(new LatLng(la, ln))
                            .title(venueList.get(k).getPost_title())
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.coffee)));
                    hashMap.put(marker1, k);
                    break;
                case 5798 :
                    Marker marker3 = googlemap.addMarker(new MarkerOptions()
                            .position(new LatLng(la, ln))
                            .title(venueList.get(k).getPost_title())
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.takeaway)));
                    hashMap.put(marker3, k);
                    break;
                case 5810 :
                    Marker marker4 = googlemap.addMarker(new MarkerOptions()
                            .position(new LatLng(la, ln))
                            .title(venueList.get(k).getPost_title())
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.restaurant_steakhouse)));
                    hashMap.put(marker4, k);
                    break;
                case 6005 :
                    Marker marker5 = googlemap.addMarker(new MarkerOptions()
                            .position(new LatLng(la, ln))
                            .title(venueList.get(k).getPost_title())
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.clambers_playcentre)));
                    hashMap.put(marker5, k);
                    break;
                case 6011 :
                    Marker marker6 = googlemap.addMarker(new MarkerOptions()
                            .position(new LatLng(la, ln))
                            .title(venueList.get(k).getPost_title())
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.thetruecrimemuseum)));
                    hashMap.put(marker6, k);

                    break;
                .........
                ...........
                ............
                default :
                    break;
            }

        }catch (Exception e){
            Log.e("addMarkers",k+"");
            e.printStackTrace();
        }

    }
}

/******************FOR MAP******************/
class Frnt_mIcons_Activity extends AsyncTask<String, String, String> {

    public ArrayList<All_products_lat_long> maplist;

    @Override
    protected void onPreExecute() {
        mDialog = new ProgressDialog(Frnt_mapActivity.this);
        mDialog.setMessage("Loading...");
        mDialog.setCancelable(false);
        mDialog.show();
        super.onPreExecute();
    }

    // Slow Implementation
    private String inputStreamToString(InputStream is) {
        String s = "";
        String line = "";
        // Wrap a BufferedReader around the InputStream
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        // Read response until the end
        try {
            while ((line = rd.readLine()) != null) {
                s += line;
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // Return full string
        return s;
    }

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
        maplist = new ArrayList<All_products_lat_long>();

        HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

        DefaultHttpClient client = new DefaultHttpClient();

        SchemeRegistry registry = new SchemeRegistry();
        SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
        socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
        registry.register(new Scheme("http", socketFactory, 443));
        SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
        DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());

  // Set verifier
                HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
        HttpPost httpPost = new HttpPost("http://towncitycards.com/webservice_action.php?action=all_products");

        try{

            HttpResponse response = httpClient.execute(httpPost);
            String data = inputStreamToString(response.getEntity().getContent());
            jsonobject3 = new JSONObject(data);
            jsonarray3 = new JSONArray(jsonobject3.getString("all_products"));
            venueList =new ArrayList<All_products_lat_long>();
            for(int j=0; j<jsonarray3.length();j++){
                JSONObject itemobj = jsonarray3.getJSONObject(j);
                //SHOW SEARCH RESULT
                All_products_lat_long searchItems = new All_products_lat_long();

                searchItems.setId(itemobj.getString("ID"));
                searchItems.setPost_title(itemobj.getString("post_title"));
                searchItems.setMap_icon(itemobj.getString("map_icon"));
                searchItems.setLongitude(itemobj.getString("longitude"));
                searchItems.setLatitude(itemobj.getString("latitude"));
                //          System.out.println("######Ashish is object >>"+itemobj);
                venueList.add(searchItems);
                //      System.out.println("SEARCHLISTSS@@@@@@@"+venueList.get(j).getLongitude());
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void onPostExecute(String result) {
        super.onPostExecute(result);

        //System.out.println("SEARCHLISTSS@@@@@@@"+venueList);
        //System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAA"+venueList);
        try{
            if(venueList.size()>0)
            {
                addMarkers();
//              Toast.makeText(Frnt_mapActivity.this,"Search for the venue11.",Toast.LENGTH_SHORT).show();

            }
            else
                Toast.makeText(Frnt_mapActivity.this,"Search for the venue.",Toast.LENGTH_SHORT).show();
            //LatLng coordinate = new LatLng(22.75852160, 75.8911550);
            LatLng coordinate = new LatLng(50.85514, 0.58382);
            CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 18);
            googlemap.animateCamera(yourLocation);
            for (int i = 0; i < jsonarray3.length(); i++) {

                jsonobject3 = jsonarray3.getJSONObject(i);

                Shop_title = jsonobject3.optString("post_title");
                Shop_address = jsonobject3.optString("map_icon");
                Shop_icons = jsonobject3.optString("map_icon");
                //}
            }

        }catch(Exception e){
            e.printStackTrace();
        }

        if(mDialog!=null && mDialog.isShowing()){
            mDialog.dismiss();
        }
    }
}
</code>```

}

答:
I dont Realy understand Your Question But

u can make

```<code>Map<String, Marker> markerMap;
</code>```

where String is your ID , or int as your want

then

int your AsynTask to get JSON data

```<code> Marker marker = YOURMAP.addMarker(options);
                    marker.setTag(YOUR_ID);
                    //   markers.add(marker);
                    markerMap.put(YOUR_ID, marker);
</code>```

where options is

```<code>MarkerOptions options = new MarkerOptions();
                    options.position(YOUR_JSON_OBJECT.Latitude, YOUR_JSON_OBJECT.Longtite));
                    options.title(YOUR_TITLE);
                     options.visible(true);
                         options.icon(YOUR_IMAGE);
</code>```

hope is`s help

ContentLicense: CC BY-SA 3.0

Body:
This is my web service

where I want to get map_icon, longitude, latitude dynamically from given web service. I am stuck at this point. How can I do this please help me out.
In old code what is done is get longitude, latitude, post_title from web service on the basis of id and then assign image statically.

Frnt_mapActivity.java

public class Frnt_mapActivity extends Activity {

public String Shop_title;
public String Shop_address;
public String Shop_icons;
ProgressDialog mDialog;
JSONObject jsonobject3;
JSONArray jsonarray3;
// Google Map
private static GoogleMap googlemap;
public static ArrayList<SearchBeams> searchdata_list;
public static ArrayList<NormalSearchBeams> normlSearchList;
ArrayList<All_products_lat_long> venueList;

private int i;
private Intent intent;
HashMap<Marker, Integer> hashMap=new HashMap<Marker, Integer>();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.frnt_map_activity);

    googlemap=((MapFragment)getFragmentManager().findFragmentById(R.id.places_map)).getMap();
    googlemap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    googlemap.setMyLocationEnabled(true);
    googlemap.getUiSettings().setZoomControlsEnabled(true);
    googlemap.getUiSettings().setMyLocationButtonEnabled(true);
    googlemap.getUiSettings().setCompassEnabled(true);
    googlemap.getUiSettings().setRotateGesturesEnabled(true);
    googlemap.getUiSettings().setZoomGesturesEnabled(true);
    googlemap.setMyLocationEnabled(true);
    intent=new Intent(Frnt_mapActivity.this,MainActivity.class);
    googlemap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {

        @Override
        public void onInfoWindowClick(Marker arg0) {
            i=hashMap.get(arg0);
            intent.putExtra("PRODUCT_ID", venueList.get(i).getId());
            startActivity(intent);
            //overridePendingTransition( R.anim.slide_right, R.anim.slide_left );
        }
    });

    new Frnt_mIcons_Activity().execute();

}

class AddMarkerAsyncTask extends AsyncTask<String,String,String>{

    private All_products_lat_long venue;
    private int k;
    BitmapDescriptor bd=null;

    AddMarkerAsyncTask(All_products_lat_long venue,int k){
        this.venue=venue;
        this.k=k;
    }

    @Override
    protected String doInBackground(String... strings) {
        try{
            bd=BitmapDescriptorFactory.fromBitmap(Glide.
                    with(Frnt_mapActivity.this).
                    load(venue.getMap_icon()).
                    asBitmap().
                    into(100, 100). // Width and height
                    get());
        }catch (Exception e){
            bd=null;
            e.printStackTrace();

        }

        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        try{
            if(bd!=null){
                Marker marker=googlemap.addMarker(new MarkerOptions()
                        .position(new LatLng(Double.parseDouble(venue.getLatitude()), Double.parseDouble(venue.getLongitude())))
                        .title(venue.getPost_title())
                        .icon(bd));
                hashMap.put(marker, k);
            }

        }catch (Exception e){
            e.printStackTrace();
        }

    }
}

private void addMarkers() {

    for(int k=0; k<venueList.size(); k += 1){

        //nirmal
        try{
            Log.e("nirmal",venueList.get(k).getMap_icon());

            //new AddMarkerAsyncTask(venueList.get(k),k).execute();

            double ln = Double.parseDouble(venueList.get(k).getLongitude());
            double la = Double.parseDouble(venueList.get(k).getLatitude());
                /*String title=venueList.get(k).getPost_title()==null?"":venueList.get(k).getPost_title();
                URL url = new URL(venueList.get(k).getMap_icon());
                Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
                BitmapDescriptor bd=BitmapDescriptorFactory.fromBitmap(image);*/

                /*Marker marker=googlemap.addMarker(new MarkerOptions()
                        .position(new LatLng(la, ln))
                        .title(title)
                        .icon(bd));
                hashMap.put(marker, k);*/

            switch (Integer.parseInt(venueList.get(k).getId()))
            {
                case 5689 :
                    Marker marker=googlemap.addMarker(new MarkerOptions()
                            .position(new LatLng(la, ln))
                            .title(venueList.get(k).getPost_title())
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.fruitandveg)));
                    hashMap.put(marker, k);
                    break;
                case 5779 :
                    Marker marker1=googlemap.addMarker(new MarkerOptions()
                            .position(new LatLng(la, ln))
                            .title(venueList.get(k).getPost_title())
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.coffee)));
                    hashMap.put(marker1, k);
                    break;
                case 5798 :
                    Marker marker3 = googlemap.addMarker(new MarkerOptions()
                            .position(new LatLng(la, ln))
                            .title(venueList.get(k).getPost_title())
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.takeaway)));
                    hashMap.put(marker3, k);
                    break;
                case 5810 :
                    Marker marker4 = googlemap.addMarker(new MarkerOptions()
                            .position(new LatLng(la, ln))
                            .title(venueList.get(k).getPost_title())
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.restaurant_steakhouse)));
                    hashMap.put(marker4, k);
                    break;
                case 6005 :
                    Marker marker5 = googlemap.addMarker(new MarkerOptions()
                            .position(new LatLng(la, ln))
                            .title(venueList.get(k).getPost_title())
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.clambers_playcentre)));
                    hashMap.put(marker5, k);
                    break;
                case 6011 :
                    Marker marker6 = googlemap.addMarker(new MarkerOptions()
                            .position(new LatLng(la, ln))
                            .title(venueList.get(k).getPost_title())
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.thetruecrimemuseum)));
                    hashMap.put(marker6, k);

                    break;
                .........
                ...........
                ............
                default :
                    break;
            }

        }catch (Exception e){
            Log.e("addMarkers",k+"");
            e.printStackTrace();
        }

    }
}

/******************FOR MAP******************/
class Frnt_mIcons_Activity extends AsyncTask<String, String, String> {

    public ArrayList<All_products_lat_long> maplist;

    @Override
    protected void onPreExecute() {
        mDialog = new ProgressDialog(Frnt_mapActivity.this);
        mDialog.setMessage("Loading...");
        mDialog.setCancelable(false);
        mDialog.show();
        super.onPreExecute();
    }

    // Slow Implementation
    private String inputStreamToString(InputStream is) {
        String s = "";
        String line = "";
        // Wrap a BufferedReader around the InputStream
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        // Read response until the end
        try {
            while ((line = rd.readLine()) != null) {
                s += line;
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // Return full string
        return s;
    }

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
        maplist = new ArrayList<All_products_lat_long>();

        HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

        DefaultHttpClient client = new DefaultHttpClient();

        SchemeRegistry registry = new SchemeRegistry();
        SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
        socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
        registry.register(new Scheme("http", socketFactory, 443));
        SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
        DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());

  // Set verifier
                HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
        HttpPost httpPost = new HttpPost("http://towncitycards.com/webservice_action.php?action=all_products");

        try{

            HttpResponse response = httpClient.execute(httpPost);
            String data = inputStreamToString(response.getEntity().getContent());
            jsonobject3 = new JSONObject(data);
            jsonarray3 = new JSONArray(jsonobject3.getString("all_products"));
            venueList =new ArrayList<All_products_lat_long>();
            for(int j=0; j<jsonarray3.length();j++){
                JSONObject itemobj = jsonarray3.getJSONObject(j);
                //SHOW SEARCH RESULT
                All_products_lat_long searchItems = new All_products_lat_long();

                searchItems.setId(itemobj.getString("ID"));
                searchItems.setPost_title(itemobj.getString("post_title"));
                searchItems.setMap_icon(itemobj.getString("map_icon"));
                searchItems.setLongitude(itemobj.getString("longitude"));
                searchItems.setLatitude(itemobj.getString("latitude"));
                //          System.out.println("######Ashish is object >>"+itemobj);
                venueList.add(searchItems);
                //      System.out.println("SEARCHLISTSS@@@@@@@"+venueList.get(j).getLongitude());
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void onPostExecute(String result) {
        super.onPostExecute(result);

        //System.out.println("SEARCHLISTSS@@@@@@@"+venueList);
        //System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAA"+venueList);
        try{
            if(venueList.size()>0)
            {
                addMarkers();
//              Toast.makeText(Frnt_mapActivity.this,"Search for the venue11.",Toast.LENGTH_SHORT).show();

            }
            else
                Toast.makeText(Frnt_mapActivity.this,"Search for the venue.",Toast.LENGTH_SHORT).show();
            //LatLng coordinate = new LatLng(22.75852160, 75.8911550);
            LatLng coordinate = new LatLng(50.85514, 0.58382);
            CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 18);
            googlemap.animateCamera(yourLocation);
            for (int i = 0; i < jsonarray3.length(); i++) {

                jsonobject3 = jsonarray3.getJSONObject(i);

                Shop_title = jsonobject3.optString("post_title");
                Shop_address = jsonobject3.optString("map_icon");
                Shop_icons = jsonobject3.optString("map_icon");
                //}
            }

        }catch(Exception e){
            e.printStackTrace();
        }

        if(mDialog!=null && mDialog.isShowing()){
            mDialog.dismiss();
        }
    }
}

}

Body:
I dont Realy understand Your Question But

u can make

Map<String, Marker> markerMap;

where String is your ID , or int as your want

then

int your AsynTask to get JSON data

 Marker marker = YOURMAP.addMarker(options);
                    marker.setTag(YOUR_ID);
                    //   markers.add(marker);
                    markerMap.put(YOUR_ID, marker);

where options is

MarkerOptions options = new MarkerOptions();
                    options.position(YOUR_JSON_OBJECT.Latitude, YOUR_JSON_OBJECT.Longtite));
                    options.title(YOUR_TITLE);
                     options.visible(true);
                         options.icon(YOUR_IMAGE);

hope is`s help


问:
ASP.NET - Authentication against Active Directory fails because of NativeObject binding
I am working on an academic project, and we have to authenticate against Active Directory Domain Services accounts from a web application.
I have followed this msdn tutorial, and as specified I changed the ldap path in the Login_Click() function.
Everything went fine, but when I tried to login in the web app, I got this:

Error authenticating. Error authenticating user. Logon Failure:
  unknown user name or bad password ... at
  System.DirectoryServices.DirectoryEntry.get_NativeObject()...

Here is the error screenshot:
Web app's error screen

For information, I filled the adPath like this (in the Login_Click() method):

```<code>string adPath = "LDAP://DC.datacenter.mex.am.company.net/"
</code>```

And we also tried with this :

```<code>string adPath = "LDAP://DC.datacenter.mex.am.company.net/DC=datacenter,DC=mex,DC=am,DC=company,DC=net/"
</code>```

The credentials we tried to login with are perfectly valids, because we tested them to access to Active Directory accounts ... But the same credentials don't work from the asp .net web app !!!

I searched everywhere on the net, but came with nothing ...

Has anyone got an idea about that ??

答:
You can do authentication via PrincipalContext</p>

```<code>using (var context = new PrincipalContext(ContextType.Domain,
                    yourdomain,
                    UsernameforAD,
                    ADUserPassword)
                {
                    bool isAuthenticated= context.ValidateCredentials(username,password);
                }
</code>```

Body:
I am working on an academic project, and we have to authenticate against Active Directory Domain Services accounts from a web application.
I have followed this msdn tutorial, and as specified I changed the ldap path in the Login_Click() function.
Everything went fine, but when I tried to login in the web app, I got this:

Error authenticating. Error authenticating user. Logon Failure:
  unknown user name or bad password ... at
  System.DirectoryServices.DirectoryEntry.get_NativeObject()...

Here is the error screenshot:
Web app's error screen

For information, I filled the adPath like this (in the Login_Click() method):

string adPath = "LDAP://DC.datacenter.mex.am.company.net/"

And we also tried with this :

string adPath = "LDAP://DC.datacenter.mex.am.company.net/DC=datacenter,DC=mex,DC=am,DC=company,DC=net/"

The credentials we tried to login with are perfectly valids, because we tested them to access to Active Directory accounts ... But the same credentials don't work from the asp .net web app !!!

I searched everywhere on the net, but came with nothing ...

Has anyone got an idea about that ??

Body:
You can do authentication via PrincipalContext

using (var context = new PrincipalContext(ContextType.Domain,
                    yourdomain,
                    UsernameforAD,
                    ADUserPassword)
                {
                    bool isAuthenticated= context.ValidateCredentials(username,password);
                }


问:
I want to make the button text unchanged once it has been changed on a click
I was working on my project in which i have grid view of which there is a status field which has button in it .
When user clicks on that button the text of that button gets changed from pending to confirm .
The problem is that when I close the browser and load the .aspx page again through visual studio the text of the button again gets set to pending which i does not want.
Can any one tell me how to keep the button text to confirm only once the button get clicked and also when I click on first row status field button all the rest  status field gets updated with confirm status in database.
Here is my code: (Front End Code)

```<code><asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand"
    Font-Bold="True" Font-Size="Small" GridLines="None">
    <Columns>
        <asp:BoundField ItemStyle-Width="150px" DataField="packagename" HeaderText="Package" />
        <asp:BoundField ItemStyle-Width="150px" DataField="name" HeaderText="Name" />
        <asp:BoundField ItemStyle-Width="150px" DataField="gender" HeaderText="Gender" />
        <asp:BoundField ItemStyle-Width="150px" DataField="mobileno" HeaderText="Mobile No" />
        <asp:BoundField ItemStyle-Width="150px" DataField="email" HeaderText="Email" />
        <asp:BoundField ItemStyle-Width="150px" DataField="noofdays" HeaderText="No. of Days" />
        <asp:BoundField ItemStyle-Width="150px" DataField="child" HeaderText="No. of Children" />
        <asp:BoundField ItemStyle-Width="150px" DataField="adults" HeaderText="No of Adults" />
        <asp:TemplateField HeaderText="Status Field">
            <ItemTemplate>
                <asp:Button ID="Button1" runat="server" CausesValidation="false" CommandName="MYCOMMAND"
                    Text="Pending" BorderStyle="None" Font-Bold="True" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
</code>```

(Back end Code):

```<code> protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        List<string> lst = new List<string>() { "asd", "xxx" };
        GridView1.DataSource = lst;
        this.BindGrid();
    }

}
protected void btnpreviewwebsite_Click1(object sender, EventArgs e)
{
    Response.Redirect("~/index.aspx");
}
protected void btnlogout_Click(object sender, EventArgs e)
{
    Session.Abandon();
    Session.Clear();
    Response.Redirect("~/Admin Panel/LoginForm.aspx");

}
private void BindGrid()
{

    using (SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\PROJECT SEM6\Online Tours and Travels\App_Data\ToursandTravels.mdf;Integrated Security=True;User Instance=True"))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT packagename,name, gender,mobileno,email,noofdays,child,adults FROM enquiry"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                }
            }
        }
    }
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{

    if (e.CommandName == "MYCOMMAND")
    {
        SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\PROJECT SEM6\Online Tours and Travels\App_Data\ToursandTravels.mdf;Integrated Security=True;User Instance=True");
        string sql;
        Button Button1 = (Button)e.CommandSource;
        if (Button1 != null)
            Button1.Text = "Confirm";
        sql = "update enquiry set statusfield='" + Button1.Text + "'";

        SqlCommand comm = new SqlCommand(sql, con);

        con.Open();
        comm.ExecuteNonQuery();

    }
}
</code>```

答:
You can use the Bind function from asp.net so your button text will be taken from DB result. like below.

In aspx page

```<code>    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand"
    Font-Bold="True" Font-Size="Small" GridLines="None">
    <Columns>
        <asp:BoundField ItemStyle-Width="150px" DataField="enquiryid" HeaderText="Enquiryid" />
        <asp:BoundField ItemStyle-Width="150px" DataField="packagename" HeaderText="Package" />
        <asp:BoundField ItemStyle-Width="150px" DataField="name" HeaderText="Name" />
        <asp:BoundField ItemStyle-Width="150px" DataField="gender" HeaderText="Gender" />
        <asp:BoundField ItemStyle-Width="150px" DataField="mobileno" HeaderText="Mobile No" />
        <asp:BoundField ItemStyle-Width="150px" DataField="email" HeaderText="Email" />
        <asp:BoundField ItemStyle-Width="150px" DataField="noofdays" HeaderText="No. of Days" />
        <asp:BoundField ItemStyle-Width="150px" DataField="child" HeaderText="No. of Children" />
        <asp:BoundField ItemStyle-Width="150px" DataField="adults" HeaderText="No of Adults" />
        <asp:TemplateField HeaderText="Status Field">
            <ItemTemplate>
                <asp:Button ID="Button1" runat="server" CausesValidation="false" CommandName="MYCOMMAND"
                    Text='<%# Bind("statusfield")%>' BorderStyle="None" Font-Bold="True" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
</code>```

In .cs file modify your BindGrid method, so that it can return the statusfield column.

```<code> private void BindGrid()
{

   using (SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\PROJECT SEM6\Online Tours and Travels\App_Data\ToursandTravels.mdf;Integrated Security=True;User Instance=True"))
    {

    using (SqlCommand cmd = new SqlCommand("SELECT enquiryid,packagename,name, gender,mobileno,email,noofdays,child,adults,statusfield FROM enquiry"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                }
            }
        }
    }
}
</code>```

Body:
I was working on my project in which i have grid view of which there is a status field which has button in it .
When user clicks on that button the text of that button gets changed from pending to confirm .
The problem is that when I close the browser and load the .aspx page again through visual studio the text of the button again gets set to pending which i does not want.
Can any one tell me how to keep the button text to confirm only once the button get clicked and also when I click on first row status field button all the rest  status field gets updated with confirm status in database.
Here is my code: (Front End Code)

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand"
    Font-Bold="True" Font-Size="Small" GridLines="None">
    <Columns>
        <asp:BoundField ItemStyle-Width="150px" DataField="packagename" HeaderText="Package" />
        <asp:BoundField ItemStyle-Width="150px" DataField="name" HeaderText="Name" />
        <asp:BoundField ItemStyle-Width="150px" DataField="gender" HeaderText="Gender" />
        <asp:BoundField ItemStyle-Width="150px" DataField="mobileno" HeaderText="Mobile No" />
        <asp:BoundField ItemStyle-Width="150px" DataField="email" HeaderText="Email" />
        <asp:BoundField ItemStyle-Width="150px" DataField="noofdays" HeaderText="No. of Days" />
        <asp:BoundField ItemStyle-Width="150px" DataField="child" HeaderText="No. of Children" />
        <asp:BoundField ItemStyle-Width="150px" DataField="adults" HeaderText="No of Adults" />
        <asp:TemplateField HeaderText="Status Field">
            <ItemTemplate>
                <asp:Button ID="Button1" runat="server" CausesValidation="false" CommandName="MYCOMMAND"
                    Text="Pending" BorderStyle="None" Font-Bold="True" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

(Back end Code):

 protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        List<string> lst = new List<string>() { "asd", "xxx" };
        GridView1.DataSource = lst;
        this.BindGrid();
    }

}
protected void btnpreviewwebsite_Click1(object sender, EventArgs e)
{
    Response.Redirect("~/index.aspx");
}
protected void btnlogout_Click(object sender, EventArgs e)
{
    Session.Abandon();
    Session.Clear();
    Response.Redirect("~/Admin Panel/LoginForm.aspx");

}
private void BindGrid()
{

    using (SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\PROJECT SEM6\Online Tours and Travels\App_Data\ToursandTravels.mdf;Integrated Security=True;User Instance=True"))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT packagename,name, gender,mobileno,email,noofdays,child,adults FROM enquiry"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                }
            }
        }
    }
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{

    if (e.CommandName == "MYCOMMAND")
    {
        SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\PROJECT SEM6\Online Tours and Travels\App_Data\ToursandTravels.mdf;Integrated Security=True;User Instance=True");
        string sql;
        Button Button1 = (Button)e.CommandSource;
        if (Button1 != null)
            Button1.Text = "Confirm";
        sql = "update enquiry set statusfield='" + Button1.Text + "'";

        SqlCommand comm = new SqlCommand(sql, con);

        con.Open();
        comm.ExecuteNonQuery();

    }
}

Body:
You can use the Bind function from asp.net so your button text will be taken from DB result. like below.

In aspx page

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand"
    Font-Bold="True" Font-Size="Small" GridLines="None">
    <Columns>
        <asp:BoundField ItemStyle-Width="150px" DataField="enquiryid" HeaderText="Enquiryid" />
        <asp:BoundField ItemStyle-Width="150px" DataField="packagename" HeaderText="Package" />
        <asp:BoundField ItemStyle-Width="150px" DataField="name" HeaderText="Name" />
        <asp:BoundField ItemStyle-Width="150px" DataField="gender" HeaderText="Gender" />
        <asp:BoundField ItemStyle-Width="150px" DataField="mobileno" HeaderText="Mobile No" />
        <asp:BoundField ItemStyle-Width="150px" DataField="email" HeaderText="Email" />
        <asp:BoundField ItemStyle-Width="150px" DataField="noofdays" HeaderText="No. of Days" />
        <asp:BoundField ItemStyle-Width="150px" DataField="child" HeaderText="No. of Children" />
        <asp:BoundField ItemStyle-Width="150px" DataField="adults" HeaderText="No of Adults" />
        <asp:TemplateField HeaderText="Status Field">
            <ItemTemplate>
                <asp:Button ID="Button1" runat="server" CausesValidation="false" CommandName="MYCOMMAND"
                    Text='<%# Bind("statusfield")%>' BorderStyle="None" Font-Bold="True" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

In .cs file modify your BindGrid method, so that it can return the statusfield column.

 private void BindGrid()
{

   using (SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\PROJECT SEM6\Online Tours and Travels\App_Data\ToursandTravels.mdf;Integrated Security=True;User Instance=True"))
    {

    using (SqlCommand cmd = new SqlCommand("SELECT enquiryid,packagename,name, gender,mobileno,email,noofdays,child,adults,statusfield FROM enquiry"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                }
            }
        }
    }
}


问:
<h> tag different color in different page
I'm trying to make that a h1 tag as two colors, for example in the "main page" the h1 is red, and in the "secondary page" the h1 is blue.

I'm trying to achieve this without success, I been doing this with a span but I would like to know if there is another way to do this.

this is my code structure

```<code>h1, h2, h3, h4, h5, p, li, ul, ol, a, a:hover, button { color: red; }

h1 .h1cor{
   color: blue;
}
</code>```

答:
You can do this with an ID like this:

#secundarypage h1{
color:red;
}

#mainpage h1{
color:blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="mainpage">
  <h1>Heading for mainpage</h1>
</div>

<div id="secundarypage">
  <h1>Heading for secundary page</h1>
</div></code>```

Body:
I'm trying to make that a h1 tag as two colors, for example in the "main page" the h1 is red, and in the "secondary page" the h1 is blue.

I'm trying to achieve this without success, I been doing this with a span but I would like to know if there is another way to do this.

this is my code structure

h1, h2, h3, h4, h5, p, li, ul, ol, a, a:hover, button { color: red; }

h1 .h1cor{
   color: blue;
}

Body:
You can do this with an ID like this:

#secundarypage h1{
color:red;
}

#mainpage h1{
color:blue;
}

<div id="mainpage">
  <h1>Heading for mainpage</h1>
</div>

<div id="secundarypage">
  <h1>Heading for secundary page</h1>
</div>


问:
Array.filter first of value
I have a json array based on this structure:

```<code>[
    {property1: "bmw", property2: value, property3: value, property4: value},
    {property1: "mercedes", property2: value, property3: value, property4: value},
    {property1: "bmw", property2: value, property3: value, property4: value},
    {property1: "nissan", property2: value, property3: value, property4: value}
]
</code>```

How can i filter the array to find the first time a new value appears for property1 and store it in a separate array?

I would like the array like: ["bmw", "mercedes", "nissan"]

答:
Given the structure of the original data, I'd reduce the array into a Map using the property as key

var cars= [
    {property1: "bmw", property2: "d", property3: "", property4: "value"},
    {property1: "mercedes", property2: "value", property3: "value", property4: "value"},
    {property1: "bmw", property2: "value", property3: "value", property4: "value"},
    {property1: "nissan", property2: "value", property3: "value", property4: "value"}
];

var m = cars.reduce((map, entry) => {
 if (!map.has(entry.property1)) {
  map.set(entry.property1, entry)
 }
 return map
}, new Map())

console.log([...m.values()]);
console.log([...m.keys()]);```

you can then extract the entries with .values() to get the full objects or .keys() to get only the unique brand names

Title: Array.filter first of value

Body:
I have a json array based on this structure:

[
    {property1: "bmw", property2: value, property3: value, property4: value},
    {property1: "mercedes", property2: value, property3: value, property4: value},
    {property1: "bmw", property2: value, property3: value, property4: value},
    {property1: "nissan", property2: value, property3: value, property4: value}
]

How can i filter the array to find the first time a new value appears for property1 and store it in a separate array?

I would like the array like: ["bmw", "mercedes", "nissan"]

Body:
Given the structure of the original data, I'd reduce the array into a Map using the property as key

var cars= [
    {property1: "bmw", property2: "d", property3: "", property4: "value"},
    {property1: "mercedes", property2: "value", property3: "value", property4: "value"},
    {property1: "bmw", property2: "value", property3: "value", property4: "value"},
    {property1: "nissan", property2: "value", property3: "value", property4: "value"}
];

var m = cars.reduce((map, entry) => {
 if (!map.has(entry.property1)) {
  map.set(entry.property1, entry)
 }
 return map
}, new Map())

console.log([...m.values()]);
console.log([...m.keys()]);

you can then extract the entries with .values() to get the full objects or .keys() to get only the unique brand names


问:
select where field equals one of multiple values
I want rows but in WHERE I have different values. How can I get these rows? Let's say I want to check names of people with different cnic values?

```<code>select name from table where cnic='123','234','134';
</code>```

It gives me an error. How can I do this?

答:
use mysql In operator for checkinng multiple values.</p>

```<code>select name from table `where cnic IN ('123','234','134');
</code>```

Body:
I want rows but in WHERE I have different values. How can I get these rows? Let's say I want to check names of people with different cnic values?

select name from table where cnic='123','234','134';

It gives me an error. How can I do this?

Body:
use mysql In operator for checkinng multiple values.

select name from table `where cnic IN ('123','234','134');


问:
Laravel Ajax cannot update database when click on a link
I have an audio file on public folder like this-

```<code>@foreach ($songs as $song)
     <a href="{{asset('/audio/' . $song->song)}}" download="" >
        <button type="button" class="download" style="margin-bottom: 15px;">
           <i class="glyphicon glyphicon-download">Download</i>
        </button>
     </a>
 @endforeach
</code>```

So, when i click that button it downloads the song. In my database, in "song" table there is column for song and another one for download_count which is set to default(0). I try to update download_count when i click on the link by ajax. My ajax:

```<code>$(function() {
  $('.download').click(function(){
 $.ajax({
   url: "/update_download_count",
   type:"POST",
   data: {
     song_id:$(this).attr('data-id')
   }
  });
});
    });
</code>```

My Route:

```<code>Route::post('/update_download_count', 'PagesController@updateDownloadCount');
</code>```

Controller:

```<code>public function updateDownloadCount(){
         $song_id = $_POST['song_id'];
         $song->download += 1;
         $song->save();
}
</code>```

But, i cannot update my database however i click on the link. it still set to 0 in download_count column. Plz help, what's the wrong?

答:
You don't actually select the song. </p>

```<code>public function updateDownloadCount(Request $request) {
    $song = Song::find($request->input("song_id"));
    $song->download += 1;
    $song->save();
}
</code>```

Body:
I have an audio file on public folder like this-

@foreach ($songs as $song)
     song)}}" download="" >
        <button type="button" class="download" style="margin-bottom: 15px;">
           Download
        </button>

 @endforeach

So, when i click that button it downloads the song. In my database, in "song" table there is column for song and another one for download_count which is set to default(0). I try to update download_count when i click on the link by ajax. My ajax:

$(function() {
  $('.download').click(function(){
 $.ajax({
   url: "/update_download_count",
   type:"POST",
   data: {
     song_id:$(this).attr('data-id')
   }
  });
});
    });

My Route:

Route::post('/update_download_count', 'PagesController@updateDownloadCount');

Controller:

public function updateDownloadCount(){
         $song_id = $_POST['song_id'];
         $song->download += 1;
         $song->save();
}

But, i cannot update my database however i click on the link. it still set to 0 in download_count column. Plz help, what's the wrong?

Body:
You don't actually select the song.

public function updateDownloadCount(Request $request) {
    $song = Song::find($request->input("song_id"));
    $song->download += 1;
    $song->save();
}


问:
C- gethostbyaddr & Valgrind
For some reason valgrind keeps throwing the following error:

```<code>==6263== Invalid read of size 4
==6263==    at 0x40151B9: (within /lib/ld-2.7.so)
==6263==    by 0x4005C29: (within /lib/ld-2.7.so)
==6263==    by 0x4007A47: (within /lib/ld-2.7.so)
==6263==    by 0x40114F3: (within /lib/ld-2.7.so)
==6263==    by 0x400D585: (within /lib/ld-2.7.so)
==6263==    by 0x4010F0D: (within /lib/ld-2.7.so)
==6263==    by 0x4141391: (within /lib/tls/i686/cmov/libc-2.7.so)
==6263==    by 0x400D585: (within /lib/ld-2.7.so)
==6263==    by 0x4141554: __libc_dlopen_mode (in /lib/tls/i686/cmov/libc-2.7.so)
==6263==    by 0x411B286: __nss_lookup_function (in /lib/tls/i686/cmov/libc-2.7.so)
==6263==    by 0x411B39F: (within /lib/tls/i686/cmov/libc-2.7.so)
==6263==    by 0x411CFC5: __nss_hosts_lookup (in /lib/tls/i686/cmov/libc-2.7.so)
==6263==  Address 0x4183d24 is 36 bytes inside a block of size 37 alloc'd
==6263==    at 0x4022AB8: malloc (vg_replace_malloc.c:207)
</code>```

Here is the way I'm doing it. Any reasons why this is happening? Thanks

```<code>#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>

char *IPtoHostname(const char *ipaddress)
{
    struct hostent *host;
    unsigned int ip = 0;
    ip = inet_addr (ipaddress);
    host = gethostbyaddr ((char *) &ip, sizeof (unsigned int), AF_INET);
    if (host == NULL) return NULL;
    return strdup(host->h_name);
}

int main () {
   const char *ip = "65.55.4.170";
   char *a =  NULL;
   a = IPtoHostname(ip);
   printf ("%s\n", a);
   free (a);

   return 0;
}
</code>```

Update: It happens when I run it under Linux hardy 2.6.24-16-generic It does not happen under Ubuntu 9.10

答:
You aren't checking the return value of gethostbyaddr.

What if it returns NULL indicating that it was unable to get the host name?

In that case, you try to de-reference NULL to call strdup on the host->h_name.

That will obviously fail.

ContentLicense: CC BY-SA 2.5

Title: C- gethostbyaddr & Valgrind

Body:
For some reason valgrind keeps throwing the following error:

==6263== Invalid read of size 4
==6263==    at 0x40151B9: (within /lib/ld-2.7.so)
==6263==    by 0x4005C29: (within /lib/ld-2.7.so)
==6263==    by 0x4007A47: (within /lib/ld-2.7.so)
==6263==    by 0x40114F3: (within /lib/ld-2.7.so)
==6263==    by 0x400D585: (within /lib/ld-2.7.so)
==6263==    by 0x4010F0D: (within /lib/ld-2.7.so)
==6263==    by 0x4141391: (within /lib/tls/i686/cmov/libc-2.7.so)
==6263==    by 0x400D585: (within /lib/ld-2.7.so)
==6263==    by 0x4141554: __libc_dlopen_mode (in /lib/tls/i686/cmov/libc-2.7.so)
==6263==    by 0x411B286: __nss_lookup_function (in /lib/tls/i686/cmov/libc-2.7.so)
==6263==    by 0x411B39F: (within /lib/tls/i686/cmov/libc-2.7.so)
==6263==    by 0x411CFC5: __nss_hosts_lookup (in /lib/tls/i686/cmov/libc-2.7.so)
==6263==  Address 0x4183d24 is 36 bytes inside a block of size 37 alloc'd
==6263==    at 0x4022AB8: malloc (vg_replace_malloc.c:207)

Here is the way I'm doing it. Any reasons why this is happening? Thanks

#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>

char *IPtoHostname(const char *ipaddress)
{
    struct hostent *host;
    unsigned int ip = 0;
    ip = inet_addr (ipaddress);
    host = gethostbyaddr ((char *) &ip, sizeof (unsigned int), AF_INET);
    if (host == NULL) return NULL;
    return strdup(host->h_name);
}

int main () {
   const char *ip = "65.55.4.170";
   char *a =  NULL;
   a = IPtoHostname(ip);
   printf ("%s\n", a);
   free (a);

   return 0;
}

Update: It happens when I run it under Linux hardy 2.6.24-16-generic It does not happen under Ubuntu 9.10


答:
Please use the In operator for this
  select name from table where cnic in ('123','234','134')

Title: select where field equals one of multiple values


问:
How to refresh an ng-repeat list when $scope is not used?
$scope.$apply() is mostly used when $scope is defined.
But this kind of definition does not seem to refresh the list.

HTML :

```<code><div ng-repeat="feed in feedCtrl.feeds"></div>
</code>```

Controller :

```<code>this.feeds = response.data;
</code>```

答:
Just reassign the this.feeds with new data and it will be refreshed.

Also you can call $scope.$apply() by injecting scope into controller, so that the whole digest cycle will be ran again and update the variables

In my opinion, the issue you are facing is using this.feeds inside a function which will not work, because this refers to the function but not original value.

So, assign this to a variable vm

var vm = this; and use vm.feeds = response.data

<!DOCTYPE html>

 {{data}}

```

The Code above changes the Feed after 2 seconds. Please run the above code

Here is a working DEMO

Body:
$scope.$apply() is mostly used when $scope is defined.
But this kind of definition does not seem to refresh the list.

HTML :

Controller :

this.feeds = response.data;

Body:
Just reassign the this.feeds with new data and it will be refreshed.

Also you can call $scope.$apply() by injecting scope into controller, so that the whole digest cycle will be ran again and update the variables

In my opinion, the issue you are facing is using this.feeds inside a function which will not work, because this refers to the function but not original value.

So, assign this to a variable vm

var vm = this; and use vm.feeds = response.data

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

<head>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"></script>

 <script type="text/javascript">
  var myApp = angular.module('myApp',[])
  .controller('MyCtrl', function MyCtrl($timeout,$scope) {

   var vm = this;
   vm.feeds = ["Feed1","Feed2","Feed3","Feed4"];

            $timeout(function () {
          vm.feeds = ["Changed Feed1","Changed Feed2","Changed Feed3","Changed Feed4"];
      }, 2000);

  })
 </script>
</head>
<body ng-controller="MyCtrl as feedCtrl">
<p ng-repeat="data in feedCtrl.feeds">
 {{data}}
</p>

</body>

</html>

The Code above changes the Feed after 2 seconds. Please run the above code

Here is a working DEMO


问:
Parameterize DocumentDB query with IN clause
I have a query somewhat like the following which I'm trying to parameterize:

```<code>List<string> poiIDs = /*List of poi ids*/;
List<string> parameterNames = /*List of parameter names*/;

string inClause = string.Join(",", parameterNames);

string query = string.Format("SELECT c.id AS poiID, c.poiName, c.latitude, c.longitude FROM c WHERE c.clusterName = @clusterName AND c.id IN ({0}) AND c.deleted = false", inClause);

IQueryable<POI> queryResult = Client.CreateDocumentQuery<POI>(Collection.SelfLink, new SqlQuerySpec
            {
                QueryText = query,
                Parameters = new SqlParameterCollection()
                {
                    new SqlParameter("@clusterName", "POI"),
                    // How do I declare the dynamically generated parameters here
                    // as new SqlParameter()?
                }
             });
</code>```

How do I declare the dynamically generated parameters as new SqlParameter() for the Parameters property of SqlQuerySpec in order to create my document query?

答:
The following gives you a SQL query, you can then run in your DocumentDB Collection, to get the Documents by their IDs. </p>

```<code>var query = $"SELECT * FROM p WHERE p.id IN ('{string.Join("', '", arrayOfIds)}')";
</code>```

Body:
I have a query somewhat like the following which I'm trying to parameterize:

List<string> poiIDs = /*List of poi ids*/;
List<string> parameterNames = /*List of parameter names*/;

string inClause = string.Join(",", parameterNames);

string query = string.Format("SELECT c.id AS poiID, c.poiName, c.latitude, c.longitude FROM c WHERE c.clusterName = @clusterName AND c.id IN ({0}) AND c.deleted = false", inClause);

IQueryable<POI> queryResult = Client.CreateDocumentQuery<POI>(Collection.SelfLink, new SqlQuerySpec
            {
                QueryText = query,
                Parameters = new SqlParameterCollection()
                {
                    new SqlParameter("@clusterName", "POI"),
                    // How do I declare the dynamically generated parameters here
                    // as new SqlParameter()?
                }
             });

How do I declare the dynamically generated parameters as new SqlParameter() for the Parameters property of SqlQuerySpec in order to create my document query?

Body:
The following gives you a SQL query, you can then run in your DocumentDB Collection, to get the Documents by their IDs.

var query = $"SELECT * FROM p WHERE p.id IN ('{string.Join("', '", arrayOfIds)}')";


问:
MySQL regex escape $
I have written an analysis on logfiles from a Microsoft IIS Server.
The complete log is pushed to a mysql datbase. The fields of my table are exact the same as in the log.

```<code>CREATE TABLE `iis_logging` (
    `ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
    `DATE_TIME` DATETIME NULL DEFAULT NULL,
    `LOG_DATE` DATE NULL DEFAULT NULL,
    `LOG_TIME` TIME NULL DEFAULT NULL,
    `S_SITENAME` VARCHAR(255) NULL DEFAULT NULL,
    `S_COMPUTERNAME` VARCHAR(255) NULL DEFAULT NULL,
    `S_IP` VARCHAR(255) NULL DEFAULT NULL,
    `CS_METHOD` VARCHAR(255) NULL DEFAULT NULL,
    `CS_URI_STEM` TEXT NULL,
    `CS_URI_QUERY` TEXT NULL,
    `S_PORT` INT(11) UNSIGNED NULL DEFAULT NULL,
    `CS_USERNAME` VARCHAR(255) NULL DEFAULT NULL,
    `C_IP` VARCHAR(255) NULL DEFAULT NULL,
    `CS_VERSION` VARCHAR(255) NULL DEFAULT NULL,
    `CS_USER_AGENT` TEXT NULL,
    `CS_COOKIE` TEXT NULL,
    `CS_REFERER` TEXT NULL,
    `CS_HOST` TEXT NULL,
    `SC_STATUS` VARCHAR(255) NULL DEFAULT NULL,
    `SC_SUBSTATUS` VARCHAR(255) NULL DEFAULT NULL,
    `SC_WIN32_STATUS` VARCHAR(255) NULL DEFAULT NULL,
    `SC_BYTES` INT(10) UNSIGNED NULL DEFAULT NULL,
    `CS_BYTES` INT(10) UNSIGNED NULL DEFAULT NULL,
    `TIME_TAKEN` INT(11) UNSIGNED NULL DEFAULT NULL,
    PRIMARY KEY (`ID`),
    INDEX `date_key` (`LOG_DATE`),
    INDEX `DATE_URL` (`LOG_DATE`, `CS_URI_STEM`(30)),
    INDEX `URL` (`CS_URI_STEM`(100))
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=82749372
;
</code>```

Now I have written a query to get only some parts of this log:

```<code>select concat(LOG_DATE,' ', LOG_TIME) as VISIT_TS, CS_METHOD, CS_URI_STEM, CS_URI_QUERY, CS_REFERER, CS_USERNAME
from iis_logging
where CS_USERNAME NOT REGEXP '-' and CS_USERNAME NOT REGEXP '_'
order by LOG_DATE DESC , LOG_TIME DESC, CS_USERNAME DESC
limit 500
</code>```

Inside the where clause I would like to filter the usernames to get rid of technical users. This query works quite well.
But some technical users re still inside my result. Their usernames end with a $.

Example:

0#.w|domain\technical1971$

How can I write a REGEX to get rid of them?
I would like to filter on the existing $, becaue I don't want to filter on fixed names.

I already tried: (not working)

```<code>and CS_USERNAME NOT REGEXP '[.dollar-sign.]'
</code>```

and

```<code>and CS_USERNAME NOT REGEXP '\$'
</code>```

答:
How about just using the LIKE operator:

```<code>WHERE CS_USERNAME NOT LIKE '%$'
</code>```

If you wanted to use REGEXP, then you would need to escape the $ with two backslashes:

```<code>WHERE CS_USERNAME NOT REGEXP '\\$$'
</code>```

This would match a literal dollar sign at the end of the string.  From the MySQL documentation:

To use a literal instance of a special character in a regular expression, precede it by two backslash () characters. The MySQL parser interprets one of the backslashes, and the regular expression library interprets the other.

Title: MySQL regex escape $

Body:
I have written an analysis on logfiles from a Microsoft IIS Server.
The complete log is pushed to a mysql datbase. The fields of my table are exact the same as in the log.

CREATE TABLE `iis_logging` (
    `ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
    `DATE_TIME` DATETIME NULL DEFAULT NULL,
    `LOG_DATE` DATE NULL DEFAULT NULL,
    `LOG_TIME` TIME NULL DEFAULT NULL,
    `S_SITENAME` VARCHAR(255) NULL DEFAULT NULL,
    `S_COMPUTERNAME` VARCHAR(255) NULL DEFAULT NULL,
    `S_IP` VARCHAR(255) NULL DEFAULT NULL,
    `CS_METHOD` VARCHAR(255) NULL DEFAULT NULL,
    `CS_URI_STEM` TEXT NULL,
    `CS_URI_QUERY` TEXT NULL,
    `S_PORT` INT(11) UNSIGNED NULL DEFAULT NULL,
    `CS_USERNAME` VARCHAR(255) NULL DEFAULT NULL,
    `C_IP` VARCHAR(255) NULL DEFAULT NULL,
    `CS_VERSION` VARCHAR(255) NULL DEFAULT NULL,
    `CS_USER_AGENT` TEXT NULL,
    `CS_COOKIE` TEXT NULL,
    `CS_REFERER` TEXT NULL,
    `CS_HOST` TEXT NULL,
    `SC_STATUS` VARCHAR(255) NULL DEFAULT NULL,
    `SC_SUBSTATUS` VARCHAR(255) NULL DEFAULT NULL,
    `SC_WIN32_STATUS` VARCHAR(255) NULL DEFAULT NULL,
    `SC_BYTES` INT(10) UNSIGNED NULL DEFAULT NULL,
    `CS_BYTES` INT(10) UNSIGNED NULL DEFAULT NULL,
    `TIME_TAKEN` INT(11) UNSIGNED NULL DEFAULT NULL,
    PRIMARY KEY (`ID`),
    INDEX `date_key` (`LOG_DATE`),
    INDEX `DATE_URL` (`LOG_DATE`, `CS_URI_STEM`(30)),
    INDEX `URL` (`CS_URI_STEM`(100))
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=82749372
;

Now I have written a query to get only some parts of this log:

select concat(LOG_DATE,' ', LOG_TIME) as VISIT_TS, CS_METHOD, CS_URI_STEM, CS_URI_QUERY, CS_REFERER, CS_USERNAME
from iis_logging
where CS_USERNAME NOT REGEXP '-' and CS_USERNAME NOT REGEXP '_'
order by LOG_DATE DESC , LOG_TIME DESC, CS_USERNAME DESC
limit 500

Inside the where clause I would like to filter the usernames to get rid of technical users. This query works quite well.
But some technical users re still inside my result. Their usernames end with a $.

Example:

0#.w|domain\technical1971$

How can I write a REGEX to get rid of them?
I would like to filter on the existing $, becaue I don't want to filter on fixed names.

I already tried: (not working)

and CS_USERNAME NOT REGEXP '[.dollar-sign.]'

and

and CS_USERNAME NOT REGEXP '\$'

Body:
How about just using the LIKE operator:

WHERE CS_USERNAME NOT LIKE '%$'

If you wanted to use REGEXP, then you would need to escape the $ with two backslashes:

WHERE CS_USERNAME NOT REGEXP '\\$$'

This would match a literal dollar sign at the end of the string.  From the MySQL documentation:

To use a literal instance of a special character in a regular expression, precede it by two backslash () characters. The MySQL parser interprets one of the backslashes, and the regular expression library interprets the other.


问:
variable in function nor returning values after else statement
Im new with Python and my function is not working as expected. Im trying to save some values in a list list_alt[i] but if i call the values outside the if or else statements i get only None.</p>

```<code>import os.path
import xlrd
import sys
import argparse

def readExcel():
     workbook = xlrd.open_workbook(path)
     sheet = workbook.sheet_by_index(0)
     sheet = workbook.sheet_by_index(0)
     j=0
     for row in range(sheet.nrows):
          j += 1
     rownumber=j
     print (rownumber)

     k=0
     i=0
     list_alt=[None]*j
     list_neu=[None]*j
     while (i<j-10):
          #get first row values
          temp = sheet.cell_value(k,0).replace('www.website.com/','')
          #get second row values
          temp2 = sheet.cell_value(k,1)
          if "http:" in temp2:
               temp2 = sheet.cell_value(k,1).replace('http:','https:')
               list_neu[i]=temp2
               list_alt[i]=temp
               k+=0
               i+=1
          else:
               list_neu[i]=temp2
               list_alt[i]=temp
               #i can print the values here
               print (list_alt[i])
               print (list_neu[i])
               i+=1
               k+=1

          #I cant print for the values here anymore
          print (list_alt[i])
          print (list_neu[i])
          print (i)

     return list_alt, list_neu
</code>```

答:
The lines past if/else are executed after i has been incremented, so of course it will print None, since that is indeed the value of list_alt[i]. Your function should be returning the proper values, regardless. If you'd like to see the value you just inserted consider two possible changes:

increment i as the last line within the while loop

print(list_alt[i-1]) instead

Body:
Im new with Python and my function is not working as expected. Im trying to save some values in a list list_alt[i] but if i call the values outside the if or else statements i get only None.

import os.path
import xlrd
import sys
import argparse

def readExcel():
     workbook = xlrd.open_workbook(path)
     sheet = workbook.sheet_by_index(0)
     sheet = workbook.sheet_by_index(0)
     j=0
     for row in range(sheet.nrows):
          j += 1
     rownumber=j
     print (rownumber)

     k=0
     i=0
     list_alt=[None]*j
     list_neu=[None]*j
     while (i<j-10):
          #get first row values
          temp = sheet.cell_value(k,0).replace('www.website.com/','')
          #get second row values
          temp2 = sheet.cell_value(k,1)
          if "http:" in temp2:
               temp2 = sheet.cell_value(k,1).replace('http:','https:')
               list_neu[i]=temp2
               list_alt[i]=temp
               k+=0
               i+=1
          else:
               list_neu[i]=temp2
               list_alt[i]=temp
               #i can print the values here
               print (list_alt[i])
               print (list_neu[i])
               i+=1
               k+=1

          #I cant print for the values here anymore
          print (list_alt[i])
          print (list_neu[i])
          print (i)

     return list_alt, list_neu


问:
Python how to print 0 if there are no negative numbers in a list?
I have to print the first negative number in a list, but if there are no negative numbers I have to return it as 0. I cannot for the life of me figure this out, I feel very dumb.

```<code>def find_negative(list_numbers):
    for list_number in list_numbers:
        if list_number < 0:
            return list_number
</code>```

Currently it works if there are negative numbers, but if there aren't, it'll return nothing. I can't seem to make it so it returns 0 instead of nothing

答:
You can use this one-liner:

```<code>num = next((x for x in numbers if x < 0), 0)
</code>```

There's a little package on PyPI providing the first() function which might be more convenient:

```<code>from first import first
num = first(numbers, key=lambda x: x < 0, default=0)
</code>```

Body:
I have to print the first negative number in a list, but if there are no negative numbers I have to return it as 0. I cannot for the life of me figure this out, I feel very dumb.

def find_negative(list_numbers):
    for list_number in list_numbers:
        if list_number < 0:
            return list_number

Currently it works if there are negative numbers, but if there aren't, it'll return nothing. I can't seem to make it so it returns 0 instead of nothing

Body:
You can use this one-liner:

num = next((x for x in numbers if x < 0), 0)

There's a little package on PyPI providing the first() function which might be more convenient:

from first import first
num = first(numbers, key=lambda x: x < 0, default=0)


问:
CSS: Can I use the classes of nested elements to narrow css down?
Here is an example of what I have:

```<code><div class="node node-blog">
  <div class="field-item even">
    <img src="image.png"/>
  </div>
</div>
</code>```

What I would like to do is apply a style to the img element only when inside the node-blog and field-item divs, but this does not work:

```<code>.node-blog .field-item img {float:right;}
</code>```

Sure I am doing something wrong.

Thanks.

答:
you could try:

.node-blog .field-item img {float:right!important;}

...another rule may be more selective

Body:
Here is an example of what I have:

What I would like to do is apply a style to the img element only when inside the node-blog and field-item divs, but this does not work:

.node-blog .field-item img {float:right;}

Sure I am doing something wrong.

Thanks.


问:
How to send form's action to ajax in vue
Working with Larave 5.4, I have a table built with vue.

Each row in the table has this form:

```<code><form @submit.prevent="submitForm" class="status-form" action="'/orders/' + row.Id + '/edit'" method="post">
   <input type="hidden" name="status" value="2">
   <button type="submit" class="btn btn-success btn-sm">Sent</button>
</form>
</code>```

My Route:
Route::resource('orders', 'OrderController', ['except => show']);

When the Sent button is clicked, I want to submit the form with AJAX.

My Ajax call:

```<code>$.ajax({
  type: "PATCH",
  headers: { 'X-CSRF-TOKEN' : $('meta[name=_token]').attr('content') },
  url: $(this).attr('action'),
  data: { 'status': 2 },
  success: function(data) {
    alert($(this).attr('action'));
  }
});
</code>```

When I click the Sent button, I get this in Firebug:

PATCH http://highland.local/orders 405 Method Not Allowed

It looks like, it does not get the form's action correctly.
How do I get the form's action from the form, in the ajax call?

答:
The only time you will get a 405 Method Not Allowed response from Laravel is if you attempt to use a HTTP method that is not defined on a route.

For example attempting to make a POST request to a GET route.

In your case you will require Route::patch( '/orders/{id}/edit', 'contoller@method' ); in your API routes file.

Body:
Working with Larave 5.4, I have a table built with vue.

Each row in the table has this form:

<form @submit.prevent="submitForm" class="status-form" action="'/orders/' + row.Id + '/edit'" method="post">
   <input type="hidden" name="status" value="2">
   <button type="submit" class="btn btn-success btn-sm">Sent</button>
</form>

My Route:
Route::resource('orders', 'OrderController', ['except => show']);

When the Sent button is clicked, I want to submit the form with AJAX.

My Ajax call:

$.ajax({
  type: "PATCH",
  headers: { 'X-CSRF-TOKEN' : $('meta[name=_token]').attr('content') },
  url: $(this).attr('action'),
  data: { 'status': 2 },
  success: function(data) {
    alert($(this).attr('action'));
  }
});

When I click the Sent button, I get this in Firebug:

PATCH http://highland.local/orders 405 Method Not Allowed

It looks like, it does not get the form's action correctly.
How do I get the form's action from the form, in the ajax call?


问:
Crawl data with Scrapy to load more?
I need to crawl some news from this site: https://www.huxiu.com/channel/103.html. Here 103 is the news category id.

But I can only get the first page if not triggering the ajax to load more:

Very strange the request url is the same for different news categories.

And the page information was delivered by headers by the referer. And the page is sent by the form data.

Here is the snippet of my code:

```<code>    self.page += 1
    url = "https://www.huxiu.com/channel/ajaxGetMore"
    method = "POST"

    headers = {
        "Host": "www.huxiu.com",
        "Origin": "https://www.huxiu.com",
        "Referer": "https://www.huxiu.com/channel/106.html",
        "User-Agent": (
            "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/"
            "537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Sa"
            "fari/537.36"
        ),
        "X-Requested-With": "XMLHttpRequest",
    }

    formdata = {
        "huxiu_hash_code": "9aee58d3507ecafed74df13e156ab01b",
        "page": str(self.page),
        "catId": "106"
    }

    yield FormRequest(
        url=url,
        method=method,
        headers=headers,
        formdata=formdata,
        callback=self.parse
    )
</code>```

Which failed to load more news feeds. How can I send the post request to crawl more news?

答:
In this case GET and POST requests seem to be interchangable.
This is a very common AJAX pagination technique:

If you'd try: https://www.huxiu.com/channel/ajaxGetMore?catId=103&page=3 in your browser and you'd see some json data that contains all pagination data aswell as some meta data like total_page. This information is easy to crawl and allows you to crawl concurrently every page since you know page count from the very first request.

See for example how this spider for python3 deals with this sort of pagination:

```<code>from scrapy import Spider, Request
from w3lib.url import add_or_replace_parameter

class MySpider(Spider):
    start_urls = ['https://www.huxiu.com/channel/ajaxGetMore?catId=103&page=1']

    def parse(self, response):
        data = json.loads(response.body_as_unicode())
        yield from parse_data(response)  # parse first page as well
        # yield async requests for every other page.
        for page in range(2, data['data']['total_page']):
            # make next page url by replacing page parameter
            url = add_or_replace_parameter(response.url, 'page', page)
            yield Request(url, callback=self.parse_data)

    def parse_data(self, response):
        data = json.loads(response.body_as_unicode())
        # parse json data
</code>```

Title: Crawl data with Scrapy to load more?

Body:
I need to crawl some news from this site: https://www.huxiu.com/channel/103.html. Here 103 is the news category id.

But I can only get the first page if not triggering the ajax to load more:

Very strange the request url is the same for different news categories.

And the page information was delivered by headers by the referer. And the page is sent by the form data.

Here is the snippet of my code:

    self.page += 1
    url = "https://www.huxiu.com/channel/ajaxGetMore"
    method = "POST"

    headers = {
        "Host": "www.huxiu.com",
        "Origin": "https://www.huxiu.com",
        "Referer": "https://www.huxiu.com/channel/106.html",
        "User-Agent": (
            "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/"
            "537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Sa"
            "fari/537.36"
        ),
        "X-Requested-With": "XMLHttpRequest",
    }

    formdata = {
        "huxiu_hash_code": "9aee58d3507ecafed74df13e156ab01b",
        "page": str(self.page),
        "catId": "106"
    }

    yield FormRequest(
        url=url,
        method=method,
        headers=headers,
        formdata=formdata,
        callback=self.parse
    )

Which failed to load more news feeds. How can I send the post request to crawl more news?

Body:
In this case GET and POST requests seem to be interchangable.
This is a very common AJAX pagination technique:

If you'd try: https://www.huxiu.com/channel/ajaxGetMore?catId=103&page=3 in your browser and you'd see some json data that contains all pagination data aswell as some meta data like total_page. This information is easy to crawl and allows you to crawl concurrently every page since you know page count from the very first request.

See for example how this spider for python3 deals with this sort of pagination:

from scrapy import Spider, Request
from w3lib.url import add_or_replace_parameter

class MySpider(Spider):
    start_urls = ['https://www.huxiu.com/channel/ajaxGetMore?catId=103&page=1']

    def parse(self, response):
        data = json.loads(response.body_as_unicode())
        yield from parse_data(response)  # parse first page as well
        # yield async requests for every other page.
        for page in range(2, data['data']['total_page']):
            # make next page url by replacing page parameter
            url = add_or_replace_parameter(response.url, 'page', page)
            yield Request(url, callback=self.parse_data)

    def parse_data(self, response):
        data = json.loads(response.body_as_unicode())
        # parse json data


问:
VueJS 2 and Vee-Validate
after playing around with the docs etc.. i got some problems with a  .. I'll paste the code below.

```<code><!-- Subject FIeld -->
  <div class="field">
    <p :class="{ 'control': true, 'has-icon': true, 'has-icon-right': true }">
      <input name="onderwerp" v-validate="'required|alpha|min:3'" :class="{'input': true, 'is-danger': fields.failed('onderwerp'), 'is-success': fields.passed('onderwerp') }" type="text"  id="onderwerp" placeholder="Onderwerp">
      <span v-show="fields.failed('onderwerp') || fields.passed('onderwerp')" class="icon is-small">
        <i :class="{ 'fa': true, 'fa-warning': fields.failed('onderwerp'), 'fa-check': fields.passed('onderwerp') }"></i>
      </span>
    </p>
  </div>
  <!-- Question Field -->
      <div class="field">
        <!--{{--<label class="label">Vraag</label>--}}-->
    <p :class="{ 'control': true, 'has-icon': true, 'has-icon-right': true }">
      <textarea v-validate="'required|alpha|min:10'" :class="{'textarea': true, 'is-danger': errors.has('vraag') }" name="vraag" id="vraag" placeholder="Vraag"></textarea>
      <span v-show="errors.has('vraag')" class="icon is-small"><i class="fa fa-warning"></i></span>
    </p>
  </div>
  <!--test Field-->
  <div class="field">
    <!--{{--<label class="label">Vraag</label>--}}-->
    <p :class="{ 'control': true, 'has-icon': true, 'has-icon-right': true }">
      <textarea name="testfield" v-validate="'required|alpha|min:10'" :class="{'textarea': true, 'is-danger': fields.failed('testfield'), 'is-success': fields.passed('testfield') }" id="testfield" placeholder="Vraag"></textarea>
      <span v-show="fields.failed('testfield') || fields.passed('testfield')" class="icon is-small">
        <i :class="{ 'fa': true, 'fa-warning': fields.failed('testfield'), 'fa-check': fields.passed('testfield') }"></i>
      </span>
    </p>
  </div>
</code>```

Script code:

```<code>    <script>
  export default {
    name: 'Contact-Form',
    data: () => ({
      name: '',
      telefoon: '',
      email: '',
      onderwerp: '',
      testfield: '',
      vraag: ''
    })
  };
</script>
</code>```

Everything works, except when i remove the question field part. Then the whole form stops working as intended.

anyone got any idea this is happening?

Thanks in advance!

答:
Fixed:

you have to show a error, can make it hidden or whatever but it needs to render.

```<code><span v-show="fields.failed('fieldname')" class="hidden">{{ errors.first('fieldname') }}</span>
</code>```

This will fix the form checks. ;)

Title: VueJS 2 and Vee-Validate

Body:
after playing around with the docs etc.. i got some problems with a  .. I'll paste the code below.

      <input name="onderwerp" v-validate="'required|alpha|min:3'" :class="{'input': true, 'is-danger': fields.failed('onderwerp'), 'is-success': fields.passed('onderwerp') }" type="text"  id="onderwerp" placeholder="Onderwerp">

      <textarea v-validate="'required|alpha|min:10'" :class="{'textarea': true, 'is-danger': errors.has('vraag') }" name="vraag" id="vraag" placeholder="Vraag"></textarea>

      <textarea name="testfield" v-validate="'required|alpha|min:10'" :class="{'textarea': true, 'is-danger': fields.failed('testfield'), 'is-success': fields.passed('testfield') }" id="testfield" placeholder="Vraag"></textarea>

Script code:

Everything works, except when i remove the question field part. Then the whole form stops working as intended.

anyone got any idea this is happening?

Thanks in advance!

Body:
Fixed:

you have to show a error, can make it hidden or whatever but it needs to render.

<span v-show="fields.failed('fieldname')" class="hidden">{{ errors.first('fieldname') }}</span>

This will fix the form checks. ;)


问:
How to scan a column for a certain word and when triggered, remove the first 4 characters
Hey everyone so here is my setup

My issue is regarding the "C" column and how to remove the "2nd|" and "3rd|" portions so it ONLY shows "Mikes Auto Shop" "Carls Auto Repair" etc

Like this

答:
https://www.mrexcel.com/forum/excel-questions/375502-remove-first-letter-each-cell-column.html

on the forum here they mention that you can use =RIGHT(A1,LEN(A1)-1), for you it would look more like =RIGHT(C1,LEN(C1)-1) and you would place it in the D column and then just grap the bottom right hand corner and drag it down the will give you all the values you need in the D column, hope this helps


问:
AngularJS1.6 ES6 component not displaying template
My folders are

```<code>client
 :src/
   :app/
     :common/
        :sidebar.module.js
        :sidebar.component.js
        :sidebar.controller.js
        :sidebar.html
   :root.module.js
   :root.component.js
   :root.html
 :index.html
</code>```

my root.module.js is

```<code>import angular from 'angular';
import {sidebar} from './common/sidebar.module';

angular.module('cms', ['sidebar']);
</code>```

The code inside my root.component.js is

```<code>import angular from 'angular';

const options = {
  templateUrl: './root.html'
}

angular.module('cms').component('root', options);
</code>```

my root.html file is

```<code><div class="root">
  <h1>Hi, I am Ayush Bahuguna</h1>
  <my-sidebar></my-sidebar>
</div>
</code>```

my sidebar.module.js is

```<code>import angular from 'angular';

export const sidebar = angular.module('sidebar', []).name;
</code>```

my sidebar.component.js is

```<code>import angular from 'angular';
import {sidebar} from './sidebar.module';
import {sidebarController} from './sidebar.controller';

const sidebar = {
  templateUrl: './sidebar.html',
  controller: 'sidebarController',
  controllerAs: 'ctrl'
}

sidebar.component('mySidebar', sidebar).name;
</code>```

my sidebar.controller.js is

```<code>    function sidebarController(){
  var ctrl = this;
  ctrl.items = [{item: 'Home', icon: 'home', status: '/'}, {item: 'New Post', icon: 'note_add', status: '/new'}]
}

export sidebarController;
</code>```

my sidebar.html is

```<code>    <div class="sidebar">
  <ul class="sidebar-items">
    <li ng-repeat="item in ctrl.items"><i class="material-icons">{{item.icon}}</i> {{item.name}}</li>
  </ul>
</div>
</code>```

And my index.html is

```<code>    <!DOCTYPE html>
<html ng-app="cms">
  <head>
    <meta charset="utf-8">
    <title>Blog Admin | Ayush Bahuguna</title>
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons"
      rel="stylesheet">
  </head>
  <body>
  <root></root>
  <!-- <script src="client/dist/js/plugins/tinymce/tinymce.min.js" charset="utf-8"></script> -->
  <script src="/dist/js/vendor.js"></script>
  <script src="/dist/js/app.js"></script>
  </body>
</html>
</code>```

Here vendor.js and app.js are bundled files, and i have checked that nothing is wrong with them. They are loading perfectly, but my <root></root> isn't displaying anything, not even concerned about <my-sidebar></my-sidebar> because it's not even displaying the h1 either.

Your help would be appreciated.

EDIT I have added more files. Also, in my server side code I have app.use(express.static('client'))

答:
AngularJS doesn't allow usage of relative paths as templateUrl (or atleast, not relative to the file you're putting the component in).

Instead, AngularJS resolves urls relative to a certain root (which can be configured iirc).

To solve this, I'm guessing you need to change your templateUrls as follows (guessing, as I can't tell for sure without a reproduction sample):

./root.html => ./src/root.html

./sidebar.html => ./src/app/common/sidebar.html

To demonstrate this, here are two plunkrs:

not working (using your approach): https://plnkr.co/edit/1jfuuPP0ry0C7aFVvq06?p=preview

working (using ./src/root.html): https://plnkr.co/edit/uaKKro6IMiOzOz0xxiSY?p=preview

Other than that, there may be more issues but that's hard to tell without a full sample. As already mentioned in the comments, you do need to ensure all components are imported (you are either not loading them, or the code loading them isn't mentioned above). I generally would replace my component and module file like so:

root.module.js:

```<code>import angular from 'angular';
import {sidebar} from './common/sidebar.module';
import {rootComponentName, rootComponent} from './root.component';

angular.module('cms', ['sidebar'])
  .component(rootComponentName, rootComponent);
</code>```

root.component.js

```<code>import angular from 'angular';

export const rootComponentName = 'root';
export const rootComponent = {
  templateUrl: './root.html'
}
</code>```

And use a comparable approach for all your other modules.

Have a look at: https://github.com/frederikprijck/angularjs-webpack-starter/blob/master/src/app/contacts/contacts.module.ts regarding this approach.

Body:
My folders are

client
 :src/
   :app/
     :common/
        :sidebar.module.js
        :sidebar.component.js
        :sidebar.controller.js
        :sidebar.html
   :root.module.js
   :root.component.js
   :root.html
 :index.html

my root.module.js is

import angular from 'angular';
import {sidebar} from './common/sidebar.module';

angular.module('cms', ['sidebar']);

The code inside my root.component.js is

import angular from 'angular';

const options = {
  templateUrl: './root.html'
}

angular.module('cms').component('root', options);

my root.html file is

Hi, I am Ayush Bahuguna

  <my-sidebar></my-sidebar>

my sidebar.module.js is

import angular from 'angular';

export const sidebar = angular.module('sidebar', []).name;

my sidebar.component.js is

import angular from 'angular';
import {sidebar} from './sidebar.module';
import {sidebarController} from './sidebar.controller';

const sidebar = {
  templateUrl: './sidebar.html',
  controller: 'sidebarController',
  controllerAs: 'ctrl'
}

sidebar.component('mySidebar', sidebar).name;

my sidebar.controller.js is

    function sidebarController(){
  var ctrl = this;
  ctrl.items = [{item: 'Home', icon: 'home', status: '/'}, {item: 'New Post', icon: 'note_add', status: '/new'}]
}

export sidebarController;

my sidebar.html is

{{item.icon}} {{item.name}}

And my index.html is

    <!DOCTYPE html>

    <meta charset="utf-8">
    <title>Blog Admin | Ayush Bahuguna</title>
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons"
      rel="stylesheet">

  <root></root>

Here vendor.js and app.js are bundled files, and i have checked that nothing is wrong with them. They are loading perfectly, but my <root></root> isn't displaying anything, not even concerned about <my-sidebar></my-sidebar> because it's not even displaying the h1 either.

Your help would be appreciated.

EDIT I have added more files. Also, in my server side code I have app.use(express.static('client'))

Body:
AngularJS doesn't allow usage of relative paths as templateUrl (or atleast, not relative to the file you're putting the component in).

Instead, AngularJS resolves urls relative to a certain root (which can be configured iirc).

To solve this, I'm guessing you need to change your templateUrls as follows (guessing, as I can't tell for sure without a reproduction sample):

./root.html => ./src/root.html

./sidebar.html => ./src/app/common/sidebar.html

To demonstrate this, here are two plunkrs:

not working (using your approach): https://plnkr.co/edit/1jfuuPP0ry0C7aFVvq06?p=preview

working (using ./src/root.html): https://plnkr.co/edit/uaKKro6IMiOzOz0xxiSY?p=preview

Other than that, there may be more issues but that's hard to tell without a full sample. As already mentioned in the comments, you do need to ensure all components are imported (you are either not loading them, or the code loading them isn't mentioned above). I generally would replace my component and module file like so:

root.module.js:

import angular from 'angular';
import {sidebar} from './common/sidebar.module';
import {rootComponentName, rootComponent} from './root.component';

angular.module('cms', ['sidebar'])
  .component(rootComponentName, rootComponent);

root.component.js

import angular from 'angular';

export const rootComponentName = 'root';
export const rootComponent = {
  templateUrl: './root.html'
}

And use a comparable approach for all your other modules.

Have a look at: https://github.com/frederikprijck/angularjs-webpack-starter/blob/master/src/app/contacts/contacts.module.ts regarding this approach.