问:
Hide or display checkboxes if checked or not JavaScript
I got a problem with some checkboxes, I don't succeed to filter them according if they are checked or not.

The principle is simple. If I click on "All" all the checkboxes are displayed, but if I click on selected, I just want to see the checkboxes selected and hidde the ones unchecked.

Here is a snippet, please update it in your answer to let me see how it could be done.

Thanks a lot !

//array of options
var choices = new Array();
choices[0] = "January";
choices[1] = "February";
choices[2] = "March";
choices[3] = "April";
choices[4] = "May";
choices[5] = "Juny";
choices[6] = "July";
choices[7] = "August";
choices[8] = "September";
choices[9] = "October";
choices[10] = "November";
choices[11] = "December";

var target = new Array()
target[0] = "5";
target[1] = "8";

var cbh = document.getElementById('checkboxes');
var val = '';
var cap = "";

var j = "";
var t = document.getElementById('t');

// the loop is creating the checkboxes with name, value...
for (var i in choices) {
  //Name of checkboxes are their number so I convert the i into a string.
  j = i.toString();

  val = j;
  //cap will be the value/text of choices[i]
  var cb = document.createElement('input');
  var label = document.createElement("label");

  cap = choices[i];
  var text = document.createTextNode(cap);
  cb.type = 'checkbox';
  cbh.appendChild(cb);
  cb.name = cap;
  cb.value = val;
  label.appendChild(cb);
  label.appendChild(text);
  cbh.appendChild(label);
  cb.addEventListener('click', updateText)
  if(target.indexOf(i)>=0){
    cb.checked =true ;
  }

}
updateText();
function updateText() {
  t.value = [null, ...document.querySelectorAll('#checkboxes [type="checkbox"]')].reduce((s, el) => el && el.checked ? s = (s || '') + el.value + '$#' : s || '')
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>   * {
       box-sizing: border-box;
   }
   #data {
       padding:5px;
    width:100vw;
   }
   .multiselect {
    overflow: visible;
    padding:0;
    padding-left:1px;
    border:none;
    background-color:#eee;
    width:100vw;
    white-space: normal;
    height:200px;
   }
   .checkboxes {
    height:100px;
    width:100px;
    border:1px solid #000;
    background-color:white;
    margin-left:-1px;
    display:inline-block;
   }

            label {
    display: inline-block;
    border: 1px grey solid;
    padding:5px;
   }</code>```

 All | Selected
 <form>

</form>
<textarea id="t"></textarea>```

答:
You could select all the checked elements with checked selector, so you could show/hide its parent:

```<code>  $("#chkAll").click(function(){
    $(":checkbox").parent().show();
  });

  $("#chkSelected").click(function(){
    $(":checkbox").parent().hide();
    $(":checked").parent().show();
  });
</code>```

Here your updated snippet:

$(document).ready(function(){
  //array of options
  var choices = new Array();
  choices[0] = "January";
  choices[1] = "February";
  choices[2] = "March";
  choices[3] = "April";
  choices[4] = "May";
  choices[5] = "Juny";
  choices[6] = "July";
  choices[7] = "August";
  choices[8] = "September";
  choices[9] = "October";
  choices[10] = "November";
  choices[11] = "December";

  var target = new Array()
  target[0] = "5";
  target[1] = "8";

  var cbh = document.getElementById('checkboxes');
  var val = '';
  var cap = "";

  var j = "";
  var t = document.getElementById('t');

  // the loop is creating the checkboxes with name, value...
  for (var i in choices) {
    //Name of checkboxes are their number so I convert the i into a string.
    j = i.toString();

    val = j;
    //cap will be the value/text of choices[i]
    var cb = document.createElement('input');
    var label = document.createElement("label");

    cap = choices[i];
    var text = document.createTextNode(cap);
    cb.type = 'checkbox';
    cbh.appendChild(cb);
    cb.name = cap;
    cb.value = val;
    label.appendChild(cb);
    label.appendChild(text);
    cbh.appendChild(label);
    cb.addEventListener('click', updateText)
    if(target.indexOf(i)>=0){
      cb.checked =true ;
    }

  }
  updateText();
  function updateText() {
    t.value = [null, ...document.querySelectorAll('#checkboxes [type="checkbox"]')].reduce((s, el) => el && el.checked ? s = (s || '') + el.value + '$#' : s || '')
  }

  $("#chkAll").click(function(){
    $(":checkbox").parent().show();
  });

  $("#chkSelected").click(function(){
    $(":checkbox").parent().hide();
    $(":checked").parent().show();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
       box-sizing: border-box;
   }
   #data {
       padding:5px;
    width:100vw;
   }
   .multiselect {
    overflow: visible;
    padding:0;
    padding-left:1px;
    border:none;
    background-color:#eee;
    width:100vw;
    white-space: normal;
    height:200px;
   }
   .checkboxes {
    height:100px;
    width:100px;
    border:1px solid #000;
    background-color:white;
    margin-left:-1px;
    display:inline-block;
   }

            label {
    display: inline-block;
    border: 1px grey solid;
    padding:5px;
   }</code>```

All | Selected
 <form>

</form>
<textarea id="t"></textarea>```

Body:
I got a problem with some checkboxes, I don't succeed to filter them according if they are checked or not.

The principle is simple. If I click on "All" all the checkboxes are displayed, but if I click on selected, I just want to see the checkboxes selected and hidde the ones unchecked.

Here is a snippet, please update it in your answer to let me see how it could be done.

Thanks a lot !

//array of options
var choices = new Array();
choices[0] = "January";
choices[1] = "February";
choices[2] = "March";
choices[3] = "April";
choices[4] = "May";
choices[5] = "Juny";
choices[6] = "July";
choices[7] = "August";
choices[8] = "September";
choices[9] = "October";
choices[10] = "November";
choices[11] = "December";

var target = new Array()
target[0] = "5";
target[1] = "8";

var cbh = document.getElementById('checkboxes');
var val = '';
var cap = "";

var j = "";
var t = document.getElementById('t');

// the loop is creating the checkboxes with name, value...
for (var i in choices) {
  //Name of checkboxes are their number so I convert the i into a string.
  j = i.toString();

  val = j;
  //cap will be the value/text of choices[i]
  var cb = document.createElement('input');
  var label = document.createElement("label");

  cap = choices[i];
  var text = document.createTextNode(cap);
  cb.type = 'checkbox';
  cbh.appendChild(cb);
  cb.name = cap;
  cb.value = val;
  label.appendChild(cb);
  label.appendChild(text);
  cbh.appendChild(label);
  cb.addEventListener('click', updateText)
  if(target.indexOf(i)>=0){
    cb.checked =true ;
  }

}
updateText();
function updateText() {
  t.value = [null, ...document.querySelectorAll('#checkboxes [type="checkbox"]')].reduce((s, el) => el && el.checked ? s = (s || '') + el.value + '$#' : s || '')
}

   * {
       box-sizing: border-box;
   }
   #data {
       padding:5px;
    width:100vw;
   }
   .multiselect {
    overflow: visible;
    padding:0;
    padding-left:1px;
    border:none;
    background-color:#eee;
    width:100vw;
    white-space: normal;
    height:200px;
   }
   .checkboxes {
    height:100px;
    width:100px;
    border:1px solid #000;
    background-color:white;
    margin-left:-1px;
    display:inline-block;
   }

            label {
    display: inline-block;
    border: 1px grey solid;
    padding:5px;
   }

 All | Selected
 <form>

</form>
<textarea id="t"></textarea>

Body:
You could select all the checked elements with checked selector, so you could show/hide its parent:

  $("#chkAll").click(function(){
    $(":checkbox").parent().show();
  });

  $("#chkSelected").click(function(){
    $(":checkbox").parent().hide();
    $(":checked").parent().show();
  });

Here your updated snippet:

$(document).ready(function(){
  //array of options
  var choices = new Array();
  choices[0] = "January";
  choices[1] = "February";
  choices[2] = "March";
  choices[3] = "April";
  choices[4] = "May";
  choices[5] = "Juny";
  choices[6] = "July";
  choices[7] = "August";
  choices[8] = "September";
  choices[9] = "October";
  choices[10] = "November";
  choices[11] = "December";

  var target = new Array()
  target[0] = "5";
  target[1] = "8";

  var cbh = document.getElementById('checkboxes');
  var val = '';
  var cap = "";

  var j = "";
  var t = document.getElementById('t');

  // the loop is creating the checkboxes with name, value...
  for (var i in choices) {
    //Name of checkboxes are their number so I convert the i into a string.
    j = i.toString();

    val = j;
    //cap will be the value/text of choices[i]
    var cb = document.createElement('input');
    var label = document.createElement("label");

    cap = choices[i];
    var text = document.createTextNode(cap);
    cb.type = 'checkbox';
    cbh.appendChild(cb);
    cb.name = cap;
    cb.value = val;
    label.appendChild(cb);
    label.appendChild(text);
    cbh.appendChild(label);
    cb.addEventListener('click', updateText)
    if(target.indexOf(i)>=0){
      cb.checked =true ;
    }

  }
  updateText();
  function updateText() {
    t.value = [null, ...document.querySelectorAll('#checkboxes [type="checkbox"]')].reduce((s, el) => el && el.checked ? s = (s || '') + el.value + '$#' : s || '')
  }

  $("#chkAll").click(function(){
    $(":checkbox").parent().show();
  });

  $("#chkSelected").click(function(){
    $(":checkbox").parent().hide();
    $(":checked").parent().show();
  });
});

* {
       box-sizing: border-box;
   }
   #data {
       padding:5px;
    width:100vw;
   }
   .multiselect {
    overflow: visible;
    padding:0;
    padding-left:1px;
    border:none;
    background-color:#eee;
    width:100vw;
    white-space: normal;
    height:200px;
   }
   .checkboxes {
    height:100px;
    width:100px;
    border:1px solid #000;
    background-color:white;
    margin-left:-1px;
    display:inline-block;
   }

            label {
    display: inline-block;
    border: 1px grey solid;
    padding:5px;
   }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="chkAll">All</span> | <span id="chkSelected">Selected</span>
 <form>
 <div id="data">
  <div class="multiselect">
   <div id="c_b">
    <div id="checkboxes">
    </div>
   </div>
  </div>
 </div>
</form>
<textarea id="t"></textarea>


来源: stackexchange

问:
App is not asking for internet permission at installation
I have an Android app written by Xamarin, and it works perfectly fine when debugging.

But when I want to release it, my *.apk installer does not ask for INTERNET permission, therefore my app crashes whenever it requires connection, which is almost in every activity since it's an online app.

I have added the permission in my manifest file, but for some reason, the app only asks for Reading and Writing data from SD card permission and totally ignores internet permission.

Here is my manifest file:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="ComicCity.ComicCity" android:versionCode="1" android:versionName="1.0" android:installLocation="preferExternal">
<uses-sdk android:minSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.DELETE_CACHE_FILES" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application android:label="ComicCity" android:icon="@drawable/CCicon"></application>
</manifest>
</code>```

答:
Internet is in the normal permissions list and thus you will not get prompted as it is auto-granted

If an app declares in its manifest that it needs a normal permission, the system automatically grants the app that permission at install time. The system does not prompt the user to grant normal permissions, and users cannot revoke these permissions.

Re: https://developer.android.com/guide/topics/permissions/normal-permissions.html

ContentLicense: CC BY-SA 3.0

Body:
I have an Android app written by Xamarin, and it works perfectly fine when debugging.

But when I want to release it, my *.apk installer does not ask for INTERNET permission, therefore my app crashes whenever it requires connection, which is almost in every activity since it's an online app.

I have added the permission in my manifest file, but for some reason, the app only asks for Reading and Writing data from SD card permission and totally ignores internet permission.

Here is my manifest file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="ComicCity.ComicCity" android:versionCode="1" android:versionName="1.0" android:installLocation="preferExternal">
<uses-sdk android:minSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.DELETE_CACHE_FILES" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application android:label="ComicCity" android:icon="@drawable/CCicon"></application>
</manifest>


问:
Scheme function error
```<code>(define affiche-gagnant
  (lambda (j1 j2 g1 g2)

(begin

  (display "Le gagnant est : ")

   (cond ((> g1 g2) j1)

         ((< g1 g2) j2)

         (else (begin (display "personne. ") (display j1) (display " et ") (display j2) (display " sont exaequos. ")))))))
</code>```

When j1 or j2 win the game it says :

```<code> Le gagnant est :

    We don't see who win the game :(
</code>```

答:
I have answered this already.</p>

```<code>(define affiche-gagnant
  (lambda (j1 j2 g1 g2)

(begin

  (display "Le gagnant est : ")

   (cond ((> g1 g2) (display j1)) ; You're returning, not displaying

         ((< g1 g2) (display j2))

         (else (begin (display "personne. ") (display j1) (display " et ") (display j2) (display " sont exaequos. ")))))))
</code>```

ContentLicense: CC BY-SA 2.5

Title: Scheme function error

Body:
(define affiche-gagnant
  (lambda (j1 j2 g1 g2)

(begin

  (display "Le gagnant est : ")

   (cond ((> g1 g2) j1)

         ((< g1 g2) j2)

         (else (begin (display "personne. ") (display j1) (display " et ") (display j2) (display " sont exaequos. ")))))))

When j1 or j2 win the game it says :

 Le gagnant est :

    We don't see who win the game :(

Body:
I have answered this already.

(define affiche-gagnant
  (lambda (j1 j2 g1 g2)

(begin

  (display "Le gagnant est : ")

   (cond ((> g1 g2) (display j1)) ; You're returning, not displaying

         ((< g1 g2) (display j2))

         (else (begin (display "personne. ") (display j1) (display " et ") (display j2) (display " sont exaequos. ")))))))


问:
Changing the rotation of tick labels in Seaborn heatmap
I'm plotting a heatmap in Seaborn. The problem is that I have too many squares in my plot so the x and y labels are too close to each other to be useful. So I'm creating a list of xticks and yticks to use. However passing this list to the function rotates the labels in the plot. It would be really nice to have seaborn automatically drop some of the ticks, but barring that I would like to be able to have the yticks upright.

```<code>import pandas as pd
import numpy as np
import seaborn as sns

data = pd.DataFrame(np.random.normal(size=40*40).reshape(40,40))

yticks = data.index
keptticks = yticks[::int(len(yticks)/10)]
yticks = ['' for y in yticks]
yticks[::int(len(yticks)/10)] = keptticks

xticks = data.columns
keptticks = xticks[::int(len(xticks)/10)]
xticks = ['' for y in xticks]
xticks[::int(len(xticks)/10)] = keptticks

sns.heatmap(data,linewidth=0,yticklabels=yticks,xticklabels=xticks)
</code>```

答:
You can also call the methods of heatmap object:

```<code>    g = sns.heatmap(data,linewidth=0,yticklabels=yticks,xticklabels=xticks)
    g.set_yticklabels(g.get_yticklabels(), rotation = 0, fontsize = 8)
</code>```

I am not sure why this isn't in the documentation for sns.heatmap, but the same methods are described here: http://seaborn.pydata.org/generated/seaborn.FacetGrid.html

I believe these methods are available to every seaborn plot object but couldn't find a general API for that.

Body:
I'm plotting a heatmap in Seaborn. The problem is that I have too many squares in my plot so the x and y labels are too close to each other to be useful. So I'm creating a list of xticks and yticks to use. However passing this list to the function rotates the labels in the plot. It would be really nice to have seaborn automatically drop some of the ticks, but barring that I would like to be able to have the yticks upright.

import pandas as pd
import numpy as np
import seaborn as sns

data = pd.DataFrame(np.random.normal(size=40*40).reshape(40,40))

yticks = data.index
keptticks = yticks[::int(len(yticks)/10)]
yticks = ['' for y in yticks]
yticks[::int(len(yticks)/10)] = keptticks

xticks = data.columns
keptticks = xticks[::int(len(xticks)/10)]
xticks = ['' for y in xticks]
xticks[::int(len(xticks)/10)] = keptticks

sns.heatmap(data,linewidth=0,yticklabels=yticks,xticklabels=xticks)

Body:
You can also call the methods of heatmap object:

    g = sns.heatmap(data,linewidth=0,yticklabels=yticks,xticklabels=xticks)
    g.set_yticklabels(g.get_yticklabels(), rotation = 0, fontsize = 8)

I am not sure why this isn't in the documentation for sns.heatmap, but the same methods are described here: http://seaborn.pydata.org/generated/seaborn.FacetGrid.html

I believe these methods are available to every seaborn plot object but couldn't find a general API for that.


问:
Android app crashes on 6.0 while seeking permissions with ActivityCompat.requestPermissions
I've following MainActivity which seeks permission for 6.0 Phone & Storage tasks. It prompts for
permission 2x times and then crashes. Do I need to re-start the MainActivity after I acquired_permission?
thanks for any help or pointers.

MainActivity.java

```<code>onCreate(){
seek_permissions()
//load db data and continue
//with the app tasks
}

public void seek_permissions(){
            boolean hasWritePermission = (ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
            if (!hasWritePermission) {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_PHONE_STATE,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.MOUNT_FORMAT_FILESYSTEMS,Manifest.permission.RECEIVE_BOOT_COMPLETED,Manifest.permission.MODIFY_PHONE_STATE}, REQUEST_PERM);
            }
    }
     @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_PERM:
            {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                acquired_perm = 1;
                }
                else {Toast.makeText(MainActivity.this, "Please consider granting these permissions", Toast.LENGTH_LONG).show(); }
            }
            return;
        }
    }
</code>```

答:
For me this was caused by using android:noHistory="true" in my manifest for this activity?

I believe this may be a bug with Android 6.0 as later versions work fine it seems.

If noHistory is set the ActivityCompat.requestPermissions call causes the onDestroy of the calling Activity to be executed thus destroying. As it isn't saved in the history due to the noHistory it no longer exists and the app is essentially closed when permission dialogue is dismissed.

As a workaround instead of "noHistory" in the manifest you can call finish() in onStop() or another appropriate location when navigating away from the Activity and remove the  tag from your manifest.

Body:
I've following MainActivity which seeks permission for 6.0 Phone & Storage tasks. It prompts for
permission 2x times and then crashes. Do I need to re-start the MainActivity after I acquired_permission?
thanks for any help or pointers.

MainActivity.java

onCreate(){
seek_permissions()
//load db data and continue
//with the app tasks
}

public void seek_permissions(){
            boolean hasWritePermission = (ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
            if (!hasWritePermission) {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_PHONE_STATE,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.MOUNT_FORMAT_FILESYSTEMS,Manifest.permission.RECEIVE_BOOT_COMPLETED,Manifest.permission.MODIFY_PHONE_STATE}, REQUEST_PERM);
            }
    }
     @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_PERM:
            {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                acquired_perm = 1;
                }
                else {Toast.makeText(MainActivity.this, "Please consider granting these permissions", Toast.LENGTH_LONG).show(); }
            }
            return;
        }
    }


问:
How to undo /revert "heroku git:clone"
I try to clone one project from heroku using the command

```<code>heroku git:remote -a projectname
</code>```

But i cloned the project in wrong folder.

How can i undo it.

答:
Git is just so great that you just have to move or rename your directory. Everything is stored in .git subdirectory

Moving a directory depends on your system and your habits. In Linux / MacOSX terminal, you could simply do

```<code>mv sourcedir targetdir
</code>```

Or, if you use any file explore, simply drag and drop your fresh folder to where you want it to be.

Title: How to undo /revert "heroku git:clone"

Body:
I try to clone one project from heroku using the command

heroku git:remote -a projectname

But i cloned the project in wrong folder.

How can i undo it.

Body:
Git is just so great that you just have to move or rename your directory. Everything is stored in .git subdirectory

Moving a directory depends on your system and your habits. In Linux / MacOSX terminal, you could simply do

mv sourcedir targetdir

Or, if you use any file explore, simply drag and drop your fresh folder to where you want it to be.


问:
Endless HTTP Stream Observable not emitting anything but data transferred
I've been digging an issue with Angular 4 and RxJS. Here is my code, the issue is, the http.post request Observable is not emitting anything to the next of the chain, the map(). The POST just get an endless response, it's a stream of Motion JPEG data. Now I have to deal with the data, say each 500KB transferred. My problem is that I cannot do anything with the data if the Observable not emitting anything.

So how to make such angular HTTP feature emit to the next of the chain each chunk of data transferred?

```<code>postActionGivenDataBinaryResponse(url:string, data:string) : Observable<any>{
    let headers = new Headers ({
        'Content-Type' : 'application/json;charset=utf-8'
    }) ;
    let options = new RequestOptions({
        headers : headers,
        responseType: ResponseContentType.ArrayBuffer
    }) ;

    //return binary data as is no json
    return this.http.post(url, data, options) //suspecting here is not emitting anything due to unknown configuration issue.
                    .map(this.extractBinaryData)
                    .catch(this.handleError) ;
}

private extractBinaryData(res:Response){
    console.log('Dealing with data in the com service.') ; // this never runs
    return res ;
}
</code>```

I call the above function like this, the post response is an endless binary data, I need to process it as string array.

```<code>this.mySubscription = this.comService.postActionGivenDataBinaryResponse(myurl,mydata)
  .do(()=>{
              console.log('Observable Passed data.') ; //this never runs.
          })
  .bufferCount(128000)
  .map((data)=>{//process the data each 128kb chunk})
  .subscribe();
</code>```

答:
I solved this issue by a trick that MDN provided. It's about how to transfer binary data

So I wrote my own request instead of using Angular's HTTP module.

And utilizing the responseText trick to keep the request never ending.

The request is like,

```<code>function load_binary_resource(url) {
  var req = new XMLHttpRequest();
  req.open('GET', url, false);
  //XHR binary charset opt by Marcus Granado 2006 [http://mgran.blogspot.com]
  req.overrideMimeType('text\/plain; charset=x-user-defined');
  req.send(null);
  if (req.status != 200) return '';
  return req.responseText;
}
</code>```

I just need to wrap this into an observable, then data would keep streaming and never stop unless the request is abort().

Body:
I've been digging an issue with Angular 4 and RxJS. Here is my code, the issue is, the http.post request Observable is not emitting anything to the next of the chain, the map(). The POST just get an endless response, it's a stream of Motion JPEG data. Now I have to deal with the data, say each 500KB transferred. My problem is that I cannot do anything with the data if the Observable not emitting anything.

So how to make such angular HTTP feature emit to the next of the chain each chunk of data transferred?

postActionGivenDataBinaryResponse(url:string, data:string) : Observable<any>{
    let headers = new Headers ({
        'Content-Type' : 'application/json;charset=utf-8'
    }) ;
    let options = new RequestOptions({
        headers : headers,
        responseType: ResponseContentType.ArrayBuffer
    }) ;

    //return binary data as is no json
    return this.http.post(url, data, options) //suspecting here is not emitting anything due to unknown configuration issue.
                    .map(this.extractBinaryData)
                    .catch(this.handleError) ;
}

private extractBinaryData(res:Response){
    console.log('Dealing with data in the com service.') ; // this never runs
    return res ;
}

I call the above function like this, the post response is an endless binary data, I need to process it as string array.

this.mySubscription = this.comService.postActionGivenDataBinaryResponse(myurl,mydata)
  .do(()=>{
              console.log('Observable Passed data.') ; //this never runs.
          })
  .bufferCount(128000)
  .map((data)=>{//process the data each 128kb chunk})
  .subscribe();

Body:
I solved this issue by a trick that MDN provided. It's about how to transfer binary data

So I wrote my own request instead of using Angular's HTTP module.

And utilizing the responseText trick to keep the request never ending.

The request is like,

function load_binary_resource(url) {
  var req = new XMLHttpRequest();
  req.open('GET', url, false);
  //XHR binary charset opt by Marcus Granado 2006 [http://mgran.blogspot.com]
  req.overrideMimeType('text\/plain; charset=x-user-defined');
  req.send(null);
  if (req.status != 200) return '';
  return req.responseText;
}

I just need to wrap this into an observable, then data would keep streaming and never stop unless the request is abort().


问:
Overloading with MVC Controllers
I have an action with the same name, one expecting no parameters and the other expecting an ID, when i try navigate through my url i get the following exception.

An unhandled exception occurred while processing the request.

AmbiguousActionException: Multiple actions matched. The following
  actions matched route data and had all constraints satisfied:

Mailer.Controllers.MailBuilderController.MailBody (Mailer)
  Mailer.Controllers.MailBuilderController.MailBody (Mailer)

My MailBuilder controller.

```<code>//[HttpGet("mailbuilder/MailBody")]
public IActionResult MailBody()
{
   Body model = new Body();
   return View(model);
}

//[HttpGet("mailbuilder/MailBody/{id}")]
public IActionResult MailBody(int id)
{
   Body model = _mailBuilderService.GetBody(id);
   return View(model);
}
</code>```

If i remove the comments above i am able to navigate but i am not able to redirect to action in the below method.

```<code>public IActionResult SaveBody(Body model)
{
  _mailBuilderService.AddBody(model);
  return RedirectToAction("MailBody", model.Id);
}
</code>```

答:
What about making the int nullable?

```<code>public IActionResult MailBody(int? id)
{
   Body model = id.HasValue ? _mailBuilderService.GetBody(id.Value) : new Body();
   return View(model);
}
</code>```

To clarify, if you're using default routing then the id is likely set to id = RouteParameter.Optional so in essence the two ActionResults are the same.

Title: Overloading with MVC Controllers

Body:
I have an action with the same name, one expecting no parameters and the other expecting an ID, when i try navigate through my url i get the following exception.

An unhandled exception occurred while processing the request.

AmbiguousActionException: Multiple actions matched. The following
  actions matched route data and had all constraints satisfied:

Mailer.Controllers.MailBuilderController.MailBody (Mailer)
  Mailer.Controllers.MailBuilderController.MailBody (Mailer)

My MailBuilder controller.

//[HttpGet("mailbuilder/MailBody")]
public IActionResult MailBody()
{
   Body model = new Body();
   return View(model);
}

//[HttpGet("mailbuilder/MailBody/{id}")]
public IActionResult MailBody(int id)
{
   Body model = _mailBuilderService.GetBody(id);
   return View(model);
}

If i remove the comments above i am able to navigate but i am not able to redirect to action in the below method.

public IActionResult SaveBody(Body model)
{
  _mailBuilderService.AddBody(model);
  return RedirectToAction("MailBody", model.Id);
}

Body:
What about making the int nullable?

public IActionResult MailBody(int? id)
{
   Body model = id.HasValue ? _mailBuilderService.GetBody(id.Value) : new Body();
   return View(model);
}

To clarify, if you're using default routing then the id is likely set to id = RouteParameter.Optional so in essence the two ActionResults are the same.


问:
Befriending a template template parameter
I've got a class template with a template template parameter, and I want to declare this parameter (that is, all of its specializations) as a friend. But I can't find the correct syntax.

```<code>template <template <class> class T>
struct Foo {

    template <class U>
    friend T;           // "C++ requires a type specifier for all declarations"

    template <class U>
    friend struct T;    // "declaration of 'T' shadows template parameter"

    template <class U>
    friend struct T<U>; // "cannot specialize a template template parameter"

    pretty<please>
    lets(be) friends T; // Compiler shook its standard output in pity
};
</code>```

How can I declare a template template parameter as friend?

Coliru snippet

答:
I've found this problem is very interesting to research. According to standard (C++11 and above) this should works fine, I guess:

```<code>template <template <class> class U>
struct identity {
    template <typename T>
    using type = U<T>;
};

template <template <class> class U>
struct Foo {
    template <typename>
    friend class identity<U>::type;
};
</code>```

Due to one indirection level, there are no any shadowing and name reusing here, and this situation described as following:

cppreference:

Both function template and class template declarations may appear with the friend specifier in any non-local class or class template (...). In this case, every specialization of the template becomes a friend, whether it is implicitly instantiated, partially specialized, or explicitly specialized. Example: class A { template<typename> friend class B; }

However, it seems like clang and MSVC think otherwise: see coliru or godbolt. Moreover, their error messages seem meaningless, so it looks like a compiler bug (or just an incorrectly detected syntax error). GCC compiles and executes mentioned snippets perfectly, but I still not sure it's a correct solution.

Body:
I've got a class template with a template template parameter, and I want to declare this parameter (that is, all of its specializations) as a friend. But I can't find the correct syntax.

template <template <class> class T>
struct Foo {

    template <class U>
    friend T;           // "C++ requires a type specifier for all declarations"

    template <class U>
    friend struct T;    // "declaration of 'T' shadows template parameter"

    template <class U>
    friend struct T; // "cannot specialize a template template parameter"

    pretty<please>
    lets(be) friends T; // Compiler shook its standard output in pity
};

How can I declare a template template parameter as friend?

Coliru snippet

Body:
I've found this problem is very interesting to research. According to standard (C++11 and above) this should works fine, I guess:

template <template <class> class U>
struct identity {
    template <typename T>
    using type = U<T>;
};

template <template <class> class U>
struct Foo {
    template <typename>
    friend class identity<U>::type;
};

Due to one indirection level, there are no any shadowing and name reusing here, and this situation described as following:

cppreference:

Both function template and class template declarations may appear with the friend specifier in any non-local class or class template (...). In this case, every specialization of the template becomes a friend, whether it is implicitly instantiated, partially specialized, or explicitly specialized. Example: class A { template<typename> friend class B; }

However, it seems like clang and MSVC think otherwise: see coliru or godbolt. Moreover, their error messages seem meaningless, so it looks like a compiler bug (or just an incorrectly detected syntax error). GCC compiles and executes mentioned snippets perfectly, but I still not sure it's a correct solution.


问:
How to fetch all the data from Smartsheet using API?
I am trying to fetch all the rows that are existing in an Smartsheet using API.
I have generated the bearer authorization token and have the report details. My Python is fetching me results of the first 100 rows (source has 1200 rows). I don't use any filters within the Python. Is this due to any default (page-size value)?

I am unable to retrieve all existing data from this API.

答:
With the Smartsheet Python SDK, the get_sheet operation (in sheets.py) specifies the default page size as 100.

You should be able to override this value by specifying the page_size parameter when you call the get_sheet operation.


问:
Does this interface require a Null modem cable?
I am enclosing here the drawing of the RS-232 9 pin connection cable to link a XT2000i Blood analyser to a host PC. Is this just any serial port cable or a Null modem cable ?

Thanks. Chak.

Since @JTON said in the answer that other pins are not swapped, i am enclosing image of which pins are in use.

答:
Looks like a variation of the null modem cable shown here:
http://en.wikipedia.org/wiki/Null_modem

basically you are crossing the send-data / receive-date
I would start with a null-modem cable


问:
UDP[number] in wireshark meaning
in wire shark data filter option when we add UDP[50] , so what is this 50 , is it index? i have hex value 93 at UDP[50]. in attached screenshot value 93 is at udp[50] but where is the starting point of this index like where is udp[0].
I want to know the start index of data under wire shark packets. what is this UDP[this number]??

答:
The udp[x] starts at the beginning of the transport layer (e.g. UDP) and starts from zero.  The UDP header is 8 bytes so you'll need to take these 8 bytes into consideration when filtering the payload.

A few examples:

```<code>udp[0-1] == 0035 # Match bytes 0 to 1 (UDP source port)
udp[0:2] == 0035 # Match 2 bytes starting from 0 (same as above)

udp[8-10] == 5600:22 # Match bytes 8 to 10 (First 3 bytes of UDP payload)
udp[8:3] == 5600:22 # Matches 3 bytes starting from 8 (same as above)
</code>```

If your payload is decoded as data, you can also use data.data[x] so you don't have to offset your filter by 8.  Be careful,though, as it will not match if Wireshark decodes the UDP payload as some other protocol.

Title: UDP[number] in wireshark meaning

Body:
The udp[x] starts at the beginning of the transport layer (e.g. UDP) and starts from zero.  The UDP header is 8 bytes so you'll need to take these 8 bytes into consideration when filtering the payload.

A few examples:

udp[0-1] == 0035 # Match bytes 0 to 1 (UDP source port)
udp[0:2] == 0035 # Match 2 bytes starting from 0 (same as above)

udp[8-10] == 5600:22 # Match bytes 8 to 10 (First 3 bytes of UDP payload)
udp[8:3] == 5600:22 # Matches 3 bytes starting from 8 (same as above)

If your payload is decoded as data, you can also use data.data[x] so you don't have to offset your filter by 8.  Be careful,though, as it will not match if Wireshark decodes the UDP payload as some other protocol.


问:
Android RelativeLayout adding rules before API17
I' m writing an Android app with minSdk=14. I have an activity with RelativeLayout, in which are placed some views. when I press the button in this Activity, I must add 5 views in this layout: 2 textviews, 2 editTexts and one ImageView. I'm trying to do this in this way:

```<code>    CustomTextView fromLabel = new CustomTextView(this);
    RelativeLayout.LayoutParams paramsForFromLabel = new RelativeLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); //ширина, длина
    paramsForFromLabel.addRule(RelativeLayout.BELOW, lastCounterId);
    paramsForFromLabel.topMargin = 10;
    fromLabel.setId(counterIds.get(5*counterMax));
    fromLabel.setGravity(Gravity.CENTER);
    fromLabel.setText(R.string.labelCommunalCounterFrom);
    int newFromLabelId = fromLabel.getId();

    EditText from = new EditText(this);
    from.setInputType(InputType.TYPE_CLASS_NUMBER);
    RelativeLayout.LayoutParams paramsForFrom = new RelativeLayout.LayoutParams(
            (int) getResources().getDimension(R.dimen.number_width), ViewGroup.LayoutParams.WRAP_CONTENT);
    paramsForFrom.addRule(RelativeLayout.BELOW, lastCounterId);
    paramsForFrom.addRule(RelativeLayout.RIGHT_OF, fromLabel.getId());
    from.setId(counterIds.get(5*counterMax+1));
    int newFromFieldId = from.getId();

    paramsForFromLabel.addRule(RelativeLayout.ALIGN_BASELINE, newFromFieldId);

    CustomTextView toLabel = new CustomTextView(this);
    RelativeLayout.LayoutParams paramsForToLabel = new RelativeLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    paramsForFromLabel.addRule(RelativeLayout.BELOW, lastCounterId);
    paramsForToLabel.addRule(RelativeLayout.RIGHT_OF, from.getId());
    paramsForFromLabel.topMargin = 10;
    toLabel.setId(counterIds.get(5*counterMax+2));
    toLabel.setGravity(Gravity.CENTER);
    toLabel.setText(R.string.labelCommunalCounterTo);
    int newToLabelId = toLabel.getId();

    EditText to = new EditText(this);
    to.setInputType(InputType.TYPE_CLASS_NUMBER);
    RelativeLayout.LayoutParams paramsForTo = new RelativeLayout.LayoutParams(
            (int) getResources().getDimension(R.dimen.number_width), ViewGroup.LayoutParams.WRAP_CONTENT);
    paramsForTo.addRule(RelativeLayout.BELOW, lastCounterId);
    paramsForTo.addRule(RelativeLayout.RIGHT_OF, toLabel.getId());
    to.setId(counterIds.get(5*counterMax+3));
    int newToFieldId = to.getId();

    paramsForToLabel.addRule(RelativeLayout.ALIGN_BASELINE, newToFieldId);

    ImageView dropCounter = new ImageView(this);
    dropCounter.setId(counterIds.get(5*counterMax+4));
    dropCounter.setImageResource(R.drawable.cancel_icon);
    RelativeLayout.LayoutParams paramsForDrop = new RelativeLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    paramsForDrop.addRule(RelativeLayout.BELOW, lastCounterId);
    paramsForDrop.addRule(RelativeLayout.RIGHT_OF, to.getId());
    paramsForDrop.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);

    layout.addView(fromLabel, paramsForFromLabel);
    layout.addView(from, paramsForFrom);
    layout.addView(toLabel, paramsForToLabel);
    layout.addView(to, paramsForTo);
    layout.addView(dropCounter, paramsForDrop);
</code>```

The problem is: for second View (EditText from), the rule RIGHT_OF is ignored. All other fields displayed well.
And the next question is: how can I rewrite rule for the View? I have a button with XML-specified LAYOUT_BELOW rule. How can I change it programmatically?

答:
Fixed! It sounds stupid, but the problem was:
I've set an id=0 for my first View (first TextField). And when I tried to refer this ID, this rule was ignored. When I set ID=1 - all problems disappeared!
Sorry for this question! I wasn't carefull during docs reading: we can use POSITIVE integers as View ID.</p>

Body:
I' m writing an Android app with minSdk=14. I have an activity with RelativeLayout, in which are placed some views. when I press the button in this Activity, I must add 5 views in this layout: 2 textviews, 2 editTexts and one ImageView. I'm trying to do this in this way:

    CustomTextView fromLabel = new CustomTextView(this);
    RelativeLayout.LayoutParams paramsForFromLabel = new RelativeLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); //ширина, длина
    paramsForFromLabel.addRule(RelativeLayout.BELOW, lastCounterId);
    paramsForFromLabel.topMargin = 10;
    fromLabel.setId(counterIds.get(5*counterMax));
    fromLabel.setGravity(Gravity.CENTER);
    fromLabel.setText(R.string.labelCommunalCounterFrom);
    int newFromLabelId = fromLabel.getId();

    EditText from = new EditText(this);
    from.setInputType(InputType.TYPE_CLASS_NUMBER);
    RelativeLayout.LayoutParams paramsForFrom = new RelativeLayout.LayoutParams(
            (int) getResources().getDimension(R.dimen.number_width), ViewGroup.LayoutParams.WRAP_CONTENT);
    paramsForFrom.addRule(RelativeLayout.BELOW, lastCounterId);
    paramsForFrom.addRule(RelativeLayout.RIGHT_OF, fromLabel.getId());
    from.setId(counterIds.get(5*counterMax+1));
    int newFromFieldId = from.getId();

    paramsForFromLabel.addRule(RelativeLayout.ALIGN_BASELINE, newFromFieldId);

    CustomTextView toLabel = new CustomTextView(this);
    RelativeLayout.LayoutParams paramsForToLabel = new RelativeLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    paramsForFromLabel.addRule(RelativeLayout.BELOW, lastCounterId);
    paramsForToLabel.addRule(RelativeLayout.RIGHT_OF, from.getId());
    paramsForFromLabel.topMargin = 10;
    toLabel.setId(counterIds.get(5*counterMax+2));
    toLabel.setGravity(Gravity.CENTER);
    toLabel.setText(R.string.labelCommunalCounterTo);
    int newToLabelId = toLabel.getId();

    EditText to = new EditText(this);
    to.setInputType(InputType.TYPE_CLASS_NUMBER);
    RelativeLayout.LayoutParams paramsForTo = new RelativeLayout.LayoutParams(
            (int) getResources().getDimension(R.dimen.number_width), ViewGroup.LayoutParams.WRAP_CONTENT);
    paramsForTo.addRule(RelativeLayout.BELOW, lastCounterId);
    paramsForTo.addRule(RelativeLayout.RIGHT_OF, toLabel.getId());
    to.setId(counterIds.get(5*counterMax+3));
    int newToFieldId = to.getId();

    paramsForToLabel.addRule(RelativeLayout.ALIGN_BASELINE, newToFieldId);

    ImageView dropCounter = new ImageView(this);
    dropCounter.setId(counterIds.get(5*counterMax+4));
    dropCounter.setImageResource(R.drawable.cancel_icon);
    RelativeLayout.LayoutParams paramsForDrop = new RelativeLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    paramsForDrop.addRule(RelativeLayout.BELOW, lastCounterId);
    paramsForDrop.addRule(RelativeLayout.RIGHT_OF, to.getId());
    paramsForDrop.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);

    layout.addView(fromLabel, paramsForFromLabel);
    layout.addView(from, paramsForFrom);
    layout.addView(toLabel, paramsForToLabel);
    layout.addView(to, paramsForTo);
    layout.addView(dropCounter, paramsForDrop);

The problem is: for second View (EditText from), the rule RIGHT_OF is ignored. All other fields displayed well.
And the next question is: how can I rewrite rule for the View? I have a button with XML-specified LAYOUT_BELOW rule. How can I change it programmatically?


问:
How to insert key-value pair into dictionary at a specified position?
How would I insert a key-value pair at a specified location in a python dictionary that was loaded from a YAML document?

For example if a dictionary is:

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

I wish to insert the element 'Phone':'1234'
before 'Age', and after 'Name' for example. The actual dictionary I shall be working on is quite large (parsed YAML file), so deleting and reinserting might be a bit cumbersome (I don't really know).

If I am given a way of inserting into a specified position in an OrderedDict, that would be okay, too.

答:
Once your have used load() (without option Loader=RoundTripLoader) and your data is in a dict() it is to late, as the order that was available in the YAML file is normally gone (the order depending on the actual keys used, the python used (implementation, version and possible compile options).

What you need to do is use round_trip_load():

```<code>import sys
from ruamel import yaml

yaml_str = "{'Name': 'Zara', 'Age': 7, 'Class': 'First'}"

data = yaml.round_trip_load(yaml_str)
pos = list(data.keys()).index('Age')  # determine position of 'Age'
# insert before position of 'Age'
data.insert(pos, 'Phone', '1234', comment='This is the phone number')
data.fa.set_block_style()   # I like block style
yaml.round_trip_dump(data, sys.stdout)
</code>```

this will invariable give:

```<code>Name: Zara
Phone: '1234'  # This is the phone number
Age: 7
Class: First
</code>```

Under the hood round_trip_dump() transparently gives you back a subclass of orderddict to make this possible (which actual implementation is dependent on your Python version).

ContentLicense: CC BY-SA 4.0

Body:
Once your have used load() (without option Loader=RoundTripLoader) and your data is in a dict() it is to late, as the order that was available in the YAML file is normally gone (the order depending on the actual keys used, the python used (implementation, version and possible compile options).

What you need to do is use round_trip_load():

import sys
from ruamel import yaml

yaml_str = "{'Name': 'Zara', 'Age': 7, 'Class': 'First'}"

data = yaml.round_trip_load(yaml_str)
pos = list(data.keys()).index('Age')  # determine position of 'Age'
# insert before position of 'Age'
data.insert(pos, 'Phone', '1234', comment='This is the phone number')
data.fa.set_block_style()   # I like block style
yaml.round_trip_dump(data, sys.stdout)

this will invariable give:

Name: Zara
Phone: '1234'  # This is the phone number
Age: 7
Class: First

Under the hood round_trip_dump() transparently gives you back a subclass of orderddict to make this possible (which actual implementation is dependent on your Python version).


问:
Can't change table design in SQL Server 2008
I created a table tbl_Candidate, but I forgot to set the primary key to the table and I saved it without primary key.

Next time I'm going to set primary key in SQL Server 2008 Express, I get a message like I have to drop the table and recreate when I'm going to save the table with primary key changes.

This is the message that pops up when I'm trying to save changes in the table:

Saving changes is not permitted. The changes you have made require
  that the following tables to dropped and recreate. You have either made
  changes to the table that can't be recreate or enable the option
  prevent saving changes that require the tables to be recreate

I'm logged into SQL Server with Windows authentication, server type as database engine and Server name as .\SQLExpress.

Please give me a way to correct this problem or way to change the settings of the SQL Server.

答:
Prevent saving changes that require table re-creation

Five swift clicks

Tools

Options

Designers

Prevent saving changes that require table re-creation

OK.

After saving, repeat the proceudure to re-tick the box. This safe-guards against accidental data loss.

Further explanation

By default SQL Server Management Studio prevents the dropping of tables, because when a table is dropped its data contents are lost.*

When altering a column's datatype in the table Design view, when saving the changes the database drops the table internally and then re-creates a new one.

*Your specific circumstances will not pose a consequence since your table is empty. I provide this explanation entirely to improve your understanding of the procedure.


问:
Inserting combobox via code
I'm trying to insert a drop-down list that has a "PASS/FAIL" criterion to the right of a cell that the user populates. The cells will be populated from top to bottom in order. Here is what I have so far:

```<code>Sub ComboBoxPassFail()
    Dim i As Integer
    Dim rng As Range

    i = 4

    For Each c In Worksheets("Inspection Report").Range("A4", Range("A4").End(xlDown)).Cells
        If c.Value <> "" Then

        Set rng = c.Offset(0, 14)

        Top = rng.Top
        Left = rng.Left

        ActiveSheet.OLEObjects.Add(classtype:="forms.combobox.1", Left:=Left, Top:=Top, Width:=8, Height:=15).Insert

        i = i + 1

        End If
    Next c

    i = 4

End Sub
</code>```

My main problem comes from dealing with comboboxes.

答:
Couple of things

top and left are reserved words in VBA. You cannot use them as variables

Since you are working with Excel rows, declare row as Long and not Integer. BTW I do not see the use of i in the code.

.Insert is not valid statement.

Is this what you are trying?

```<code>Sub ComboBoxPassFail()
    Dim rng As Range, c As Range
    Dim rngTop As Double, rngLeft As Double

    For Each c In Worksheets("Inspection Report").Range("A4", Range("A4").End(xlDown)).Cells
        If c.Value <> "" Then
            Set rng = c.Offset(0, 14)
            rngTop = rng.Top
            rngLeft = rng.Left

            '~~> You may want to decide on a more appropriate width value? :)
            ActiveSheet.OLEObjects.Add classtype:="forms.combobox.1", _
                                       Left:=rngLeft, Top:=rngTop, _
                                       Width:=8, Height:=15
        End If
    Next c
End Sub
</code>```

Title: Inserting combobox via code

Body:
I'm trying to insert a drop-down list that has a "PASS/FAIL" criterion to the right of a cell that the user populates. The cells will be populated from top to bottom in order. Here is what I have so far:

Sub ComboBoxPassFail()
    Dim i As Integer
    Dim rng As Range

    i = 4

    For Each c In Worksheets("Inspection Report").Range("A4", Range("A4").End(xlDown)).Cells
        If c.Value <> "" Then

        Set rng = c.Offset(0, 14)

        Top = rng.Top
        Left = rng.Left

        ActiveSheet.OLEObjects.Add(classtype:="forms.combobox.1", Left:=Left, Top:=Top, Width:=8, Height:=15).Insert

        i = i + 1

        End If
    Next c

    i = 4

End Sub

My main problem comes from dealing with comboboxes.

Body:
Couple of things

top and left are reserved words in VBA. You cannot use them as variables

Since you are working with Excel rows, declare row as Long and not Integer. BTW I do not see the use of i in the code.

.Insert is not valid statement.

Is this what you are trying?

Sub ComboBoxPassFail()
    Dim rng As Range, c As Range
    Dim rngTop As Double, rngLeft As Double

    For Each c In Worksheets("Inspection Report").Range("A4", Range("A4").End(xlDown)).Cells
        If c.Value <> "" Then
            Set rng = c.Offset(0, 14)
            rngTop = rng.Top
            rngLeft = rng.Left

            '~~> You may want to decide on a more appropriate width value? :)
            ActiveSheet.OLEObjects.Add classtype:="forms.combobox.1", _
                                       Left:=rngLeft, Top:=rngTop, _
                                       Width:=8, Height:=15
        End If
    Next c
End Sub


问:
Reference Figures in reStructuredText via Figure Numbers using :numref:
I am currently trying to setup a reStructuredText template. I want to include numbered figures and references to those. So I followed the instructions given in the sphinx documentation ( http://www.sphinx-doc.org/en/stable/markup/inline.html ).

First I included the line

```<code>numfig = True
</code>```

in the file 'conf.py'. I implemented the figure and the reference to it in my file 'rstTemplate.rst' as follows:

```<code>.. _my-figure:

.. figure:: images/scen-smartcity.*
    :scale: 50 %
    :alt: smartcity symbol
    :align: center

    This is the caption of the figure (a simple paragraph).

    This is the legend of the figure

Reference to the figure :numref:`(Fig. %s) my-figure`
</code>```

When I build the html file using make html

```<code>Running Sphinx v1.6.1
loading pickled environment... done
building [mo]: targets for 0 po files that are out of date
building [html]: targets for 1 source files that are out of date
updating environment: 0 added, 2 changed, 0 removed
reading sources... [100%] rstTemplate
rstTemplate.rst:: WARNING: duplicate label my-figure, other instance in ><path-to-file>\rstTemplate.rst
<path-to-file>\rstTemplate.rst:: WARNING: duplicate label my-figure, other instance in <path-to-file>\index.rst
looking for now-outdated files... none found
pickling environment... done
checking consistency... done
preparing documents... done
writing output... [100%] rstTemplate
rstTemplate.rst:41: WARNING: undefined label: (fig. %s) my-figure
<path-to-file>\rstTemplate.rst:41: WARNING: undefined label: (fig. %s) my-figure
generating indices... genindex
writing additional pages... search
copying images... [100%] images/scen-smartcity.svg
copying static files... done
copying extra files... done
dumping search index in English (code: en) ... done
dumping object inventory... done
build succeeded, 6 warnings.
</code>```

The file index.html then shows the figure, the caption and the reference to it as shown here:
output index.html

So the caption shows a nice 'Fig. 1' but the reference using :numref: obviously does not work. I also tried

```<code>:numref:`my-figure`
</code>```

which led to a similar result.

Does anybody know why the reference does not work here?

What is also interesting: all the above mentioned is in my file 'rstTemplate.rst' which I included in the file 'index.rst' via .. include:: rstTemplate.rst. After the html build I recieve the files 'index.html' and 'rstTemplate.html'. Unlike in the 'index.html' version the 'Fig. 1' is not included in the caption of the figure in 'rstTemplate.html'. Might that be related to what is going wrong here?

Thanks in advance.

答:
Assuming your conf.py contains the following:

```<code>import sys
import os
html_theme = 'sphinx_rtd_theme'
numfig = True
</code>```

and your index.rst contains:

```<code>.. toctree::
   :maxdepth: 2
   :caption: Home
   :hidden:

 mychapter
</code>```

Here is a working example for a chapter RST document mychapter.rst:

```<code>.. figure:: images/my-image.png
   :name: my-custom-label

This is a caption of the image

This is a reference to :numref:`my-custom-label` bla bla ...
</code>```

This renders as:

```<code>This is a reference to Fig.1 bla bla ...
</code>```

Body:
I am currently trying to setup a reStructuredText template. I want to include numbered figures and references to those. So I followed the instructions given in the sphinx documentation ( http://www.sphinx-doc.org/en/stable/markup/inline.html ).

First I included the line

numfig = True

in the file 'conf.py'. I implemented the figure and the reference to it in my file 'rstTemplate.rst' as follows:

.. _my-figure:

.. figure:: images/scen-smartcity.*
    :scale: 50 %
    :alt: smartcity symbol
    :align: center

    This is the caption of the figure (a simple paragraph).

    This is the legend of the figure

Reference to the figure :numref:`(Fig. %s) my-figure`

When I build the html file using make html

Running Sphinx v1.6.1
loading pickled environment... done
building [mo]: targets for 0 po files that are out of date
building [html]: targets for 1 source files that are out of date
updating environment: 0 added, 2 changed, 0 removed
reading sources... [100%] rstTemplate
rstTemplate.rst:: WARNING: duplicate label my-figure, other instance in ><path-to-file>\rstTemplate.rst
<path-to-file>\rstTemplate.rst:: WARNING: duplicate label my-figure, other instance in <path-to-file>\index.rst
looking for now-outdated files... none found
pickling environment... done
checking consistency... done
preparing documents... done
writing output... [100%] rstTemplate
rstTemplate.rst:41: WARNING: undefined label: (fig. %s) my-figure
<path-to-file>\rstTemplate.rst:41: WARNING: undefined label: (fig. %s) my-figure
generating indices... genindex
writing additional pages... search
copying images... [100%] images/scen-smartcity.svg
copying static files... done
copying extra files... done
dumping search index in English (code: en) ... done
dumping object inventory... done
build succeeded, 6 warnings.

The file index.html then shows the figure, the caption and the reference to it as shown here:
output index.html

So the caption shows a nice 'Fig. 1' but the reference using :numref: obviously does not work. I also tried

:numref:`my-figure`

which led to a similar result.

Does anybody know why the reference does not work here?

What is also interesting: all the above mentioned is in my file 'rstTemplate.rst' which I included in the file 'index.rst' via .. include:: rstTemplate.rst. After the html build I recieve the files 'index.html' and 'rstTemplate.html'. Unlike in the 'index.html' version the 'Fig. 1' is not included in the caption of the figure in 'rstTemplate.html'. Might that be related to what is going wrong here?

Thanks in advance.

Body:
Assuming your conf.py contains the following:

import sys
import os
html_theme = 'sphinx_rtd_theme'
numfig = True

and your index.rst contains:

.. toctree::
   :maxdepth: 2
   :caption: Home
   :hidden:

 mychapter

Here is a working example for a chapter RST document mychapter.rst:

.. figure:: images/my-image.png
   :name: my-custom-label

This is a caption of the image

This is a reference to :numref:`my-custom-label` bla bla ...

This renders as:

This is a reference to Fig.1 bla bla ...


问:
Web development
First of all hi to all, I am new at web development and I have some questions. I have  started a web site few weeks ago(html,css,js) and now I don't know how to continue. what is the next step for my project and how can I practice without publish it in a server? Nowdays I am learning php and ruby but it is more complex to understand the back end of a web site.</p>

答:
Since you have already started a website, add more functionalities to it. This way, you can enhance the project and at the same time learn new things as you develop. For example, if the project is in HTML, learn Bootstrap and implement the same to the project. You can publish various versions of the project. If you do not wish to publish, you can work on it locally too.

You mentioned that you are learning PHP. Why not just throw in some data to the HTML using PHP and perform some CRUD operations on it? That would be a great way to learn!

https://www.w3schools.com/ is a great website to learn.

Wish you Goodluck and I hope I helped!

Title: Web development


问:
Need Help regarding backup css
I need your help.

My website css has been crashed due to suddenly power supply off and next while I saw css, CSS was cleaned totally.
Anyone suggest me How can I get them again?

Thanks in advance.

答:
Retrieve them from your source code control system.

If you don't have one, consider this a lesson in why you should.

Title: Need Help regarding backup css


问:
C# Display data from program to DataGridView
I'm trying to display data that I pulled from text files within my program to a DataGridView but I'm having trouble finding out how to do it, another problem I have is that when the form opens it stops running through the code.

Here is the main part of my code:

```<code>DataGridView dataGridView = new DataGridView();
IList<Machine> machines = new BindingList<Machine>();
dataGridView.DataSource = machines;

SessionOptions sessionOptions = new SessionOptions
        {
            Protocol = Protocol.Sftp,
            HostName = hostIP,
            UserName = userName,
            Password = passWord,
            PortNumber = 22,
            SshHostKeyFingerprint = "ssh-rsa 2048 96:48:96:52:8c:e7:de:c6:e1:00:08:7e:db:ad:e4:06"

        };

        using (Session session = new Session())
        {
            session.Open(sessionOptions);

            TransferOptions transferOptions = new TransferOptions();
            transferOptions.TransferMode = TransferMode.Binary;

            session.GetFiles(remotePath, @"C:\Users\mark\Desktop\Project Dex\Temp\").Check();
        }

        DirectoryInfo directorySelected = new DirectoryInfo(@"C:\Users\mark\Desktop\Project Dex\Temp\PROCESSED\");
        List<string> fileNames = new List<string>();

        foreach (FileInfo fileInfo in directorySelected.GetFiles("*.zip"))
        {
            fileNames.Add(fileInfo.Name);
        }

        foreach (string fileName in fileNames)
        {
            string zipFilePath = localPath + fileName;

            using (ZipFile zip1 = ZipFile.Read(zipFilePath))
            {
                var selection = (from e in zip1.Entries
                                 where (e.FileName).StartsWith("01e")
                                 select e);

                Directory.CreateDirectory(zipTemp);

                foreach (var e in selection)
                {
                    e.Extract(zipTemp, ExtractExistingFileAction.OverwriteSilently);
                }
            }

            DirectoryInfo dexDirect = new DirectoryInfo(@"C:\Users\mark\Desktop\Project Dex\zipTemp\");
            List<string> dexName = new List<string>();

            foreach (FileInfo dexInfo in dexDirect.GetFiles("*.dex"))
            {
                dexName.Add(dexInfo.Name);
            }

            foreach (string dexNames in dexName)
            {
                string dexFilePath = zipTemp + dexNames;

                string[] lines = System.IO.File.ReadAllLines(dexFilePath);

                foreach (string line in lines)
                {
                    machineCashCount = Array.Find(lines,
                element => element.StartsWith("VA1", StringComparison.Ordinal));
                }
                string[] MCC1 = machineCashCount.Split('*');
                string[] nm = dexNames.Split('.');

                int nam = int.Parse(nm[0], System.Globalization.NumberStyles.HexNumber);

                //Console.WriteLine((nam + (":") + "Total cash count: ") + MCC1[1]);
                //Console.WriteLine((nam + (":") + "Number of paid vends: ") + MCC1[2]);

                Machine m = new Machine();

                m.MacNum = nm[0];
                m.CashCount = MCC1[1];
                m.VendCount = MCC1[2];
                machines.Add(m);

            }
        }

        Application.Run(new Form1());
    }
}
</code>```

}

screenshot

答:
For your specific error of "cannot create an instance of the abstract class or interface IList", the problem is that you're trying to create an instance of an interface. You want a concrete class. For example, List implements IList so you can do

```<code>IList<string> names = new List<string>();
</code>```

An interface is basically just a contract describing what a class that implements it can do.

As for you question, you want to create a class to hold your data, parse your files into objects, put them in a BindingList or any other appropriate collection then bind your datagridview to that collection.

```<code>class Machine
{
    public string Name {get; set;}
    public decimal CashCount {get; set;}
}

public static void main()
{
    IList<Machine> machines = new BindingList<Machine>();

    foreach(string fileName in fileNames)
    {
        //read your files, put data in a Machine object
        Machine m =new Machine();
        m.Name=nm[0];
        m.CashCount=MCC1[0];
        //add it to the list
        machines.add(m);
    }

    //then bind the collection to your datagridview
    datagridView.Datasource = machines;
}
</code>```

Then in your form designer, you can add 2 columns to the datagridview and set their binding to Name and CashCount respectively. You could also, for example, set the format of the CashCount columns to be displayed as money.

Edit: adding minimal working example

```<code>using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;

namespace datagridview
{
    public partial class Form1 : Form
    {
        private DataGridView dgvMachines;

        public Form1()
        {
            InitializeComponent();
            //this is the Designer.cs code...
            this.dgvMachines = new System.Windows.Forms.DataGridView();
            ((System.ComponentModel.ISupportInitialize)(this.dgvMachines)).BeginInit();
            this.SuspendLayout();
            //
            // dgvMachines
            //
            this.dgvMachines.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dgvMachines.Location = new System.Drawing.Point(12, 12);
            this.dgvMachines.Name = "dgvMachines";
            this.dgvMachines.Size = new System.Drawing.Size(606, 400);
            this.dgvMachines.TabIndex = 0;
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(630, 434);
            this.Controls.Add(this.dgvMachines);
            this.Name = "Form1";
            this.Text = "Form1";
            ((ISupportInitialize)(this.dgvMachines)).EndInit();
            this.ResumeLayout(false);

            IList<Machine> machines = new BindingList<Machine>();
            dgvMachines.DataSource = machines;
            machines.Add(new Machine { Name = "#1", CashCount = 100 });
            machines.Add(new Machine { Name = "#2", CashCount = 200 });
            machines.Add(new Machine { Name = "#3", CashCount = 300 });
            machines.Add(new Machine { Name = "#4", CashCount = 400 });
        }
    }

    class Machine
    {
        public string Name { get; set; }
        public decimal CashCount { get; set; }
    }
}
</code>```

Body:
I'm trying to display data that I pulled from text files within my program to a DataGridView but I'm having trouble finding out how to do it, another problem I have is that when the form opens it stops running through the code.

Here is the main part of my code:

DataGridView dataGridView = new DataGridView();
IList<Machine> machines = new BindingList<Machine>();
dataGridView.DataSource = machines;

SessionOptions sessionOptions = new SessionOptions
        {
            Protocol = Protocol.Sftp,
            HostName = hostIP,
            UserName = userName,
            Password = passWord,
            PortNumber = 22,
            SshHostKeyFingerprint = "ssh-rsa 2048 96:48:96:52:8c:e7:de:c6:e1:00:08:7e:db:ad:e4:06"

        };

        using (Session session = new Session())
        {
            session.Open(sessionOptions);

            TransferOptions transferOptions = new TransferOptions();
            transferOptions.TransferMode = TransferMode.Binary;

            session.GetFiles(remotePath, @"C:\Users\mark\Desktop\Project Dex\Temp\").Check();
        }

        DirectoryInfo directorySelected = new DirectoryInfo(@"C:\Users\mark\Desktop\Project Dex\Temp\PROCESSED\");
        List<string> fileNames = new List<string>();

        foreach (FileInfo fileInfo in directorySelected.GetFiles("*.zip"))
        {
            fileNames.Add(fileInfo.Name);
        }

        foreach (string fileName in fileNames)
        {
            string zipFilePath = localPath + fileName;

            using (ZipFile zip1 = ZipFile.Read(zipFilePath))
            {
                var selection = (from e in zip1.Entries
                                 where (e.FileName).StartsWith("01e")
                                 select e);

                Directory.CreateDirectory(zipTemp);

                foreach (var e in selection)
                {
                    e.Extract(zipTemp, ExtractExistingFileAction.OverwriteSilently);
                }
            }

            DirectoryInfo dexDirect = new DirectoryInfo(@"C:\Users\mark\Desktop\Project Dex\zipTemp\");
            List<string> dexName = new List<string>();

            foreach (FileInfo dexInfo in dexDirect.GetFiles("*.dex"))
            {
                dexName.Add(dexInfo.Name);
            }

            foreach (string dexNames in dexName)
            {
                string dexFilePath = zipTemp + dexNames;

                string[] lines = System.IO.File.ReadAllLines(dexFilePath);

                foreach (string line in lines)
                {
                    machineCashCount = Array.Find(lines,
                element => element.StartsWith("VA1", StringComparison.Ordinal));
                }
                string[] MCC1 = machineCashCount.Split('*');
                string[] nm = dexNames.Split('.');

                int nam = int.Parse(nm[0], System.Globalization.NumberStyles.HexNumber);

                //Console.WriteLine((nam + (":") + "Total cash count: ") + MCC1[1]);
                //Console.WriteLine((nam + (":") + "Number of paid vends: ") + MCC1[2]);

                Machine m = new Machine();

                m.MacNum = nm[0];
                m.CashCount = MCC1[1];
                m.VendCount = MCC1[2];
                machines.Add(m);

            }
        }

        Application.Run(new Form1());
    }
}

}

screenshot

Body:
For your specific error of "cannot create an instance of the abstract class or interface IList", the problem is that you're trying to create an instance of an interface. You want a concrete class. For example, List implements IList so you can do

IList<string> names = new List<string>();

An interface is basically just a contract describing what a class that implements it can do.

As for you question, you want to create a class to hold your data, parse your files into objects, put them in a BindingList or any other appropriate collection then bind your datagridview to that collection.

class Machine
{
    public string Name {get; set;}
    public decimal CashCount {get; set;}
}

public static void main()
{
    IList<Machine> machines = new BindingList<Machine>();

    foreach(string fileName in fileNames)
    {
        //read your files, put data in a Machine object
        Machine m =new Machine();
        m.Name=nm[0];
        m.CashCount=MCC1[0];
        //add it to the list
        machines.add(m);
    }

    //then bind the collection to your datagridview
    datagridView.Datasource = machines;
}

Then in your form designer, you can add 2 columns to the datagridview and set their binding to Name and CashCount respectively. You could also, for example, set the format of the CashCount columns to be displayed as money.

Edit: adding minimal working example

using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;

namespace datagridview
{
    public partial class Form1 : Form
    {
        private DataGridView dgvMachines;

        public Form1()
        {
            InitializeComponent();
            //this is the Designer.cs code...
            this.dgvMachines = new System.Windows.Forms.DataGridView();
            ((System.ComponentModel.ISupportInitialize)(this.dgvMachines)).BeginInit();
            this.SuspendLayout();
            //
            // dgvMachines
            //
            this.dgvMachines.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dgvMachines.Location = new System.Drawing.Point(12, 12);
            this.dgvMachines.Name = "dgvMachines";
            this.dgvMachines.Size = new System.Drawing.Size(606, 400);
            this.dgvMachines.TabIndex = 0;
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(630, 434);
            this.Controls.Add(this.dgvMachines);
            this.Name = "Form1";
            this.Text = "Form1";
            ((ISupportInitialize)(this.dgvMachines)).EndInit();
            this.ResumeLayout(false);

            IList<Machine> machines = new BindingList<Machine>();
            dgvMachines.DataSource = machines;
            machines.Add(new Machine { Name = "#1", CashCount = 100 });
            machines.Add(new Machine { Name = "#2", CashCount = 200 });
            machines.Add(new Machine { Name = "#3", CashCount = 300 });
            machines.Add(new Machine { Name = "#4", CashCount = 400 });
        }
    }

    class Machine
    {
        public string Name { get; set; }
        public decimal CashCount { get; set; }
    }
}


答:
If it is anything like the previous versions of MVC then you will need to uncomment those route attributes ([HttpGet("mailbuilder/MailBody/{id}")]) but also rename your post action to the same name. Alternatively, you can set the action in the form helper (if that still exists).

Also so the router can find the right method you need to provide the route data as an object return RedirectToAction("MailBody", new { id = model.Id });

The following code example is untested but I think it will be on the right track...

```<code>[HttpGet("mailbuilder/MailBody")]
public IActionResult MailBody()
{
   Body model = new Body();
   return View(model);
}

[HttpGet("mailbuilder/MailBody/{id}")]
public IActionResult MailBody(int id)
{
   Body model = _mailBuilderService.GetBody(id);
   return View(model);
}

[HttpPost("mailbuilder/MailBody")]
public IActionResult MailBody(Body model)
{
  _mailBuilderService.AddBody(model);
  return RedirectToAction("MailBody", new { id = model.Id });
}
</code>```

Title: Overloading with MVC Controllers

Body:
If it is anything like the previous versions of MVC then you will need to uncomment those route attributes ([HttpGet("mailbuilder/MailBody/{id}")]) but also rename your post action to the same name. Alternatively, you can set the action in the form helper (if that still exists).

Also so the router can find the right method you need to provide the route data as an object return RedirectToAction("MailBody", new { id = model.Id });

The following code example is untested but I think it will be on the right track...

[HttpGet("mailbuilder/MailBody")]
public IActionResult MailBody()
{
   Body model = new Body();
   return View(model);
}

[HttpGet("mailbuilder/MailBody/{id}")]
public IActionResult MailBody(int id)
{
   Body model = _mailBuilderService.GetBody(id);
   return View(model);
}

[HttpPost("mailbuilder/MailBody")]
public IActionResult MailBody(Body model)
{
  _mailBuilderService.AddBody(model);
  return RedirectToAction("MailBody", new { id = model.Id });
}


问:
clicking on dynamic values in a web table in selenium
Below is my Table structure:

I want to click on the first cell of "policyno " column only if value is not empty

How do I achieve this?

答:
Try using this.

```<code>WebElement elem = driver.findElement(By.xpath("//table/tbody/tr[2]/td[3]/span/a"));

if(!(elem.getText().trim().equals(""))){
    elem.click();
}
</code>```

Body:
Try using this.

WebElement elem = driver.findElement(By.xpath("//table/tbody/tr[2]/td[3]/span/a"));

if(!(elem.getText().trim().equals(""))){
    elem.click();
}


问:
NFC or BLE to read Mac address of device
Objective: Public WiFi login

Instead of customers connecting to wifi and captive portal to login to WiFi I want the customer to show his phone to a magic ball which will read device MAC address using either NFC or BLE and add that Mac address to the list of allowed devices.

Challenge: reading MAC address using ble or NFC without any apps!

Your input please on how this can be achieved.

Thanks.

答: That's not possible without any app. Remember that the Bluetooth Device Address is usually different from the WiFi MAC address.</p>


问:
Is it possible to secure a ColdFusion 11 REST Service with HTTP BASIC Authentication?
I am setting up a simple REST Service in ColdFusion 11. The web server is IIS 8.5 on Windows Server 2012R2.

This REST Service needs to be secured to prevent unauthorized users from accessing/writing data. For the time being, there will be only one authorized user, so I want to keep authentication/authorization as simple as possible. My initial thought is to use HTTP BASIC Authentication.

Here's the setup for the REST Service:

Source Directory: C:\web\site1\remoteapi\
REST path: inventory

To implement this, I configured the source directory of the REST Service in IIS to authorize only one user, disable Anonymous authentication, and enable Basic authentication.

When I call the source directory directly in a browser (i.e. http://site1/remoteapi/inventory.cfc?method=read), I am presented with the Basic authentication dialog.

However, when I attempt to request the REST path (http://site1/rest/inventory/), I am not challenged at all.

How can I implement HTTP BASIC authentication on the REST path?

答:
So, due to the need to get this done without much delay, I went ahead and using some principles from Ben Nadel's website, I wrote my own authentication into the onRequestStart() method of the REST Service's Application.cfc. Here is the basic code, though it uses hard-coded values in the VARIABLES scope to validate the username and password and also does not include any actual "authorization" setting:</p>

```<code>public boolean function onRequestStart(required string targetPage) {
    LOCAL.Response = SUPER.onRequestStart(ARGUMENTS.targetpage);

    if  (!StructKeyExists(GetHTTPRequestData().Headers, "Authorization")) {
        cfheader(
            name="WWW-Authenticate",
            value="Basic realm=""REST API Access"""
            );

        LOCAL.RESTResponse = {
            status = 401,
            content = {Message = "Unauthorized"}
            };

        restSetResponse(LOCAL.RESTResponse);
    }
    else {
        LOCAL.IsAuthenticated = true;

        LOCAL.EncodedCredentials =
            GetToken( GetHTTPRequestData().Headers.Authorization, 2, " " );

        //  Credential string is not Base64
        if  (   !ArrayLen(
                    REMatch(
                        "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$",
                        LOCAL.EncodedCredentials
                        )
                    )
            ) {
            LOCAL.IsAuthenticated = false;
        }
        else {
            //  Convert Base64 to String
            LOCAL.Credentials =
                ToString(ToBinary( LOCAL.EncodedCredentials ));

            LOCAL.Username = GetToken( LOCAL.Credentials, 1, ":" );
            LOCAL.Password = GetToken( LOCAL.Credentials, 2, ":" );

            if  (   LOCAL.Username != VARIABLES.CREDENTIALS.Username
                ||  LOCAL.Password != VARIABLES.CREDENTIALS.Password
                ) {
                LOCAL.IsAuthenticated = false;
            }
        }

        if  (!LOCAL.IsAuthenticated) {
            LOCAL.Response = {
                status = 403,
                content = {Message = "Forbidden"}
                };

            restSetResponse(LOCAL.Response);
        }
    }

    return LOCAL.Response;
}
</code>```

Body:
So, due to the need to get this done without much delay, I went ahead and using some principles from Ben Nadel's website, I wrote my own authentication into the onRequestStart() method of the REST Service's Application.cfc. Here is the basic code, though it uses hard-coded values in the VARIABLES scope to validate the username and password and also does not include any actual "authorization" setting:

public boolean function onRequestStart(required string targetPage) {
    LOCAL.Response = SUPER.onRequestStart(ARGUMENTS.targetpage);

    if  (!StructKeyExists(GetHTTPRequestData().Headers, "Authorization")) {
        cfheader(
            name="WWW-Authenticate",
            value="Basic realm=""REST API Access"""
            );

        LOCAL.RESTResponse = {
            status = 401,
            content = {Message = "Unauthorized"}
            };

        restSetResponse(LOCAL.RESTResponse);
    }
    else {
        LOCAL.IsAuthenticated = true;

        LOCAL.EncodedCredentials =
            GetToken( GetHTTPRequestData().Headers.Authorization, 2, " " );

        //  Credential string is not Base64
        if  (   !ArrayLen(
                    REMatch(
                        "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$",
                        LOCAL.EncodedCredentials
                        )
                    )
            ) {
            LOCAL.IsAuthenticated = false;
        }
        else {
            //  Convert Base64 to String
            LOCAL.Credentials =
                ToString(ToBinary( LOCAL.EncodedCredentials ));

            LOCAL.Username = GetToken( LOCAL.Credentials, 1, ":" );
            LOCAL.Password = GetToken( LOCAL.Credentials, 2, ":" );

            if  (   LOCAL.Username != VARIABLES.CREDENTIALS.Username
                ||  LOCAL.Password != VARIABLES.CREDENTIALS.Password
                ) {
                LOCAL.IsAuthenticated = false;
            }
        }

        if  (!LOCAL.IsAuthenticated) {
            LOCAL.Response = {
                status = 403,
                content = {Message = "Forbidden"}
                };

            restSetResponse(LOCAL.Response);
        }
    }

    return LOCAL.Response;
}


问:
Is there any value in including SQLite in VCS's
Having an argument with my team. We are developing an application using SQLite and some want to add it to the repo (GIT) and some don't. Previously with RDBMS system there has been no perceived benefit of using VCS on the DB. However SQLite is a self contained file with no external dependencies so i assume, even though it is binary, that a commit of the project code + the SQLite  file will give an accurate snapshot of the state of play at that point.

I also assume that a branch and merge would work as well.

Has anyone actually done this and if so does it work?

答:
Generally speaking, it's preferable to include full set of dependencies in a VCS repository. This makes your life a whole lot simpler.

If you're after versioning DB schema, check out Wizardby.


问:
Geo-location in Ionic 2
I'm working on Ionic app, which should show users on the map by their current geo-location.

For example, User 1 can turn on GPS, and other Users can see him on
the map after opening a MapComponent. For example, GeoService can fetch current data of the Users's location, on safe it frequently in db (once a minute, for example), and other users, when open MapComponent, can fetch all of data from db collection, and see the Points on the map.

What plugins should I use, or tutorials to archive it? How to get access of the GPS location. How to enable and disable it?

答:
Ionic Native will be a life saver for you.

Ionic Native is a TypeScript wrapper for Cordova/PhoneGap plugins that make adding any native functionality you need to your Ionic mobile app easy.

Geolocation

Depending on how accurate you want the geolocation ping to be and how energy you want it to use you can either go for Background Geolocation (cheap) or Geolocation.

Map Component

In order to display a map with markers on it you should use the Google Maps plugin.

Local Data Cache

You will probably also need a way to cache locally any data you get from the backend (or anything else). The best and easiest way to go about it is using ionic-storage.

Developing using native cordova plugins

In any case, since all these APIs are operating on top of Cordova, you should only test this functionality in an actual device or in an emulator. Of course when geolocation is involved, you cannot go run around the block each time you make a code change so I strongly advise you to mock these plugins during development.

Title: Geo-location in Ionic 2


问:
C++ Template : Choosing overloaded functions using implicit conversion to template instantiated type!
Consider these overloaded functions,

```<code>void fun(Int2Type<1>) {}
void fun(Int2Type<2>) {}
void fun(Int2Type<3>) {}
void fun(Int2Type<4>) {}
</code>```

I want to call these in this way,

```<code>fun(1); // this should call first function
fun(4); // this should call fourth function
</code>```

Is there a way to do that? If yes, so can we do the same with some runtime value, say this,
(please note that in the above calls, the argument is known at compile-time)

```<code>fun(value); // value can be decided at runtime!
</code>```

Or any alternative if that is not possible? The goal is, different function should be called based on different integral value!

EDIT

By the way, I cannot use any of the following:

Using switch(value)

using some SomeFuncTable funTable[] = {fun(Int2Type<1>(), fun(Int2Type<2>()} etc

答:
There is no way to accomplish what you want, because they all boil down to the same thing- a jump table, or a large series of if/else. That's it. Any other feature is going to become just that. Just make a jump table. You could use an array of function pointers (the fastest) or something more flexible like an unordered_map<int, std::function<void()>>.

Oh, unless you want to write your own JIT compiler and JIT the new assembly code when you need it. You could do that. But I don't really see the point, as you still run down to the same problem- how to pick the code path to take, which is going to become a jump table or if/else chain.

Body:
Consider these overloaded functions,

void fun(Int2Type<1>) {}
void fun(Int2Type<2>) {}
void fun(Int2Type<3>) {}
void fun(Int2Type<4>) {}

I want to call these in this way,

fun(1); // this should call first function
fun(4); // this should call fourth function

Is there a way to do that? If yes, so can we do the same with some runtime value, say this,
(please note that in the above calls, the argument is known at compile-time)

fun(value); // value can be decided at runtime!

Or any alternative if that is not possible? The goal is, different function should be called based on different integral value!

EDIT

By the way, I cannot use any of the following:

Using switch(value)

using some SomeFuncTable funTable[] = {fun(Int2Type<1>(), fun(Int2Type<2>()} etc


问:
Trouble installling elastic search
I am having trouble installing elasticsearch on windows 7 professional. When I click on elasticsearch.bat it  gives me the following error:

'findstr' is not recognized as an internal or external command,
  operable program or batch file. Could not find any executable java
  binary. Please install java in your PATH or set JAVA_HOME Press any
  key to continue . . .

答: This means you haven't installed java or you have not set JAVA_HOME path properly. First Install java and then try installing elasticsearch</p>

Title: Trouble installling elastic search


问:
Assigning event to subscribe with new
I'm making QuestSystem in unity.

what i want to do is assigning to my questData an event so it can know when the quest objective has been completed.

Lets say there is a class named A and action called a.

and i want Class B, Action b want to have reference to A.a

So if i do

b = A.a;,

b+= someAction;, it actually does a+=someAction;

but when if i do that. It will just simply b+=someAction and A.a will remain null

what should i do to perform what i want?

here are some tags. (i don't know what the answer would be. so..)

```<code># event
# subscribing event
# assigning event
# referencing event
# action
# delegate
</code>```

====== Edited =======
here is my code.

QuestData.cs

```<code>public class QuestData
{
    public string questName;
    public string qusetID;
    public string questDescription;
    public SceneType questSceneType;

    private string isActivePrefsKey { get { return $"QuestKey{qusetID}"; } }
    public bool isActive {
        get {
            return Convert.ToBoolean (PlayerPrefs.GetInt (isActivePrefsKey));
        }
        set { PlayerPrefs.SetInt (isActivePrefsKey, Convert.ToInt16 (value)); }
    }
    public QuestObjective questObjective;
    public QuestReward questReward;

    public void Activate ()
    {
        if (AppController.CurrentScene == questSceneType) {
            questObjective.ActivateObjective ();

        }
    }

}
</code>```

QuestObjective.cs

```<code>public class QuestObjective
{
    // TODO rename all
    public int goalObjectiveCount;
    public int currentObjectiveCount;

    public Action questAction;

    public void OnConditionMatch ()
    {
        Debug.Log ("OnConditionMatch");
        currentObjectiveCount += 1;
    }

    public void ActivateObjective ()
    {
        questAction += OnConditionMatch;
    }

}
</code>```

QuestManager.cs

```<code>public class QuestManager : MonoBehaviour
{

    List<QuestData> questDatas;

    void Awake ()
    {
        PrepareQuestDatas ();
        ActivateActiveQuests ();
    }

    void ActivateActiveQuests ()
    {
        var activeQuests = GetActiveQuests ();
        foreach (var activeQuest in activeQuests) {
            activeQuest.Activate ();
        }
    }

    List<QuestData> GetActiveQuests ()
    {
        // for debuging
        return questDatas;

        // real code
        return questDatas.Where (q => q.isActive == true).ToList ();
    }

    public void PrepareQuestDatas ()
    {
        questDatas = new List<QuestData> {
            new QuestData {
                questName = "Foot Print",
                questDescription  = "win the game for first time",
                questSceneType = SceneType.Main,
                questObjective = new QuestObjective {
                    goalObjectiveCount = 1,
                    questAction = GamePlayController.instance.endGameCon.onWinGame
                },
                questReward = new QuestCoinReward{
                    rewardAmount = 100,
                },
            }
        };
    }

}
</code>```

答:
Reading into your example, I have written up some code where "A" is QuestObjective and "B" is Quest.  The Quest object needs to know when objective has been marked as completed.

Using event handlers, we can set it up so that B is notified when an action occurs on A.

Like this:

```<code>// B
public class Quest
{
    public Quest()
    {
        Objectives = new List<QuestObjective>();
        // load objectives... Fake
        Objectives.Add(new QuestObjective("obj 1"));
        Objectives.Add(new QuestObjective("obj 2"));
        Objectives.Add(new QuestObjective("obj 3"));

        foreach(var o in Objectives) // subscribe to QuestObjective events
        {
            o.ObjectiveCompleted += (sender, args) => ReportObjectiveCompleted();
        }
    }

    public void ReportObjectiveCompleted()
    {
        // let 'em know
    }

    public List<QuestObjective> Objectives { get; set; }
}

// A
public class QuestObjective
{
    public string Name { get; set; }
    public QuestObjective(string name = "unknown")
    {
        Name = name;
    }
    public event EventHandler ObjectiveCompleted;

    public void MarkCompleted()
    {
        // when a task is marked as complete and IF there are
        // subscribers to this event then call the event handler
        var a = ObjectiveCompleted;
        if (a != null)
        {
            a(this, new EventArgs()); // use different event args to pass data
        }
    }
}
</code>```

Title: Assigning event to subscribe with new

Body:
I'm making QuestSystem in unity.

what i want to do is assigning to my questData an event so it can know when the quest objective has been completed.

Lets say there is a class named A and action called a.

and i want Class B, Action b want to have reference to A.a

So if i do

b = A.a;,

b+= someAction;, it actually does a+=someAction;

but when if i do that. It will just simply b+=someAction and A.a will remain null

what should i do to perform what i want?

here are some tags. (i don't know what the answer would be. so..)

# event
# subscribing event
# assigning event
# referencing event
# action
# delegate

====== Edited =======
here is my code.

QuestData.cs

public class QuestData
{
    public string questName;
    public string qusetID;
    public string questDescription;
    public SceneType questSceneType;

    private string isActivePrefsKey { get { return $"QuestKey{qusetID}"; } }
    public bool isActive {
        get {
            return Convert.ToBoolean (PlayerPrefs.GetInt (isActivePrefsKey));
        }
        set { PlayerPrefs.SetInt (isActivePrefsKey, Convert.ToInt16 (value)); }
    }
    public QuestObjective questObjective;
    public QuestReward questReward;

    public void Activate ()
    {
        if (AppController.CurrentScene == questSceneType) {
            questObjective.ActivateObjective ();

        }
    }

}

QuestObjective.cs

public class QuestObjective
{
    // TODO rename all
    public int goalObjectiveCount;
    public int currentObjectiveCount;

    public Action questAction;

    public void OnConditionMatch ()
    {
        Debug.Log ("OnConditionMatch");
        currentObjectiveCount += 1;
    }

    public void ActivateObjective ()
    {
        questAction += OnConditionMatch;
    }

}

QuestManager.cs

public class QuestManager : MonoBehaviour
{

    List<QuestData> questDatas;

    void Awake ()
    {
        PrepareQuestDatas ();
        ActivateActiveQuests ();
    }

    void ActivateActiveQuests ()
    {
        var activeQuests = GetActiveQuests ();
        foreach (var activeQuest in activeQuests) {
            activeQuest.Activate ();
        }
    }

    List<QuestData> GetActiveQuests ()
    {
        // for debuging
        return questDatas;

        // real code
        return questDatas.Where (q => q.isActive == true).ToList ();
    }

    public void PrepareQuestDatas ()
    {
        questDatas = new List<QuestData> {
            new QuestData {
                questName = "Foot Print",
                questDescription  = "win the game for first time",
                questSceneType = SceneType.Main,
                questObjective = new QuestObjective {
                    goalObjectiveCount = 1,
                    questAction = GamePlayController.instance.endGameCon.onWinGame
                },
                questReward = new QuestCoinReward{
                    rewardAmount = 100,
                },
            }
        };
    }

}

Body:
Reading into your example, I have written up some code where "A" is QuestObjective and "B" is Quest.  The Quest object needs to know when objective has been marked as completed.

Using event handlers, we can set it up so that B is notified when an action occurs on A.

Like this:

// B
public class Quest
{
    public Quest()
    {
        Objectives = new List<QuestObjective>();
        // load objectives... Fake
        Objectives.Add(new QuestObjective("obj 1"));
        Objectives.Add(new QuestObjective("obj 2"));
        Objectives.Add(new QuestObjective("obj 3"));

        foreach(var o in Objectives) // subscribe to QuestObjective events
        {
            o.ObjectiveCompleted += (sender, args) => ReportObjectiveCompleted();
        }
    }

    public void ReportObjectiveCompleted()
    {
        // let 'em know
    }

    public List<QuestObjective> Objectives { get; set; }
}

// A
public class QuestObjective
{
    public string Name { get; set; }
    public QuestObjective(string name = "unknown")
    {
        Name = name;
    }
    public event EventHandler ObjectiveCompleted;

    public void MarkCompleted()
    {
        // when a task is marked as complete and IF there are
        // subscribers to this event then call the event handler
        var a = ObjectiveCompleted;
        if (a != null)
        {
            a(this, new EventArgs()); // use different event args to pass data
        }
    }
}