问:
Rows in a Multi Column ListView are not properly ordered while Scrolling: Android
I've populated the data into a multi column ListView from firebase database.

I've extended BaseAdapter class for getting getting this view as shown in below figures.

Why does the item positions change while scrolling ?

Rows are getting aligned up and down when scrolled. This is the scenario:

Scrolled a bit down... ( Looks fine! )

Scrolling...

( The records were not displayed in the order, as you can see they are getting changed every time I scroll through the list. )

What can be the reason for this? Can anyone explain?

Code for Adapter class:

```<code>    public class ReportAdapter extends BaseAdapter {

    public ArrayList<HashMap<String, String>> list;
    Activity activity;
    TextView childOneNameColumn, childTwoNameColumn, childThreeNameColumn;
    TextView checkInColumn;
    TextView parentCheckInColumn;
    TextView checkOutColumn;
    TextView parentCheckOutColumn;
    TextView familyNameColumn;

    public ReportAdapter(Activity activity, ArrayList<HashMap<String, String>> list) {
        super();
        this.activity = activity;
        this.list = list;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder viewHolder;

        LayoutInflater inflater = activity.getLayoutInflater();

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.column_row, parent, false);
            viewHolder = new ViewHolder(convertView);
            convertView.setTag(viewHolder);

        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        HashMap<String, String> map = list.get(position);
        familyNameColumn.setText(map.get(FAMILY_NAME_COLUMN));
        childOneNameColumn.setText(map.get(CHILD_ONE_NAME_COLUMN));
        childTwoNameColumn.setText(map.get(CHILD_TWO_NAME_COLUMN));
        childThreeNameColumn.setText(map.get(CHILD_THREE_NAME_COLUMN));
        checkInColumn.setText(map.get(CHECKIN_COLUMN));
        parentCheckInColumn.setText(map.get(PARENT_CHECKIN_COLUMN));
        checkOutColumn.setText(map.get(CHECKOUT_COLUMN));
        parentCheckOutColumn.setText(map.get(PARENT_CHECKOUT_COLUMN));

        return convertView;
    }

    private class ViewHolder {

        public ViewHolder(View view) {
            childOneNameColumn = (TextView) view.findViewById(R.id.child1NameColumn);
            childTwoNameColumn = (TextView) view.findViewById(R.id.child2NameColumn);
            childThreeNameColumn = (TextView) view.findViewById(R.id.child3NameColumn);
            checkInColumn = (TextView) view.findViewById(R.id.checkInColumn);
            parentCheckInColumn = (TextView) view.findViewById(R.id.parentCheckInColumn);
            checkOutColumn = (TextView) view.findViewById(R.id.checkOutColumn);
            parentCheckOutColumn = (TextView) view.findViewById(R.id.parentCheckOutColumn);
            familyNameColumn = (TextView) view.findViewById(R.id.familyNameColumn);
        }
    }
}
</code>```

Layout column_row.xml:

```<code><?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp">

    <LinearLayout
        android:id="@+id/linearLayout5"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="30dp"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/familyNameColumn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.8"
            android:textColor="@color/colorBlack" />

        <TextView
            android:id="@+id/child1NameColumn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.5" />

        <TextView
            android:id="@+id/child2NameColumn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.5" />

        <TextView
            android:id="@+id/child3NameColumn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.5" />

        <TextView
            android:id="@+id/checkInColumn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:textColor="@color/colorGreen" />

        <TextView
            android:id="@+id/parentCheckInColumn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.7" />

        <TextView
            android:id="@+id/checkOutColumn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:textColor="@color/colorGreen" />

        <TextView
            android:id="@+id/parentCheckOutColumn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.7" />

    </LinearLayout>
</RelativeLayout>
</code>```

ListView properties:

```<code><ListView
    android:id="@+id/reportListView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginTop="40dp"
    android:transcriptMode="alwaysScroll" />
</code>```

答:
The main reason for messed up rows are that you are not setting the text at the correct TextView objects.

You have 8 TextViews each row. That means, for all the rows showing on the screen, they each has 8 TextView objects.

For example, if you have 10 rows on screen, then you will have 10 individual copies of those 8 TextView.

You can use ViewHolder. The main purpose for the View Holder Pattern is to eliminate the need to call findViewById every time and that will give you better performance.

Body:
I've populated the data into a multi column ListView from firebase database.

I've extended BaseAdapter class for getting getting this view as shown in below figures.

Why does the item positions change while scrolling ?

Rows are getting aligned up and down when scrolled. This is the scenario:

Scrolled a bit down... ( Looks fine! )

Scrolling...

( The records were not displayed in the order, as you can see they are getting changed every time I scroll through the list. )

What can be the reason for this? Can anyone explain?

Code for Adapter class:

    public class ReportAdapter extends BaseAdapter {

    public ArrayList<HashMap<String, String>> list;
    Activity activity;
    TextView childOneNameColumn, childTwoNameColumn, childThreeNameColumn;
    TextView checkInColumn;
    TextView parentCheckInColumn;
    TextView checkOutColumn;
    TextView parentCheckOutColumn;
    TextView familyNameColumn;

    public ReportAdapter(Activity activity, ArrayList<HashMap<String, String>> list) {
        super();
        this.activity = activity;
        this.list = list;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder viewHolder;

        LayoutInflater inflater = activity.getLayoutInflater();

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.column_row, parent, false);
            viewHolder = new ViewHolder(convertView);
            convertView.setTag(viewHolder);

        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        HashMap<String, String> map = list.get(position);
        familyNameColumn.setText(map.get(FAMILY_NAME_COLUMN));
        childOneNameColumn.setText(map.get(CHILD_ONE_NAME_COLUMN));
        childTwoNameColumn.setText(map.get(CHILD_TWO_NAME_COLUMN));
        childThreeNameColumn.setText(map.get(CHILD_THREE_NAME_COLUMN));
        checkInColumn.setText(map.get(CHECKIN_COLUMN));
        parentCheckInColumn.setText(map.get(PARENT_CHECKIN_COLUMN));
        checkOutColumn.setText(map.get(CHECKOUT_COLUMN));
        parentCheckOutColumn.setText(map.get(PARENT_CHECKOUT_COLUMN));

        return convertView;
    }

    private class ViewHolder {

        public ViewHolder(View view) {
            childOneNameColumn = (TextView) view.findViewById(R.id.child1NameColumn);
            childTwoNameColumn = (TextView) view.findViewById(R.id.child2NameColumn);
            childThreeNameColumn = (TextView) view.findViewById(R.id.child3NameColumn);
            checkInColumn = (TextView) view.findViewById(R.id.checkInColumn);
            parentCheckInColumn = (TextView) view.findViewById(R.id.parentCheckInColumn);
            checkOutColumn = (TextView) view.findViewById(R.id.checkOutColumn);
            parentCheckOutColumn = (TextView) view.findViewById(R.id.parentCheckOutColumn);
            familyNameColumn = (TextView) view.findViewById(R.id.familyNameColumn);
        }
    }
}

Layout column_row.xml:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp">

    <LinearLayout
        android:id="@+id/linearLayout5"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="30dp"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/familyNameColumn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.8"
            android:textColor="@color/colorBlack" />

        <TextView
            android:id="@+id/child1NameColumn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.5" />

        <TextView
            android:id="@+id/child2NameColumn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.5" />

        <TextView
            android:id="@+id/child3NameColumn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.5" />

        <TextView
            android:id="@+id/checkInColumn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:textColor="@color/colorGreen" />

        <TextView
            android:id="@+id/parentCheckInColumn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.7" />

        <TextView
            android:id="@+id/checkOutColumn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:textColor="@color/colorGreen" />

        <TextView
            android:id="@+id/parentCheckOutColumn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.7" />

    </LinearLayout>
</RelativeLayout>

ListView properties:

<ListView
    android:id="@+id/reportListView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginTop="40dp"
    android:transcriptMode="alwaysScroll" />


来源: stackexchange

问:
Combining Two Queries Without the Use of Certain Functions
I have two separate queries:

```<code>SELECT TIME_TO_SEC(SUM(odchodDoch - prichodDoch)) AS cisloDoch,
  SUM(prestavkaDoch) as presDoch,
  operatorDoch
  FROM dochazkaVyroba
    WHERE operatorDoch IN ("x","y","z")
    AND datumDoch BETWEEN "2017-06-01" AND "2017-06-02"
    GROUP BY operatorDoch;

SELECT SUM(CAS) as cisloVyk,
  JMENO
  FROM produkce
    WHERE JMENO IN ("x","y","z")
    AND DATUM BETWEEN "2017-06-01" AND "2017-06-02"
    GROUP BY JMENO;
</code>```

And I wish to combine these into a single query.

and separately I get the following results:

```<code>cisloDoch presDoch operatorDoch
 57600      60         x
  0         0          y
 57600      0          z

cisloVyk JMENO
 532       x
  0        y
 780       z
</code>```

What I am looking to do is combine the above queries into one, based on:

produkce.JMENO = dochazkaVyroba.operatorDoch,

so that I get following:

```<code>cisloDoch presDoch operatorDoch  cisloVyk JMENO
 57600      60         x             532    x
  0         0          y               0    y
 57600      0          z              780   z
</code>```

Unfortunately, FULL OUTER JOIN isn't usable in  MySQL.

I also cannot use UNION with ON produkce.JMENO = dochazkaVyroba.operatorDoch.

答:
You can use union all and group by:

```<code>SELECT MAX(cisloDoch) as cisloDoch,
       MAX(presDoch) as presDoch,
       MAX(operatorDoch) as operatorDoch,
       MAX(cisloVyk) as cisloVyk,
       MAX(JMENO) as JMENO
FROM ((SELECT TIME_TO_SEC(SUM(odchodDoch - prichodDoch)) AS cisloDoch,
              SUM(prestavkaDoch) as presDoch, operatorDoch,
              NULL as cisloVyk, NULL as JMENO
       FROM dochazkaVyroba
       WHERE operatorDoch IN ('x', 'y', 'z') AND
             datumDoch BETWEEN '2017-06-01' AND '2017-06-02'
       GROUP BY operatorDoch
      ) UNION ALL
      (SELECT NULL NULL, NULL, SUM(CAS) as cisloVyk, JMENO
       FROM produkce
       WHERE JMENO IN ('x', 'y', 'z') AND
             datum BETWEEN '2017-06-01' AND '2017-06-02'
       GROUP BY JMENO
      )
     ) op
GROUP BY COALESCE(operatorDoch, JMENO);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have two separate queries:

SELECT TIME_TO_SEC(SUM(odchodDoch - prichodDoch)) AS cisloDoch,
  SUM(prestavkaDoch) as presDoch,
  operatorDoch
  FROM dochazkaVyroba
    WHERE operatorDoch IN ("x","y","z")
    AND datumDoch BETWEEN "2017-06-01" AND "2017-06-02"
    GROUP BY operatorDoch;

SELECT SUM(CAS) as cisloVyk,
  JMENO
  FROM produkce
    WHERE JMENO IN ("x","y","z")
    AND DATUM BETWEEN "2017-06-01" AND "2017-06-02"
    GROUP BY JMENO;

And I wish to combine these into a single query.

and separately I get the following results:

cisloDoch presDoch operatorDoch
 57600      60         x
  0         0          y
 57600      0          z

cisloVyk JMENO
 532       x
  0        y
 780       z

What I am looking to do is combine the above queries into one, based on:

produkce.JMENO = dochazkaVyroba.operatorDoch,

so that I get following:

cisloDoch presDoch operatorDoch  cisloVyk JMENO
 57600      60         x             532    x
  0         0          y               0    y
 57600      0          z              780   z

Unfortunately, FULL OUTER JOIN isn't usable in  MySQL.

I also cannot use UNION with ON produkce.JMENO = dochazkaVyroba.operatorDoch.

Body:
You can use union all and group by:

SELECT MAX(cisloDoch) as cisloDoch,
       MAX(presDoch) as presDoch,
       MAX(operatorDoch) as operatorDoch,
       MAX(cisloVyk) as cisloVyk,
       MAX(JMENO) as JMENO
FROM ((SELECT TIME_TO_SEC(SUM(odchodDoch - prichodDoch)) AS cisloDoch,
              SUM(prestavkaDoch) as presDoch, operatorDoch,
              NULL as cisloVyk, NULL as JMENO
       FROM dochazkaVyroba
       WHERE operatorDoch IN ('x', 'y', 'z') AND
             datumDoch BETWEEN '2017-06-01' AND '2017-06-02'
       GROUP BY operatorDoch
      ) UNION ALL
      (SELECT NULL NULL, NULL, SUM(CAS) as cisloVyk, JMENO
       FROM produkce
       WHERE JMENO IN ('x', 'y', 'z') AND
             datum BETWEEN '2017-06-01' AND '2017-06-02'
       GROUP BY JMENO
      )
     ) op
GROUP BY COALESCE(operatorDoch, JMENO);


问:
AlarmManager interval changes when other application is running
I'm working on an app which sets a repeating alarm.

It's supposed to run one of my services every 2 min for example.
When myApplication activity is running it works fine, but when other app is running in foreground the interval goes to 5 min!!!

I run this code inside another service which is starting in foreground.

I don't know why this is happening.

```<code>public class Serv1 extends Service{

 public static Intent intentServ2 = new Intent(G.context,Serv2.class);
public static   PendingIntent pendingIntend=PendingIntent.getService(G.context,0,intentServ2,0);
public  static AlarmManager alarmManager;

public int onStartCommand(Intent intent, int flags, int startId) {
 alarmManager =(AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis()+(2*1000),120*1000,pendingIntend);

  Intent notificationIntent = new Intent(this, Serv1.class);

    PendingIntent pendingIntent = PendingIntent.getService(this, 0,
            notificationIntent, 0);

    Notification notification = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("Serive1")
            .setContentText("Service is working...")
            .setContentIntent(pendingIntent).build();

    startForeground(254698, notification);

    return Service.START_STICKY;

}
</code>```

答:
From AlarmManager docs:

Note: as of API 19, all repeating alarms are inexact. If your application needs precise delivery times then it must use one-time exact alarms, rescheduling each time as described above. Legacy applications whose targetSdkVersion is earlier than API 19 will continue to have all of their alarms, including repeating alarms, treated as exact.

You might be experiencing those inexact alarms.

Also note that if you want the device to wake up when the alarm goes off, you need RTC_WAKEUP.

Body:
I'm working on an app which sets a repeating alarm.

It's supposed to run one of my services every 2 min for example.
When myApplication activity is running it works fine, but when other app is running in foreground the interval goes to 5 min!!!

I run this code inside another service which is starting in foreground.

I don't know why this is happening.

public class Serv1 extends Service{

 public static Intent intentServ2 = new Intent(G.context,Serv2.class);
public static   PendingIntent pendingIntend=PendingIntent.getService(G.context,0,intentServ2,0);
public  static AlarmManager alarmManager;

public int onStartCommand(Intent intent, int flags, int startId) {
 alarmManager =(AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis()+(2*1000),120*1000,pendingIntend);

  Intent notificationIntent = new Intent(this, Serv1.class);

    PendingIntent pendingIntent = PendingIntent.getService(this, 0,
            notificationIntent, 0);

    Notification notification = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("Serive1")
            .setContentText("Service is working...")
            .setContentIntent(pendingIntent).build();

    startForeground(254698, notification);

    return Service.START_STICKY;

}


问:
Get a subset of data from one row of Dataframe
Let's say I have a dataframe df with columns 'A', 'B', 'C'
Now I just want to extract row 2 of df and only columns 'B' and 'C'. What is the most efficient way to do that?

Can you please tell me why df.ix[2, ['B', 'C']] didn't work?

Thank you!

答:
Consider the dataframe df

```<code>df = pd.DataFrame(np.arange(9).reshape(3, 3), list('xyz'), list('ABC'))
df

   A  B  C
x  0  1  2
y  3  4  5
z  6  7  8
</code>```

If you want to maintain a dataframe

```<code>df.loc[df.index[[1]], ['B', 'C']]

   B  C
y  4  5
</code>```

If you want a series

```<code>df.loc[df.index[1], ['B', 'C']]

B    4
C    5
Name: y, dtype: int64
</code>```

Body:
Consider the dataframe df

df = pd.DataFrame(np.arange(9).reshape(3, 3), list('xyz'), list('ABC'))
df

   A  B  C
x  0  1  2
y  3  4  5
z  6  7  8

If you want to maintain a dataframe

df.loc[df.index[[1]], ['B', 'C']]

   B  C
y  4  5

If you want a series

df.loc[df.index[1], ['B', 'C']]

B    4
C    5
Name: y, dtype: int64


问:
Design of the Protobuf binary format: performance and varint
I need to design a binary format to save data from a scientific application. This data has to be encoded in a binary format that can't be easily read by any other application (it is a requirement by some of our clients). As a consequence, we decided to build our own binary format, its encoder and its decoder.

We got some inspiration from many binary format, including protobuf. One thing that puzzles me is the way protobuf encodes the length of embedded messages. According to https://developers.google.com/protocol-buffers/docs/encoding, the size of an embedded message is encoded at its very beginning as a varint.
But before we encode an embedded message, we don't know yet its size (think for instance of an embedded message that contains many integers encoded as varint). As a consequence, we need to encode the message entirely, before we write it to the disk so we know its size.
Imagine that this message is huge. As a consequence, it is very difficult to encode it in an efficient way. We could encode this size as a full int and seek back to this part of the file once the embedded message is written, but we loose the nice property of varints: you don't need to specify if you have a 32-bit or a 64-bit integer. So going back to Google's implementation using a varint:

Is there an implementation trick I am missing, or is this scheme likely to be inefficient for large messages?

答:
Yes, the correct way to do this is to write the message first, at the back of the buffer, and then prepend the size.  With proper buffer management, you can write the message in reverse.

That said, why write your own message format when you can just use protobuf?   It would be better to just use Protobuf directly and encrypt the file format.  That would be easy for you to use, and still be hard for other applications to read.


问:
Python: Callbacks, Delegates, ... ? What is common?
Just want to know what's the common way to react on events in python. There are several ways in other languages like callback functions, delegates, listener-structures and so on.
Is there a common way? Which default language concepts or additional modules are there and which can you recommend?</p>

答:
I can't speak for common approaches, but this page (actual copy is unavailable) has an implementation of the observer pattern that I like.

Here's the Internet Archive link:
http://web.archive.org/web/20060612061259/http://www.suttoncourtenay.org.uk/duncan/accu/pythonpatterns.html

OwnerDisplayName: okoman

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Matthew Maravillas

LastEditorDisplayName: Matthew Maravillas


问:
How to remove the tags using Meta in angular 4
I am able to set the tags dynamically in index.html with Meta concept in angular 4.but when I try to remove tags.its not
removing ,How can I remove the tags whatever I have added before?

here is what I tried:
setting the tags:

```<code>import {Meta ,MetaDefinition } from '@angular/platform-browser';
@Component({
  selector: 'app-share-video',
  templateUrl: './share-video.component.html',
  })
export class ShareVideoComponent implements OnInit {
constructor(public metaServic:Meta){}
ngOnInit(){
    const ogtitle: MetaDefinition   =  { name: 'og:title', content: 'Grace' };
    const ogSitename: MetaDefinition = { name: 'og:site_name', content: 'My Favourite Albums'};
    const ogUrl: MetaDefinition = { name: 'og:url', content: 'https://angular.io/docs/ts/latest/api/platform-browser/index/Meta-class.html'};
    const ogdesc: MetaDefinition = { name: 'og:description', content: 'angular 4 share video description'};
    this.metaService.addTag(ogtitle);
    this.metaService.addTag(ogSitename);
    this.metaService.addTag(ogUrl);
    this.metaService.addTag(ogdesc);
  }
ngOnDestroy() {
   this.metaService.removeTag("property='og:title'");
   this.metaService.removeTag("property='og:site_name'");
   this.metaService.removeTag("property='og:url'");
   this.metaService.removeTag("property='og:description'");
    }
}
</code>```

In the destroy method I am removing the tags, but these tags are not removing,how can I remove the tags?
followed this:meta tags blog

答:
The attribute selector that you are trying to use is name, not property.

You have to use

```<code>this.metaService.removeTag("name='og:title'");
this.metaService.removeTag("name='og:site_name'");
this.metaService.removeTag("name='og:url'");
this.metaService.removeTag("name='og:description'");
</code>```

instead of

```<code>this.metaService.removeTag("property='og:title'");
this.metaService.removeTag("property='og:site_name'");
this.metaService.removeTag("property='og:url'");
this.metaService.removeTag("property='og:description'");
</code>```

plnkr

Body:
I am able to set the tags dynamically in index.html with Meta concept in angular 4.but when I try to remove tags.its not
removing ,How can I remove the tags whatever I have added before?

here is what I tried:
setting the tags:

import {Meta ,MetaDefinition } from '@angular/platform-browser';
@Component({
  selector: 'app-share-video',
  templateUrl: './share-video.component.html',
  })
export class ShareVideoComponent implements OnInit {
constructor(public metaServic:Meta){}
ngOnInit(){
    const ogtitle: MetaDefinition   =  { name: 'og:title', content: 'Grace' };
    const ogSitename: MetaDefinition = { name: 'og:site_name', content: 'My Favourite Albums'};
    const ogUrl: MetaDefinition = { name: 'og:url', content: 'https://angular.io/docs/ts/latest/api/platform-browser/index/Meta-class.html'};
    const ogdesc: MetaDefinition = { name: 'og:description', content: 'angular 4 share video description'};
    this.metaService.addTag(ogtitle);
    this.metaService.addTag(ogSitename);
    this.metaService.addTag(ogUrl);
    this.metaService.addTag(ogdesc);
  }
ngOnDestroy() {
   this.metaService.removeTag("property='og:title'");
   this.metaService.removeTag("property='og:site_name'");
   this.metaService.removeTag("property='og:url'");
   this.metaService.removeTag("property='og:description'");
    }
}

In the destroy method I am removing the tags, but these tags are not removing,how can I remove the tags?
followed this:meta tags blog

Body:
The attribute selector that you are trying to use is name, not property.

You have to use

this.metaService.removeTag("name='og:title'");
this.metaService.removeTag("name='og:site_name'");
this.metaService.removeTag("name='og:url'");
this.metaService.removeTag("name='og:description'");

instead of

this.metaService.removeTag("property='og:title'");
this.metaService.removeTag("property='og:site_name'");
this.metaService.removeTag("property='og:url'");
this.metaService.removeTag("property='og:description'");

plnkr


问:
How could I pass std::function as function pointer?
I am trying to write a class template and internally it use a C function (implementation of BFGS optimization, provided by the R environment) with the following interface:

```<code>void vmmin(int n, double *x, double *Fmin,
           optimfn fn, optimgr gr, ... ,
           void *ex, ... );
</code>```

where fn and gr are function pointers of type

```<code>typedef double optimfn(int n, double *par, void *ex);
</code>```

and

```<code>typedef void optimgr(int n, double *par, double *gr, void *ex);
</code>```

respectively. My C++ class template looks like this:

```<code>template <typename T>
class optim {
 public:
  // ...
  void minimize(T& func, arma::vec &dpar, void *ex) {
    std::function<optimfn> fn =
      std::bind(&T::fr, func, std::placeholders::_1,
                std::placeholders::_2, std::placeholders::_3);
    std::function<optimgr> gr =
      std::bind(&T::grr, func, std::placeholders::_1,
                std::placeholders::_2, std::placeholders::_3,
                std::placeholders::_4);
    // ERROR: cannot convert std::function to function pointer
    vmmin(... , fn, gr, ...);
    // ...
  }
};
</code>```

so that it can be instantiated by any class with two specified member functions, e.g.:

```<code>class Rosen {
 public:
  // ...
  double fr(int n, double *par, void *ex);
  void grr(int n, double *par, double *gr, void *ex);
 private:
  // ...
};

// main.cc
Rosen func;
optim<Rosen> obj;
obj.minimize(func, dpar, ex);
</code>```

Is this possible? Or maybe there is a better way of doing this -- pass the two member functions separately as function pointer? (If the objective function and the corresponding gradient are simple, it is absolutely okay to write two functions. However, most of the time, the problem I got is far more complicated and I have to implement the problem as a class).

答:
Let me say up front:

I do not endorse the usage of the following library

```<code>#include<tuple>
#include<type_traits>
#include<utility>

// func_traits
template <typename T>
struct func_traits : public func_traits<decltype(&std::remove_reference_t<T>::operator())> {};

template <typename Callable, typename Ret, typename... Args>
struct func_traits<Ret(Callable::*)(Args...) const> {
    using ptr_type = Ret (*) (Args...);
    using return_type =  Ret;

    template<std::size_t i>
    struct arg
    {
        using type = typename std::tuple_element<i, std::tuple<Args...>>::type;
    };

    template<typename Ret2>
    using cast_return_type = Ret2 (*) (Args...);
};

template<typename Ret, typename... Args>
struct func_traits<Ret (&) (Args...)> : public func_traits<Ret (*) (Args...)> {};

template <typename Ret, typename... Args>
struct func_traits<Ret (*) (Args...)>
{
    using ptr_type = Ret (*) (Args...);
    using return_type =  Ret;

    template<std::size_t i>
    struct arg
    {
        using type = typename std::tuple_element<i, std::tuple<Args...>>::type;
    };

    template<typename Ret2>
    using cast_return_type = Ret2 (*) (Args...);
};

// constexpr counter
template <int N>
struct flag
{
    friend constexpr int adl_flag(flag<N>);
    constexpr operator int() { return N; }
};

template <int N>
struct write
{
    friend constexpr int adl_flag(flag<N>) { return N; }
    static constexpr int value = N;
};

template <int N, int = adl_flag(flag<N>{})>
constexpr int read(int, flag<N>, int R = read(0, flag<N + 1>{}))
{
    return R;
}

template <int N>
constexpr int read(float, flag<N>)
{
    return N;
}

template <int N = 0>
constexpr int counter(int R = write<read(0, flag<N>{})>::value)
{
    return R;
}

// fnptr
template<int nonce = counter()>
class fnptr
{
    //these are to make sure fnptr is never constructed
    //technically the first one should be enough, but compilers are not entirely standard conformant
    explicit fnptr() = delete;
    fnptr(const fnptr&) {}
    ~fnptr() = delete;

    template<typename Callable, typename Ret, typename... Args>
    static auto cast(Callable&& c, Ret(*fp)(Args...)) -> decltype(fp)
    {
        using callable_type = std::remove_reference_t<Callable>;
        static callable_type clb{std::forward<Callable>(c)};
        static bool full = false;
        if(full)
        {
            clb.~callable_type();
            new (&clb) decltype(clb){std::forward<Callable>(c)};
        }
        else
            full = true;
        return [](Args... args) noexcept(noexcept(clb(std::forward<Args>(args)...))) -> Ret
        {
            return Ret(clb(std::forward<Args>(args)...));
        };
    }

public:
    template<typename Signature, typename Callable>
    static Signature* cast(Callable&& c)
    {
        return cast(std::forward<Callable>(c), static_cast<Signature*>(nullptr));
    }

    template<typename Signature, typename Ret, typename... Args>
    static auto cast(Ret (*fp)(Args...))
    {
        static decltype(fp) fnptr;
        fnptr = fp;
        using return_type = typename func_traits<Signature*>::return_type;
        return [](Args... args) noexcept(noexcept(fp(std::forward<Args>(args)...)) -> return_type
        {
            return return_type(fnptr(std::forward<Args>(args)...));
        };
    }

    template<typename Callable>
    static auto get(Callable&& c)
    {
        return cast(std::forward<Callable>(c), typename func_traits<Callable>::ptr_type{nullptr});
    }

    template<typename Ret, typename... Args>
    static auto get(Ret (*fp)(Args...))
    {
        return fp;
    }
};
</code>```

And use it as

```<code>#include<functional>
#include<iostream>

using optimfn = double (int, double*, void*);
using optimgr = void (int, double*, double*, void*);

void test(optimfn* fn, optimgr* gr)
{
    double d;
    fn(42, &d, &d);
    gr(42, &d, &d, &d);
}

int main()
{
    std::function<optimfn> fn = [](int, double*, void*){
        std::cout << "I'm fn" << std::endl;
        return 0.;
    };
    std::function<optimgr> gr = [](int, double*, double*, void*){
        std::cout << "I'm gr" << std::endl;
    };

    test(fnptr<>::get(fn), fnptr<>::get(gr));
}
</code>```

Live example

func_traits

Is just a helper traits type that will fetch the type of any callable in an easily accessible form

constexpr counter

This is half the evilness of what's going on. For details visit is stateful metaprogramming ill formed yet?

fnptr

The actual meat of the code. It takes any callable with appropriate signatures and implicitly declares an anonymous C function at every point it is called and coerces the callable into the C function.

It has the funky syntax fnptr<>::get and fnptr<>::cast<Ret(Args...)>. This is intentional.

get will declare the anonymous C function with the same signature as the callable object.

cast works on any compatible callable type, that is, if the return type and arguments are implicitly convertible, it can be casted.

Caveats

fnptr implicitly declares an anonymous C function at each point in the code it is called. It is not the same as std::function that is actually a variable.

If you call the same fnptr in the code again, all hell breaks lose.

```<code>std::vector<int(*)()> v;
for(int i = 0; i < 10; i++)
    v.push_back(fnptr<>::get([i]{return i;}));  // This will implode
</code>```

You have been warned.

Body:
I am trying to write a class template and internally it use a C function (implementation of BFGS optimization, provided by the R environment) with the following interface:

void vmmin(int n, double *x, double *Fmin,
           optimfn fn, optimgr gr, ... ,
           void *ex, ... );

where fn and gr are function pointers of type

typedef double optimfn(int n, double *par, void *ex);

and

typedef void optimgr(int n, double *par, double *gr, void *ex);

respectively. My C++ class template looks like this:

template <typename T>
class optim {
 public:
  // ...
  void minimize(T& func, arma::vec &dpar, void *ex) {
    std::function<optimfn> fn =
      std::bind(&T::fr, func, std::placeholders::_1,
                std::placeholders::_2, std::placeholders::_3);
    std::function<optimgr> gr =
      std::bind(&T::grr, func, std::placeholders::_1,
                std::placeholders::_2, std::placeholders::_3,
                std::placeholders::_4);
    // ERROR: cannot convert std::function to function pointer
    vmmin(... , fn, gr, ...);
    // ...
  }
};

so that it can be instantiated by any class with two specified member functions, e.g.:

class Rosen {
 public:
  // ...
  double fr(int n, double *par, void *ex);
  void grr(int n, double *par, double *gr, void *ex);
 private:
  // ...
};

// main.cc
Rosen func;
optim<Rosen> obj;
obj.minimize(func, dpar, ex);

Is this possible? Or maybe there is a better way of doing this -- pass the two member functions separately as function pointer? (If the objective function and the corresponding gradient are simple, it is absolutely okay to write two functions. However, most of the time, the problem I got is far more complicated and I have to implement the problem as a class).

Body:
Let me say up front:

I do not endorse the usage of the following library

#include<tuple>
#include<type_traits>
#include<utility>

// func_traits
template <typename T>
struct func_traits : public func_traits<decltype(&std::remove_reference_t<T>::operator())> {};

template <typename Callable, typename Ret, typename... Args>
struct func_traits<Ret(Callable::*)(Args...) const> {
    using ptr_type = Ret (*) (Args...);
    using return_type =  Ret;

    template<std::size_t i>
    struct arg
    {
        using type = typename std::tuple_element<i, std::tuple<Args...>>::type;
    };

    template<typename Ret2>
    using cast_return_type = Ret2 (*) (Args...);
};

template<typename Ret, typename... Args>
struct func_traits<Ret (&) (Args...)> : public func_traits<Ret (*) (Args...)> {};

template <typename Ret, typename... Args>
struct func_traits<Ret (*) (Args...)>
{
    using ptr_type = Ret (*) (Args...);
    using return_type =  Ret;

    template<std::size_t i>
    struct arg
    {
        using type = typename std::tuple_element<i, std::tuple<Args...>>::type;
    };

    template<typename Ret2>
    using cast_return_type = Ret2 (*) (Args...);
};

// constexpr counter
template <int N>
struct flag
{
    friend constexpr int adl_flag(flag<N>);
    constexpr operator int() { return N; }
};

template <int N>
struct write
{
    friend constexpr int adl_flag(flag<N>) { return N; }
    static constexpr int value = N;
};

template <int N, int = adl_flag(flag<N>{})>
constexpr int read(int, flag<N>, int R = read(0, flag<N + 1>{}))
{
    return R;
}

template <int N>
constexpr int read(float, flag<N>)
{
    return N;
}

template <int N = 0>
constexpr int counter(int R = write<read(0, flag<N>{})>::value)
{
    return R;
}

// fnptr
template<int nonce = counter()>
class fnptr
{
    //these are to make sure fnptr is never constructed
    //technically the first one should be enough, but compilers are not entirely standard conformant
    explicit fnptr() = delete;
    fnptr(const fnptr&) {}
    ~fnptr() = delete;

    template<typename Callable, typename Ret, typename... Args>
    static auto cast(Callable&& c, Ret(*fp)(Args...)) -> decltype(fp)
    {
        using callable_type = std::remove_reference_t<Callable>;
        static callable_type clb{std::forward<Callable>(c)};
        static bool full = false;
        if(full)
        {
            clb.~callable_type();
            new (&clb) decltype(clb){std::forward<Callable>(c)};
        }
        else
            full = true;
        return [](Args... args) noexcept(noexcept(clb(std::forward<Args>(args)...))) -> Ret
        {
            return Ret(clb(std::forward<Args>(args)...));
        };
    }

public:
    template<typename Signature, typename Callable>
    static Signature* cast(Callable&& c)
    {
        return cast(std::forward<Callable>(c), static_cast<Signature*>(nullptr));
    }

    template<typename Signature, typename Ret, typename... Args>
    static auto cast(Ret (*fp)(Args...))
    {
        static decltype(fp) fnptr;
        fnptr = fp;
        using return_type = typename func_traits<Signature*>::return_type;
        return [](Args... args) noexcept(noexcept(fp(std::forward<Args>(args)...)) -> return_type
        {
            return return_type(fnptr(std::forward<Args>(args)...));
        };
    }

    template<typename Callable>
    static auto get(Callable&& c)
    {
        return cast(std::forward<Callable>(c), typename func_traits<Callable>::ptr_type{nullptr});
    }

    template<typename Ret, typename... Args>
    static auto get(Ret (*fp)(Args...))
    {
        return fp;
    }
};

And use it as

#include<functional>
#include<iostream>

using optimfn = double (int, double*, void*);
using optimgr = void (int, double*, double*, void*);

void test(optimfn* fn, optimgr* gr)
{
    double d;
    fn(42, &d, &d);
    gr(42, &d, &d, &d);
}

int main()
{
    std::function<optimfn> fn = [](int, double*, void*){
        std::cout << "I'm fn" << std::endl;
        return 0.;
    };
    std::function<optimgr> gr = [](int, double*, double*, void*){
        std::cout << "I'm gr" << std::endl;
    };

    test(fnptr<>::get(fn), fnptr<>::get(gr));
}

Live example

func_traits

Is just a helper traits type that will fetch the type of any callable in an easily accessible form

constexpr counter

This is half the evilness of what's going on. For details visit is stateful metaprogramming ill formed yet?

fnptr

The actual meat of the code. It takes any callable with appropriate signatures and implicitly declares an anonymous C function at every point it is called and coerces the callable into the C function.

It has the funky syntax fnptr<>::get and fnptr<>::cast<Ret(Args...)>. This is intentional.

get will declare the anonymous C function with the same signature as the callable object.

cast works on any compatible callable type, that is, if the return type and arguments are implicitly convertible, it can be casted.

Caveats

fnptr implicitly declares an anonymous C function at each point in the code it is called. It is not the same as std::function that is actually a variable.

If you call the same fnptr in the code again, all hell breaks lose.

std::vector<int(*)()> v;
for(int i = 0; i < 10; i++)
    v.push_back(fnptr<>::get([i]{return i;}));  // This will implode

You have been warned.


问:
Android Alarm set using Alarm manager is destroyed when the app is swiped off in some devices(Le2)
I am developing an android app which uses alarm manager's setrepeating method for setting repeat alarms and then showing notifications though onreceive of the receiver when the alarm triggers.But there is a problem.<br>
When I swipe the app off from the devices like Samsung Galaxy,it works well and notifies through alarm but in Le2,the alarm is destroyed and hence the notification is not shown.Even if I open the app again,the old alarm set is lost.I went through many answers but those just tell about the device problem(Le2) that force stops the app when swiped.None of the answers gave a good solution. </p>

答:
Got it. In Leeco LE2, just go to settings ->
battery -> power saving management -> app protection and disable your app for auto cleaning. Works now. It's because the manufacturer has messed up lot of things  to improve battery life and hence has become nightmare for developers to catch the solution.</p>

Body:
I am developing an android app which uses alarm manager's setrepeating method for setting repeat alarms and then showing notifications though onreceive of the receiver when the alarm triggers.But there is a problem.

When I swipe the app off from the devices like Samsung Galaxy,it works well and notifies through alarm but in Le2,the alarm is destroyed and hence the notification is not shown.Even if I open the app again,the old alarm set is lost.I went through many answers but those just tell about the device problem(Le2) that force stops the app when swiped.None of the answers gave a good solution.


问:
Position of two closest points on the lines
I have found algorithm to calculate shortest distance between two lines in 3D and rewrite it in Python.But also I would like to enchanced it that it could return not only distance,but also the postion of closest points.

```<code>def line2line(-0.073455669 4.9843092 0.26107353 0.0 0.0 -1.0 -3.85838175 12.1999998 -4.50372314 0.405142069 -0.76723671 0.497199893):
    epsilon = 0.00000001
    L1P0 = np.array([xbeam,ybeam,zbeam]) #position of P0 on first line
    L2P0= np.array([xout,yout,zout]) #position of P0 on first line
    L1P1 = np.array([xbeam + ubeam ,ybeam + vbeam ,zbeam + wbeam]) #ubeam,vbeam and wbeam are direction cosines
    L2P1 = np.array([xout + cx,yout + cy,zout + cz]) #cx,cy,cz are direction cosines
    u = L1P1 - L1P0
    v = L2P1 - L2P0
    w = L1P0 - L2P0
    a = np.dot(u,u)
    b = np.dot(u,v)
    c = np.dot(v,v)
    d = np.dot(u,w)
    e = np.dot(v,w)
    D = a*c - b*b
    if D < epsilon:
        sc = 0.0
        tc = d/b if b>c else e/c
    else:
        sc = (b*e - c*d) / D
        tc = (a*e - b*d) / D
    dP = w + (sc * u) - (tc * v)
    return np.linalg.norm(dP)
</code>```

It returns around 0.049 which is correct but when I tried to print
    w + (sc * u) or
    (tc * v) what I was thinking it was position,it printed me:

```<code>0.        ,   0.        , -19.82274615
3.8142822 , -7.22328672,  4.68097699
</code>```

It's not correct.Coordinates I'm looking for for one of these points are:

```<code>-0.073455669 4.9843092 0.26107353
</code>```

Algorithm I have found here

答:
I think I have the approach.

The algorithm does find the unit vector normal to both lines.  You also know the distance.  That gives you the vector of the line segment connecting the two points of interest.

Apply that vector as a linear transformation to u.  This gives you a new line, u-prime, which is shifted in the direction of the normal vector, by a distance you've computed.  u-prime will intersect v at one of the two points.  Find that intersection (which is the point on v of closest approach), subtract the connecting vector, and that gives your other point (on the original u).

If it helps to visualize, not that u-prime and v define a plane that is perpendicular to the normal vector.

Body:
I have found algorithm to calculate shortest distance between two lines in 3D and rewrite it in Python.But also I would like to enchanced it that it could return not only distance,but also the postion of closest points.

def line2line(-0.073455669 4.9843092 0.26107353 0.0 0.0 -1.0 -3.85838175 12.1999998 -4.50372314 0.405142069 -0.76723671 0.497199893):
    epsilon = 0.00000001
    L1P0 = np.array([xbeam,ybeam,zbeam]) #position of P0 on first line
    L2P0= np.array([xout,yout,zout]) #position of P0 on first line
    L1P1 = np.array([xbeam + ubeam ,ybeam + vbeam ,zbeam + wbeam]) #ubeam,vbeam and wbeam are direction cosines
    L2P1 = np.array([xout + cx,yout + cy,zout + cz]) #cx,cy,cz are direction cosines
    u = L1P1 - L1P0
    v = L2P1 - L2P0
    w = L1P0 - L2P0
    a = np.dot(u,u)
    b = np.dot(u,v)
    c = np.dot(v,v)
    d = np.dot(u,w)
    e = np.dot(v,w)
    D = a*c - b*b
    if D < epsilon:
        sc = 0.0
        tc = d/b if b>c else e/c
    else:
        sc = (b*e - c*d) / D
        tc = (a*e - b*d) / D
    dP = w + (sc * u) - (tc * v)
    return np.linalg.norm(dP)

It returns around 0.049 which is correct but when I tried to print
    w + (sc * u) or
    (tc * v) what I was thinking it was position,it printed me:

0.        ,   0.        , -19.82274615
3.8142822 , -7.22328672,  4.68097699

It's not correct.Coordinates I'm looking for for one of these points are:

-0.073455669 4.9843092 0.26107353

Algorithm I have found here


问:
How to make git gui not show untracked files
I have a lot of untracked files in my project. I would like to be able to tell git gui not to show them when showing the list of candidate-for-staging files. Is there a way to do that?

Similarly, it would be nice to be able to see only files in a certain .

Thank you for any help!

答:
Go to

Git Gui > Preferences

It has an option

Show untracked files

and uncheck it.


问:
Autofilter PHPExcel
I have an excel file who contains filter in a row.

I convert my excel file to HTML Table like that :

```<code>        $excel = glob(''.$path'.{xlsx,xls,xlsm,xlsm.ink}', GLOB_BRACE);
    $filterSubset = new \PHPExcel_Reader_DefaultReadFilter('A','N');
    $objReader = \PHPExcel_IOFactory::createReaderForFile($excel[0]);
    $objReader->setReadFilter($filterSubset);
    /**  Read the list of worksheet names and select the one that we want to load  **/
    $worksheetList = $objReader->listWorksheetNames($excel[0]);
    $sheetname = $worksheetList[0];
    /**  Advise the Reader of which WorkSheets we want to load  **/
    $objReader->setLoadSheetsOnly($sheetname);
    /**  Load $inputFileName to a PHPExcel Object  **/

    $objPHPExcel = $objReader->load($excel[0]);

    ### HERE I DONT KNOW WHAT TO DO ###

    $autoFilter = $objPHPExcel->getActiveSheet()->getAutoFilter();
    $autoFilter->showHideRows();

    var_dump($autoFilter);

    $objPHPExcel->getActiveSheet()->setAutoFilter('A1:N1');

    ### HELP ME PLEASE ###

    $writer = \PHPExcel_IOFactory::createWriter($objPHPExcel, "HTML");
    $writer->generateStyles();
    $writer->generateSheetData();
</code>```

I just wanna know how to apply and display my filters. range('A1:N1') .

Thanks for help

答: When you set Autofilter, you need to set the full range of data, not simply the headers; but Autofilter is only provided for native Excel formats only, and not available for HTML</p>

Title: Autofilter PHPExcel

Body:
I have an excel file who contains filter in a row.

I convert my excel file to HTML Table like that :

        $excel = glob(''.$path'.{xlsx,xls,xlsm,xlsm.ink}', GLOB_BRACE);
    $filterSubset = new \PHPExcel_Reader_DefaultReadFilter('A','N');
    $objReader = \PHPExcel_IOFactory::createReaderForFile($excel[0]);
    $objReader->setReadFilter($filterSubset);
    /**  Read the list of worksheet names and select the one that we want to load  **/
    $worksheetList = $objReader->listWorksheetNames($excel[0]);
    $sheetname = $worksheetList[0];
    /**  Advise the Reader of which WorkSheets we want to load  **/
    $objReader->setLoadSheetsOnly($sheetname);
    /**  Load $inputFileName to a PHPExcel Object  **/

    $objPHPExcel = $objReader->load($excel[0]);

    ### HERE I DONT KNOW WHAT TO DO ###

    $autoFilter = $objPHPExcel->getActiveSheet()->getAutoFilter();
    $autoFilter->showHideRows();

    var_dump($autoFilter);

    $objPHPExcel->getActiveSheet()->setAutoFilter('A1:N1');

    ### HELP ME PLEASE ###

    $writer = \PHPExcel_IOFactory::createWriter($objPHPExcel, "HTML");
    $writer->generateStyles();
    $writer->generateSheetData();

I just wanna know how to apply and display my filters. range('A1:N1') .

Thanks for help


问:
crontab to run python file if not running already
I want to execute my python file via crontab only if its down or not running already. I tried adding below entry in cron tab but it does not work

```<code>24 07 * * * pgrep -f test.py || nohup python /home/dp/script/test.py & > /var/tmp/test.out
</code>```

test.py works fine if i run  pgrep -f test.py || nohup python /home/dp/script/test.py & > /var/tmp/test.out manually and it also works in crontab if i remove pgrep -f test.py || from my crontab and just keep 24 07 * * * nohup python /home/dp/script/test.py & > /var/tmp/test.out

Any idea why crontab does not work if i add pgrep -f? is there any other way i can run test.py just one time to avoid multiple running processes of test.py?
Thanks,
Deepak

答:
Came across this old question looking for solution myself.

Use psutil:

```<code>import psutil
import sys
from subprocess import Popen

for process in psutil.process_iter():
    if process.cmdline() == ['python', 'your_script.py']:
        sys.exit('Process found: exiting.')

print('Process not found: starting it.')
Popen(['python', 'your_script.py'])
</code>```

You can also use start time of the previous process to determine if it's running too long and might be hung:

```<code>process.create_time()
</code>```

There is tons of other useful metadata of the process.

Body:
I want to execute my python file via crontab only if its down or not running already. I tried adding below entry in cron tab but it does not work

24 07 * * * pgrep -f test.py || nohup python /home/dp/script/test.py & > /var/tmp/test.out

test.py works fine if i run  pgrep -f test.py || nohup python /home/dp/script/test.py & > /var/tmp/test.out manually and it also works in crontab if i remove pgrep -f test.py || from my crontab and just keep 24 07 * * * nohup python /home/dp/script/test.py & > /var/tmp/test.out

Any idea why crontab does not work if i add pgrep -f? is there any other way i can run test.py just one time to avoid multiple running processes of test.py?
Thanks,
Deepak

Body:
Came across this old question looking for solution myself.

Use psutil:

import psutil
import sys
from subprocess import Popen

for process in psutil.process_iter():
    if process.cmdline() == ['python', 'your_script.py']:
        sys.exit('Process found: exiting.')

print('Process not found: starting it.')
Popen(['python', 'your_script.py'])

You can also use start time of the previous process to determine if it's running too long and might be hung:

process.create_time()

There is tons of other useful metadata of the process.


问:
UIImagePickerController delegate not called Swift 3
On the surface I thought that this had to be a delegate issue, but after asking for the delegate the right one was returned.

I created an ImagePicker class to handle all the UIImagePickerController stuff. Every thing works until the delegate methods need to be called. After I pick a photo, the imagePicker dismisses, but the didFinishPickingMediaWithInfo method never gets called. Please help! Thanks :)

```<code>func selectPhoto() {
    imagePicker.delegate = self //Delegate gets set here

    let photoAsk = UIAlertController.init( //Ask user if they want to take picture or choose one
        title: "Edit Profile Picture",
        message: nil,
        preferredStyle: .alert)
    let cameraAction = UIAlertAction.init(
        title: "Take Photo",
        style: .default) { (UIAlertAction) in
            if (UIImagePickerController.isSourceTypeAvailable(.camera)) {
                self.imagePicker.sourceType = .camera
                UIApplication.topViewController()!.present(self.imagePicker, animated: true, completion:nil)
            } else {
                print("Cannot access camera in simulator.")
                return
            }
    }
    let photoLibraryAction = UIAlertAction.init(
        title: "Photo Library",
        style: .default) { (UIAlertAction) in
            self.imagePicker.sourceType = .photoLibrary
            UIApplication.topViewController()!.present(self.imagePicker, animated: true, completion:nil)
            print("UIImagePickerDelegate: \(self.imagePicker.delegate.debugDescription)") // <--THIS PRINTS OUT "AppName.ImagePicker: 0x145d7bdf0>", and the class name is ImagePicker
    }
    let cancelAction = UIAlertAction.init(
        title: "Cancel",
        style: .cancel) { (UIAlertAction) in return }

    photoAsk.addAction(cameraAction)
    photoAsk.addAction(photoLibraryAction)
    photoAsk.addAction(cancelAction)

    imagePicker.mediaTypes = [kUTTypeImage as String]

    UIApplication.topViewController()?.present(photoAsk, animated: true, completion: nil)
    }
}
</code>```

This never gets called:

```<code>func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    print("Image picked.") //NEVER PRINTS
}
</code>```

答:
Yo have to make sure that UIImagePickerController was not released before delegate called.

I created an ImagePicker class to handle all the
  UIImagePickerController stuff.

I created similar class, but

```<code>func onButtonDidTap(sender: UIButton) {
.....
    let picker = VLImagePickerController()
    picker.show(fromSender: sender, handler: { (image: UIImage?) -> (Void) in
        if (image != nil) {
            self.setImage(image!)
        }
    })
....
}
</code>```

did not work for me.
'picker' was released before 'handler' could be called.

I created permanent reference, and it worked:

```<code>let picker = VLImagePickerController()

    func onButtonDidTap(sender: UIButton) {
    .....
            //let picker = VLImagePickerController()
            picker.show(fromSender: sender, handler: { (image: UIImage?) -> (Void) in
                if (image != nil) {
                    self.setImage(image!)
                }
            })
    ....
        }
</code>```

Body:
On the surface I thought that this had to be a delegate issue, but after asking for the delegate the right one was returned.

I created an ImagePicker class to handle all the UIImagePickerController stuff. Every thing works until the delegate methods need to be called. After I pick a photo, the imagePicker dismisses, but the didFinishPickingMediaWithInfo method never gets called. Please help! Thanks :)

func selectPhoto() {
    imagePicker.delegate = self //Delegate gets set here

    let photoAsk = UIAlertController.init( //Ask user if they want to take picture or choose one
        title: "Edit Profile Picture",
        message: nil,
        preferredStyle: .alert)
    let cameraAction = UIAlertAction.init(
        title: "Take Photo",
        style: .default) { (UIAlertAction) in
            if (UIImagePickerController.isSourceTypeAvailable(.camera)) {
                self.imagePicker.sourceType = .camera
                UIApplication.topViewController()!.present(self.imagePicker, animated: true, completion:nil)
            } else {
                print("Cannot access camera in simulator.")
                return
            }
    }
    let photoLibraryAction = UIAlertAction.init(
        title: "Photo Library",
        style: .default) { (UIAlertAction) in
            self.imagePicker.sourceType = .photoLibrary
            UIApplication.topViewController()!.present(self.imagePicker, animated: true, completion:nil)
            print("UIImagePickerDelegate: \(self.imagePicker.delegate.debugDescription)") // <--THIS PRINTS OUT "AppName.ImagePicker: 0x145d7bdf0>", and the class name is ImagePicker
    }
    let cancelAction = UIAlertAction.init(
        title: "Cancel",
        style: .cancel) { (UIAlertAction) in return }

    photoAsk.addAction(cameraAction)
    photoAsk.addAction(photoLibraryAction)
    photoAsk.addAction(cancelAction)

    imagePicker.mediaTypes = [kUTTypeImage as String]

    UIApplication.topViewController()?.present(photoAsk, animated: true, completion: nil)
    }
}

This never gets called:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    print("Image picked.") //NEVER PRINTS
}

Body:
Yo have to make sure that UIImagePickerController was not released before delegate called.

I created an ImagePicker class to handle all the
  UIImagePickerController stuff.

I created similar class, but

func onButtonDidTap(sender: UIButton) {
.....
    let picker = VLImagePickerController()
    picker.show(fromSender: sender, handler: { (image: UIImage?) -> (Void) in
        if (image != nil) {
            self.setImage(image!)
        }
    })
....
}

did not work for me.
'picker' was released before 'handler' could be called.

I created permanent reference, and it worked:

let picker = VLImagePickerController()

    func onButtonDidTap(sender: UIButton) {
    .....
            //let picker = VLImagePickerController()
            picker.show(fromSender: sender, handler: { (image: UIImage?) -> (Void) in
                if (image != nil) {
                    self.setImage(image!)
                }
            })
    ....
        }


问:
Unresolved Promise issue in Node.js
I'm getting an unresolved Promise.

I have this function:

```<code>export async function readData(dir) {
await fs.readFile(dir, `utf-8`, (err, data) => {
    if (err) throw err
    console.log("data1:", data)
    return data
})
}
</code>```

Which I'm calling from this function:

```<code>app.get('/server/survey', (ctx) => {
let dir = path.join(__dirname, 'src/DB/index.json')
let data = funcs.readData(dir)
data.then((result) => {
    console.log("Content:", result)
    ctx.body = `${result}`
})
</code>```

The first one logs out the data correctly but the second logs out an unresolved Promise.

答:
fs.readFile() doesn't return a promise, so you can't await on it.

You have to wrap it with a promise manually:

```<code>export function readData(dir) {
  return new Promise((resolve, reject) => {
    fs.readFile(dir, `utf-8`, (err, data) => {
      if (err) return reject(err);
      console.log("data1:", data);
      return resolve(data);
    })
  });
}
</code>```

Or promisify fs.readFile, for instance using Node v8's util.promisify:

```<code>const util     = require('util');
const fs       = require('fs');
const readFile = util.promisify(fs.readFile);

async function readData(dir) {
  let data = await readFile(dir, `utf-8`);
  console.log("data1:", data)
  return data;
}
</code>```

Instead of using Node v8, you can also use a library like bluebird that provides promisification.

Notice in the await example that the callback is not being used anymore.

Title: Unresolved Promise issue in Node.js

Body:
I'm getting an unresolved Promise.

I have this function:

export async function readData(dir) {
await fs.readFile(dir, `utf-8`, (err, data) => {
    if (err) throw err
    console.log("data1:", data)
    return data
})
}

Which I'm calling from this function:

app.get('/server/survey', (ctx) => {
let dir = path.join(__dirname, 'src/DB/index.json')
let data = funcs.readData(dir)
data.then((result) => {
    console.log("Content:", result)
    ctx.body = `${result}`
})

The first one logs out the data correctly but the second logs out an unresolved Promise.

Body:
fs.readFile() doesn't return a promise, so you can't await on it.

You have to wrap it with a promise manually:

export function readData(dir) {
  return new Promise((resolve, reject) => {
    fs.readFile(dir, `utf-8`, (err, data) => {
      if (err) return reject(err);
      console.log("data1:", data);
      return resolve(data);
    })
  });
}

Or promisify fs.readFile, for instance using Node v8's util.promisify:

const util     = require('util');
const fs       = require('fs');
const readFile = util.promisify(fs.readFile);

async function readData(dir) {
  let data = await readFile(dir, `utf-8`);
  console.log("data1:", data)
  return data;
}

Instead of using Node v8, you can also use a library like bluebird that provides promisification.

Notice in the await example that the callback is not being used anymore.


问:
Sampling a list with linq
I need a helper method for adding axis labels to a chart. I don't want to add a label at every point along the axis that has values in the chart because that would get too busy. So I need to extract samples at regular intervals. So far I've come up with the following method which meets the requirements but I think there must be a neater way of accomplishing this with Linq. Can anyone think of how this could be made more concise (n represents the total number of samples I want back)?</p>

```<code>public static List<T> Sample<T>(this List<T> list, int n)
{
  var samples = new List<T>();
  var divisor = list.Count/n;
  for (var i = 0; i < list.Count; i++)
    if (samples.Count == i/divisor)
      samples.Add(list[i]);
  return samples;
}
</code>```

答:
Try</p>

```<code>list.Where((o, index) => index % divisor == 0)
</code>```

Title: Sampling a list with linq

Body:
I need a helper method for adding axis labels to a chart. I don't want to add a label at every point along the axis that has values in the chart because that would get too busy. So I need to extract samples at regular intervals. So far I've come up with the following method which meets the requirements but I think there must be a neater way of accomplishing this with Linq. Can anyone think of how this could be made more concise (n represents the total number of samples I want back)?

public static List<T> Sample<T>(this List<T> list, int n)
{
  var samples = new List<T>();
  var divisor = list.Count/n;
  for (var i = 0; i < list.Count; i++)
    if (samples.Count == i/divisor)
      samples.Add(list[i]);
  return samples;
}

Body:
Try

list.Where((o, index) => index % divisor == 0)


问:
C# Find Closest Time greater than DateTime.Now
Im struggling to get my little function to work.

What I'm trying to do:

I have an ObservableCollection of parsed DateTimes like

```<code>{"13:00","14:00,"17:00","22:00","22:00"}
</code>```

and i want the closest time greater than the current DateTime.Now.

Code:

```<code>private DateTime GetNearestTime() {

    var nearestTime= (from x in TimeCollection
                      where x.MyTimeProperty.Ticks > DateTime.Now.Ticks
                      orderby x.MyTimeProperty.Ticks ascending
                      select x).First();
    return nearestTime;
}
</code>```

What I'm getting is 1 value greater than the expected value.

Edit:

values for better understanding

```<code>var now = DateTime.Now.TimeOfDay // {18:32:35.4378850}
</code>```

DateTime.TimeOfDay values in the collection.

```<code>[0:] 03:03:00
[0:] 05:03:00
[0:] 13:01:00
[0:] 17:16:00
[0:] 17:16:00
[0:] 23:01:00
</code>```

The Collection is of type:

```<code>public class TimeData
{
   public DateTime MyTimeProperty {get;set;}
}
</code>```

答:
If you don't care about the date portion, then TimeOfDay is the appropriate property to compare:

```<code>private DateTime GetNearestTime()
{
    var now = DateTime.Now.TimeOfDay;
    var nearestTime= (from x in TimeCollection
                      where x.MyTimeProperty.TimeOfDay > now
                      orderby x.MyTimeProperty.TimeOfDay ascending
                      select x).First();
    return nearestTime;
}
</code>```

The Ticks property is documented as:

The value of this property represents the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001 (0:00:00 UTC on January 1, 0001, in the Gregorian calendar), which represents DateTime.MinValue. It does not include the number of ticks that are attributable to leap seconds.

Body:
Im struggling to get my little function to work.

What I'm trying to do:

I have an ObservableCollection of parsed DateTimes like

{"13:00","14:00,"17:00","22:00","22:00"}

and i want the closest time greater than the current DateTime.Now.

Code:

private DateTime GetNearestTime() {

    var nearestTime= (from x in TimeCollection
                      where x.MyTimeProperty.Ticks > DateTime.Now.Ticks
                      orderby x.MyTimeProperty.Ticks ascending
                      select x).First();
    return nearestTime;
}

What I'm getting is 1 value greater than the expected value.

Edit:

values for better understanding

var now = DateTime.Now.TimeOfDay // {18:32:35.4378850}

DateTime.TimeOfDay values in the collection.

[0:] 03:03:00
[0:] 05:03:00
[0:] 13:01:00
[0:] 17:16:00
[0:] 17:16:00
[0:] 23:01:00

The Collection is of type:

public class TimeData
{
   public DateTime MyTimeProperty {get;set;}
}

Body:
If you don't care about the date portion, then TimeOfDay is the appropriate property to compare:

private DateTime GetNearestTime()
{
    var now = DateTime.Now.TimeOfDay;
    var nearestTime= (from x in TimeCollection
                      where x.MyTimeProperty.TimeOfDay > now
                      orderby x.MyTimeProperty.TimeOfDay ascending
                      select x).First();
    return nearestTime;
}

The Ticks property is documented as:

The value of this property represents the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001 (0:00:00 UTC on January 1, 0001, in the Gregorian calendar), which represents DateTime.MinValue. It does not include the number of ticks that are attributable to leap seconds.


问:
centering an SVG inside a div
I want to display an SVG image inside a position:fixed div. I have

```<code><div class="main">
  <svg class="svg" viewBox="0 0 180 100">
    <rect height="100%" width="100%" fill="#003300"></rect>
  </svg>
</div>
</code>```

and style

```<code>.main {
  position:fixed;
  left: 100px;
  height: 100%;
  width:100%;
  background: #33AAAA;
}

.svg {
  display: block;
  height: 100%;
  width: 100%;
  position:static;
}
</code>```

I want to center the SVG horizontally and vertically. I get a strange behavior. Changing the size of the browser window, shows that when the svg is smaller than available width, it is weirdly placed. For example:  there is more space on the left than on the right.

Codepen (including CSS reset): Codepen

答:
It looks like its because you have the left: 100px in your main class. If you take that out it centers correctly.

here is the main class that should work:

```<code>.main {
  position:fixed;
  left:100px;
  height: 100%;
  right: 0;
  top:0;
  bottom:0;
  background: #33AAAA;
}
</code>```

Title: centering an SVG inside a div

Body:
I want to display an SVG image inside a position:fixed div. I have

  <svg class="svg" viewBox="0 0 180 100">
    <rect height="100%" width="100%" fill="#003300"></rect>
  </svg>

and style

.main {
  position:fixed;
  left: 100px;
  height: 100%;
  width:100%;
  background: #33AAAA;
}

.svg {
  display: block;
  height: 100%;
  width: 100%;
  position:static;
}

I want to center the SVG horizontally and vertically. I get a strange behavior. Changing the size of the browser window, shows that when the svg is smaller than available width, it is weirdly placed. For example:  there is more space on the left than on the right.

Codepen (including CSS reset): Codepen

Body:
It looks like its because you have the left: 100px in your main class. If you take that out it centers correctly.

here is the main class that should work:

.main {
  position:fixed;
  left:100px;
  height: 100%;
  right: 0;
  top:0;
  bottom:0;
  background: #33AAAA;
}


问:
jquery validate notEqualTo added method
From another, older stack post that looked like it would do exactly as needed, I added a method to validator that (should) compare an input to a list of banned values and then return an error message if the input is on the list.

```<code>jQuery.validator.addMethod('notEqualTo',function(value, element, param) {
    var notEqual = true;
    value = $.trim(value);
      for (i = 0; i < param.length; i++) {
        if (value == $.trim($(param[i]).val())) { notEqual = false; }
      }
      return this.optional(element) || notEqual;
        },"The value you entered is not permitted in this field.");
</code>```

The problem seems to be in the comparison.  No matter what I specify as the banned value, this always returns true, when it looks like it should return false on a match.

```<code>userloginname: {
    required: true,
    notEqualTo: ['password','anotherword','#email']
</code>```

Using the above, if the user entered "password", "anotheword", or the username matched the e-mail field, it should set notEqual = false and throw the error.

答:
You seem to be treating strings that represent words and strings that represent the id of another element as the same thing.

```<code>notEqualTo: ['password','anotherword','#email']
</code>```

The root problem for the first two parameters is here:

```<code>if (value == $.trim($(param[i]).val()))
</code>```

.val() is only for retrieving the value of a form element.  You are incorrectly attaching it to param which is a variable that represents a word.

Wrapping param[i] within a jQuery function, $(), turns this variable into a jQuery object, which is what you don't need in the case of the firs two parameters.

Simply compare the two variables...

```<code>if (value === param[i])
</code>```

DEMO:  jsfiddle.net/kwxtvur8/

That being said, if your third parameter is the value of another field, then you'll need to handle this separately from the other parameters that are strings.  I recommend one method to handle comparing the value to words (as in my demo), and another totally separate method for comparing the value of this field to another field's value.

```<code>$('#myform').validate({
    rules: {
        userloginname: {
            required: true,
            notEqualTo: ['password', 'anotherword'],
            notEqual: '#email'
        }
    }
    ....
</code>```

notEqual method:

```<code>jQuery.validator.addMethod('notEqual', function(value, element, param) {
    value = $.trim(value);
    return this.optional(element) || (value !== $.trim($(param).val()));
}, "The value you entered is not permitted in this field.");
</code>```

DEMO 2:  jsfiddle.net/hp1dgcug/

Title: jquery validate notEqualTo added method

Body:
From another, older stack post that looked like it would do exactly as needed, I added a method to validator that (should) compare an input to a list of banned values and then return an error message if the input is on the list.

jQuery.validator.addMethod('notEqualTo',function(value, element, param) {
    var notEqual = true;
    value = $.trim(value);
      for (i = 0; i < param.length; i++) {
        if (value == $.trim($(param[i]).val())) { notEqual = false; }
      }
      return this.optional(element) || notEqual;
        },"The value you entered is not permitted in this field.");

The problem seems to be in the comparison.  No matter what I specify as the banned value, this always returns true, when it looks like it should return false on a match.

userloginname: {
    required: true,
    notEqualTo: ['password','anotherword','#email']

Using the above, if the user entered "password", "anotheword", or the username matched the e-mail field, it should set notEqual = false and throw the error.

Body:
You seem to be treating strings that represent words and strings that represent the id of another element as the same thing.

notEqualTo: ['password','anotherword','#email']

The root problem for the first two parameters is here:

if (value == $.trim($(param[i]).val()))

.val() is only for retrieving the value of a form element.  You are incorrectly attaching it to param which is a variable that represents a word.

Wrapping param[i] within a jQuery function, $(), turns this variable into a jQuery object, which is what you don't need in the case of the firs two parameters.

Simply compare the two variables...

if (value === param[i])

DEMO:  jsfiddle.net/kwxtvur8/

That being said, if your third parameter is the value of another field, then you'll need to handle this separately from the other parameters that are strings.  I recommend one method to handle comparing the value to words (as in my demo), and another totally separate method for comparing the value of this field to another field's value.

$('#myform').validate({
    rules: {
        userloginname: {
            required: true,
            notEqualTo: ['password', 'anotherword'],
            notEqual: '#email'
        }
    }
    ....

notEqual method:

jQuery.validator.addMethod('notEqual', function(value, element, param) {
    value = $.trim(value);
    return this.optional(element) || (value !== $.trim($(param).val()));
}, "The value you entered is not permitted in this field.");

DEMO 2:  jsfiddle.net/hp1dgcug/


问:
Duo Security API with python client
I'm trying to work with Duo's python client (https://github.com/duosecurity/duo_client_python) and I believe I'm simply missing something with my novice python eyes.  I somehow need to authenticate my requests to the API using an HMAC signature -- which I've not worked with before but seems trivial to generate (they even provide a python function).  Doc here https://duo.com/docs/adminapi#authentication

I'm at a loss as to HOW to craft this signature for authentication, prior to passing my request to the API.  From https://duo.com/docs/adminapi#authentication:

The API uses HTTP Basic Authentication to authenticate requests. Use your >Duo application’s integration key as the HTTP Username.

Generate the HTTP Password as an HMAC signature of the request. This will >be different for each request and must be re-generated each time.

It then goes into which parameters are added and necessary for the HMAC signature to be generated properly.  I understand this part.  My issue is how and when to pass the HMAC signature that I generate.  As the Duo doc doesn't specifically go into that, I'm thinking that this is something I should already know [were I not such a python novice].

For example, simple auth calls work fine (as they need no authentication):

```root@box:~# python -m duo_client.client --ikey XXXXXXXX --skey XXXXXXXX --host XXXXXXXX.duosecurity.com --method GET --path /auth/v2/check 200 OK
{
"response":
{ "time": 1496437236 }
,
"stat": "OK"
}```

However, calls using admin require authentication, and thus fail with:

```root@box:~# python -m duo_client.client --ikey XXXXXXXX --skey XXXXXXXX --host XXXXXXXX.duosecurity.com --method GET --path /admin/v1/users signature=XXXXXXXX
401 Unauthorized
{
    "code": 40103,
    "message": "Invalid signature in request credentials",
    "stat": "FAIL"
}```

Thanks in advance for any insight!

==EDIT==

So I thought I'd post the function that Duo provide for creating the signature, which appears similar to what is happening in the StackOverflow question I found that I thought might help (Python, HTTPS GET with basic authentication).  From https://duo.com/docs/adminapi#authentication:

```
def sign(method, host, path, params, skey, ikey):
    """
    Return HTTP Basic Authentication ("Authorization" and "Date") headers.
    method, host, path: strings from request
    params: dict of request parameters
    skey: secret key
    ikey: integration key
    """

    # create canonical string
    now = email.Utils.formatdate()
    canon = [now, method.upper(), host.lower(), path]
    args = []
    for key in sorted(params.keys()):
        val = params[key]
        if isinstance(val, unicode):
            val = val.encode("utf-8")
        args.append(
            '%s=%s' % (urllib.quote(key, '~'), urllib.quote(val, '~')))
    canon.append('&'.join(args))
    canon = '\n'.join(canon)

    # sign canonical string
    sig = hmac.new(skey, canon, hashlib.sha1)
    auth = '%s:%s' % (ikey, sig.hexdigest())

    # return headers
    return {'Date': now, 'Authorization': 'Basic %s' % base64.b64encode(auth)}
```

I've used the above function in a simple script to print out (just so I can visualize) what should be getting passed within the script I'll create to server our needs -- I added the function to a script and used print by adding the following:

```
# Printing Signature Headers ### TESTING ###
print sign('GET', 'XXXhostXXX', '/admin/v1/users', 'XXXparamXXX', 'XXXskeyXXX', 'XXXXikeyXXXX')
```

However, I'm getting this error:

```
root@box:~# ./duo.py
Traceback (most recent call last):
  File "./duo.py", line 39, in
    print sign('GET', 'XXXhostXXX', '/admin/v1/users', 'XXXparamXXX', 'XXXskeyXXX', 'XXXikeyXXX')
  File "./duo.py", line 18, in sign
    for key in sorted(params.keys()):
AttributeError: 'str' object has no attribute 'keys'
```

Am I just missing something here?  I've been looking for what could cause that error but I thought I'd ask here as well.

答: This was an "issue" on Duo's side...wrong skey was being used and my user did not have the proper access.</p>

Title: Duo Security API with python client

Body:
I'm trying to work with Duo's python client (https://github.com/duosecurity/duo_client_python) and I believe I'm simply missing something with my novice python eyes.  I somehow need to authenticate my requests to the API using an HMAC signature -- which I've not worked with before but seems trivial to generate (they even provide a python function).  Doc here https://duo.com/docs/adminapi#authentication

I'm at a loss as to HOW to craft this signature for authentication, prior to passing my request to the API.  From https://duo.com/docs/adminapi#authentication:

The API uses HTTP Basic Authentication to authenticate requests. Use your >Duo application’s integration key as the HTTP Username.

Generate the HTTP Password as an HMAC signature of the request. This will >be different for each request and must be re-generated each time.

It then goes into which parameters are added and necessary for the HMAC signature to be generated properly.  I understand this part.  My issue is how and when to pass the HMAC signature that I generate.  As the Duo doc doesn't specifically go into that, I'm thinking that this is something I should already know [were I not such a python novice].

For example, simple auth calls work fine (as they need no authentication):

root@box:~# python -m duo_client.client --ikey XXXXXXXX --skey XXXXXXXX --host XXXXXXXX.duosecurity.com --method GET --path /auth/v2/check 200 OK
{
"response":
{ "time": 1496437236 }
,
"stat": "OK"
}

However, calls using admin require authentication, and thus fail with:

root@box:~# python -m duo_client.client --ikey XXXXXXXX --skey XXXXXXXX --host XXXXXXXX.duosecurity.com --method GET --path /admin/v1/users signature=XXXXXXXX
401 Unauthorized
{
    "code": 40103,
    "message": "Invalid signature in request credentials",
    "stat": "FAIL"
}

Thanks in advance for any insight!

==EDIT==

So I thought I'd post the function that Duo provide for creating the signature, which appears similar to what is happening in the StackOverflow question I found that I thought might help (Python, HTTPS GET with basic authentication).  From https://duo.com/docs/adminapi#authentication:

def sign(method, host, path, params, skey, ikey):
    """
    Return HTTP Basic Authentication ("Authorization" and "Date") headers.
    method, host, path: strings from request
    params: dict of request parameters
    skey: secret key
    ikey: integration key
    """

    # create canonical string
    now = email.Utils.formatdate()
    canon = [now, method.upper(), host.lower(), path]
    args = []
    for key in sorted(params.keys()):
        val = params[key]
        if isinstance(val, unicode):
            val = val.encode("utf-8")
        args.append(
            '%s=%s' % (urllib.quote(key, '~'), urllib.quote(val, '~')))
    canon.append('&'.join(args))
    canon = '\n'.join(canon)

    # sign canonical string
    sig = hmac.new(skey, canon, hashlib.sha1)
    auth = '%s:%s' % (ikey, sig.hexdigest())

    # return headers
    return {'Date': now, 'Authorization': 'Basic %s' % base64.b64encode(auth)}

I've used the above function in a simple script to print out (just so I can visualize) what should be getting passed within the script I'll create to server our needs -- I added the function to a script and used print by adding the following:

# Printing Signature Headers ### TESTING ###
print sign('GET', 'XXXhostXXX', '/admin/v1/users', 'XXXparamXXX', 'XXXskeyXXX', 'XXXXikeyXXXX')

However, I'm getting this error:

root@box:~# ./duo.py
Traceback (most recent call last):
  File "./duo.py", line 39, in
    print sign('GET', 'XXXhostXXX', '/admin/v1/users', 'XXXparamXXX', 'XXXskeyXXX', 'XXXikeyXXX')
  File "./duo.py", line 18, in sign
    for key in sorted(params.keys()):
AttributeError: 'str' object has no attribute 'keys'

Am I just missing something here?  I've been looking for what could cause that error but I thought I'd ask here as well.


问:
Get field values using reflection
I am not able to get the field value.What I am trying to do is get the Object at runtime. Please let me know where I am going wrong.

Test.class

```<code>import java.lang.reflect.Field;

public class Test {

public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException,
        IllegalArgumentException, IllegalAccessException {

    final Field field = Class.forName("com.logging.EX").getDeclaredField("value");
    field.setAccessible(true);
    field.get(Class.forName("com.logging.EX"));
}
</code>```

}

EX.class

```<code>public class EX {

private String value;

public EX(){
    value="data";
}
/**
 * @return the value
 */
public String getValue() {
    return value;
}

/**
 * @param value
 *            the value to set
 */
public void setValue(String value) {
    this.value = value;
}
</code>```

}

答:
So, have got the below answer. It is working fine for now. Not sure whether this is the best one to follow.

Your Test class :

```<code>public class Test {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException,
            IllegalArgumentException, IllegalAccessException, InstantiationException {

        Field[] fields = Class.forName("com.logging.EX").newInstance().getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            System.out.println(field.getName() + " : " + field.get(Class.forName("com.logging.EX").newInstance()));
        }

    }
}
</code>```

I'm extracting all the fields in to an array by invoking the instance of com.logging.EX and then loops through all the fields and extracts the name and the value the field holds. Haven't hardcoded any field name here.

There are few security caveats with mine as I've accessed the variable with private access modifier but that always exists with reflection.  Just a disclaimer!

Hope this helps!

Title: Get field values using reflection

Body:
I am not able to get the field value.What I am trying to do is get the Object at runtime. Please let me know where I am going wrong.

Test.class

import java.lang.reflect.Field;

public class Test {

public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException,
        IllegalArgumentException, IllegalAccessException {

    final Field field = Class.forName("com.logging.EX").getDeclaredField("value");
    field.setAccessible(true);
    field.get(Class.forName("com.logging.EX"));
}

}

EX.class

public class EX {

private String value;

public EX(){
    value="data";
}
/**
 * @return the value
 */
public String getValue() {
    return value;
}

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

}

Body:
So, have got the below answer. It is working fine for now. Not sure whether this is the best one to follow.

Your Test class :

public class Test {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException,
            IllegalArgumentException, IllegalAccessException, InstantiationException {

        Field[] fields = Class.forName("com.logging.EX").newInstance().getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            System.out.println(field.getName() + " : " + field.get(Class.forName("com.logging.EX").newInstance()));
        }

    }
}

I'm extracting all the fields in to an array by invoking the instance of com.logging.EX and then loops through all the fields and extracts the name and the value the field holds. Haven't hardcoded any field name here.

There are few security caveats with mine as I've accessed the variable with private access modifier but that always exists with reflection.  Just a disclaimer!

Hope this helps!


问:
Using Caffe in C++; Unable to pass caffe::SolverParameter to function without error
I am attempting to compile the "Hello World XOR" C++ example given by:

https://medium.com/@shiyan/caffe-c-helloworld-example-with-memorydata-input-20c692a82a22

Hardware:
EX50-UD3R Motherboard
GT-640 NVidia cards (2 Cards)
Intel 980 (6 core)
16Gig (4x4) DDR3 RAM

Environment:
Ubuntu 16.04.2 LTS   Kernel: 4.4.0-78-generic
Eclipse Neon3 R4.6.3
CUDA 8.0
Caffe:  whatever ver I downloaded from Berkley on 06/04/2017

I followed the installation instructions for installing Caffe in Ubuntu 16.04:  https://github.com/BVLC/caffe/wiki/Ubuntu-16.04-or-15.10-Installation-Guide

and all the make commands succeeded.

However when I try to use the libraries in a simple cpp program:

```<code>#include <memory>

#include <cstdlib>    // Provides NULL, rand, size_t;
#include <stdio.h>  // For printf
#include <cstring>  // For string
#include "/home/caffe-master/include/caffe/layers/memory_data_layer.hpp"
#include "/home/caffe-master-path>/include/caffe/caffe.hpp"

void blah( caffe::SolverParameter *sp);

int main()
{
... standard c++ code to generate random data deleted for brevity...
    caffe::SolverParameter solver_param;  // No errors given here for this declaration

    blah( solver_param);   // Simple function created to test error, same error appears here

    caffe::ReadSolverParamsFromTextFileOrDie( path, &solver_param);  // Actual function from XOR example, same error

    caffe::ReadSolverParamsFromTextFileOrDie("./solver.prototxt", &solver_param);  // This also gives same error

    boost::shared_ptr<caffe::Solver<float> > solver(caffe::SolverRegistry<float>::CreateSolver(solver_param)); // Same error here

... code that would of passed random data to caffe deleted ...
    return 0;
}

void blah( caffe::SolverParameter *sp)
{
    std::cout << "BLAH: " << sp->rms_decay_;
    return;
}
</code>```

In Eclipse Neon I get the following error for any line that includes the variable solver_param including the lines that where I created the simple function blah which takes one argument of type caffe::SolverParameter *

Invalid arguments 'Candidates are:
void ReadSolverParamsFromTextFileOrDie(const std::__cxx11::basic_string,std::allocator> &, ? *)'  caffe_hellow.cpp    /caffe  line 47 Semantic Error

I tried setting the full paths in the include path and that got rid of some errors, I added the libpath in eclipse to include caffe and boost and that got rid of more errors leaving only this one for now. I've been searching for a solution, looking at the .hpp caffe files to try to understand them and trying different settings in eclipse to get rid of this error but nothing works.  Casting did not work either.

For some reason it does not recognize any variable declared as type SolverParameter as a compatible argument to a function that requires it.  The error message gives "? *" as the argument type.  What does that mean?  Can you help?  Thank you.

答:
I am able to compile now. It is a consequence of being a noob at using IDE.
I had to add the libraries in Project->Properties->GCC C++ Linker-> Libraries (-l):
caffe
boost_system
glog
... and this may not be needed ... cuda

I also needed to add -L paths for the above. Then I needed to update either /etc/environment or .bashrc to include the paths for caffe and cuda in the LD_LIBRARY_PATH variable otherwise I would get an unable t link binary error. Again cuda may not be needed to solve this error the other three sure are.  I plan to use Cuda-C to access the GPU processors.   Thank you Shai for your response on the protoc item it lead me to the other comments on including libraries.

Body:
I am attempting to compile the "Hello World XOR" C++ example given by:

https://medium.com/@shiyan/caffe-c-helloworld-example-with-memorydata-input-20c692a82a22

Hardware:
EX50-UD3R Motherboard
GT-640 NVidia cards (2 Cards)
Intel 980 (6 core)
16Gig (4x4) DDR3 RAM

Environment:
Ubuntu 16.04.2 LTS   Kernel: 4.4.0-78-generic
Eclipse Neon3 R4.6.3
CUDA 8.0
Caffe:  whatever ver I downloaded from Berkley on 06/04/2017

I followed the installation instructions for installing Caffe in Ubuntu 16.04:  https://github.com/BVLC/caffe/wiki/Ubuntu-16.04-or-15.10-Installation-Guide

and all the make commands succeeded.

However when I try to use the libraries in a simple cpp program:

#include <memory>

#include <cstdlib>    // Provides NULL, rand, size_t;
#include <stdio.h>  // For printf
#include <cstring>  // For string
#include "/home/caffe-master/include/caffe/layers/memory_data_layer.hpp"
#include "/home/caffe-master-path>/include/caffe/caffe.hpp"

void blah( caffe::SolverParameter *sp);

int main()
{
... standard c++ code to generate random data deleted for brevity...
    caffe::SolverParameter solver_param;  // No errors given here for this declaration

    blah( solver_param);   // Simple function created to test error, same error appears here

    caffe::ReadSolverParamsFromTextFileOrDie( path, &solver_param);  // Actual function from XOR example, same error

    caffe::ReadSolverParamsFromTextFileOrDie("./solver.prototxt", &solver_param);  // This also gives same error

    boost::shared_ptr<caffe::Solver<float> > solver(caffe::SolverRegistry<float>::CreateSolver(solver_param)); // Same error here

... code that would of passed random data to caffe deleted ...
    return 0;
}

void blah( caffe::SolverParameter *sp)
{
    std::cout << "BLAH: " << sp->rms_decay_;
    return;
}

In Eclipse Neon I get the following error for any line that includes the variable solver_param including the lines that where I created the simple function blah which takes one argument of type caffe::SolverParameter *

Invalid arguments 'Candidates are:
void ReadSolverParamsFromTextFileOrDie(const std::__cxx11::basic_string,std::allocator> &, ? *)'  caffe_hellow.cpp    /caffe  line 47 Semantic Error

I tried setting the full paths in the include path and that got rid of some errors, I added the libpath in eclipse to include caffe and boost and that got rid of more errors leaving only this one for now. I've been searching for a solution, looking at the .hpp caffe files to try to understand them and trying different settings in eclipse to get rid of this error but nothing works.  Casting did not work either.

For some reason it does not recognize any variable declared as type SolverParameter as a compatible argument to a function that requires it.  The error message gives "? *" as the argument type.  What does that mean?  Can you help?  Thank you.


问:
Finding memory violations/leaks
I have an application developed in VC 2008 (C++) which uses axis dlls, which use openssl dlls. And someone in the chain corrupts heap - a situation which ends up giving me "memory access violation" in my application in places where violation shouldn't/couldn't happen. So, someone in the chain axis-ssl corrupts something, but I cannot find who or what.

I tried using DevPartner's tool for memory leaks, but it finds no leaks - no anything.

How should I approach this problem? I looked over axis and ssl documentation a number of times, and implemented and checked all possible memory management issues and fixes, but to no avail.

Thank you very much!
Marin

答: Why do you think a leak could be somehow responsible for a corruption? You'd need to watch out for out-of-bounds access, dead pointer access, illegal casts and things like that, not for a leak. It's a tricky thing to do. Valgrind is a great tool for chasing this sort of issues, but unfortunately it's not available for Win32. If your code is portable, you could try debugging it on Linux, otherwise you'd either need to use commercial tools like Purify, or do it the good old way, with a help of logging and assertions, and a debugger of course.</p>

Title: Finding memory violations/leaks


问:
Add selection to range in jquery
I have a problem. For example I have a
Helloworld
. And now I want to select (for example) 5th to 9th word. So, I want to have Helloworld ("worl" is hightlighted). Any ideas, how to do this?

答:
Collect the innerHTML using .html() or .text().

HTML

```<code><div id="id">Helloworld</div>
</code>```

CSS

```<code>.highlight {
  background-color: yellow;
}
</code>```

JavaScript

```<code>$(function(){
  var myText = $("#id").html();
  var newText = myText.slice(0,5) + "<span class='highlight'>" + myText.slice(5,9) + "</span>" + myText.slice(9);
  $("#id").html(newText);
});
</code>```

Example: https://jsfiddle.net/Twisty/t0yu8pce/

Update

Example: https://jsfiddle.net/Twisty/t0yu8pce/2/

JavaScript

```<code>$(function() {
  var myText = $("#id").html();
  var newText = myText.slice(0, 5) + "<input value='" + myText.slice(5, 9) + "' />" + myText.slice(9);
  $("#id").html(newText);
  $("#highlight").click(function(e) {
    $("#id input:text").select();
  })
});
</code>```

The text to select has to be in a <input> or <textbox> element.

Update 2

Using click: https://jsfiddle.net/Twisty/t0yu8pce/3/

Title: Add selection to range in jquery

Body:
Collect the innerHTML using .html() or .text().

HTML

<div id="id">Helloworld</div>

CSS

.highlight {
  background-color: yellow;
}

JavaScript

$(function(){
  var myText = $("#id").html();
  var newText = myText.slice(0,5) + "<span class='highlight'>" + myText.slice(5,9) + "</span>" + myText.slice(9);
  $("#id").html(newText);
});

Example: https://jsfiddle.net/Twisty/t0yu8pce/

Update

Example: https://jsfiddle.net/Twisty/t0yu8pce/2/

JavaScript

$(function() {
  var myText = $("#id").html();
  var newText = myText.slice(0, 5) + "<input value='" + myText.slice(5, 9) + "' />" + myText.slice(9);
  $("#id").html(newText);
  $("#highlight").click(function(e) {
    $("#id input:text").select();
  })
});

The text to select has to be in a <input> or <textbox> element.

Update 2

Using click: https://jsfiddle.net/Twisty/t0yu8pce/3/