问:
Connection terminated parsing multipart data in Angulrjs and JAX-RS
I wish to send my localhost (in spring boot server) a selected image from the user using AngularJS and add data object in BD using JAX-RS.

-Code HTML:

```<code><form role="form" enctype="multipart/form-data" name="myForm" ng-submit="uploadfile()">
<label class="control-label">Image:</label>
<input type="file" class="form-control " file-model="Image" >
<input type="text" class="form-control " ng-model="name" >
 <input type="text" class="form-control " ng-model="lastname" >
<button type="submit"> save</button>
</form>
</code>```

--code AngularJS;

```<code>var app = angular.module('Mainapp', ['ngRoute','file-model','ui.bootstrap']);
app.directive('fileModel', ['$parse', function ($parse) {
    return {
       restrict: 'A',
       link: function(scope, element, attrs) {
          var model = $parse(attrs.fileModel);
          var modelSetter = model.assign;

          element.bind('change', function(){
             scope.$apply(function(){
                modelSetter(scope, element[0].files[0]);
             });
          });
       }
    };
 }]);

app.service('fileUpload', ['$http', function ($http) {
    this.uploadFileToUrl = function(file, uploadUrl){
        var fd = new FormData();
        //fd.append('file', file);
       angular.forEach(file, function(file) {
            fd.append('file', file);
        });

        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        }).then(function(response) {
            console.log("done post "+response);
    }).catch(function(e) {
        console.log('failed to post: ', e);
        throw e;
    })

    }
}]);
//upload file and data object of user
$scope.uploadfile = function() {
        var file = $scope.Image;
         console.dir(file);
        var uploadUrl ="http://localhost:8000/auditconfig/images/"+file.name;
        fileUpload.uploadFileToUrl(file, uploadUrl); // error here "failed to post"

var user = {
              name: $scope.name,
              lastname: $scope.lastname,
              image:file.name
             };
$http.post(url+"/add", user) //The user is added to the database
.success(function(data) {
      $scope.ListUsers = data;
}).error(function(err, data) {
    console.log("error: " +data);
});
  };
</code>```

-After a test of the "uploadfile ()", I get the following results:

```<code>//**console.dir(file);
*File:
lastModified:1490260924299
lastModifiedDate; Thu Mar 23 2017 10:22:04 GMT+0100 (Paris, Madrid)
name:"01.png"
size:1637
type:"image/png"
webkitRelativePath:""
__proto__:File
</code>```

-Test of upload file:

```<code>//**console.log('failed to post: ', e);
Failed to load resource: the server responded with a status of 500 (Internal Server Error) :8099/AuditConf/images/01.png
failed to post: Object
Config:Objectd
ata:FormData
__proto__:FormData
headers:Object
Accept:"application/json, text/plain, */*"
Content-Type:undefined
__proto__:Object
method:"POST"
transformRequest:function identity($)
transformResponse:Array(1)
url:"http://localhost:8099/AuditConf/images/Exception--JAX-RS.png"
__proto__:Object
data:Object
error:"Internal Server Error"
exception:"java.lang.RuntimeException"
message:"java.io.IOException: UT000036: Connection terminated parsing multipart data"
path:"/auditconfig/images/Exception--JAX-RS.png"
status:500
timestamp:1490778930961
__proto__:Object
headers:function (name)
status:500 statusText
:"Internal Server Error"
__proto__;Object
</code>```

答:
The solution is:</p>

```<code>var app = angular.module('Mainapp', ['ngRoute','file-model','ui.bootstrap']);
app.directive('fileModel', ['$parse', function ($parse) {
    return {
       restrict: 'A',
       link: function(scope, element, attrs) {
          var model = $parse(attrs.fileModel);
          var modelSetter = model.assign;

          element.bind('change', function(){
             scope.$apply(function(){
                modelSetter(scope, element[0].files[0]);
             });
          });
       }
    };
 }]);
this.uploadFileToUrl = function(file, uploadUrl){
    var data = new FormData();
    data.append('file', file);
    return $http.post(uploadUrl, data, {
        transformRequest: angular.identity,
        headers: { 'Content-Type': undefined }
      }).then(function (results) {
        return results;
    });
}
//upload file and data object of user
$scope.uploadfile = function() {
        var file = $scope.Image;
         console.dir(file);

      //URL of API not path of floder
        var uploadUrl ="http://localhost:8000/auditconfig/UpFile";
        fileUpload.uploadFileToUrl(file, uploadUrl);
var user = {
              name: $scope.name,
              lastname: $scope.lastname,
              image:file.name
             };
$http.post(url+"/add", user)
.success(function(data) {
      $scope.ListUsers = data;
}).error(function(err, data) {
    console.log("error: " +data);
});
  };
</code>```

Body:
I wish to send my localhost (in spring boot server) a selected image from the user using AngularJS and add data object in BD using JAX-RS.

-Code HTML:

<form role="form" enctype="multipart/form-data" name="myForm" ng-submit="uploadfile()">
Image:
<input type="file" class="form-control " file-model="Image" >
<input type="text" class="form-control " ng-model="name" >
 <input type="text" class="form-control " ng-model="lastname" >
<button type="submit"> save</button>
</form>

--code AngularJS;

var app = angular.module('Mainapp', ['ngRoute','file-model','ui.bootstrap']);
app.directive('fileModel', ['$parse', function ($parse) {
    return {
       restrict: 'A',
       link: function(scope, element, attrs) {
          var model = $parse(attrs.fileModel);
          var modelSetter = model.assign;

          element.bind('change', function(){
             scope.$apply(function(){
                modelSetter(scope, element[0].files[0]);
             });
          });
       }
    };
 }]);

app.service('fileUpload', ['$http', function ($http) {
    this.uploadFileToUrl = function(file, uploadUrl){
        var fd = new FormData();
        //fd.append('file', file);
       angular.forEach(file, function(file) {
            fd.append('file', file);
        });

        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        }).then(function(response) {
            console.log("done post "+response);
    }).catch(function(e) {
        console.log('failed to post: ', e);
        throw e;
    })

    }
}]);
//upload file and data object of user
$scope.uploadfile = function() {
        var file = $scope.Image;
         console.dir(file);
        var uploadUrl ="http://localhost:8000/auditconfig/images/"+file.name;
        fileUpload.uploadFileToUrl(file, uploadUrl); // error here "failed to post"

var user = {
              name: $scope.name,
              lastname: $scope.lastname,
              image:file.name
             };
$http.post(url+"/add", user) //The user is added to the database
.success(function(data) {
      $scope.ListUsers = data;
}).error(function(err, data) {
    console.log("error: " +data);
});
  };

-After a test of the "uploadfile ()", I get the following results:

//**console.dir(file);
*File:
lastModified:1490260924299
lastModifiedDate; Thu Mar 23 2017 10:22:04 GMT+0100 (Paris, Madrid)
name:"01.png"
size:1637
type:"image/png"
webkitRelativePath:""
__proto__:File

-Test of upload file:

//**console.log('failed to post: ', e);
Failed to load resource: the server responded with a status of 500 (Internal Server Error) :8099/AuditConf/images/01.png
failed to post: Object
Config:Objectd
ata:FormData
__proto__:FormData
headers:Object
Accept:"application/json, text/plain, */*"
Content-Type:undefined
__proto__:Object
method:"POST"
transformRequest:function identity($)
transformResponse:Array(1)
url:"http://localhost:8099/AuditConf/images/Exception--JAX-RS.png"
__proto__:Object
data:Object
error:"Internal Server Error"
exception:"java.lang.RuntimeException"
message:"java.io.IOException: UT000036: Connection terminated parsing multipart data"
path:"/auditconfig/images/Exception--JAX-RS.png"
status:500
timestamp:1490778930961
__proto__:Object
headers:function (name)
status:500 statusText
:"Internal Server Error"
__proto__;Object

Body:
The solution is:

var app = angular.module('Mainapp', ['ngRoute','file-model','ui.bootstrap']);
app.directive('fileModel', ['$parse', function ($parse) {
    return {
       restrict: 'A',
       link: function(scope, element, attrs) {
          var model = $parse(attrs.fileModel);
          var modelSetter = model.assign;

          element.bind('change', function(){
             scope.$apply(function(){
                modelSetter(scope, element[0].files[0]);
             });
          });
       }
    };
 }]);
this.uploadFileToUrl = function(file, uploadUrl){
    var data = new FormData();
    data.append('file', file);
    return $http.post(uploadUrl, data, {
        transformRequest: angular.identity,
        headers: { 'Content-Type': undefined }
      }).then(function (results) {
        return results;
    });
}
//upload file and data object of user
$scope.uploadfile = function() {
        var file = $scope.Image;
         console.dir(file);

      //URL of API not path of floder
        var uploadUrl ="http://localhost:8000/auditconfig/UpFile";
        fileUpload.uploadFileToUrl(file, uploadUrl);
var user = {
              name: $scope.name,
              lastname: $scope.lastname,
              image:file.name
             };
$http.post(url+"/add", user)
.success(function(data) {
      $scope.ListUsers = data;
}).error(function(err, data) {
    console.log("error: " +data);
});
  };


来源: stackexchange

问:
Display version name
I want to display the versionName ( number) located in the android manifest on my spalsh screen. I found some example codes but they are not working. This seems like a simple task but it does not display for me

text view from splash xml:

```<code>   <TextView
        android:id="@+id/ver_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="33dp"
        android:layout_marginRight="30dp"
        android:text=" " />
</code>```

display method:

```<code>    private void displayVersionName() {
    String versionName = "";
    PackageInfo packageInfo;
    try {
        packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
        versionName = "ver:" + packageInfo.versionName;
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    }
    TextView tv = (TextView) findViewById(R.id.ver_name);
    tv.setText(versionName);
  }
</code>```

答:
Try this :

```<code> TextView tv = (TextView) findViewById(R.id.ver_name);
 tv.setText("version : " + BuildConfig.VERSION_NAME);
</code>```

And import the BuildConfig of the package where you want to have the versionName :

```<code>import com.yourpackage.BuildConfig;
</code>```

ContentLicense: CC BY-SA 3.0

Title: Display version name

Body:
I want to display the versionName ( number) located in the android manifest on my spalsh screen. I found some example codes but they are not working. This seems like a simple task but it does not display for me

text view from splash xml:

   <TextView
        android:id="@+id/ver_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="33dp"
        android:layout_marginRight="30dp"
        android:text=" " />

display method:

    private void displayVersionName() {
    String versionName = "";
    PackageInfo packageInfo;
    try {
        packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
        versionName = "ver:" + packageInfo.versionName;
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    }
    TextView tv = (TextView) findViewById(R.id.ver_name);
    tv.setText(versionName);
  }

Body:
Try this :

 TextView tv = (TextView) findViewById(R.id.ver_name);
 tv.setText("version : " + BuildConfig.VERSION_NAME);

And import the BuildConfig of the package where you want to have the versionName :

import com.yourpackage.BuildConfig;


问:
How do I display the number of total responders to a poll?
I have a poll which I made using PHP and Ajax, the poll is a yes/no question, and my code only shows the % of yes and no. The big question is: how I display the number of total responders. In following, Ii will display the code I use:

```<code><script>
function getVote(int) {
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else {  // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function() {
    if (this.readyState==4 && this.status==200) {
      document.getElementById("poll").innerHTML=this.responseText;
    }
  }
  xmlhttp.open("GET","poll_app/poll_vote.php?vote="+int,true);
  xmlhttp.send();
}
</script>
<h3 align="center">Are you satisfied with our services?</h3><br>
<form id="pollform">
yes:
<input type="radio" name="vote" value="0" onclick="getVote(this.value)">
<br>no:
<input type="radio" name="vote" value="1" onclick="getVote(this.value)">
</form>
</div>
</code>```

The php code:

```<code>$vote = $_REQUEST['vote'];
//get content of textfile
$filename = "poll_result.txt";
$content = file($filename);

//put content in array
$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];

if ($vote == 0) {
  $yes = $yes + 1;
}
if ($vote == 1) {
  $no = $no + 1;
}

//insert votes to txt file
$insertvote = $yes."||".$no;
$fp = fopen($filename,"w");
fputs($fp,$insertvote);
fclose($fp);
?>

<h2>Result:</h2>
<table>
<tr>
<td>Yes:</td>
<td>
<img src="poll1.gif"
width='<?php echo(100*round($yes/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($yes/($no+$yes),2)); ?>%
</td>
</tr>
<tr>
<td>No:</td>
<td>
<img src="poll2.gif"
width='<?php echo(100*round($no/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($no/($no+$yes),2)); ?>%
</td>
</tr>
</table>
</code>```

答:
You have both total answers in you text file. You can simply show both individual responses with percentage (%) and total responses below to them. Just like below in html code you can write something:</p>

```<code><h2>Result:</h2>
<table>
<tr>
<td>Yes:</td>
<td>
<img src="poll1.gif"
width='<?php echo(100*round($yes/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($yes/($no+$yes),2)); ?>%
(<?php echo $yes;  ?> Vote) </td>
</tr>
<tr>
<td>No:</td>
<td>
<img src="poll2.gif"
width='<?php echo(100*round($no/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($no/($no+$yes),2)); ?>%
  : (<?php echo $no;  ?> Vote)   </td>
</tr>
<tr> <?php echo $yes+$no; ?> total responses. </tr>
</table>
</code>```

Body:
I have a poll which I made using PHP and Ajax, the poll is a yes/no question, and my code only shows the % of yes and no. The big question is: how I display the number of total responders. In following, Ii will display the code I use:

Are you satisfied with our services?

<form id="pollform">
yes:
<input type="radio" name="vote" value="0" onclick="getVote(this.value)">

no:
<input type="radio" name="vote" value="1" onclick="getVote(this.value)">
</form>

The php code:

$vote = $_REQUEST['vote'];
//get content of textfile
$filename = "poll_result.txt";
$content = file($filename);

//put content in array
$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];

if ($vote == 0) {
  $yes = $yes + 1;
}
if ($vote == 1) {
  $no = $no + 1;
}

//insert votes to txt file
$insertvote = $yes."||".$no;
$fp = fopen($filename,"w");
fputs($fp,$insertvote);
fclose($fp);
?>

Result:

Yes:

<img src="poll1.gif"
width='<?php echo(100*round($yes/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($yes/($no+$yes),2)); ?>%

No:

<img src="poll2.gif"
width='<?php echo(100*round($no/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($no/($no+$yes),2)); ?>%

Body:
You have both total answers in you text file. You can simply show both individual responses with percentage (%) and total responses below to them. Just like below in html code you can write something:

<h2>Result:</h2>
<table>
<tr>
<td>Yes:</td>
<td>
<img src="poll1.gif"
width='<?php echo(100*round($yes/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($yes/($no+$yes),2)); ?>%
(<?php echo $yes;  ?> Vote) </td>
</tr>
<tr>
<td>No:</td>
<td>
<img src="poll2.gif"
width='<?php echo(100*round($no/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($no/($no+$yes),2)); ?>%
  : (<?php echo $no;  ?> Vote)   </td>
</tr>
<tr> <?php echo $yes+$no; ?> total responses. </tr>
</table>


问:
Deleted rows reappear after grid reload
When I press a grid's delete button, the row disappears from the grid but when grid is reloaded that row reappears. I tried a lot of commands with no results. Please help!
Thanks in advance.

This is the function that creates the grid:

```<code>// create the data store
var store = new Ext.data.Store({
    proxy: new Ext.ux.data.PagingMemoryProxy(myData),
    remoteSort:true,
    sortInfo: {field:'del', direction:'DESC'},

    reader: new Ext.data.ArrayReader({
        fields: [
           {name: 'id'},
           {name: 'name'},
           {name: 'category'},
           {name: 'price', type: 'float'},
           {name: 'active', type: 'int'},
           {name: 'actions', type:'text'}
        ]
    })
});
</code>```

And here is the remove function:

```<code>        buttons: [{
        text: 'Add',
        iconCls: 'silk-add',
        handler: this.onAdd

    }, '-', {
        text: 'Delete',
        iconCls: 'silk-delete',
                   handler: function(sm, rowIdx,r){

            var s = grid.getSelectionModel().getSelections();
            for(var i = 0, r; r = s[i]; i++){

              // store.remove(r);
               var index = store.data.indexOf(r);
               if(index > -1){
                r.join(null);
                store.data.removeAt(index);

            }
                store.modified.remove(r);

            if(index > -1){
                store.fireEvent('remove', store, r, index);
            }
                store.destroyRecord(store, r, index);
            }

           store.reload();
        },
    }]
</code>```

答: I found the solution, how to delete from mydata for ex: myData.splice (1,1);</p>

Title: Deleted rows reappear after grid reload

Body:
When I press a grid's delete button, the row disappears from the grid but when grid is reloaded that row reappears. I tried a lot of commands with no results. Please help!
Thanks in advance.

This is the function that creates the grid:

// create the data store
var store = new Ext.data.Store({
    proxy: new Ext.ux.data.PagingMemoryProxy(myData),
    remoteSort:true,
    sortInfo: {field:'del', direction:'DESC'},

    reader: new Ext.data.ArrayReader({
        fields: [
           {name: 'id'},
           {name: 'name'},
           {name: 'category'},
           {name: 'price', type: 'float'},
           {name: 'active', type: 'int'},
           {name: 'actions', type:'text'}
        ]
    })
});

And here is the remove function:

        buttons: [{
        text: 'Add',
        iconCls: 'silk-add',
        handler: this.onAdd

    }, '-', {
        text: 'Delete',
        iconCls: 'silk-delete',
                   handler: function(sm, rowIdx,r){

            var s = grid.getSelectionModel().getSelections();
            for(var i = 0, r; r = s[i]; i++){

              // store.remove(r);
               var index = store.data.indexOf(r);
               if(index > -1){
                r.join(null);
                store.data.removeAt(index);

            }
                store.modified.remove(r);

            if(index > -1){
                store.fireEvent('remove', store, r, index);
            }
                store.destroyRecord(store, r, index);
            }

           store.reload();
        },
    }]

ContentLicense: CC BY-SA 2.5


问:
Using Angular2 ngFor index
I have this code:

```<code><div class="row list-group">
  <div *ngFor="let product of products" >
    <app-product [product]="product"></app-product>
  </div>
</div>
</code>```

I was wondering is there any way i can get products from array in buckets? Something like this:

```<code><div class="list-group">
  <div *ngFor="products; index+3" >
    <div class="row">
      <app-product [product]="products[index]"></app-product>
      <app-product [product]="products[index+1]"></app-product>
      <app-product [product]="products[index+2]"></app-product>
    </div>
  </div>
</div>
</code>```

That way I could have all elements i need in a row

UPD

Thanks to Teddy Sterne I ended up with this solution:

```<code><div class="list-group">
  <div *ngFor="let product of products;let i = index">
    <div class="row" *ngIf="i%3===0">
      <app-product [product]="products[i]"></app-product>
      <div *ngIf="products[i + 1]">
        <app-product [product]="products[i + 1]"></app-product>
      </div>
      <div *ngIf="products[i + 2]">
        <app-product [product]="products[i + 2]"></app-product>
      </div>
    </div>
  </div>
</div>
</code>```

答:
Angular does not provide this functionality out of the box. I think that the simplest way to achieve the desired result is to only display data on every third index like so:

```<code><div class="list-group">
  <div *ngFor="let p of products; let idx = index" >
    <div class="row" *ngIf="idx % 3 === 0">
      <app-product [product]="products[idx]"></app-product>
      <app-product [product]="products[idx+1]"></app-product>
      <app-product [product]="products[idx+2]"></app-product>
    </div>
  </div>
</div>
</code>```

Demo

Title: Using Angular2 ngFor index

Body:
I have this code:

    <app-product [product]="product"></app-product>

I was wondering is there any way i can get products from array in buckets? Something like this:

      <app-product [product]="products[index]"></app-product>
      <app-product [product]="products[index+1]"></app-product>
      <app-product [product]="products[index+2]"></app-product>

That way I could have all elements i need in a row

UPD

Thanks to Teddy Sterne I ended up with this solution:

      <app-product [product]="products[i]"></app-product>

        <app-product [product]="products[i + 1]"></app-product>

        <app-product [product]="products[i + 2]"></app-product>

Body:
Angular does not provide this functionality out of the box. I think that the simplest way to achieve the desired result is to only display data on every third index like so:

<div class="list-group">
  <div *ngFor="let p of products; let idx = index" >
    <div class="row" *ngIf="idx % 3 === 0">
      <app-product [product]="products[idx]"></app-product>
      <app-product [product]="products[idx+1]"></app-product>
      <app-product [product]="products[idx+2]"></app-product>
    </div>
  </div>
</div>

Demo

ContentLicense: CC BY-SA 4.0


问:
BASE64 decode and ungzip data in PHP
I am working with OpenSubtitles API and need to BASE64 decode and ungzip API response ('$data' parameter) in PHP.

Full '$data' parameter you can find here:
https://jsfiddle.net/noxjmz40/

I can easily BASE64 decode this parameter with base64_decode($data) but I am not sure how to ungzip and get a normal result.

Please, advice me how to solve this task in a short and efficient way.
Thanks!

答:
This way you can get your output</p>

```<code>$output = gzdecode(base64_decode($data));
</code>```

Title: BASE64 decode and ungzip data in PHP

Body:
This way you can get your output

$output = gzdecode(base64_decode($data));


问:
Font Awesome With HTTPS
So I'm experiencing an issue with Font Awesome in IE8 when using HTTPS in my own site and this is even reproducible on Font Awesome's own site. If I go to Font Awesome over HTTPS  in IE8 I get boxes for all of the icons however if I go to Font Awesome over HTTP I get the icons rendered correctly.

What is the problem here? I've heard it could be something to do with the relative font paths in Font Awesome over HTTPS but not sure about that.

Here is a screenshot for those who like such things:

Update

So here is the code that references the fonts and loads the CSS. I'm going to use the code from Font Awesome's site since this seems to be an issue with Font Awesome and not
necessarily something with my site:

HTML that references CSS and an icon:

```<code><link rel="stylesheet" href="../assets/css/site.css">
<link rel="stylesheet" href="../assets/css/pygments.css">
<link rel="stylesheet" href="../assets/font-awesome/css/font-awesome.css">
...
<div class="fa-hover col-md-3 col-sm-4">
   <a href="../icon/adjust"><i class="fa fa-adjust"></i> fa-adjust</a>
</div>
</code>```

Within in font-awesome.css:

```<code>@font-face {
  font-family: 'FontAwesome';
  src: url('../fonts/fontawesome-webfont.eot');
  src: url('../fonts/fontawesome-webfont.eot?#iefix') format('embedded-opentype'),
  url('../fonts/fontawesome-webfont.woff?v=4.0.3') format('woff'),
  url('../fonts/fontawesome-webfont.ttf?v=4.0.3') format('truetype'), url('../fonts/fontawesome-webfont.svg?v=4.0.3#fontawesomeregular') format('svg');
  font-weight: normal;
  font-style: normal;
}
</code>```

答:
The practical answer is,using a proxy, to hide to the browser any cache-control and pragma: "no-cache" header returned to the browser.
I used nginx like this, adding the folowing commands the https proxied location:

```<code>  proxy_hide_header Cache-Control;
  proxy_hide_header Pragma;
</code>```

See here for details.

Title: Font Awesome With HTTPS

Body:
So I'm experiencing an issue with Font Awesome in IE8 when using HTTPS in my own site and this is even reproducible on Font Awesome's own site. If I go to Font Awesome over HTTPS  in IE8 I get boxes for all of the icons however if I go to Font Awesome over HTTP I get the icons rendered correctly.

What is the problem here? I've heard it could be something to do with the relative font paths in Font Awesome over HTTPS but not sure about that.

Here is a screenshot for those who like such things:

Update

So here is the code that references the fonts and loads the CSS. I'm going to use the code from Font Awesome's site since this seems to be an issue with Font Awesome and not
necessarily something with my site:

HTML that references CSS and an icon:

<link rel="stylesheet" href="../assets/css/site.css">
<link rel="stylesheet" href="../assets/css/pygments.css">
<link rel="stylesheet" href="../assets/font-awesome/css/font-awesome.css">
...

    fa-adjust

Within in font-awesome.css:

@font-face {
  font-family: 'FontAwesome';
  src: url('../fonts/fontawesome-webfont.eot');
  src: url('../fonts/fontawesome-webfont.eot?#iefix') format('embedded-opentype'),
  url('../fonts/fontawesome-webfont.woff?v=4.0.3') format('woff'),
  url('../fonts/fontawesome-webfont.ttf?v=4.0.3') format('truetype'), url('../fonts/fontawesome-webfont.svg?v=4.0.3#fontawesomeregular') format('svg');
  font-weight: normal;
  font-style: normal;
}

Body:
The practical answer is,using a proxy, to hide to the browser any cache-control and pragma: "no-cache" header returned to the browser.
I used nginx like this, adding the folowing commands the https proxied location:

  proxy_hide_header Cache-Control;
  proxy_hide_header Pragma;

See here for details.


问:
How can I convert OsStr to &[u8]/Vec<u8> on Windows?
I'm trying to persistent raw OS file names to storage, so I need to get the raw bytes of an OsStr.

It seems possible to call as_bytes() on *nix platforms, but that isn't defined on MS Windows.

Is there a portable way to convert OsStr to bytes?

答:
There is no defined interface for getting  the bytes of an OsStr on Windows in Rust 1.16. The actual implementation of OsStr delegates to system-specific code. On *nix, this is a wrapper around a Vec<u8>; on Windows, this is a wrapper around a Wtf8Buf. While Wtf8Buf is implemented with a Vec<u8>, that implementation detail is not exposed. More detail about WTF-8 is available on its website, which includes this quote, emphasis mine:

On Windows (which uses potentially ill-formed UTF-16 in its APIs), the
  Rust standard library uses WTF-8 internally for OS strings, but does
  not expose the WTF-8 byte sequences.

The "problem" is that on different platforms, there's no unified concept of a "string" when it comes to passing it to an operating system interface. On *nix, usually interfaces accept something almost like UTF-8, except they don't handle embedded NUL values. On Windows, it depends on if you are calling the W or A variant of the API, although the W variant is strongly preferred.

This is made more difficult because libraries may also use different encodings from the OS. This is especially true if you use a C library created on *nix on Windows — it's almost guaranteed to take in a pseudo-UTF-8 string and then some sort of lossy transformation occurs to call the right underlying API.

Rust avoids all that by providing the opaque types OsStr and OsString.

If you need to pass an OsStr to a function that accepts UTF-8 data, you need to convert it to a String or &str, then you can get the bytes of that. If you need to pass it to a function that accepts a LPCWSTR, you first need to convert to a Vec<u16> and then pass the pointer to that buffer to the Windows API. You can see an example of how Rust itself does this.


问:
google pie chart show slice text outside for small slices
I'm using google charts, and I want to show the pie slice text for the small slices without rotating the pie chart (chart should not be rotated).

Is it possible to show pie slice text outside the pie only for small slices(similar to charts in MS Excel as shown in below image), remaining should display the slice text within the slice itself.

Thanks in advance :)

答:
Are you looking for this: fiddler Here

use legend property legend: {position: 'labeled'}

```<code>      google.charts.load('current', {'packages':['corechart']});
  google.charts.setOnLoadCallback(drawChart);

  function drawChart() {

    var data = google.visualization.arrayToDataTable([
      ['Task', 'Hours per Day'],
      ['Work',     11],
      ['Eat',      2],
      ['Commute',  2],
      ['Watch TV', 2],
      ['Sleep',    7]
    ]);

    var options = {
      title: 'Activities',
       legend: {position: 'labeled'}
    };

    var chart = new google.visualization.PieChart(document.getElementById('piechart'));

    chart.draw(data, options);
  }
</code>```

Body:
Are you looking for this: fiddler Here

use legend property legend: {position: 'labeled'}

      google.charts.load('current', {'packages':['corechart']});
  google.charts.setOnLoadCallback(drawChart);

  function drawChart() {

    var data = google.visualization.arrayToDataTable([
      ['Task', 'Hours per Day'],
      ['Work',     11],
      ['Eat',      2],
      ['Commute',  2],
      ['Watch TV', 2],
      ['Sleep',    7]
    ]);

    var options = {
      title: 'Activities',
       legend: {position: 'labeled'}
    };

    var chart = new google.visualization.PieChart(document.getElementById('piechart'));

    chart.draw(data, options);
  }


问:
Returning javascript view in Laravel
In Ruby on Rails In my controller I can do something like this:

```<code>def jstest
    respond_to do |format|
        format.js
    end
end
</code>```

This would return jstest.js.erb from the relevant views directory

jstest.js.erb

```<code>alert("Hello World")
</code>```

The result being I get hello world alert.

I want to do the same thing in Laravel

In my controller I have:

```<code>public function jstest(  )
{
    return view('jstest');
}
</code>```

in my view (which I have tried with both jstest.blade.js and just jstest.js)

but I get the error, view cannot be found.

The only way I get this to work is by calling the view jstest.blade.php and including my js in a

答:
I don't know if Laravel supports this out of the box, but this is my take on your issue.

This is how I understood your problem: you want to specify a path to .js file as an argument to a function and you want this .js file to be immediately executed when loaded via browser.

I'd do it in these 2 steps

Create a jsview() function that accepts a path, similar to view()

Create the base .blade.php file which will be used by the above

The .blade.php contents

Assumption is that this view will be named javascript.blade.php and it's in resources/views/ directory.

```<code><!DOCTYPE html>
<html lang="en">
    <head>
        <script type="text/javascript" src="{{$path}}"></script>
    </head>

    <body></body>

</html>
</code>```

The function

```<code>function jsview($path)
{
    return view('javascript', ['path' => $path]);
}
</code>```

Usage

```<code><?php

Route::get('/test', function()
{
    return jsview('/assets/my.js');
});
</code>```

This answer isn't really fully complete because your browser will be loading files from public/ directory so all .js files you specify this way would be read from there. I believe Laravel does have something related to resources, but I'm not expert enough on that matter.

This is posted only to outline how to achieve something that you need, but isn't available out of the box.

Title: Returning javascript view in Laravel

Body:
In Ruby on Rails In my controller I can do something like this:

def jstest
    respond_to do |format|
        format.js
    end
end

This would return jstest.js.erb from the relevant views directory

jstest.js.erb

alert("Hello World")

The result being I get hello world alert.

I want to do the same thing in Laravel

In my controller I have:

public function jstest(  )
{
    return view('jstest');
}

in my view (which I have tried with both jstest.blade.js and just jstest.js)

but I get the error, view cannot be found.

The only way I get this to work is by calling the view jstest.blade.php and including my js in a

Body:
I don't know if Laravel supports this out of the box, but this is my take on your issue.

This is how I understood your problem: you want to specify a path to .js file as an argument to a function and you want this .js file to be immediately executed when loaded via browser.

I'd do it in these 2 steps

Create a jsview() function that accepts a path, similar to view()

Create the base .blade.php file which will be used by the above

The .blade.php contents

Assumption is that this view will be named javascript.blade.php and it's in resources/views/ directory.

<!DOCTYPE html>
<html lang="en">
    <head>
        <script type="text/javascript" src="{{$path}}"></script>
    </head>

    <body></body>

</html>

The function

function jsview($path)
{
    return view('javascript', ['path' => $path]);
}

Usage

<?php

Route::get('/test', function()
{
    return jsview('/assets/my.js');
});

This answer isn't really fully complete because your browser will be loading files from public/ directory so all .js files you specify this way would be read from there. I believe Laravel does have something related to resources, but I'm not expert enough on that matter.

This is posted only to outline how to achieve something that you need, but isn't available out of the box.


问:
How to convert/get name of variable or maybe convert part of code into string?
Help please to get name of variable from this self variable.</p>

```<code>let variable = 'blablabla'
magic... and i have: variable = 'variable'
</code>```

答:
You can't do that with plain variables as far as I can tell.
That said, it's easy to get the keys from an object.

Example:

```<code>let variable = {
  prop1: 'value'
};

console.log(Object.keys(variable)); // <= will print ['prop1']
</code>```

Body:
Help please to get name of variable from this self variable.

let variable = 'blablabla'
magic... and i have: variable = 'variable'

Body:
You can't do that with plain variables as far as I can tell.
That said, it's easy to get the keys from an object.

Example:

let variable = {
  prop1: 'value'
};

console.log(Object.keys(variable)); // <= will print ['prop1']


问:
Pulling username from Database
I'm setting up a login page for a program I'm making for a Uni Degree.

The login page itself works, but I'm having an issue with something else.

The login page itself is just a passcode.
Numeric characters in a text box get verified through an access database.

I set up my own subroutine (LoginProcedure) with the following code:

```<code>SELECT        COUNT(*) AS Result, [Password] AS Pass, Username AS [User]
FROM            users
GROUP BY [Password], Username
HAVING        (COUNT(*) = 1) AND ([Password] = ?)
</code>```

And on the login button, have the following code:

```<code>Dim login = UsersTableAdapter.LoginProcedure(txtPass.Text)
        If login Is Nothing Then
            MsgBox("Passcode Not Recognised!", MsgBoxStyle.Critical)
        Else
            Till.Show()
        End If
</code>```

So if the Text in txtPass matches any of the passwords in the Database, the Till form opens, otherwise they receive an error.

However, I also have a text box which I want a Username to appear in.
Is there anyway for the Username to automatically fill in, from the password provided??

PS.
It's VB2013... Uni has old software.

答:
Are you not requiring a username on login? Usually you would take the username and find that in the database, and then you would compare the encrypted password to the stored encrypted password you have in the database.

If you want to stay with your current system you should just be able to select the username from the same index.

Title: Pulling username from Database

Body:
I'm setting up a login page for a program I'm making for a Uni Degree.

The login page itself works, but I'm having an issue with something else.

The login page itself is just a passcode.
Numeric characters in a text box get verified through an access database.

I set up my own subroutine (LoginProcedure) with the following code:

SELECT        COUNT(*) AS Result, [Password] AS Pass, Username AS [User]
FROM            users
GROUP BY [Password], Username
HAVING        (COUNT(*) = 1) AND ([Password] = ?)

And on the login button, have the following code:

Dim login = UsersTableAdapter.LoginProcedure(txtPass.Text)
        If login Is Nothing Then
            MsgBox("Passcode Not Recognised!", MsgBoxStyle.Critical)
        Else
            Till.Show()
        End If

So if the Text in txtPass matches any of the passwords in the Database, the Till form opens, otherwise they receive an error.

However, I also have a text box which I want a Username to appear in.
Is there anyway for the Username to automatically fill in, from the password provided??

PS.
It's VB2013... Uni has old software.


问:
How boto3.s3.transfer handles multipart upload
I am uploading to S3 using below code:

```<code>config = TransferConfig(multipart_threshold=1024)
transfer= S3Transfer(s3_client, config)
transfer.upload_file(fileadded, bucket, key,callback=ProgressPercentage(file))
</code>```

I couldnt get anything on how internally boto handles multipart upload.
I have few questions regarding the same, lets assume I have 2.5 MB file:

Then the file will it be uploaded in 3 parts like 1, 1 and .5 MB?

All the 3 parts will be uploaded in parallel or sequential?

In aws library for java we have TransferManager, any similar thing in boto?

If this code sufficient for multi part uploads? Because I came across some complicated code samples for the same

Any help would be greatly appreciated.

答:
Your code is correct. The S3 transfer will use the config you created to transfer the files.  Check the documentation on TransferConfig to see the parameters you can set and their defaults.

To answer your questions:

yes

parallel, using threads

boto3 uses s3transfer
internally, but normally you would just use the TransferConfig

yes

Body:
I am uploading to S3 using below code:

config = TransferConfig(multipart_threshold=1024)
transfer= S3Transfer(s3_client, config)
transfer.upload_file(fileadded, bucket, key,callback=ProgressPercentage(file))

I couldnt get anything on how internally boto handles multipart upload.
I have few questions regarding the same, lets assume I have 2.5 MB file:

Then the file will it be uploaded in 3 parts like 1, 1 and .5 MB?

All the 3 parts will be uploaded in parallel or sequential?

In aws library for java we have TransferManager, any similar thing in boto?

If this code sufficient for multi part uploads? Because I came across some complicated code samples for the same

Any help would be greatly appreciated.


问:
Perl XML LibXML to replace a node with the other on xsd schema
I have an XML Schema and I would like to replace the RootNode with the element found inside of the RootNode complex Type with.

For example, below expected result is to have the <xs:element name="RootNode" ...> replaced by <xs:element name="real_node" type="RealNode"/> and remove the whole node of <xs:complexType name="RootNode">.

XML Schema:

```<code><xs:schema xmlns="test" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="test" elementFormDefault="qualified">
    <xs:element name="RootNode" type="RootNode"/>

    <xs:complexType name="RootNode">
            <xs:sequence>
                    <xs:element name="real_node" type="RealNode"/>
            </xs:sequence>
    </xs:complexType>

    <xs:complexType name="RealNode">
            <xs:annotation>
                    <xs:documentation source="Name" xml:lang="EN">TestName</xs:documentation>
                    <xs:documentation source="Type" xml:lang="EN">TestType</xs:documentation>
            </xs:annotation>
            <xs:sequence>
                    <xs:element name="Elem2" type="Type2" minOccurs="1">
                            <xs:annotation>
                                    <xs:documentation source="Name3" xml:lang="EN">TestName3</xs:documentation>
                                    <xs:documentation source="Type3" xml:lang="EN">TestType3</xs:documentation>
                            </xs:annotation>
                    </xs:element>
                    <xs:element name="Elem4" type="Type4" maxOccurs="99" />
            </xs:sequence>
    </xs:complexType>

    <xs:simpleType name="Type2">
            <xs:restriction base="xs:string">
                    <xs:pattern value="[A-Z]{9,9}"/>
            </xs:restriction>
    </xs:simpleType>

    <xs:simpleType name="Type4">
            <xs:annotation>
                    <xs:documentation source="Name5" xml:lang="EN">TestName5</xs:documentation>
                    <xs:documentation source="Type5" xml:lang="EN">TestType5</xs:documentation>
            </xs:annotation>
            <xs:restriction base="xs:string">
                    <xs:pattern value="[A-Z]{7,9}"/>
            </xs:restriction>
    </xs:simpleType>

</xs:schema>
</code>```

Expected result:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns="test" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="test" elementFormDefault="qualified">
    <xs:element name="real_node" type="RealNode"/>

    <xs:complexType name="RealNode">
            <xs:annotation>
                    <xs:documentation source="Name" xml:lang="EN">TestName</xs:documentation>
                    <xs:documentation source="Type" xml:lang="EN">TestType</xs:documentation>
            </xs:annotation>
            <xs:sequence>
                    <xs:element name="Elem2" type="Type2" minOccurs="1">
                            <xs:annotation>
                                    <xs:documentation source="Name3" xml:lang="EN">TestName3</xs:documentation>
                                    <xs:documentation source="Type3" xml:lang="EN">TestType3</xs:documentation>
                            </xs:annotation>
                    </xs:element>
                    <xs:element name="Elem4" type="Type4" maxOccurs="99" />
            </xs:sequence>
    </xs:complexType>

    <xs:simpleType name="Type2">
            <xs:restriction base="xs:string">
                    <xs:pattern value="[A-Z]{9,9}"/>
            </xs:restriction>
    </xs:simpleType>

    <xs:simpleType name="Type4">
            <xs:annotation>
                    <xs:documentation source="Name5" xml:lang="EN">TestName5</xs:documentation>
                    <xs:documentation source="Type5" xml:lang="EN">TestType5</xs:documentation>
            </xs:annotation>
            <xs:restriction base="xs:string">
                    <xs:pattern value="[A-Z]{7,9}"/>
            </xs:restriction>
    </xs:simpleType>

</xs:schema>
</code>```

My script:

```<code>#!/opt/perl/bin/perl -w
use strict;
use warnings;

use XML::LibXML               qw( );
use XML::LibXML::XPathContext qw( );
use File::Copy;
use File::Basename;

my $in_qfn  = $ARGV[0];
my ($parser, $doc, $root, $out_qfn);
my ($name, $path, $suffix);
my ($documentroot, $complexdoc, $copyelem, $test, $fnd_type, $parent);

my @files = glob "$in_qfn/*.xsd";

foreach my $file (@files) {
   print "###LI### 1 $file\n";
   ($name, $path, $suffix) = fileparse($file);
   $out_qfn = "${name}NoRoot.${suffix}";

   $parser = XML::LibXML->new();
   $doc    = $parser->parse_file($file);
   $root   = $doc->documentElement();

   my $xpc = XML::LibXML::XPathContext->new($doc);
   $xpc->registerNs('xsd', 'http://www.w3.org/2001/XMLSchema');

   # Get the RootNode element node and delete it
   foreach $test ($xpc->findnodes("//xsd:element", $root)) {
      $fnd_type = $test->getAttribute('type') or next;

      if ( $xpc->findnodes('./@name[.="RootNode"]', $test) ) {
         foreach my $fnd_node ($xpc->findnodes('./@name[.="RootNode"]', $test)) {
            $fnd_type = $fnd_node->getAttribute('type') or next;
            $parent = $fnd_node->[0]->parentNode;
            $parent->removeChild($fnd_node->[0]);
         }
      }
   }

   # Get the RootNode Complext Type node
   foreach $test ($xpc->findnodes("//xsd:complexType", $root)) {
      if ($xpc->findnodes('./@name[.="RootNode"]', $root)) {
         $complexdoc = $xpc->findnodes('./@name[.="RootNode"]', $root);
         $copyelem = $xpc->findnodes("//xsd:element", $complexdoc);
         # Copy the element node within RootNode node to the top level
         $root->appendChild($copyelem->cloneNode(1));
      }
   }

   $doc->toFile($out_qfn);
}
</code>```

However, the script throws error:

```<code>Can't locate object method "getAttribute" via package "XML::LibXML::NodeList"
</code>```

Any help is appreciated.

答:
You haven't described the logic what elements to remove and replace. The following code just does what you said: replaces one element by another and removes a third one.

```<code>#!/usr/bin/perl
use warnings;
use strict;

use XML::LibXML;
use XML::LibXML::XPathContext;

my $dom = 'XML::LibXML'->load_xml(location => shift);
my $xpc = 'XML::LibXML::XPathContext'->new($dom);
$xpc->registerNs(xsd => 'http://www.w3.org/2001/XMLSchema');
my $root = $dom->documentElement;

my $replace    = $xpc->findnodes('//xsd:element[@name="RootNode"]');
my $replace_by = $xpc->findnodes('//xsd:element[@name="real_node"]');
my $remove     = $xpc->findnodes('//xsd:complexType[@name="RootNode"]');

die "Can't replace by several" if $replace_by->size > 1;

$_->parentNode->removeChild($_) for @$remove;
$_->replaceNode($replace_by->[0]) for @$replace;

print $dom;
</code>```

Note that findnodes returns a nodelist, you can check its size with ->size as shown in the code, and access it members as elements of an array reference.

Body:
I have an XML Schema and I would like to replace the RootNode with the element found inside of the RootNode complex Type with.

For example, below expected result is to have the <xs:element name="RootNode" ...> replaced by <xs:element name="real_node" type="RealNode"/> and remove the whole node of <xs:complexType name="RootNode">.

XML Schema:

<xs:schema xmlns="test" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="test" elementFormDefault="qualified">
    <xs:element name="RootNode" type="RootNode"/>

    <xs:complexType name="RootNode">
            <xs:sequence>
                    <xs:element name="real_node" type="RealNode"/>
            </xs:sequence>
    </xs:complexType>

    <xs:complexType name="RealNode">
            <xs:annotation>
                    <xs:documentation source="Name" xml:lang="EN">TestName</xs:documentation>
                    <xs:documentation source="Type" xml:lang="EN">TestType</xs:documentation>
            </xs:annotation>
            <xs:sequence>
                    <xs:element name="Elem2" type="Type2" minOccurs="1">
                            <xs:annotation>
                                    <xs:documentation source="Name3" xml:lang="EN">TestName3</xs:documentation>
                                    <xs:documentation source="Type3" xml:lang="EN">TestType3</xs:documentation>
                            </xs:annotation>
                    </xs:element>
                    <xs:element name="Elem4" type="Type4" maxOccurs="99" />
            </xs:sequence>
    </xs:complexType>

    <xs:simpleType name="Type2">
            <xs:restriction base="xs:string">
                    <xs:pattern value="[A-Z]{9,9}"/>
            </xs:restriction>
    </xs:simpleType>

    <xs:simpleType name="Type4">
            <xs:annotation>
                    <xs:documentation source="Name5" xml:lang="EN">TestName5</xs:documentation>
                    <xs:documentation source="Type5" xml:lang="EN">TestType5</xs:documentation>
            </xs:annotation>
            <xs:restriction base="xs:string">
                    <xs:pattern value="[A-Z]{7,9}"/>
            </xs:restriction>
    </xs:simpleType>

</xs:schema>

Expected result:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns="test" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="test" elementFormDefault="qualified">
    <xs:element name="real_node" type="RealNode"/>

    <xs:complexType name="RealNode">
            <xs:annotation>
                    <xs:documentation source="Name" xml:lang="EN">TestName</xs:documentation>
                    <xs:documentation source="Type" xml:lang="EN">TestType</xs:documentation>
            </xs:annotation>
            <xs:sequence>
                    <xs:element name="Elem2" type="Type2" minOccurs="1">
                            <xs:annotation>
                                    <xs:documentation source="Name3" xml:lang="EN">TestName3</xs:documentation>
                                    <xs:documentation source="Type3" xml:lang="EN">TestType3</xs:documentation>
                            </xs:annotation>
                    </xs:element>
                    <xs:element name="Elem4" type="Type4" maxOccurs="99" />
            </xs:sequence>
    </xs:complexType>

    <xs:simpleType name="Type2">
            <xs:restriction base="xs:string">
                    <xs:pattern value="[A-Z]{9,9}"/>
            </xs:restriction>
    </xs:simpleType>

    <xs:simpleType name="Type4">
            <xs:annotation>
                    <xs:documentation source="Name5" xml:lang="EN">TestName5</xs:documentation>
                    <xs:documentation source="Type5" xml:lang="EN">TestType5</xs:documentation>
            </xs:annotation>
            <xs:restriction base="xs:string">
                    <xs:pattern value="[A-Z]{7,9}"/>
            </xs:restriction>
    </xs:simpleType>

</xs:schema>

My script:

#!/opt/perl/bin/perl -w
use strict;
use warnings;

use XML::LibXML               qw( );
use XML::LibXML::XPathContext qw( );
use File::Copy;
use File::Basename;

my $in_qfn  = $ARGV[0];
my ($parser, $doc, $root, $out_qfn);
my ($name, $path, $suffix);
my ($documentroot, $complexdoc, $copyelem, $test, $fnd_type, $parent);

my @files = glob "$in_qfn/*.xsd";

foreach my $file (@files) {
   print "###LI### 1 $file\n";
   ($name, $path, $suffix) = fileparse($file);
   $out_qfn = "${name}NoRoot.${suffix}";

   $parser = XML::LibXML->new();
   $doc    = $parser->parse_file($file);
   $root   = $doc->documentElement();

   my $xpc = XML::LibXML::XPathContext->new($doc);
   $xpc->registerNs('xsd', 'http://www.w3.org/2001/XMLSchema');

   # Get the RootNode element node and delete it
   foreach $test ($xpc->findnodes("//xsd:element", $root)) {
      $fnd_type = $test->getAttribute('type') or next;

      if ( $xpc->findnodes('./@name[.="RootNode"]', $test) ) {
         foreach my $fnd_node ($xpc->findnodes('./@name[.="RootNode"]', $test)) {
            $fnd_type = $fnd_node->getAttribute('type') or next;
            $parent = $fnd_node->[0]->parentNode;
            $parent->removeChild($fnd_node->[0]);
         }
      }
   }

   # Get the RootNode Complext Type node
   foreach $test ($xpc->findnodes("//xsd:complexType", $root)) {
      if ($xpc->findnodes('./@name[.="RootNode"]', $root)) {
         $complexdoc = $xpc->findnodes('./@name[.="RootNode"]', $root);
         $copyelem = $xpc->findnodes("//xsd:element", $complexdoc);
         # Copy the element node within RootNode node to the top level
         $root->appendChild($copyelem->cloneNode(1));
      }
   }

   $doc->toFile($out_qfn);
}

However, the script throws error:

Can't locate object method "getAttribute" via package "XML::LibXML::NodeList"

Any help is appreciated.

Body:
You haven't described the logic what elements to remove and replace. The following code just does what you said: replaces one element by another and removes a third one.

#!/usr/bin/perl
use warnings;
use strict;

use XML::LibXML;
use XML::LibXML::XPathContext;

my $dom = 'XML::LibXML'->load_xml(location => shift);
my $xpc = 'XML::LibXML::XPathContext'->new($dom);
$xpc->registerNs(xsd => 'http://www.w3.org/2001/XMLSchema');
my $root = $dom->documentElement;

my $replace    = $xpc->findnodes('//xsd:element[@name="RootNode"]');
my $replace_by = $xpc->findnodes('//xsd:element[@name="real_node"]');
my $remove     = $xpc->findnodes('//xsd:complexType[@name="RootNode"]');

die "Can't replace by several" if $replace_by->size > 1;

$_->parentNode->removeChild($_) for @$remove;
$_->replaceNode($replace_by->[0]) for @$replace;

print $dom;

Note that findnodes returns a nodelist, you can check its size with ->size as shown in the code, and access it members as elements of an array reference.


问:
Javascript/jquery: Remove parent of class and keep it's child
I'd like to remove a parent of a child with specific classname with javascript/jquery. It's a span wrapper which i'd like to remove. I only know the class (or id) of the child to work with.

How can i do that?

So this:

```<code><span>
  <input class="removespan" type="text">
</span>
</code>```

Needs to be this:

```<code><input class="removespan" type="text">
</code>```

答:
Amazingly, jQuery has a method for doing exactly that: unwrap

```<code>$(".removespan").unwrap();
</code>```

Live example:

setTimeout(function() {
  $(".removespan").unwrap();
}, 1000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>span {
  border: 1px solid green;
  padding: 4px;
}</code>```

The span has a green border. The span is removed after a second:

  <input class="removespan" type="text">

```

Body:
I'd like to remove a parent of a child with specific classname with javascript/jquery. It's a span wrapper which i'd like to remove. I only know the class (or id) of the child to work with.

How can i do that?

So this:

  <input class="removespan" type="text">

Needs to be this:

<input class="removespan" type="text">

Body:
Amazingly, jQuery has a method for doing exactly that: unwrap

$(".removespan").unwrap();

Live example:

setTimeout(function() {
  $(".removespan").unwrap();
}, 1000);

span {
  border: 1px solid green;
  padding: 4px;
}

<div style="margin-bottom: 8px">
The span has a green border. The span is removed after a second:
</div>
<div>
<span>
  <input class="removespan" type="text">
</span>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
.NET Regex taking long time to find the match
Why this innocent looking regex is killing my requests?

```<code>([\d\w-]+.){6}hi
</code>```

Is this candidate for catastrophic backtracking?

Running this on .NET framework 4.5.2, C#

答:
To match a literal dot, you must escape it.  If you do not, a quantified group ([\d\w-]+.){6} will lead to a catastrophic backtracking with longer inputs. Change to ([\w-]+\.){6}hi.

Note that [\d\w-]+ matches 1 or more (unknown number) letters, digits, _ or -. A . matches any char. When you apply a quantifier, the regex engine tries all possible ways to match a string before it fails. It is usually not a problem with a string where a match is found, it usually happens with strings where the match cannot be found since all possible ways are tried then (until the engine reports a crash).

Besides, the \d pattern matches digits, and \w matches digits, too, so there is no point using both inside a character class.

Body:
Why this innocent looking regex is killing my requests?

([\d\w-]+.){6}hi

Is this candidate for catastrophic backtracking?

Running this on .NET framework 4.5.2, C#


问:
Javascript get Property name from class declaration
Lets have a javascript "class"

```<code>  var User= function(id, firstName, lastName) {
      this.id=id;
      this.firstName=firstName;
      this.lastName=lastName
  }
  var user = new User (1,"I", "am");
</code>```

I would like to reference a specific field name of user class, lets say the id field, without using the String "id"

... something like (user->id).getName(); (should return the String "id")

Note : Enumerating the user Object properties is not helping me since I will have to choose among them using the String "id" and so hard code somewhere

hope I am clear.

The goal is to select some properties of user Object to fill in a table without hard coding the object properties as Strings.
Thanks

答: I try to implement it in PHP, for those interested : the github link</p>

Body:
Lets have a javascript "class"

  var User= function(id, firstName, lastName) {
      this.id=id;
      this.firstName=firstName;
      this.lastName=lastName
  }
  var user = new User (1,"I", "am");

I would like to reference a specific field name of user class, lets say the id field, without using the String "id"

... something like (user->id).getName(); (should return the String "id")

Note : Enumerating the user Object properties is not helping me since I will have to choose among them using the String "id" and so hard code somewhere

hope I am clear.

The goal is to select some properties of user Object to fill in a table without hard coding the object properties as Strings.
Thanks


问:
Check if column value is in other columns in pandas
I have the following dataframe in pandas

```<code>  target   A       B      C
0 cat      bridge  cat    brush
1 brush    dog     cat    shoe
2 bridge   cat     shoe   bridge
</code>```

How do I test whether df.target is in any of the columns ['A','B','C', etc.], where there are many columns to check?

I have tried merging A,B and C into a string to use df.abcstring.str.contains(df.target) but this does not work.

答:
Another approach using index difference method:

```<code>matches = df[df.columns.difference(['target'])].eq(df['target'], axis = 0)

#       A      B      C
#0  False   True  False
#1  False  False  False
#2  False  False   True

# Check if at least one match:
matches.any(axis = 1)

#Out[30]:
#0     True
#1    False
#2     True
</code>```

In case you wanted to see which columns meet the target, here is a possible solution:

```<code>matches.apply(lambda x: ", ".join(x.index[np.where(x.tolist())]), axis = 1)

Out[53]:
0    B
1
2    C
dtype: object
</code>```

Body:
I have the following dataframe in pandas

  target   A       B      C
0 cat      bridge  cat    brush
1 brush    dog     cat    shoe
2 bridge   cat     shoe   bridge

How do I test whether df.target is in any of the columns ['A','B','C', etc.], where there are many columns to check?

I have tried merging A,B and C into a string to use df.abcstring.str.contains(df.target) but this does not work.

Body:
Another approach using index difference method:

matches = df[df.columns.difference(['target'])].eq(df['target'], axis = 0)

#       A      B      C
#0  False   True  False
#1  False  False  False
#2  False  False   True

# Check if at least one match:
matches.any(axis = 1)

#Out[30]:
#0     True
#1    False
#2     True

In case you wanted to see which columns meet the target, here is a possible solution:

matches.apply(lambda x: ", ".join(x.index[np.where(x.tolist())]), axis = 1)

Out[53]:
0    B
1
2    C
dtype: object


问:
How to jump X second with axWindowsMediaPlayer in C#
I am using axWindowsMediaPlayer, and I have a video loaded, but I want to jump X seconds.  So, for example, if the current time is 1 minute into the video, I want to jump to 1 minute 10 seconds.</p>

答:
Okay, I found my solution.  I was actually running it correctly, but I was not accounting for the time it takes to load the video.

Specifically, the needed code is like

```<code>axWindowsMediaPlayer1.Ctlcontrols.currentPosition += 10;
</code>```

However I wrote a function to check to see if the video had finished loading and attached a timer to it

```<code>private bool isPlaying()
{
   return axWindowsMediaPlayer1.playState == WMPPlayState.wmppsReady || axWindowsMediaPlayer1.playState == WMPPlayState.wmppsPlaying;
}
</code>```

Then called my skip function when I got a true.

Body:
Okay, I found my solution.  I was actually running it correctly, but I was not accounting for the time it takes to load the video.

Specifically, the needed code is like

axWindowsMediaPlayer1.Ctlcontrols.currentPosition += 10;

However I wrote a function to check to see if the video had finished loading and attached a timer to it

private bool isPlaying()
{
   return axWindowsMediaPlayer1.playState == WMPPlayState.wmppsReady || axWindowsMediaPlayer1.playState == WMPPlayState.wmppsPlaying;
}

Then called my skip function when I got a true.


问:
Pass angularJs variable to javascript Variable
I have Angularjs variable that I want to pass in javascript variable.
I found solution
 here
so it didn't work. My code :

```<code><script>
var demo=angular.module('demo', []);
demo.controller('metrics', function($scope, $http) {
$http.get('http://localhost:8080/metrics').then(function(response)
    {
     $scope.metrics = response.data;
    });
    });
</script>

<div ng-controller="metrics">
<p>{{metrics}}<p>
</div>
<script>
var e = angular.element(document.querySelector('[ng-controller="metrics"]'));
var e1 = e.scope().metrics ;
alert(e1)
</script>
</code>```

I got result from {{metrics}}  but  e1  didn't return something.

Thanks for your help.

答:
angular.element() is a function in angular to get a raw DOM

if you want to get a particular
 then assign id attribute on it

with that raw DOM, you can add attribute, add classes or else (check this link for more info)

but if you want to do something with metrics then just use $scope.metrics after you get it from $http

```<code><div ng-controller="metricsCtrl">
  <p id="metric">{{metrics}}<p>
</div>

<script>
  var demo=angular.module('demo', []);
  demo.controller('metricsCtrl', function($scope, $http) {
  $http.get('http://localhost:8080/metrics').then(function(response)
      {
       $scope.metrics = response.data;

       // you can do whatever with $scope.metrics here
       console.log($scope.metrics);

      });
  var e = angular.element(document.querySelector('#metric'));
  console.log(e);
  e.addClass('some-class');     // here p will be <p class="some-class" id="metric">{{metrics}}<p>
  });
</script>
</code>```

Body:
I have Angularjs variable that I want to pass in javascript variable.
I found solution
 here
so it didn't work. My code :

{{metrics}}

I got result from {{metrics}}  but  e1  didn't return something.

Thanks for your help.

Body:
angular.element() is a function in angular to get a raw DOM

if you want to get a particular <p> then assign id attribute on it

with that raw DOM, you can add attribute, add classes or else (check this link for more info)

but if you want to do something with metrics then just use $scope.metrics after you get it from $http

<div ng-controller="metricsCtrl">
  <p id="metric">{{metrics}}<p>
</div>

<script>
  var demo=angular.module('demo', []);
  demo.controller('metricsCtrl', function($scope, $http) {
  $http.get('http://localhost:8080/metrics').then(function(response)
      {
       $scope.metrics = response.data;

       // you can do whatever with $scope.metrics here
       console.log($scope.metrics);

      });
  var e = angular.element(document.querySelector('#metric'));
  console.log(e);
  e.addClass('some-class');     // here p will be <p class="some-class" id="metric">{{metrics}}<p>
  });
</script>


问:
How to add an image to a Drawable Resource File
I have created a drawable resource file and all I need is to add an image to this drawable resource file that contains layer list which this layer list contains an item and shape like this example
resoucedrawablefile.xml</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item>

        <bitmap android:gravity="center" android:src="@drawable/remove" />

    </item>

    <!-- Drop Shadow Stack -->
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
            <corners android:radius="10dp" />
            <solid android:color="#00CCCCCC" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
            <corners android:radius="10dp" />
            <solid android:color="#10CCCCCC" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
            <corners android:radius="10dp" />
            <solid android:color="#20CCCCCC" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
            <corners android:radius="10dp" />
            <solid android:color="#30CCCCCC" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
            <corners android:radius="10dp" />
            <solid android:color="#50CCCCCC" />
        </shape>
    </item>

    <!-- Background -->
    <item>
        <shape>
            <solid android:color="#b5e40008" />
            <corners android:radius="10dp" />
        </shape>
    </item>
</layer-list>
</code>```

答:
Hope this helps.</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/image" />

    <!-- Drop Shadow Stack -->
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
            <corners android:radius="10dp" />
            <solid android:color="#00CCCCCC" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
            <corners android:radius="10dp" />
            <solid android:color="#10CCCCCC" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
            <corners android:radius="10dp" />
            <solid android:color="#20CCCCCC" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
            <corners android:radius="10dp" />
            <solid android:color="#30CCCCCC" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
            <corners android:radius="10dp" />
            <solid android:color="#50CCCCCC" />
        </shape>
    </item>

</layer-list>
</code>```

Body:
I have created a drawable resource file and all I need is to add an image to this drawable resource file that contains layer list which this layer list contains an item and shape like this example
resoucedrawablefile.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item>

        <bitmap android:gravity="center" android:src="@drawable/remove" />

    </item>

    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
            <corners android:radius="10dp" />
            <solid android:color="#00CCCCCC" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
            <corners android:radius="10dp" />
            <solid android:color="#10CCCCCC" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
            <corners android:radius="10dp" />
            <solid android:color="#20CCCCCC" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
            <corners android:radius="10dp" />
            <solid android:color="#30CCCCCC" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
            <corners android:radius="10dp" />
            <solid android:color="#50CCCCCC" />
        </shape>
    </item>

    <item>
        <shape>
            <solid android:color="#b5e40008" />
            <corners android:radius="10dp" />
        </shape>
    </item>
</layer-list>

Body:
Hope this helps.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/image" />

    <!-- Drop Shadow Stack -->
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
            <corners android:radius="10dp" />
            <solid android:color="#00CCCCCC" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
            <corners android:radius="10dp" />
            <solid android:color="#10CCCCCC" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
            <corners android:radius="10dp" />
            <solid android:color="#20CCCCCC" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
            <corners android:radius="10dp" />
            <solid android:color="#30CCCCCC" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="2dp" android:left="1dp" />
            <corners android:radius="10dp" />
            <solid android:color="#50CCCCCC" />
        </shape>
    </item>

</layer-list>


答:
You can add like below.</p>

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

        <item>
            <shape>
                <solid android:color="#000000"/>
                <padding android:right="#000000"/>
            </shape>
        </item>

        <item>

            <bitmap android:gravity="right|center" android:src="@drawable/down_arrow" />

        </item>

    </layer-list>
</code>```

Title: How to add an image to a Drawable Resource File

Body:
You can add like below.

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

        <item>
            <shape>
                <solid android:color="#000000"/>
                <padding android:right="#000000"/>
            </shape>
        </item>

        <item>

            <bitmap android:gravity="right|center" android:src="@drawable/down_arrow" />

        </item>

    </layer-list>


答:
Found an easy solution after some seconds of searching.
The solution is gzdecode().

```<code>$data = ... ; // Your string
$decoded = base64_decode($data);
$plain_string = gzdecode($decoded);
</code>```

Title: BASE64 decode and ungzip data in PHP

Body:
I am working with OpenSubtitles API and need to BASE64 decode and ungzip API response ('$data' parameter) in PHP.

Full '$data' parameter you can find here:
https://jsfiddle.net/noxjmz40/

I can easily BASE64 decode this parameter with base64_decode($data) but I am not sure how to ungzip and get a normal result.

Please, advice me how to solve this task in a short and efficient way.
Thanks!

Body:
Found an easy solution after some seconds of searching.
The solution is gzdecode().

$data = ... ; // Your string
$decoded = base64_decode($data);
$plain_string = gzdecode($decoded);


问:
CORS on CakePHP 1.3
I'm creating a JSON webservice in CakePHP 1.3.

I want to be able to send AJAX requests from a different server to this webservice.

I know this is a cinch in Cake 2+, but I cannot for the life of me figure it out for v1.3. Based on what I have found in the docs, I have attempted the following in my controller:

```<code>public $components = array('RequestHandler');

function beforeFilter() {
    Configure::write('debug', 0);
    $this->header('Access-Control-Allow-Origin','*');
    $this->header('Access-Control-Allow-Methods','*');
    $this->header('Access-Control-Allow-Headers','X-Requested-With');
    $this->header('Access-Control-Allow-Headers','Content-Type, x-xsrf-token');
    $this->header('Access-Control-Max-Age','172800');
}
</code>```

This unfortunately results in 500 ERR_INVALID_RESPONSE.

I have attempted to do $this->response->header instead of $this->header, and same problem. I've also attempted header instead of $this->header, and again I'm getting a server response of 500. I have also attempted moving the header block into my action in the controller, into the top-level app_controller.php file, into the bootstrap.php file, and into the view file itself (with every variation of header, $this->header, and $this->response->header attempted). Removing Configure::write('debug', 0); does not solve the issue.

Heck, I even have this in my .htaccess file:

```<code><IfModule mod_headers.c>
    <FilesMatch "\.(json)$">
        Header set Access-Control-Allow-Origin "*"
    </FilesMatch>
</IfModule>
</code>```

Although that doesn't seem to do anything. I have mod_headers.load in my mods-available folder in Apache as well.

Anyone know how to set the Access-Control-Allow-Origin header in CakePHP 1.3?

答:
```<code>header("Access-Control-Allow-Origin: *");
</code>```

I know this is an old post but I jut want to answer this to help others.

Title: CORS on CakePHP 1.3

Body:
I'm creating a JSON webservice in CakePHP 1.3.

I want to be able to send AJAX requests from a different server to this webservice.

I know this is a cinch in Cake 2+, but I cannot for the life of me figure it out for v1.3. Based on what I have found in the docs, I have attempted the following in my controller:

public $components = array('RequestHandler');

function beforeFilter() {
    Configure::write('debug', 0);
    $this->header('Access-Control-Allow-Origin','*');
    $this->header('Access-Control-Allow-Methods','*');
    $this->header('Access-Control-Allow-Headers','X-Requested-With');
    $this->header('Access-Control-Allow-Headers','Content-Type, x-xsrf-token');
    $this->header('Access-Control-Max-Age','172800');
}

This unfortunately results in 500 ERR_INVALID_RESPONSE.

I have attempted to do $this->response->header instead of $this->header, and same problem. I've also attempted header instead of $this->header, and again I'm getting a server response of 500. I have also attempted moving the header block into my action in the controller, into the top-level app_controller.php file, into the bootstrap.php file, and into the view file itself (with every variation of header, $this->header, and $this->response->header attempted). Removing Configure::write('debug', 0); does not solve the issue.

Heck, I even have this in my .htaccess file:

<IfModule mod_headers.c>
    <FilesMatch "\.(json)$">
        Header set Access-Control-Allow-Origin "*"
    </FilesMatch>
</IfModule>

Although that doesn't seem to do anything. I have mod_headers.load in my mods-available folder in Apache as well.

Anyone know how to set the Access-Control-Allow-Origin header in CakePHP 1.3?

Body:
header("Access-Control-Allow-Origin: *");

I know this is an old post but I jut want to answer this to help others.


问:
SFML.NET particle system
I've written particle systems before and, put simply, it's more effort than it's worth given the size of the projects I want it for. What I'm ideally looking for is a particle system which can be easily dropped into an SFML.NET project without needing a great deal of manual integration.

Does anything already exist to fill this need (ideally without needing to rely on Tao for OpenGL access), or can someone recommend a particle system they've used for another .NET-based grapics framework which should be fairly easy to adapt?

Keep in mind that if it needs work to integrate wtih SFML.NET, the work involved should be LESS than the work required to write one from scratch.

答: It looks like the simple but unfortunate answer is: no.</p>

Title: SFML.NET particle system


问:
Does specifying Charset.Unicode in a DllImport allocate a string?
```<code>[DllImport("foo.dll", CharSet = CharSet.Unicode)]
static extern void Process_utf16(string text, int text_length);
</code>```

The native function is written to receive utf-16 data (which is also what .net strings use.) It does not use the string data after it returns. Therefore, I'm trying to ensure that the pointer to the string's buffer is passed directly without any unnecessary allocation or copying.

In this declaration, is a pointer to the string's buffer passed with no allocation? Or is a temporary buffer allocated and the string copied to it? If an allocation occurs, is it to the native or managed heap? And who is responsible for deallocating it?

Note that the code above has been tested and works, I'm just trying to find out whether it incurs an allocation and copy, and if so, how to avoid it.

答:
The rules for marshaling strings are described in "Default Marshaling for Strings". For native functions (platform interop), the documentation specifies:

Platform invoke copies string arguments, converting from the .NET
  Framework format (Unicode) to the platform unmanaged format. Strings
  are immutable and are not copied back from unmanaged memory to managed
  memory when the call returns.

However, as can be trivially established experimentally, this is not true if no conversion is necessary at all, that is, the method is decorated with CharSet.Unicode or the string is explicitly marked as MarshalAs(UnmanagedType.LPWStr). In this case, a pointer to the string contents is passed directly. This sounds very efficient, and it is, but it's also dangerous because there's nothing to stop the unmanaged function from modifying the string passed to it. This is bad because .NET strings are supposed to be immutable, and code may depend on that. It's especially bad if this ends up overwriting the string intern pool.

trample.c:

```<code>__declspec(dllexport) void __stdcall Trample(wchar_t* text) {
    memcpy(text, L"Adios", (sizeof L"Adios") - 2);
}
</code>```

Program.cs:

static class NativeMethods {
    [DllImport("trample.dll", CharSet = CharSet.Unicode)]
    public static extern void Trample(string text);
}

class Program {
    static void Main(string[] args) {
        Console.WriteLine("Hello, world!");
        NativeMethods.Trample("Hello, world!");
        Console.WriteLine("Hello, world!");
    }
}
```

<p>Output:</p>

<pre class="lang-none prettyprint-override"><code>Hello, world!
Adios, world!
</code>```

Since "Hello, world!" is a string literal, all instances of it end up in the string intern pool, and every time it's used we're using "the same" string. Our unmanaged function overwrites this, so now whenever we think we're writing "Hello, world!" in our managed code, we end up with something else instead. Oops.

The way to avoid this if you know the unmanaged function changes the string is to pass a StringBuilder instead. Here you can even choose if you want to copy to be in, out or both (with InAttribute/OutAttribute). This does involve copying to/from buffers -- specifically, CoTaskMemAlloc will be used to allocate memory for the unmanaged code (and CoTaskMemFree will be called when the call is done). This code is invoked by the marshaler as part of the call; neither the managed caller nor the unmanaged callee need to concern themselves with this.

Calling a function that expects an ANSI string also involves allocating a buffer, but in this case the buffer is allocated using the localloc instruction, not CoTaskMemAlloc, which is bunches more efficient. That said -- if you are actually going for efficiency, what you want to do is eliminate calling unmanaged code altogether if possible, not merely optimizing string passing. Even ignoring copying memory, there's quite a bit of overhead involved in managed/unmanaged transitions. If you find yourself calling unmanaged code in a loop, it pays off to see if that code can be ported to managed code.

Source: coreclr/src/vm/ilmarshalers.cpp, specifically ILWSTRMarshaler::EmitConvertSpaceAndContentsCLRToNativeTemp.

Body:
[DllImport("foo.dll", CharSet = CharSet.Unicode)]
static extern void Process_utf16(string text, int text_length);

The native function is written to receive utf-16 data (which is also what .net strings use.) It does not use the string data after it returns. Therefore, I'm trying to ensure that the pointer to the string's buffer is passed directly without any unnecessary allocation or copying.

In this declaration, is a pointer to the string's buffer passed with no allocation? Or is a temporary buffer allocated and the string copied to it? If an allocation occurs, is it to the native or managed heap? And who is responsible for deallocating it?

Note that the code above has been tested and works, I'm just trying to find out whether it incurs an allocation and copy, and if so, how to avoid it.

Body:
The rules for marshaling strings are described in "Default Marshaling for Strings". For native functions (platform interop), the documentation specifies:

Platform invoke copies string arguments, converting from the .NET
  Framework format (Unicode) to the platform unmanaged format. Strings
  are immutable and are not copied back from unmanaged memory to managed
  memory when the call returns.

However, as can be trivially established experimentally, this is not true if no conversion is necessary at all, that is, the method is decorated with CharSet.Unicode or the string is explicitly marked as MarshalAs(UnmanagedType.LPWStr). In this case, a pointer to the string contents is passed directly. This sounds very efficient, and it is, but it's also dangerous because there's nothing to stop the unmanaged function from modifying the string passed to it. This is bad because .NET strings are supposed to be immutable, and code may depend on that. It's especially bad if this ends up overwriting the string intern pool.

trample.c:

__declspec(dllexport) void __stdcall Trample(wchar_t* text) {
    memcpy(text, L"Adios", (sizeof L"Adios") - 2);
}

Program.cs:

static class NativeMethods {
    [DllImport("trample.dll", CharSet = CharSet.Unicode)]
    public static extern void Trample(string text);
}

class Program {
    static void Main(string[] args) {
        Console.WriteLine("Hello, world!");
        NativeMethods.Trample("Hello, world!");
        Console.WriteLine("Hello, world!");
    }
}

Output:

Hello, world!
Adios, world!

Since "Hello, world!" is a string literal, all instances of it end up in the string intern pool, and every time it's used we're using "the same" string. Our unmanaged function overwrites this, so now whenever we think we're writing "Hello, world!" in our managed code, we end up with something else instead. Oops.

The way to avoid this if you know the unmanaged function changes the string is to pass a StringBuilder instead. Here you can even choose if you want to copy to be in, out or both (with InAttribute/OutAttribute). This does involve copying to/from buffers -- specifically, CoTaskMemAlloc will be used to allocate memory for the unmanaged code (and CoTaskMemFree will be called when the call is done). This code is invoked by the marshaler as part of the call; neither the managed caller nor the unmanaged callee need to concern themselves with this.

Calling a function that expects an ANSI string also involves allocating a buffer, but in this case the buffer is allocated using the localloc instruction, not CoTaskMemAlloc, which is bunches more efficient. That said -- if you are actually going for efficiency, what you want to do is eliminate calling unmanaged code altogether if possible, not merely optimizing string passing. Even ignoring copying memory, there's quite a bit of overhead involved in managed/unmanaged transitions. If you find yourself calling unmanaged code in a loop, it pays off to see if that code can be ported to managed code.

Source: coreclr/src/vm/ilmarshalers.cpp, specifically ILWSTRMarshaler::EmitConvertSpaceAndContentsCLRToNativeTemp.


问:
ASM ByteCode - override visitLine() method
The visitLine() method of the ASM bytecode manipulation framework visits each line of the source code from which it was compiled.

If I have a line broken down in the source code like

```<code>Line 45:   ArrayList<Integer> test = new ArrayList<
Line 46:                                 Integer>();
</code>```

Then it shows both 45 and 46. Is there a way to override it so that it shows this execution as just Line 45?

答: ASM adds all line information that is added by the Jaca compiler. If you want to drop a line, you would need to filter such lines yourself. For example, you could check if a line does not include an instruction, you could suppress the call to any underlying method visitor.</p>

Body:
The visitLine() method of the ASM bytecode manipulation framework visits each line of the source code from which it was compiled.

If I have a line broken down in the source code like

Line 45:   ArrayList<Integer> test = new ArrayList<
Line 46:                                 Integer>();

Then it shows both 45 and 46. Is there a way to override it so that it shows this execution as just Line 45?


问:
Algorithm for Determining Tic Tac Toe Game Over
I've written a game of tic-tac-toe in Java, and my current method of determining the end of the game accounts for the following possible scenarios for the game being over:

The board is full, and no winner has yet been declared: Game is a draw.

Cross has won.

Circle has won.

Unfortunately, to do so, it reads through a predefined set of these scenarios from a table. This isn't necessarily bad considering that there are only 9 spaces on a board, and thus the table is somewhat small, but is there a better algorithmic way of determining if the game is over? The determination of whether someone has won or not is the meat of the problem, since checking if 9 spaces are full is trivial.

The table method might be the solution, but if not, what is? Also, what if the board were not size n=9? What if it were a much larger board, say n=16, n=25, and so on, causing the number of consecutively placed items to win to be x=4, x=5, etc? A general algorithm to use for all n = { 9, 16, 25, 36 ... }?

答:
If you have boarder field 5*5 for examle, I used next method of checking:

```<code>public static boolean checkWin(char symb) {
  int SIZE = 5;

        for (int i = 0; i < SIZE-1; i++) {
            for (int j = 0; j <SIZE-1 ; j++) {
                //vertical checking
            if (map[0][j] == symb && map[1][j] == symb && map[2][j] == symb && map[3][j] == symb && map[4][j] == symb) return true;      // j=0
            }
            //horisontal checking
            if(map[i][0] == symb && map[i][1] == symb && map[i][2] == symb && map[i][3] == symb && map[i][4] == symb) return true;  // i=0
        }
        //diagonal checking (5*5)
        if (map[0][0] == symb && map[1][1] == symb && map[2][2] == symb && map[3][3] == symb && map[4][4] == symb) return true;
        if (map[4][0] == symb && map[3][1] == symb && map[2][2] == symb && map[1][3] == symb && map[0][4] == symb) return true;

        return false;
        }
</code>```

I think, it's more clear, but probably is not the most optimal way.

Body:
If you have boarder field 5*5 for examle, I used next method of checking:

public static boolean checkWin(char symb) {
  int SIZE = 5;

        for (int i = 0; i < SIZE-1; i++) {
            for (int j = 0; j <SIZE-1 ; j++) {
                //vertical checking
            if (map[0][j] == symb && map[1][j] == symb && map[2][j] == symb && map[3][j] == symb && map[4][j] == symb) return true;      // j=0
            }
            //horisontal checking
            if(map[i][0] == symb && map[i][1] == symb && map[i][2] == symb && map[i][3] == symb && map[i][4] == symb) return true;  // i=0
        }
        //diagonal checking (5*5)
        if (map[0][0] == symb && map[1][1] == symb && map[2][2] == symb && map[3][3] == symb && map[4][4] == symb) return true;
        if (map[4][0] == symb && map[3][1] == symb && map[2][2] == symb && map[1][3] == symb && map[0][4] == symb) return true;

        return false;
        }

I think, it's more clear, but probably is not the most optimal way.


问:
Where is the Firebase Storage traffic statistics?
Where are the Firebase Storage traffic statistics? I want to use Firebase Storage, but I don't know where are the traffic statistics.</p>

答: At this point of time you can't view Firebase Storage traffic statistics. Firebase team might be working on it for sure. </p>


问:
Make A Scrolling Background
I have been having trouble getting a scrolling background on my site. I have tried a bunch off different methods and StackOverflow topics and I can't get it to work. Basically, I have a background and I need it to keep looping. Please help. Thanks!

This is not the same as the linked question, because I tried that and I didn't work for me, and the method provided is a different method.

答: Although your question is quite vague, I believe this would assist you, look into the background-repeat property.

Title: Make A Scrolling Background


问:
Why does HTML Canvas getImageData() not return the exact same values that were just set?
When writing pixels to an HTML Canvas context using putImageData I find that the pixel values are not exactly the same when I fetch them again. I have put up a sample test page showing the problem. Boiled down, the problem is:

```<code>var id = someContext.getImageData(0,0,1,1);
id.data[0]=id.data[3]=64; // 25% red, 25% alpha
id.data[1]=id.data[2]=0;  // No blue or green
someContext.putImageData(id,0,0);
var newData = someContext.getImageData(0,0,1,1);
console.log( newData.data[0] );
</code>```

On Chrome v8, the red value comes back as 63; on Firefox v3.6, Safari v5, and IE9 the red value comes back as 67 (all on Windows). On OS X, Chrome v7, Safari v5, and Firefox v3.6 also come back as 67. None of them come back as the 64 value originally set!

Using setTimeout to delay between setting and re-fetching makes no difference. Changing the background of the page makes no difference. Using save() and restore() on the context (per this unlikely article) makes no difference.

答:
Looks like a rounding issue to me...

```<code>64/255 = 0.2509... (rounded down to give 0.25)
0.25 * 255 = 63.75 (rounded down to give 63)
== OR ==
64/255 = 0.2509... (rounded up to give 0.26)
0.26 * 255 = 66.3  (rounded up to give 67)
</code>```

Remember that 255 is the maximum value, not 256 ;)

EDIT: Of course, this wouldn't explain why the alpha channel is behaving...

Body:
When writing pixels to an HTML Canvas context using putImageData I find that the pixel values are not exactly the same when I fetch them again. I have put up a sample test page showing the problem. Boiled down, the problem is:

var id = someContext.getImageData(0,0,1,1);
id.data[0]=id.data[3]=64; // 25% red, 25% alpha
id.data[1]=id.data[2]=0;  // No blue or green
someContext.putImageData(id,0,0);
var newData = someContext.getImageData(0,0,1,1);
console.log( newData.data[0] );

On Chrome v8, the red value comes back as 63; on Firefox v3.6, Safari v5, and IE9 the red value comes back as 67 (all on Windows). On OS X, Chrome v7, Safari v5, and Firefox v3.6 also come back as 67. None of them come back as the 64 value originally set!

Using setTimeout to delay between setting and re-fetching makes no difference. Changing the background of the page makes no difference. Using save() and restore() on the context (per this unlikely article) makes no difference.

Body:
Looks like a rounding issue to me...

64/255 = 0.2509... (rounded down to give 0.25)
0.25 * 255 = 63.75 (rounded down to give 63)
== OR ==
64/255 = 0.2509... (rounded up to give 0.26)
0.26 * 255 = 66.3  (rounded up to give 67)

Remember that 255 is the maximum value, not 256 ;)

EDIT: Of course, this wouldn't explain why the alpha channel is behaving...


问:
XSL for-each: how to detect last node?
I have this simple code:

```<code><xsl:for-each select="GroupsServed">
  <xsl:value-of select="."/>,<br/>
</xsl:for-each></font>
</code>```

I'm trying to add a comma for each item added.

This has 2 flaws:

Case of when there's only 1 item: the code would unconditionally add a comma.

Case of when there's more than 1 item: the last item would have a comma to it.

What do you think is the most elegant solution to solve this?

I'm using XSLT 2.0

答:
```<code><xsl:variable name="GROUPS_SERVED_COUNT" select="count(GroupsServed)"/>
<xsl:for-each select="GroupsServed">
    <xsl:value-of select="."/>
    <xsl:if test="position() < $GROUPS_SERVED_COUNT">
        ,<br/>
    </xsl:if>
</xsl:for-each></font>
</code>```

Title: XSL for-each: how to detect last node?

Body:
I have this simple code:

<xsl:for-each select="GroupsServed">
  <xsl:value-of select="."/>,

</xsl:for-each>

I'm trying to add a comma for each item added.

This has 2 flaws:

Case of when there's only 1 item: the code would unconditionally add a comma.

Case of when there's more than 1 item: the last item would have a comma to it.

What do you think is the most elegant solution to solve this?

I'm using XSLT 2.0


问:
VBA error 1004 - Runtime
I'm having a little 'error 1004' with my project and I can't find a way to correct it "properly".

I get an error when I use this code :

```<code>If Total_account = "OUI" Or (Total_account = "NON" And Range(Cfin).Row = "2") Then GoTo fin
</code>```

I am getting the error when the first condition is met:

```<code>If Total_account = "OUI"
</code>```

When I have Total_account = "NON" and Range(Cfin).Row = 2, no error.

The only way to fix I found was to do it like that, but it does not look good :

```<code>If Total_account = "OUI" Then GoTo fin
If (Total_account = "NON" And Range(Cfin).Row = "2") Then GoTo fin
</code>```

I also read the Microsoft support for this error but I don't get it : https://support.microsoft.com/fr-fr/help/963259/runtime-error-1004-method-range-of-object-global-failed

Could you help me understand/ find a way to correct this?
The error screenshot is attached to my post.

Thanks in advance !

Jean

答:
Put this code in a standard module in a new workbook. I guarantee it cannot cause an error, no matter what value you have for Total_account.

```<code>Sub foo()
Dim Total_account as String
Dim CFin as String
CFin = "$C$2"
Total_account = "OUI"

If Total_account = "OUI" Or (Total_account = "NON" And Range(CFin).Row = "2") Then GoTo fin

fin:
End Sub
</code>```

This suggest a problem elsewhere in your code. Judging from the 1004 message, if the error raises on your boolean expression, this can only be because CFin is unassigned (empty string, empty/zero numeric value).

If CFin has a zero or empty value at run-time, therefore the Range(cfin) will raise a 1004 error, since Range("").Row is not valid.

Title: VBA error 1004 - Runtime

Body:
I'm having a little 'error 1004' with my project and I can't find a way to correct it "properly".

I get an error when I use this code :

If Total_account = "OUI" Or (Total_account = "NON" And Range(Cfin).Row = "2") Then GoTo fin

I am getting the error when the first condition is met:

If Total_account = "OUI"

When I have Total_account = "NON" and Range(Cfin).Row = 2, no error.

The only way to fix I found was to do it like that, but it does not look good :

If Total_account = "OUI" Then GoTo fin
If (Total_account = "NON" And Range(Cfin).Row = "2") Then GoTo fin

I also read the Microsoft support for this error but I don't get it : https://support.microsoft.com/fr-fr/help/963259/runtime-error-1004-method-range-of-object-global-failed

Could you help me understand/ find a way to correct this?
The error screenshot is attached to my post.

Thanks in advance !

Jean

Body:
Put this code in a standard module in a new workbook. I guarantee it cannot cause an error, no matter what value you have for Total_account.

Sub foo()
Dim Total_account as String
Dim CFin as String
CFin = "$C$2"
Total_account = "OUI"

If Total_account = "OUI" Or (Total_account = "NON" And Range(CFin).Row = "2") Then GoTo fin

fin:
End Sub

This suggest a problem elsewhere in your code. Judging from the 1004 message, if the error raises on your boolean expression, this can only be because CFin is unassigned (empty string, empty/zero numeric value).

If CFin has a zero or empty value at run-time, therefore the Range(cfin) will raise a 1004 error, since Range("").Row is not valid.