问:
AngularJS 1.x: Dynamically created multiple File Upload fields
You have to excuse me, I do not use Angular that often. I need to implement a solution in which I can upload files from dynamically generated input fields.

The catch is that I cannot use any directives (this is due to the framework I am using in which AngularJS is implemented).

My current code for creating fields:

```<code>$scope.addNewFile = function() {
    var newFileNo = $scope.files.length + 1;
    $scope.files.push({'id': 'file' + newFileNo});
};

$scope.removeFile = function() {
    var lastFile = $scope.files.length - 1;
    $scope.files.splice(lastFile);
};
</code>```

And here is the code for uploading files (not correct, because of static id and name values:

```<code>$scope.uploadFile = function() {
    var file = document.getElementById('file').files[0],
        r = new FileReader;
    r.onloadend = function (e) {
        var data = e.target.result;
        console.log('data');
        console.log(data);
        // http.post
    };
    r.readAsArrayBuffer(file);
};
</code>```

And here is my HTML:

```<code><div data-ng-repeat="file in files">
    <div class="row top-buffer">
        <div class="col-lg-10">
            <input type="file"
                   ng-model="file.name"
                   name="file"
                   class="form-control"
                   id="file">
        </div>
        <div class="col-lg-2 text-right">
            <div class="btn btn-primary" ng-click="uploadFile()">Upload</div>
        </div>
    </div>
</div>
<div class="row top-buffer">
    <div class="col-lg-11"></div>
    <div class="col-lg-1 text-right">
        <div class="glyphicon glyphicon-plus" aria-hidden="true" ng-click="addNewFile()"></div>
        <div class="glyphicon glyphicon-minus" aria-hidden="true" ng-click="removeFile()"></div>
    </div>
</div>
</code>```

I can't really understand how I can get the values of dynamically generated file fields... any help appreciated!

答:
Writing an uploader properly is a very difficult task. A major problem with an upload component/directive is getting it to work in Internet Explorer; because it can only be used once in IE. Another problem is that IE will not let you programmatically "press" the button, it must be a real mouse click.

There are upload libraries out there for AngularJs, just google. However if you are intent on doing it yourself then you can use my git repo as an example of how it should be done. Just use the jwtUploader and jwtUploaderButton directives.

https://github.com/smylydon/SEPE-7WCM0033-0206-FRONTEND/tree/master/client/app

Body:
You have to excuse me, I do not use Angular that often. I need to implement a solution in which I can upload files from dynamically generated input fields.

The catch is that I cannot use any directives (this is due to the framework I am using in which AngularJS is implemented).

My current code for creating fields:

$scope.addNewFile = function() {
    var newFileNo = $scope.files.length + 1;
    $scope.files.push({'id': 'file' + newFileNo});
};

$scope.removeFile = function() {
    var lastFile = $scope.files.length - 1;
    $scope.files.splice(lastFile);
};

And here is the code for uploading files (not correct, because of static id and name values:

$scope.uploadFile = function() {
    var file = document.getElementById('file').files[0],
        r = new FileReader;
    r.onloadend = function (e) {
        var data = e.target.result;
        console.log('data');
        console.log(data);
        // http.post
    };
    r.readAsArrayBuffer(file);
};

And here is my HTML:

            <input type="file"
                   ng-model="file.name"
                   name="file"
                   class="form-control"
                   id="file">

Upload

I can't really understand how I can get the values of dynamically generated file fields... any help appreciated!


来源: stackexchange

问:
When using asio+ssl, the async_write doesn't send the data
Given:

```<code>asio::ssl::stream<asio::ip::tcp::socket&> &m_socket;
async_write(self->m_socket, asio::buffer(self->m_v),
    [self, handler](asio::error_code ec, std::size_t s)
{
    handler(ec);
});
</code>```

Result:
the handler is invoked before the data is sent (socket.send() function is called).
Result 2:
the data is actually sent after a long while - in my reproducible case about 1 min.
So, the sequence of events is as follows:
1. async_write is called;
2. handler is called;
3. data is sent.

I believe that correct sequence must be:
1. async_write is called;
2. data is sent.
3. handler is called;

It doesn't happen always, but very reproducible. I searched all over Internet for similar cases - found nothing.

I need advice: what to do about that. Is it a bug in asio or is it some tricky bug in my program and where to look to fix it.

I can reproduce the case easily, can provide log files etc.

答:
If you see a timestamp later than 2. in MMA, that doesn't mean it got sent after 2. (depending on where in the protocol you see the timestamp). It may just mean MMA saw it later. Also, things like Nagle's algorithm could be at play.

Try setting TCP NODELAY, e.g.

```<code>socket.open(tcp::v4());
socket.set_option(tcp::no_delay(true));
socket.async_connect(endpoint, handler);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Given:

asio::ssl::stream<asio::ip::tcp::socket&> &m_socket;
async_write(self->m_socket, asio::buffer(self->m_v),
    [self, handler](asio::error_code ec, std::size_t s)
{
    handler(ec);
});

Result:
the handler is invoked before the data is sent (socket.send() function is called).
Result 2:
the data is actually sent after a long while - in my reproducible case about 1 min.
So, the sequence of events is as follows:
1. async_write is called;
2. handler is called;
3. data is sent.

I believe that correct sequence must be:
1. async_write is called;
2. data is sent.
3. handler is called;

It doesn't happen always, but very reproducible. I searched all over Internet for similar cases - found nothing.

I need advice: what to do about that. Is it a bug in asio or is it some tricky bug in my program and where to look to fix it.

I can reproduce the case easily, can provide log files etc.

Body:
If you see a timestamp later than 2. in MMA, that doesn't mean it got sent after 2. (depending on where in the protocol you see the timestamp). It may just mean MMA saw it later. Also, things like Nagle's algorithm could be at play.

Try setting TCP NODELAY, e.g.

socket.open(tcp::v4());
socket.set_option(tcp::no_delay(true));
socket.async_connect(endpoint, handler);


问:
Check if any value in array is equal to current value added to array
I have a 2D array initialized to Storage[100][3].

I insert a group values to each row of the array and move on to the next row and do the same,
for example:

1 1 3

2 5 6

3 1 3

(keeps going on to 100 rows)

After completing the insertion of 1 entire row I want to check if the values in this current insertion's column's 2 and 3 match the values in all the previous row's, column's 2 and 3.

for example in the above data set I look at column's 2 and 3 in each row and see that rows 1 and 3 have the same values in those columns.

I wrote a program that can compare the current insertion to the previous insertion. But I want to compare the current insertion with all the insertions in the array.

```<code>const int col=0;

//inserting the values//
for (int row= 0; row < 100; row++) {
    storage[row][col] = t;
    storage[row][col += 1] = xi;
    storage[row][col += 2] = yi;
}

//trying to check if the values are same. need help here//
for (int row = 0; row < 100; row++) {
    if (storage[row][col + 1]==storage[row + 1][col + 1]
        && storage[row][col + 2] == storage[row + 1][col + 2]) {

    }
}
</code>```

答:
If you want to create an algorithm that scales nicely O(log2n) rather than O(n^2) try using a Hash table to keep track of encountered numbers.  My example numbers for the first iteration are 4, 2, 3.

You can get a count of how many times you've encountered your duplicate numbers and most importantly you don't have to do the heavy lifting of loop-searching yourself!

```<code>int main(array<System::String ^> ^args)
{
   std::map<int, int> twoColsCounts;
   int storage[100][3];

   int ordinal1 = 4;
   int ordinal2 = 2;
   int ordinal3 = 3;

   for (int i = 0; i < 100; i++)
   {
      storage[i][0] = ordinal1;
      storage[i][1] = ordinal2;
      storage[i][2] = ordinal3;

      int lastTwoDigits = ordinal2 * 10 + ordinal3;

      auto inMapRecord = twoColsCounts.find(lastTwoDigits);
      if (inMapRecord != twoColsCounts.end())
      {
         // Number Already Found.  Increment count for posterity!
         twoColsCounts[lastTwoDigits]++;
      }
      else
      {
         // Not already encountered - Add it to record with count of 1
         twoColsCounts[lastTwoDigits] = 1;
      }
   }

    Console::WriteLine(L"Done 'big data' style!");
    return 0;
}
</code>```

Good luck!

Body:
I have a 2D array initialized to Storage[100][3].

I insert a group values to each row of the array and move on to the next row and do the same,
for example:

1 1 3

2 5 6

3 1 3

(keeps going on to 100 rows)

After completing the insertion of 1 entire row I want to check if the values in this current insertion's column's 2 and 3 match the values in all the previous row's, column's 2 and 3.

for example in the above data set I look at column's 2 and 3 in each row and see that rows 1 and 3 have the same values in those columns.

I wrote a program that can compare the current insertion to the previous insertion. But I want to compare the current insertion with all the insertions in the array.

const int col=0;

//inserting the values//
for (int row= 0; row < 100; row++) {
    storage[row][col] = t;
    storage[row][col += 1] = xi;
    storage[row][col += 2] = yi;
}

//trying to check if the values are same. need help here//
for (int row = 0; row < 100; row++) {
    if (storage[row][col + 1]==storage[row + 1][col + 1]
        && storage[row][col + 2] == storage[row + 1][col + 2]) {

    }
}

Body:
If you want to create an algorithm that scales nicely O(log2n) rather than O(n^2) try using a Hash table to keep track of encountered numbers.  My example numbers for the first iteration are 4, 2, 3.

You can get a count of how many times you've encountered your duplicate numbers and most importantly you don't have to do the heavy lifting of loop-searching yourself!

int main(array<System::String ^> ^args)
{
   std::map<int, int> twoColsCounts;
   int storage[100][3];

   int ordinal1 = 4;
   int ordinal2 = 2;
   int ordinal3 = 3;

   for (int i = 0; i < 100; i++)
   {
      storage[i][0] = ordinal1;
      storage[i][1] = ordinal2;
      storage[i][2] = ordinal3;

      int lastTwoDigits = ordinal2 * 10 + ordinal3;

      auto inMapRecord = twoColsCounts.find(lastTwoDigits);
      if (inMapRecord != twoColsCounts.end())
      {
         // Number Already Found.  Increment count for posterity!
         twoColsCounts[lastTwoDigits]++;
      }
      else
      {
         // Not already encountered - Add it to record with count of 1
         twoColsCounts[lastTwoDigits] = 1;
      }
   }

    Console::WriteLine(L"Done 'big data' style!");
    return 0;
}

Good luck!


问:
MAC A fatal error has been detected by the Java Runtime Environment
Running tests in Chrome browser, it suddenly crashes on the same step with this error:
fatal error has been detected by the Java Runtime Environment in Intelij Idea (2016.2.2) https://www.refheap.com/122660

and MAC throws this kind of report https://www.refheap.com/122658 If I run mvn package - it crashes with error ForkedBooter quit unexpectedly

Using Java jdk1.8.0_45.jdk with JUnit and Maven.

Can you please help me to find out, what causes this problem?

答:
Try to use a shell terminal and type in:

export LD_BIND_NOW=1


问:
Dealing with Large Bitmaps (tiling a small bitmap to create wallpaper)
I'm having memory problems and think it might have to do with creating large bitmaps.

The task at hand is to get a fairly small tile image and create a larger tiled image and set this as the phone wallpaper. The way I'm doing this is:

1) Create a view that is 2 * screen width, 1 * screen height

2) Set the view background to a BitmapDrawable with the tile mode set to repeat

3) Create a bitmap with the views dimensions

4) draw the view to the bitmap by: view.draw(new Canvas(bitmap))

5) set wallpper: getApplicationContext().setWallpaper(bitmap)

This works fine on my phone (HTC Magic) and other phones that I have tried. But I am getting bug reports relating to this issue. I tried to recreate the problem by doubling the required dimensions and the problem seems to be happening in the 4th step when the view is being drawn to the bitmap:

ERROR/dalvikvm-heap(124): Heap Massage needed (7372800-byte external allocation too big)

I'm not sure how to go about solving this. Please help!
Thanks

答:
Actually you could refactor your code. You'll have better performance and probably use less memory if you don't use a View

Create a Bitmap of the desired size bitmap = Bitmap.createBitmap(width,height,Bitamp.Config.RGV_565) (or ARGB_8888, that might work too)

Create a canvas = new Canvas(bitmap)

Create the tiled image yourself, from your src

simplified Code:

```<code>// set another matrix if you want rotation/scaling of the input
Matrix identity=new Matrix();
for (int i=0; i<maxLines; i++) {
  for (int j=0; j<maxCol; j++) {
    canvas.draw(src, identity,anyPaint);
  }
}
</code>```

Keep the end  set wallpaper getApplicationContext().setWallpaper(bitmap)

ContentLicense: CC BY-SA 2.5

Body:
Actually you could refactor your code. You'll have better performance and probably use less memory if you don't use a View

Create a Bitmap of the desired size bitmap = Bitmap.createBitmap(width,height,Bitamp.Config.RGV_565) (or ARGB_8888, that might work too)

Create a canvas = new Canvas(bitmap)

Create the tiled image yourself, from your src

simplified Code:

// set another matrix if you want rotation/scaling of the input
Matrix identity=new Matrix();
for (int i=0; i<maxLines; i++) {
  for (int j=0; j<maxCol; j++) {
    canvas.draw(src, identity,anyPaint);
  }
}

Keep the end  set wallpaper getApplicationContext().setWallpaper(bitmap)


问:
Unable to parse xml to json properly
I'm trying to parse a xml to json & i'm using xml2js in nodejs.
Below is my code

```<code>var chai = require('chai');
var chaiHttp = require('chai-http');
var request = chai.request;
var should = chai.should();
var expect = chai.expect;
var assert = chai.assert;
var supertest = require('supertest');
var fs = require('fs');
var xmlLocation = "./configdata/xmlDoc.xml";

var xml2js = require('xml2js');
var parser = new xml2js.Parser();

//Plugin for HTTP, etc.
chai.use(chaiHttp);
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';

//xmlFile = JSON.parse(fs.readFileSync(xmlData, 'utf8'));

describe("Test : ", function () {

    it("convert xml to json", function (done) {

        r = fs.readFileSync(xmlLocation, 'UTF-8');
        parser.parseString(r, function (err, parsedData) {
            if (err) throw err;
            else {
                fs.writeFile("jsonData.json", JSON.stringify(parsedData), function (err, response) {
                });
            }
        });

        done();
    });

})
</code>```

My sample xml file :

```<code><?xml version="1.0" encoding="UTF-8" ?>
<ALEXA>
    <SD TITLE="A" FLAGS="" HOST="davidwalsh.name">
        <TITLE TEXT="David Walsh Blog :: PHP, MySQL, CSS, Javascript, MooTools, and Everything Else"/>
        <LINKSIN NUM="1102"/>
        <SPEED TEXT="1421" PCT="51"/>
    </SD>
    <SD>
        <POPULARITY URL="davidwalsh.name/" TEXT="7131"/>
        <REACH RANK="5952"/>
        <RANK DELTA="-1648"/>
    </SD>
</ALEXA>
</code>```

I'm getting the below output :

```<code>{
  "ALEXA": {
    "SD": [
      {
        "$": {
          "TITLE": "A",
          "FLAGS": "",
          "HOST": "davidwalsh.name"
        },
        "TITLE": [
          {
            "$": {
              "TEXT": "David Walsh Blog :: PHP, MySQL, CSS, Javascript, MooTools, and Everything Else"
            }
          }
        ],
        "LINKSIN": [
          {
            "$": {
              "NUM": "1102"
            }
          }
        ],
        "SPEED": [
          {
            "$": {
              "TEXT": "1421",
              "PCT": "51"
            }
          }
        ]
      },
      {
        "POPULARITY": [
          {
            "$": {
              "URL": "davidwalsh.name/",
              "TEXT": "7131"
            }
          }
        ],
        "REACH": [
          {
            "$": {
              "RANK": "5952"
            }
          }
        ],
        "RANK": [
          {
            "$": {
              "DELTA": "-1648"
            }
          }
        ]
      }
    ]
  }
}
</code>```

'$' is getting added to the parsed json. How to avoid it..??

Looking for a solution. Thanks in advance.

答:
library like this usually parse everything and sometimes resulting in having many properties which you don't need.

i created camaro for this purpose.

downside of this is you have to write your own template file for the structure you want xml to be transform to.

```<code>const transform = require('camaro')
const fs = require('fs')

const xml = fs.readFileSync('ean.xml', 'utf-8')
const template = {
    cache_key: "/HotelListResponse/cacheKey",
    hotels: ["//HotelSummary", {
        hotel_id: "hotelId",
        name: "name",
        rooms: ["RoomRateDetailsList/RoomRateDetails", {
            rates: ["RateInfos/RateInfo", {
                currency: "ChargeableRateInfo/@currencyCode",
                non_refundable: "nonRefundable",
                price: "ChargeableRateInfo/@total"
            }],
            room_name: "roomDescription",
            room_type_id: "roomTypeCode"
        }]
    }],
    session_id: "/HotelListResponse/customerSessionId"
}

const result = transform(xml, template)
</code>```

Title: Unable to parse xml to json properly

Body:
I'm trying to parse a xml to json & i'm using xml2js in nodejs.
Below is my code

var chai = require('chai');
var chaiHttp = require('chai-http');
var request = chai.request;
var should = chai.should();
var expect = chai.expect;
var assert = chai.assert;
var supertest = require('supertest');
var fs = require('fs');
var xmlLocation = "./configdata/xmlDoc.xml";

var xml2js = require('xml2js');
var parser = new xml2js.Parser();

//Plugin for HTTP, etc.
chai.use(chaiHttp);
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';

//xmlFile = JSON.parse(fs.readFileSync(xmlData, 'utf8'));

describe("Test : ", function () {

    it("convert xml to json", function (done) {

        r = fs.readFileSync(xmlLocation, 'UTF-8');
        parser.parseString(r, function (err, parsedData) {
            if (err) throw err;
            else {
                fs.writeFile("jsonData.json", JSON.stringify(parsedData), function (err, response) {
                });
            }
        });

        done();
    });

})

My sample xml file :

<?xml version="1.0" encoding="UTF-8" ?>
<ALEXA>
    <SD TITLE="A" FLAGS="" HOST="davidwalsh.name">
        <TITLE TEXT="David Walsh Blog :: PHP, MySQL, CSS, Javascript, MooTools, and Everything Else"/>
        <LINKSIN NUM="1102"/>
        <SPEED TEXT="1421" PCT="51"/>
    </SD>
    <SD>
        <POPULARITY URL="davidwalsh.name/" TEXT="7131"/>
        <REACH RANK="5952"/>
        <RANK DELTA="-1648"/>
    </SD>
</ALEXA>

I'm getting the below output :

{
  "ALEXA": {
    "SD": [
      {
        "$": {
          "TITLE": "A",
          "FLAGS": "",
          "HOST": "davidwalsh.name"
        },
        "TITLE": [
          {
            "$": {
              "TEXT": "David Walsh Blog :: PHP, MySQL, CSS, Javascript, MooTools, and Everything Else"
            }
          }
        ],
        "LINKSIN": [
          {
            "$": {
              "NUM": "1102"
            }
          }
        ],
        "SPEED": [
          {
            "$": {
              "TEXT": "1421",
              "PCT": "51"
            }
          }
        ]
      },
      {
        "POPULARITY": [
          {
            "$": {
              "URL": "davidwalsh.name/",
              "TEXT": "7131"
            }
          }
        ],
        "REACH": [
          {
            "$": {
              "RANK": "5952"
            }
          }
        ],
        "RANK": [
          {
            "$": {
              "DELTA": "-1648"
            }
          }
        ]
      }
    ]
  }
}

'$' is getting added to the parsed json. How to avoid it..??

Looking for a solution. Thanks in advance.

Body:
library like this usually parse everything and sometimes resulting in having many properties which you don't need.

i created camaro for this purpose.

downside of this is you have to write your own template file for the structure you want xml to be transform to.

const transform = require('camaro')
const fs = require('fs')

const xml = fs.readFileSync('ean.xml', 'utf-8')
const template = {
    cache_key: "/HotelListResponse/cacheKey",
    hotels: ["//HotelSummary", {
        hotel_id: "hotelId",
        name: "name",
        rooms: ["RoomRateDetailsList/RoomRateDetails", {
            rates: ["RateInfos/RateInfo", {
                currency: "ChargeableRateInfo/@currencyCode",
                non_refundable: "nonRefundable",
                price: "ChargeableRateInfo/@total"
            }],
            room_name: "roomDescription",
            room_type_id: "roomTypeCode"
        }]
    }],
    session_id: "/HotelListResponse/customerSessionId"
}

const result = transform(xml, template)


问:
.Net Core Serialize an Object with IEnumerables<T> to Save as XML
I am using .net Core 1.1 and writing a console application. I need to Serialize an Object with some basic properties of strings and int as well as some IEnumerable Objects and serialize it as XML so I can save it to a "data.xml" file.

I receive the Exception:
System.Runtime.Serialization.SerializationException: 'Type 'System.Collections.Generic.List`1[[CorpsDataExtractor.ViewModels.LegacyView, CorpsDataExtractor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' with data contract name 'ArrayOfLegacyView:http://schemas.datacontract.org/2004/07/CorpsDataExtractor.ViewModels' is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.'

I currently am able to serialize my Object as JSON, but am having trouble utilizing the DataContractSerializer. I Added the Known Type List that the exception states I am missing but it still fails.

```<code>// This List isretrieved using Entity Framework Core
      List<LegacyView> legacyData = await _corpsRepo.ListLegacyData();

// The Below Line will write to a JSON File. No Error and works
        File.WriteAllText(@"E:\\CorporationsDataLegacy.json", JsonConvert.SerializeObject(legacyData));

// This Creates a Known Type List for the DataContractSerializer
        var knownTypeList = new List<Type>
        {
            typeof(LegacyView),
            typeof(People),
            typeof(DocumentType)
        };

        FileStream writer = new FileStream(@"E:\\data.xml", FileMode.Create);
        var ser = new DataContractSerializer(typeof(LegacyView), knownTypeList );
// When Debugging I Receive The stated exception at this line
        ser.WriteObject(writer, legacyData);
</code>```

Below Are my Class ViewModels:

Legacy View

```<code>[DataContract]
public class LegacyView
{
    [DataMember]
    public string Ubi { get; set; }
    [DataMember]
    public IEnumerable<Person> People{ get; set; }
    [DataMember]
    public IEnumerable<DocumentType> DocumentTypes { get; set; }
}
</code>```

Person

```<code>[DataContract]
public class Person
{
    [DataMember]
    public string FirstName { get; set; }
    [DataMember]
    public string MiddleName { get; set; }
}
</code>```

Documents

```<code>[DataContract]
public class DocumentType
{
    [DataMember]
    public string Document { get; set; }
    [DataMember]
    public DateTime? CompletedDate { get; set; }
}
</code>```

Any Direction on what I am missing?

答: I might be a bit off as I've done more of XmlSerialize rather than DataContracts one, but I believe both assume eventual deserialization of the content.  And with IEnumerable<T> as the type, deserializer wouldn't know what class to actually instantiate to back the interface during deserialization.  Change fields to concrete classes instead of enumeration, and that should work.

Body:
I am using .net Core 1.1 and writing a console application. I need to Serialize an Object with some basic properties of strings and int as well as some IEnumerable Objects and serialize it as XML so I can save it to a "data.xml" file.

I receive the Exception:
System.Runtime.Serialization.SerializationException: 'Type 'System.Collections.Generic.List`1[[CorpsDataExtractor.ViewModels.LegacyView, CorpsDataExtractor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' with data contract name 'ArrayOfLegacyView:http://schemas.datacontract.org/2004/07/CorpsDataExtractor.ViewModels' is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.'

I currently am able to serialize my Object as JSON, but am having trouble utilizing the DataContractSerializer. I Added the Known Type List that the exception states I am missing but it still fails.

// This List isretrieved using Entity Framework Core
      List<LegacyView> legacyData = await _corpsRepo.ListLegacyData();

// The Below Line will write to a JSON File. No Error and works
        File.WriteAllText(@"E:\\CorporationsDataLegacy.json", JsonConvert.SerializeObject(legacyData));

// This Creates a Known Type List for the DataContractSerializer
        var knownTypeList = new List<Type>
        {
            typeof(LegacyView),
            typeof(People),
            typeof(DocumentType)
        };

        FileStream writer = new FileStream(@"E:\\data.xml", FileMode.Create);
        var ser = new DataContractSerializer(typeof(LegacyView), knownTypeList );
// When Debugging I Receive The stated exception at this line
        ser.WriteObject(writer, legacyData);

Below Are my Class ViewModels:

Legacy View

[DataContract]
public class LegacyView
{
    [DataMember]
    public string Ubi { get; set; }
    [DataMember]
    public IEnumerable<Person> People{ get; set; }
    [DataMember]
    public IEnumerable<DocumentType> DocumentTypes { get; set; }
}

Person

[DataContract]
public class Person
{
    [DataMember]
    public string FirstName { get; set; }
    [DataMember]
    public string MiddleName { get; set; }
}

Documents

[DataContract]
public class DocumentType
{
    [DataMember]
    public string Document { get; set; }
    [DataMember]
    public DateTime? CompletedDate { get; set; }
}

Any Direction on what I am missing?


问:
PHP Startup Unable to load dynamic library php_mongo.dll
I'm a beginner for this. I'm trying to install mongodb driver on php.

```<code>Platform: Windows 8.1 64bit.
PHP 5.5.9
Apache/2.4.7
</code>```

Followed the instruction here:http://php.net/manual/en/mongo.installation.php#mongo.installation.windows

I've tried all php_mongo.dll file with VC11 and put in php/ext folder. and added extension=php_mongo.dll in php.ini file but when I tried to start apache in xampp controller I got an error.

```<code>    Php Startup: Unable to load dynamic library
  'C:\xampp\php\ext\php_mongo.dll' -%1 is not a valid Win32 application.
</code>```

I've already check my VC compilator version inside phpinfo() and it's stated there MSVC11 with architecture: x86.

it would be nice if someone can help me.
Thanks. appreciate it.

答:
For anyone googling this in 2017, the PECL Package has been updated and is now found at http://pecl.php.net/package/mongodb/1.2.9/windows

and use:

```<code>extension=php_mongodb.dll
</code>```

instead of:

```<code>extension=php_mongo.dll
</code>```

Body:
I'm a beginner for this. I'm trying to install mongodb driver on php.

Platform: Windows 8.1 64bit.
PHP 5.5.9
Apache/2.4.7

Followed the instruction here:http://php.net/manual/en/mongo.installation.php#mongo.installation.windows

I've tried all php_mongo.dll file with VC11 and put in php/ext folder. and added extension=php_mongo.dll in php.ini file but when I tried to start apache in xampp controller I got an error.

    Php Startup: Unable to load dynamic library
  'C:\xampp\php\ext\php_mongo.dll' -%1 is not a valid Win32 application.

I've already check my VC compilator version inside phpinfo() and it's stated there MSVC11 with architecture: x86.

it would be nice if someone can help me.
Thanks. appreciate it.

Body:
For anyone googling this in 2017, the PECL Package has been updated and is now found at http://pecl.php.net/package/mongodb/1.2.9/windows

and use:

extension=php_mongodb.dll

instead of:

extension=php_mongo.dll


问:
Maximum and minimum caps for list values in Python
I have a list of values and I'd like to set the maximum value of any element in the list to 255 and the minimum value to 0 while leaving those within the range unchanged.

```<code>oldList = [266, 40, -15, 13]

newList = [255, 40, 0, 13]
</code>```

Currently I'm doing

```<code>for i in range(len(oldList)):
    if oldList[i] > 255:
        oldList[i] = 255
    if oldList[i] < 0:
        oldList[i] = 0
</code>```

or similarly with newList.append(oldList[i]).

But there has to be a better way than that, right?

答:
Another option is is numpy.clip

```<code>>>> import numpy as np
>>> np.clip([266, 40, -15, 13], 0, 255)
array([255,  40,   0,  13])
</code>```

Body:
I have a list of values and I'd like to set the maximum value of any element in the list to 255 and the minimum value to 0 while leaving those within the range unchanged.

oldList = [266, 40, -15, 13]

newList = [255, 40, 0, 13]

Currently I'm doing

for i in range(len(oldList)):
    if oldList[i] > 255:
        oldList[i] = 255
    if oldList[i] < 0:
        oldList[i] = 0

or similarly with newList.append(oldList[i]).

But there has to be a better way than that, right?

Body:
Another option is is numpy.clip

>>> import numpy as np
>>> np.clip([266, 40, -15, 13], 0, 255)
array([255,  40,   0,  13])


问:
FOSRestBundle forms
I am trying to build symfony2 rest api, but I am struggling with FOSRestBundle

At first I could make work "@View()" annotation because it always would say that I template is missing, not matter what config options I would use I would get the same error, then in my routing yml I added "defaults: { _format: json }" and suddenly it stated working.

```<code>v1:
    resource: "@AppBundle/Controller/"
    defaults: { _format: json }
    type:     annotation
    prefix:   /v1
</code>```

But now I am having problem with forms I create a form class and a service and setup simple controller method:

```<code>/**
 * Creates a new Order entity.
 *
 * @Rest\Post("/products", name="products_create")
 * @Rest\View()
 * @param Request $request
 * @return Product|array
 */
public function createAction(Request $request)
{
    $product = new Product();
    $form = $this->createForm('product', $product);

    $form->handleRequest($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($product);
        $em->flush();

        return $product;
    }

    return $form;
}
</code>```

Now if form is invalid which is in my test case, I would expect to get similar response to that, that is showed in documentation: http://symfony.com/doc/current/bundles/FOSRestBundle/2-the-view-layer.html#forms-and-views

but instead of something like this:

```<code>{
    "code": 400,
    "message": "Validation Failed";
    "errors": {
        "children": {
            "code": {
                "errors": [
                    "This value should not be blank."
                ]
            },
            "name": {
                "errors": [
                    "This value should not be blank."
                ]
            },
            "description": {
                "errors": [
                    "This value should not be blank."
                ]
            }
        }
    }
}
</code>```

I get:

```<code>{
    "children": {
        "code": [],
        "name": [],
        "description": []
    }
}
</code>```

What's happening here? Is something wrong with my setup or I am missing something? By the way, I set form validation in my entity

答:
I know this is marked as solved, but I recently encountered the same issue with FOSRestBundle not returning an invalid form in the way it is documented at

http://symfony.com/doc/current/bundles/FOSRestBundle/2-the-view-layer.html#forms-and-views

I found the actual issue has to do with the order of registering bundles in AppKernel when JMS Serializer is used.  You MUST make sure to load in this order:

```<code>new JMS\SerializerBundle\JMSSerializerBundle(),
new FOS\RestBundle\FOSRestBundle()
</code>```

Once I did that, I started seeing results consistent with the documentation when a form fails validation.

Title: FOSRestBundle forms

Body:
I am trying to build symfony2 rest api, but I am struggling with FOSRestBundle

At first I could make work "@View()" annotation because it always would say that I template is missing, not matter what config options I would use I would get the same error, then in my routing yml I added "defaults: { _format: json }" and suddenly it stated working.

v1:
    resource: "@AppBundle/Controller/"
    defaults: { _format: json }
    type:     annotation
    prefix:   /v1

But now I am having problem with forms I create a form class and a service and setup simple controller method:

/**
 * Creates a new Order entity.
 *
 * @Rest\Post("/products", name="products_create")
 * @Rest\View()
 * @param Request $request
 * @return Product|array
 */
public function createAction(Request $request)
{
    $product = new Product();
    $form = $this->createForm('product', $product);

    $form->handleRequest($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($product);
        $em->flush();

        return $product;
    }

    return $form;
}

Now if form is invalid which is in my test case, I would expect to get similar response to that, that is showed in documentation: http://symfony.com/doc/current/bundles/FOSRestBundle/2-the-view-layer.html#forms-and-views

but instead of something like this:

{
    "code": 400,
    "message": "Validation Failed";
    "errors": {
        "children": {
            "code": {
                "errors": [
                    "This value should not be blank."
                ]
            },
            "name": {
                "errors": [
                    "This value should not be blank."
                ]
            },
            "description": {
                "errors": [
                    "This value should not be blank."
                ]
            }
        }
    }
}

I get:

{
    "children": {
        "code": [],
        "name": [],
        "description": []
    }
}

What's happening here? Is something wrong with my setup or I am missing something? By the way, I set form validation in my entity

Body:
I know this is marked as solved, but I recently encountered the same issue with FOSRestBundle not returning an invalid form in the way it is documented at

http://symfony.com/doc/current/bundles/FOSRestBundle/2-the-view-layer.html#forms-and-views

I found the actual issue has to do with the order of registering bundles in AppKernel when JMS Serializer is used.  You MUST make sure to load in this order:

new JMS\SerializerBundle\JMSSerializerBundle(),
new FOS\RestBundle\FOSRestBundle()

Once I did that, I started seeing results consistent with the documentation when a form fails validation.


问:
Help with converting bool to integer
I keep getting an error saying "Cannot implicitly covert type bool to int" I cannot figure out what to do with this. I get the error on: DisplayIndex = columns[i].Visible,

Code:

```<code>    private void SaveColumnOrder()
    {
        if (dgPortStatus.CanUserReorderColumns == true)
        {
            List<ColumnOrderItem> columnOrder = new List<ColumnOrderItem>();
            DataGridViewColumnCollection columns = this.Columns;
            for (int i = 0; i < columns.Count; i++)
            {
                columnOrder.Add(new ColumnOrderItem
                {
                    ColumnIndex = i,
                    DisplayIndex = columns[i].Visible,
                    Width = columns[i].Width
                });

            }

            portalDataGridViewSetting.Default.ColumnOrder[this.Name] = columnOrder;
            portalDataGridViewSetting.Default.Save();
        }
    }
</code>```

Code:

```<code> public sealed class ColumnOrderItem
    {
        public int DisplayIndex { get; set; }
        public int Width { get; set; }
        public bool Visible  { get; set; }
        public int ColumnIndex { get; set; }
    }
</code>```

答: It's telling you what's wrong. Visible is a bool and you're trying to assign it to DisplayIndex which is an int.

Title: Help with converting bool to integer

Body:
I keep getting an error saying "Cannot implicitly covert type bool to int" I cannot figure out what to do with this. I get the error on: DisplayIndex = columns[i].Visible,

Code:

    private void SaveColumnOrder()
    {
        if (dgPortStatus.CanUserReorderColumns == true)
        {
            List<ColumnOrderItem> columnOrder = new List<ColumnOrderItem>();
            DataGridViewColumnCollection columns = this.Columns;
            for (int i = 0; i < columns.Count; i++)
            {
                columnOrder.Add(new ColumnOrderItem
                {
                    ColumnIndex = i,
                    DisplayIndex = columns[i].Visible,
                    Width = columns[i].Width
                });

            }

            portalDataGridViewSetting.Default.ColumnOrder[this.Name] = columnOrder;
            portalDataGridViewSetting.Default.Save();
        }
    }

Code:

 public sealed class ColumnOrderItem
    {
        public int DisplayIndex { get; set; }
        public int Width { get; set; }
        public bool Visible  { get; set; }
        public int ColumnIndex { get; set; }
    }


问:
Unable to post the form data to controller
Model: I have a view with collection of addresses and names. I know i am missing something but not able to figure out. I am new to knockout trying to create some sample from using mvc. I see null values coming in the controller. Here is the fiddle:
https://jsfiddle.net/iamsrk/9kf41vd7/32/

```<code>     public class PersonModel
        {
            public virtual ICollection<NameModel> NameModel { get; set; } = new HashSet<NameModel>();
            public virtual ICollection<AddressModel> AddressModel { get; set; } = new HashSet<AddressModel>();
        }

        public class NameModel
        {
            public string FirstName { get; set; }
            public string MiddleName { get; set; }
            public string LastName { get; set; }
            public string Gender { get; set; }
            public string Suffix { get; set; }
        }
        public class AddressModel
        {
            public string FirstName { get; set; }
            public string MiddleName { get; set; }
            public string LastName { get; set; }
            public string ReportingDate { get; set; }
            public string Gender { get; set; }
            public string Suffix { get; set; }
        }
</code>```

Controller Action:

```<code>public ActionResult GetPerson(PersonModel personModel)
        {
            return null;
        }
</code>```

View:

```<code>  <div class="row">
        <div class="col-md-12">
            <div class="panel panel-info">
                <div class="panel-heading">
                    <h1 class="panel-title">
                        Names
                    </h1>
                </div>
                <div data-bind="with: nameModel" class="panel-body">
                    <table class="table table-hover table-responsive">
                        <thead>
                            <tr>
                                <th>First</th>
                                <th>Middle</th>
                                <th>Last</th>
                                <th>Suffix</th>
                                <th>Gender</th>
                            </tr>
                        </thead>
                        <tbody data-bind="foreach: names">
                            <tr>
                                <td>
                                    <input class="form-control" data-bind="value: firstName" />
                                </td>
                                <td>
                                    <input class="form-control" data-bind="value: middleName" />
                                </td>
                                <td>
                                    <input class="form-control" data-bind="value: lastName" />
                                </td>
                                <td>
                                    <input class="form-control" data-bind="value: suffix" />
                                </td>
                                <td>
                                    <input class="form-control" data-bind="value: gender" />
                                </td>
                                <td style="vertical-align: inherit;"><a href="#" data-bind="click:$parent.removeName.bind($data)">Delete</a></td>
                            </tr>
                        </tbody>
                    </table>
                    <button class="btn btn-success btn-sm" data-bind="click: addName.bind($data)">Add Name</button>
                </div>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
            <div class="panel panel-info">
                <div class="panel-heading">
                    <h1 class="panel-title">
                        Addresses
                    </h1>
                </div>
                <div data-bind="with: addressModel" class="panel-body">
                    <table class="table table-hover table-responsive">
                        <thead>
                            <tr>
                                <th>street</th>
                                <th>city</th>
                                <th>state</th>
                                <th>country</th>
                            </tr>
                        </thead>
                        <tbody data-bind="foreach:names">
                            <tr>
                                <td>
                                    <input class="form-control" data-bind="value: street" />
                                </td>
                                <td>
                                    <input class="form-control" data-bind="value: city" />
                                </td>
                                <td>
                                    <input class="form-control" data-bind="value: state" />
                                </td>
                                <td>
                                    <input class="form-control" data-bind="value: country" />
                                </td>
                                <td style="vertical-align: inherit;"><a href="#" data-bind="click:$parent.removeAddress.bind($data)">Delete</a></td>
                            </tr>
                        </tbody>
                    </table>
                    <button class="btn btn-success btn-sm" data-bind="click: addAddress.bind($data)">Add Address</button>
                </div>
            </div>
        </div>
    </div>
    <button id="saveButton" type="button" class="btn btn-primary btn-company pull-right" data-bind="click: save">
        Save
        <span class="glyphicon glyphicon-download-alt"> </span>
    </button>
</code>```

KnockOut Script:

```<code><script>
    var NameModel = function(names) {
        var self = this;
        self.addName = function() {
            self.names.push({
                firstName: "",
                middleName: "",
                lastName: "",
                suffix: "",
                gender: ""
            });
        };
        self.removeName = function(name) {
            self.names.remove(name);
        };
        if (names != null)
            self.names(names);
    };
    var AddressModel = function(addresses) {
        var self = this;
        self.names = ko.observableArray(addresses);

        self.addAddress = function() {
            self.names.push({
                street: "",
                city: "",
                state: "",
                country: ""
            });
        };
        self.removeAddress = function(address) {
            self.names.remove(address);
        };
        if (addresses != null)
            self.names(addresses);
    };
    var viewModel = {
        nameModel: new NameModel([
            {
                firstName: "",
                middleName: "",
                lastName: "",
                suffix: "",
                gender: ""
            }
        ]),
        addressModel: new AddressModel([
            {
                street: "",
                city: "",
                state: "",
                country: ""
            }
        ]),
        save: function () {
            var self = this;
            $.ajax({
                url: '@Url.Action("GetPerson", "Person")',
                type: 'POST',
                contentType: 'application/json',
                data: ko.toJSON({ PersonModel: self
        })
            });
        }
    };
    ko.applyBindings(viewModel);

</script>
</code>```

答:
This

```<code>data: ko.toJSON({ PersonModel: self })
</code>```

will send this

```<code>{ PersonModel: { nameModel: { names: [...] }, addressModel: { addresses: [...] } }
</code>```

which does not match your C# classes.  You want to send this

```<code>{ nameModel: [...], addressModel: [...] }
</code>```

because in JSON the root object is not named and your C# class does not have a names or addresses property.  Try

```<code>data: ko.toJSON({ nameModel: self.nameModel.names,
                  addressModel: self.addressModel.addresses })
</code>```

Also, POSTing to a controller action called "GetPerson" is a really bad idea.  And your address model has an observable array called names, which I assume is a copy-paste error.

Body:
Model: I have a view with collection of addresses and names. I know i am missing something but not able to figure out. I am new to knockout trying to create some sample from using mvc. I see null values coming in the controller. Here is the fiddle:
https://jsfiddle.net/iamsrk/9kf41vd7/32/

     public class PersonModel
        {
            public virtual ICollection<NameModel> NameModel { get; set; } = new HashSet<NameModel>();
            public virtual ICollection<AddressModel> AddressModel { get; set; } = new HashSet<AddressModel>();
        }

        public class NameModel
        {
            public string FirstName { get; set; }
            public string MiddleName { get; set; }
            public string LastName { get; set; }
            public string Gender { get; set; }
            public string Suffix { get; set; }
        }
        public class AddressModel
        {
            public string FirstName { get; set; }
            public string MiddleName { get; set; }
            public string LastName { get; set; }
            public string ReportingDate { get; set; }
            public string Gender { get; set; }
            public string Suffix { get; set; }
        }

Controller Action:

public ActionResult GetPerson(PersonModel personModel)
        {
            return null;
        }

View:

                        Names

                                First
                                Middle
                                Last
                                Suffix
                                Gender

                                    <input class="form-control" data-bind="value: firstName" />

                                    <input class="form-control" data-bind="value: middleName" />

                                    <input class="form-control" data-bind="value: lastName" />

                                    <input class="form-control" data-bind="value: suffix" />

                                    <input class="form-control" data-bind="value: gender" />

                                Delete

                    <button class="btn btn-success btn-sm" data-bind="click: addName.bind($data)">Add Name</button>

                        Addresses

                                street
                                city
                                state
                                country

                                    <input class="form-control" data-bind="value: street" />

                                    <input class="form-control" data-bind="value: city" />

                                    <input class="form-control" data-bind="value: state" />

                                    <input class="form-control" data-bind="value: country" />

                                Delete

                    <button class="btn btn-success btn-sm" data-bind="click: addAddress.bind($data)">Add Address</button>

    <button id="saveButton" type="button" class="btn btn-primary btn-company pull-right" data-bind="click: save">
        Save

    </button>

KnockOut Script:

Body:
This

data: ko.toJSON({ PersonModel: self })

will send this

{ PersonModel: { nameModel: { names: [...] }, addressModel: { addresses: [...] } }

which does not match your C# classes.  You want to send this

{ nameModel: [...], addressModel: [...] }

because in JSON the root object is not named and your C# class does not have a names or addresses property.  Try

data: ko.toJSON({ nameModel: self.nameModel.names,
                  addressModel: self.addressModel.addresses })

Also, POSTing to a controller action called "GetPerson" is a really bad idea.  And your address model has an observable array called names, which I assume is a copy-paste error.


问:
Sorting array based on player position
I have a singular situation where I am trying to sort football players based on their positions.

Let's say I have 10 players and I need to sort them based on their positions:

```<code>John | Position 1
Bill | Position 1
Gael | Position 2
Phil | Position 2
Joao | Position 2
Cale | Position 3
Bruu | Position 4
Aron | Position 5
Jimm | Position 5
Carl | Position 5
</code>```

I need to try to sort them as equal as possible, in this case:

Team 1 - John, Gael, Cale, Jimm, Carl

Team 2 - Bill, Phil, Joao, Bruu, Aron

I started trying dividing the positions and then sort them in one or another team, but it didn't work as expected because sometimes I have only one player on a position and 3 on the other position.

答:
Seems like the only reasonable way to do it if you don't have enough players in each position is to sort the players by position, and then go through the list, assigning the next player to the next team. That is, given your list and two teams, you'd write code that does this:

```<code>John | Position 1 | Team 1
Bill | Position 1 | Team 2
Gael | Position 2 | Team 1
Phil | Position 2 | Team 2
Joao | Position 2 | Team 1
Cale | Position 3 | Team 2
Bruu | Position 4 | Team 1
Aron | Position 5 | Team 2
Jimm | Position 5 | Team 1
Carl | Position 5 | Team 2
</code>```

The code is pretty simple:

```<code>int numTeams = 2
int team = 0
for each player
{
    Assign player to teams[team]
    team = team + 1
    if (team == numTeams) then
    {
        team = 0
    }
}
</code>```

If you have other restrictions, like a team ideally has x number of position y, then the algorithm would change somewhat to accommodate those restrictions. But you'd have to give me more information before I could supply a suggestion.

Title: Sorting array based on player position

Body:
I have a singular situation where I am trying to sort football players based on their positions.

Let's say I have 10 players and I need to sort them based on their positions:

John | Position 1
Bill | Position 1
Gael | Position 2
Phil | Position 2
Joao | Position 2
Cale | Position 3
Bruu | Position 4
Aron | Position 5
Jimm | Position 5
Carl | Position 5

I need to try to sort them as equal as possible, in this case:

Team 1 - John, Gael, Cale, Jimm, Carl

Team 2 - Bill, Phil, Joao, Bruu, Aron

I started trying dividing the positions and then sort them in one or another team, but it didn't work as expected because sometimes I have only one player on a position and 3 on the other position.

Body:
Seems like the only reasonable way to do it if you don't have enough players in each position is to sort the players by position, and then go through the list, assigning the next player to the next team. That is, given your list and two teams, you'd write code that does this:

John | Position 1 | Team 1
Bill | Position 1 | Team 2
Gael | Position 2 | Team 1
Phil | Position 2 | Team 2
Joao | Position 2 | Team 1
Cale | Position 3 | Team 2
Bruu | Position 4 | Team 1
Aron | Position 5 | Team 2
Jimm | Position 5 | Team 1
Carl | Position 5 | Team 2

The code is pretty simple:

int numTeams = 2
int team = 0
for each player
{
    Assign player to teams[team]
    team = team + 1
    if (team == numTeams) then
    {
        team = 0
    }
}

If you have other restrictions, like a team ideally has x number of position y, then the algorithm would change somewhat to accommodate those restrictions. But you'd have to give me more information before I could supply a suggestion.


问:
get data from XML file using jQuery
I am trying to get an attribute value from an XML file using jQuery, but it returns undefined and the image doesn't load.

In my HTML file I have a
 with id answer and one <button> with id showInfo.

```<code>xml code:
<?xml version="1.0"?>
    <student studentNum="5678">
        <image>images/mypic.jpg</image>
    </student>
</code>```

my jQuery code:

```<code>$(document).ready(function(){
  $.ajax( {
   url:'stu.xml',
   data:{},
   type:'GET',
   dataType:'xml',
   success: function(resp){

$('#showInfo').click(function () {

   var myInfo = $(resp).find('student');
   myInfo.each(function(index, obj) {

    var myNum = ($(obj).find('student').attr('studentNum'));
    var myImg = $(obj).find('image').text();

    $('#answer').append("<p> " + "Student Number:  " +myNum+
    "<img src='" + myImg + "'/><br/>" );
});
});
});
</code>```

答:
obj is instance of <student> so find() isn't applicable for the attribute.

Not sure what proper path to images is ... try adding a leading / if images directory is in root of site

Try

```<code>var $student = $(obj);
var myNum = $student.attr('studentNum');
var myImg = $student.find('image').text();

$('#answer').append("<p> " + "Student Number:  " +myNum+
    "<img src='/" + myImg + "'/><br/>" );
</code>```

Title: get data from XML file using jQuery

Body:
I am trying to get an attribute value from an XML file using jQuery, but it returns undefined and the image doesn't load.

In my HTML file I have a
 with id answer and one <button> with id showInfo.

xml code:
<?xml version="1.0"?>
    <student studentNum="5678">
        <image>images/mypic.jpg</image>
    </student>

my jQuery code:

$(document).ready(function(){
  $.ajax( {
   url:'stu.xml',
   data:{},
   type:'GET',
   dataType:'xml',
   success: function(resp){

$('#showInfo').click(function () {

   var myInfo = $(resp).find('student');
   myInfo.each(function(index, obj) {

    var myNum = ($(obj).find('student').attr('studentNum'));
    var myImg = $(obj).find('image').text();

    $('#answer').append("
 " + "Student Number:  " +myNum+
    "
" );
});
});
});

Body:
obj is instance of <student> so find() isn't applicable for the attribute.

Not sure what proper path to images is ... try adding a leading / if images directory is in root of site

Try

var $student = $(obj);
var myNum = $student.attr('studentNum');
var myImg = $student.find('image').text();

$('#answer').append("<p> " + "Student Number:  " +myNum+
    "<img src='/" + myImg + "'/><br/>" );


问:
With SQL Server how to get the most recent date while summing on amount and the sum of the amount is greater than 0?
I have a transaction table:

```<code>CREATE TABLE [dbo].[Trans](
[ID] [char](6) NOT NULL,
[PersonID] [char](6) NULL,
[TransCode] [char](2) NULL,
[TransDesc] [char](45) NULL,
[TransDate] [datetime] NULL,
[TransAmount] [numeric](18, 2) NULL)
</code>```

What I want is the date and amount of the most recent payment made by each person.  Payments are defined by the TransCode (see the WHERE clause below).

There can be multiple transactions on any given day, so I want the sum of transactions on the most recent day.  Also there can be "reversal" transactions that could make the sum of the transactions on the most recent day be 0 (zero) -- I don't want these to be in the results (hence the "HAVING   (SUM(TransAmount) > 0)" below).

Here is my most recent attempt, that is not working, but I don't know why!

```<code>SELECT  PersonID, MAX(TransDate) AS LastPaymentDate, TotalAmount
FROM    (SELECT   PersonID, TransDate, SUM(TransAmount) AS TotalAmount
         FROM     Trans
         WHERE    (TransCode IN ('11', '12', '13', '14', '18', '19', '61', '63', '68', '70', '71', '72', '73', '74', '75', '76', '78', '79', '80', '81', '94', 'P2'))
         GROUP BY PersonID, TransDate
         HAVING   (SUM(TransAmount) > 0)
         ORDER BY PersonID, TransDate) AS TotalAmount
GROUP BY PersonID, TotalAmount
ORDER BY PersonID
</code>```

When I run the inner query I get what expect, a list of amounts summed by date, for each person.  The outer query though, for some reason, is returning multiple rows for each person.  It should only return one row for each person :-(

Can someone one tell me what I am doing wrong?

Please let me know if there is any additional information you may need to understand the problem better.

Thank you in advance for any help you can provide,

Ben

答:
You're getting multiple rows since you're grouping by PersonId and TotalAmount, and there are multiple dates with the same TotalAmount.

Just wrap the entire SQL you have in another select to grab the MAX(LastPaymentDate):

```<code>SELECT PersonID, LastPaymentDate, TotalAmount  FROM (
SELECT  PersonID, MAX(TransDate) AS LastPaymentDate, TotalAmount
FROM    (SELECT   PersonID, TransDate, SUM(TransAmount) AS TotalAmount
         FROM     Trans
         WHERE    (TransCode IN ('11', '12', '13', '14', '18', '19', '61', '63',
'68', '70', '71', '72', '73', '74', '75', '76', '78', '79', '80', '81', '94', 'P2'))
         GROUP BY PersonID, TransDate
         HAVING   (SUM(TransAmount) > 0)
         ORDER BY PersonID, TransDate) AS InnerSelect
GROUP BY PersonID, TotalAmount
ORDER BY PersonID
)
GROUP BY PersonID, LastPaymentDate, TotalAmount
HAVING LastPaymentDate = MAX(LastPaymentDate)
</code>```

Body:
I have a transaction table:

CREATE TABLE [dbo].[Trans](
[ID] [char](6) NOT NULL,
[PersonID] [char](6) NULL,
[TransCode] [char](2) NULL,
[TransDesc] [char](45) NULL,
[TransDate] [datetime] NULL,
[TransAmount] [numeric](18, 2) NULL)

What I want is the date and amount of the most recent payment made by each person.  Payments are defined by the TransCode (see the WHERE clause below).

There can be multiple transactions on any given day, so I want the sum of transactions on the most recent day.  Also there can be "reversal" transactions that could make the sum of the transactions on the most recent day be 0 (zero) -- I don't want these to be in the results (hence the "HAVING   (SUM(TransAmount) > 0)" below).

Here is my most recent attempt, that is not working, but I don't know why!

SELECT  PersonID, MAX(TransDate) AS LastPaymentDate, TotalAmount
FROM    (SELECT   PersonID, TransDate, SUM(TransAmount) AS TotalAmount
         FROM     Trans
         WHERE    (TransCode IN ('11', '12', '13', '14', '18', '19', '61', '63', '68', '70', '71', '72', '73', '74', '75', '76', '78', '79', '80', '81', '94', 'P2'))
         GROUP BY PersonID, TransDate
         HAVING   (SUM(TransAmount) > 0)
         ORDER BY PersonID, TransDate) AS TotalAmount
GROUP BY PersonID, TotalAmount
ORDER BY PersonID

When I run the inner query I get what expect, a list of amounts summed by date, for each person.  The outer query though, for some reason, is returning multiple rows for each person.  It should only return one row for each person :-(

Can someone one tell me what I am doing wrong?

Please let me know if there is any additional information you may need to understand the problem better.

Thank you in advance for any help you can provide,

Ben

Body:
You're getting multiple rows since you're grouping by PersonId and TotalAmount, and there are multiple dates with the same TotalAmount.

Just wrap the entire SQL you have in another select to grab the MAX(LastPaymentDate):

SELECT PersonID, LastPaymentDate, TotalAmount  FROM (
SELECT  PersonID, MAX(TransDate) AS LastPaymentDate, TotalAmount
FROM    (SELECT   PersonID, TransDate, SUM(TransAmount) AS TotalAmount
         FROM     Trans
         WHERE    (TransCode IN ('11', '12', '13', '14', '18', '19', '61', '63',
'68', '70', '71', '72', '73', '74', '75', '76', '78', '79', '80', '81', '94', 'P2'))
         GROUP BY PersonID, TransDate
         HAVING   (SUM(TransAmount) > 0)
         ORDER BY PersonID, TransDate) AS InnerSelect
GROUP BY PersonID, TotalAmount
ORDER BY PersonID
)
GROUP BY PersonID, LastPaymentDate, TotalAmount
HAVING LastPaymentDate = MAX(LastPaymentDate)


问:
Having an issue getting ANYTHING to apply styles within nested DIVs
I've already asked Google about this, and I've spent quite a long time experimenting. I can't possibly recreate the entire HTML and CSS environment this is occurring in, but this is part of it:

#footer-copyright{
    clear:both;
    color:black !important;
    font-size: 12px !important;
    text-align:center !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer id="footer" class="fullwidth">
    <div class="container">
        <div id="footer-section-one" class="col-sm-7 col-xs-12">
            <?php if (!function_exists('dynamic_sidebar') || !dynamic_sidebar('Footer Section One')) : endif; ?>
        </div>
        <div id="footer-section-two" class="col-sm-5 col-xs-12">
            <?php if (!function_exists('dynamic_sidebar') || !dynamic_sidebar('Footer Section Two')) : endif; ?>
        </div>
    </div>
    <div class="container">
        <p id="footer-copyright">This text is immune to formatting</p>
    </div>
    </footer></code>```

No matter what I've tried, the text "This text is immune to formatting" is displayed in the p style for the footer object. I've tried making the CSS ID more specific (footer.footer-copyright). I've tried putting the ID on the DIV, and then specifying the style is for "#footer-copyright p{". I've tried footer-copyright as a class style and as a style for that particular ID (as it is now). I don't want to bore you listing all the things I've tried, but think permutations and combinations.

I've spent quite a bit of time in Chrome inspecting the paragraph, and it mostly seems to have no style at all, or to take the style defined by #footer p.

The only thing that I've found works is to completely override the CSS and put the style info into the paragraph itself ("

If you can, please explain why I can't seem to override the parent object's CSS style, and how to use Chrome's reporting of the HTML hierarchy to understand how to specify the CSS style.

THANKS!

答:
In your sample above you have this....

```<code><div class="container">
  <p id="footer-copyright">This text is actually NOT immune to formatting</p>
</div>
</code>```

In your ACTUAL page you have this...

```<code><div class="container">
  <p>Copyright © 2017 - Do The Most Good, Montgomery County, MD</p>
</div>
</code>```

The element (the P tag) in the ACTUAL page is being rendered/styled using these statements...

```<code>#footer p
{
  color:#fff;
}
</code>```

When, what you want is for it to be styled with this style...

```<code>#footer-copyright p
{
  clear:both;
  color:black !important;
  font-size: 12px !important;
 text-align:center !important;
}
</code>```

So all you need is for your code to be thus....

```<code><div class="container">
  <p id="footer-copyright">Copyright © 2017 - Do The Most Good, Montgomery County, MD</p>
</div>
</code>```

It is simply a case of, that the footer-copyright element (the P tag) was not assigned the style because the ID tag was not set.

Body:
I've already asked Google about this, and I've spent quite a long time experimenting. I can't possibly recreate the entire HTML and CSS environment this is occurring in, but this is part of it:

#footer-copyright{
    clear:both;
    color:black !important;
    font-size: 12px !important;
    text-align:center !important;
}

            <?php if (!function_exists('dynamic_sidebar') || !dynamic_sidebar('Footer Section One')) : endif; ?>

            <?php if (!function_exists('dynamic_sidebar') || !dynamic_sidebar('Footer Section Two')) : endif; ?>

This text is immune to formatting

No matter what I've tried, the text "This text is immune to formatting" is displayed in the p style for the footer object. I've tried making the CSS ID more specific (footer.footer-copyright). I've tried putting the ID on the DIV, and then specifying the style is for "#footer-copyright p{". I've tried footer-copyright as a class style and as a style for that particular ID (as it is now). I don't want to bore you listing all the things I've tried, but think permutations and combinations.

I've spent quite a bit of time in Chrome inspecting the paragraph, and it mostly seems to have no style at all, or to take the style defined by #footer p.

The only thing that I've found works is to completely override the CSS and put the style info into the paragraph itself ("

If you can, please explain why I can't seem to override the parent object's CSS style, and how to use Chrome's reporting of the HTML hierarchy to understand how to specify the CSS style.

THANKS!

Body:
In your sample above you have this....

<div class="container">
  <p id="footer-copyright">This text is actually NOT immune to formatting</p>
</div>

In your ACTUAL page you have this...

<div class="container">
  <p>Copyright © 2017 - Do The Most Good, Montgomery County, MD</p>
</div>

The element (the P tag) in the ACTUAL page is being rendered/styled using these statements...

#footer p
{
  color:#fff;
}

When, what you want is for it to be styled with this style...

#footer-copyright p
{
  clear:both;
  color:black !important;
  font-size: 12px !important;
 text-align:center !important;
}

So all you need is for your code to be thus....

<div class="container">
  <p id="footer-copyright">Copyright © 2017 - Do The Most Good, Montgomery County, MD</p>
</div>

It is simply a case of, that the footer-copyright element (the P tag) was not assigned the style because the ID tag was not set.


问:
Javascript es6 array mapping
I need help creating a function that gonna return me 3 elements from an array each time with time interval of 3 seconds.
Let say I have an array

```<code>const Array = [{name:'A'},{name:'B'},{name:'C'},{name:'D'},{name:'E'},{name:'F'},{name:'G'},{name:'H'},{name:'I'}];
</code>```

It should return array like

```<code> [{name:'A'},{name:'B'},{name:'C'}]
</code>```

then after 3 seconds it should return array

```<code> [{name:'D'},{name:'E'},{name:'F'}]
</code>```

And so on also when the arrays gets end repeat the loop again.

I tried using chunk where i used slice and filter but that just return me an array of chunks together.

Thanks so much

答:
You can do this with a generator:

```<code>// Takes an array and the of the slice/subarray
function* subArray(array, size) {
  let i = 0;
  let remaining = true;
  while (remaining) {
    yield array.slice(i, i + size);
    i += size;
    if (i >= array.length) {
      remaining = false;
    }
  }
}

// Takes an array, a subarray size, and an interval in seconds
const getSubArraysAtInterval = (array, size, seconds) => {
  const iter = subArray(array, size);
  const interval = setInterval(() => {
    const next = iter.next();
    if (next.done) {
      clearInterval(interval);
      console.log('No values remaining');
    } else {
      console.log(next.value);
    }
  }, seconds * 1000)
}

getSubArraysAtInterval([1, 2, 3, 4, 5, 6], 3, 3);
</code>```

Working fiddle: https://jsfiddle.net/adrice727/msx3sf03/1/

Title: Javascript es6 array mapping

Body:
I need help creating a function that gonna return me 3 elements from an array each time with time interval of 3 seconds.
Let say I have an array

const Array = [{name:'A'},{name:'B'},{name:'C'},{name:'D'},{name:'E'},{name:'F'},{name:'G'},{name:'H'},{name:'I'}];

It should return array like

 [{name:'A'},{name:'B'},{name:'C'}]

then after 3 seconds it should return array

 [{name:'D'},{name:'E'},{name:'F'}]

And so on also when the arrays gets end repeat the loop again.

I tried using chunk where i used slice and filter but that just return me an array of chunks together.

Thanks so much

Body:
You can do this with a generator:

// Takes an array and the of the slice/subarray
function* subArray(array, size) {
  let i = 0;
  let remaining = true;
  while (remaining) {
    yield array.slice(i, i + size);
    i += size;
    if (i >= array.length) {
      remaining = false;
    }
  }
}

// Takes an array, a subarray size, and an interval in seconds
const getSubArraysAtInterval = (array, size, seconds) => {
  const iter = subArray(array, size);
  const interval = setInterval(() => {
    const next = iter.next();
    if (next.done) {
      clearInterval(interval);
      console.log('No values remaining');
    } else {
      console.log(next.value);
    }
  }, seconds * 1000)
}

getSubArraysAtInterval([1, 2, 3, 4, 5, 6], 3, 3);

Working fiddle: https://jsfiddle.net/adrice727/msx3sf03/1/


问:
What does self.new_with_session(params, session) do in this case
I am trying to implement facebook login in a rails app and I used the code from the following example: https://github.com/rails-camp/facebook-omniauth-demo

```<code># app/models/user.rb

def self.new_with_session(params, session)
  super.tap do |user|
    if data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["raw_info"]
      user.email = data["email"] if user.email.blank?
    end
  end
end

def self.from_omniauth(auth)
  where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
    user.email = auth.info.email
    user.password = Devise.friendly_token[0,20]
    user.name = auth.info.name   # assuming the user model has a name
    user.image = auth.info.image # assuming the user model has an image
  end
end
</code>```

What does the method self.new_with_session(params, session) do specifically in this case?

答:
you're overwriting new_with_session function.

```<code>def self.new_with_session(params, session)
  # call super(the overwritten function), it will return a resource and in this case you are
  # naming it 'user' in the block
  super.tap do |user|
    # if extra information was provided by facebook when user logged in, assign whatever comes in
    # session["devise.facebook_data"]["extra"]["raw_info"] to 'data' variable
    if data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["raw_info"]
      # assign 'email' given by facebook in case the 'user' object doesn't have one yet
      user.email = data["email"] if user.email.blank?
    end
  end
end
</code>```

Body:
I am trying to implement facebook login in a rails app and I used the code from the following example: https://github.com/rails-camp/facebook-omniauth-demo

# app/models/user.rb

def self.new_with_session(params, session)
  super.tap do |user|
    if data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["raw_info"]
      user.email = data["email"] if user.email.blank?
    end
  end
end

def self.from_omniauth(auth)
  where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
    user.email = auth.info.email
    user.password = Devise.friendly_token[0,20]
    user.name = auth.info.name   # assuming the user model has a name
    user.image = auth.info.image # assuming the user model has an image
  end
end

What does the method self.new_with_session(params, session) do specifically in this case?

Body:
you're overwriting new_with_session function.

def self.new_with_session(params, session)
  # call super(the overwritten function), it will return a resource and in this case you are
  # naming it 'user' in the block
  super.tap do |user|
    # if extra information was provided by facebook when user logged in, assign whatever comes in
    # session["devise.facebook_data"]["extra"]["raw_info"] to 'data' variable
    if data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["raw_info"]
      # assign 'email' given by facebook in case the 'user' object doesn't have one yet
      user.email = data["email"] if user.email.blank?
    end
  end
end


问:
Animate certain elements out on page change
So I have been reading into page transitions and they get very complex very quickly. I am still new to jQuery so I was hoping to get a simplified answer as to how to execute animations (namely on individual elements) on page transitions.

I apologise for how basic these questions are but as I am sure you all know, once you grasp the basic fundamentals and their simplistic concepts it makes the rest a whole lot easier.

So from what I have read, you would use jQuery to detect the page change, execute the animation then allow for the change of page.

Then jQuery would execute on page load and animate the elements in.

Question 1:
So for the first part, I have figured out that I would need to use:

```<code>$( window ).unload(function() {
  return "Handler for .unload() called.";
});
</code>```

How would I use this to delay the change of page long enough to complete my animations, and would this account for page changes using the back and forward browser buttons?

Question 2:
How would I make sure my elements start off screen when the new page is loading and only animate in once the content has been loaded?

The $(document).ready function will only execute once the page is ready and thus will show the logo on screen and the jump it off screen and animate it back on.

P.s I will update this thread with detailed steps on how I get to my desired result once I figure it all out. Massive thanks.

答:
If you need to provide animations for page changes within one site - you probably planning to make something what is called "one page application".

If that is your goal I think you really should start from here:
https://github.com/browserstate/history.js/wiki/The-State-of-the-HTML5-History-API

Then answer to your Question1 would be:
- Use ajax and History API instead

Answer for Question2:
- You never leave the page actually. Using ajaxy loader you changing the content (with animations when you hide previous page content and when you show the new page content), and then you pushing a new history state to make it possible for user to navigate with the browser buttons.
PS. You can achieve some nice looking effects leaving the repeated part of the content in place (eg. logo image) and animate only the rest of the content.

Alternatively - have a look here For some other solution (might be easier to start with):
https://github.com/miguel-perez/smoothState.js?files=1
to achieve something like this or like this

Body:
So I have been reading into page transitions and they get very complex very quickly. I am still new to jQuery so I was hoping to get a simplified answer as to how to execute animations (namely on individual elements) on page transitions.

I apologise for how basic these questions are but as I am sure you all know, once you grasp the basic fundamentals and their simplistic concepts it makes the rest a whole lot easier.

So from what I have read, you would use jQuery to detect the page change, execute the animation then allow for the change of page.

Then jQuery would execute on page load and animate the elements in.

Question 1:
So for the first part, I have figured out that I would need to use:

$( window ).unload(function() {
  return "Handler for .unload() called.";
});

How would I use this to delay the change of page long enough to complete my animations, and would this account for page changes using the back and forward browser buttons?

Question 2:
How would I make sure my elements start off screen when the new page is loading and only animate in once the content has been loaded?

The $(document).ready function will only execute once the page is ready and thus will show the logo on screen and the jump it off screen and animate it back on.

P.s I will update this thread with detailed steps on how I get to my desired result once I figure it all out. Massive thanks.


问:
How to convert "commands module" into "subprocess module"?
I would like to know how to use "subprocess module" to rewrite the following code:

```<code>import commands
print commands.getoutput('convert -quality 100 ___t*.png images/transient_heat.gif')
print commands.getoutput('rm ___t*.png')
</code>```

Because "commands module" does not support Python 3, I would like to use "subprocess module". I tried the following code but it does not work.

```<code>import subprocess
print ( subprocess.Popen('convert -quality 100 ___t*.png images/transient_heat.gif') )
print ( subprocess.Popen('rm ___t*.png') )
</code>```

Thank you very much! The code was originally taken from Kitchin's blog: http://kitchingroup.cheme.cmu.edu/blog/2013/03/07/Transient-heat-conduction-partial-differential-equations/

答:
You can just use subprocess.check_output

```<code>print subprocess.check_output('rm ___t*.png', shell=True)
</code>```

Body:
I would like to know how to use "subprocess module" to rewrite the following code:

import commands
print commands.getoutput('convert -quality 100 ___t*.png images/transient_heat.gif')
print commands.getoutput('rm ___t*.png')

Because "commands module" does not support Python 3, I would like to use "subprocess module". I tried the following code but it does not work.

import subprocess
print ( subprocess.Popen('convert -quality 100 ___t*.png images/transient_heat.gif') )
print ( subprocess.Popen('rm ___t*.png') )

Thank you very much! The code was originally taken from Kitchin's blog: http://kitchingroup.cheme.cmu.edu/blog/2013/03/07/Transient-heat-conduction-partial-differential-equations/

Body:
You can just use subprocess.check_output

print subprocess.check_output('rm ___t*.png', shell=True)


问:
Run only ONE test with Jest
I want to run just one test with Jest.

I use it.only or describe.only, but it still runs a whole lot of tests. I think it runs all the tests since my last commit, but it shouldn't have this behavior with the only flag explicitly set, right?

What causes this behavior and how can I run a single test?

答:
Jest parallelizes test runs and it doesn't know upfront which tests it
should run and which it shouldn't run.
This means when you use "fit", it will only run one test in that file.
But it still runs all other test files in your project.

fit, fdescribe and it.only, describe.only have the same purpose: skip other tests and run only me.

Source: https://github.com/facebook/jest/issues/698#issuecomment-177673281

Use the Jest filtering mechanism. When you run your tests like,

```<code>jest --config=jest.config.json --watch
</code>```

you can filter tests by a testname or filename. Just follow the instructions in the terminal.

Press p, and then type a filename.

Then you can use describe.only and it.only which will skip all other tests from the filtered, tested file.

ContentLicense: CC BY-SA 4.0

Title: Run only ONE test with Jest

Body:
Jest parallelizes test runs and it doesn't know upfront which tests it
should run and which it shouldn't run.
This means when you use "fit", it will only run one test in that file.
But it still runs all other test files in your project.

fit, fdescribe and it.only, describe.only have the same purpose: skip other tests and run only me.

Source: https://github.com/facebook/jest/issues/698#issuecomment-177673281

Use the Jest filtering mechanism. When you run your tests like,

jest --config=jest.config.json --watch

you can filter tests by a testname or filename. Just follow the instructions in the terminal.

Press p, and then type a filename.

Then you can use describe.only and it.only which will skip all other tests from the filtered, tested file.


问:
R Building a function with a condition as variable
I have a data.frame consisting of two columns, time and value. Let's say:

```<code>> s
>          time      value
>1  -1.40325749 -0.5282231
>2  -0.32640410 -1.8719568
>3  -0.26288196 -0.9861694
>4  -0.19906006 -0.8487832
>5  -0.18720951 -0.2248195
>6  -0.14219086  0.3387807
>7  -0.05981503  1.3872106
>8   0.37187516  2.0057095
>9   0.42432858  2.6805815
>10  1.19915563  1.9988563
</code>```

I want to build a function which will filter this data, according to the specific condition. Here is my code:

```<code>> select<-function(object,cond)
 {
     subset(object,eval(deparse(substitute(cond))))
 }
</code>```

If I use now my new function as follows:

```<code>>select(s,value<0)
</code>```

I would like to see only rows, where value is < 0. E.g.

```<code>> s
>          time      value
>1  -1.40325749 -0.5282231
>2  -0.32640410 -1.8719568
>3  -0.26288196 -0.9861694
>4  -0.19906006 -0.8487832
>5  -0.18720951 -0.2248195
</code>```

However, after running this code, I have an error, that subset must be logical. I tried everything I know about to make the "value<0" visible as expression for R. Does anyone know how to fix it?

```<code>Error in subset.data.frame(object, eval(deparse(substitute(cond)))) :
'subset' must be logical
</code>```

Regards
Michal

答:
I also like dplyr for this:

```<code>library(dplyr)
s <- s %>%
     filter(value < 0)
</code>```

to filter rows by condition

Body:
I have a data.frame consisting of two columns, time and value. Let's say:

> s
>          time      value
>1  -1.40325749 -0.5282231
>2  -0.32640410 -1.8719568
>3  -0.26288196 -0.9861694
>4  -0.19906006 -0.8487832
>5  -0.18720951 -0.2248195
>6  -0.14219086  0.3387807
>7  -0.05981503  1.3872106
>8   0.37187516  2.0057095
>9   0.42432858  2.6805815
>10  1.19915563  1.9988563

I want to build a function which will filter this data, according to the specific condition. Here is my code:

> select<-function(object,cond)
 {
     subset(object,eval(deparse(substitute(cond))))
 }

If I use now my new function as follows:

>select(s,value<0)

I would like to see only rows, where value is < 0. E.g.

> s
>          time      value
>1  -1.40325749 -0.5282231
>2  -0.32640410 -1.8719568
>3  -0.26288196 -0.9861694
>4  -0.19906006 -0.8487832
>5  -0.18720951 -0.2248195

However, after running this code, I have an error, that subset must be logical. I tried everything I know about to make the "value<0" visible as expression for R. Does anyone know how to fix it?

Error in subset.data.frame(object, eval(deparse(substitute(cond)))) :
'subset' must be logical

Regards
Michal

Body:
I also like dplyr for this:

library(dplyr)
s <- s %>%
     filter(value < 0)

to filter rows by condition


问:
My position: sticky element isn't sticky when using flexbox
I was stuck on this for a little bit and thought I'd share this position: sticky + flexbox gotcha:

My sticky div was working fine until I switched my view to a flex box container, and suddenly the div wasn't sticky when it was wrapped in a flexbox parent.

.flexbox-wrapper {
  display: flex;
  height: 600px;
}
.regular {
  background-color: blue;
}
.sticky {
  position: -webkit-sticky;
  position: sticky;
  top: 0;
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flexbox-wrapper">
  <div class="regular">
    This is the regular box
  </div>
  <div class="sticky">
    This is the sticky box
  </div>
</div></code>```

JSFiddle showing the problem

答:
Since flex box elements default to stretch, all the elements are the same height, which can't be scrolled against.

Adding align-self: flex-start to the sticky element set the height to auto, which allowed scrolling, and fixed it.

Currently this is supported in all major browsers, but Safari is still behind a -webkit- prefix, and other browsers except for Firefox have some issues with position: sticky tables.

.flexbox-wrapper {
  display: flex;
  overflow: auto;
  height: 200px;          /* Not necessary -- for example only */
}
.regular {
  background-color: blue; /* Not necessary -- for example only */
  height: 600px;          /* Not necessary -- for example only */
}
.sticky {
  position: -webkit-sticky; /* for Safari */
  position: sticky;
  top: 0;
  align-self: flex-start; /* <-- this is the fix */
  background-color: red;  /* Not necessary -- for example only */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flexbox-wrapper">
  <div class="regular">
    This is the regular box
  </div>
  <div class="sticky">
    This is the sticky box
  </div>
</div></code>```

JSFiddle showing the solution

Body:
I was stuck on this for a little bit and thought I'd share this position: sticky + flexbox gotcha:

My sticky div was working fine until I switched my view to a flex box container, and suddenly the div wasn't sticky when it was wrapped in a flexbox parent.

.flexbox-wrapper {
  display: flex;
  height: 600px;
}
.regular {
  background-color: blue;
}
.sticky {
  position: -webkit-sticky;
  position: sticky;
  top: 0;
  background-color: red;
}

    This is the regular box

    This is the sticky box

JSFiddle showing the problem

Body:
Since flex box elements default to stretch, all the elements are the same height, which can't be scrolled against.

Adding align-self: flex-start to the sticky element set the height to auto, which allowed scrolling, and fixed it.

Currently this is supported in all major browsers, but Safari is still behind a -webkit- prefix, and other browsers except for Firefox have some issues with position: sticky tables.

.flexbox-wrapper {
  display: flex;
  overflow: auto;
  height: 200px;          /* Not necessary -- for example only */
}
.regular {
  background-color: blue; /* Not necessary -- for example only */
  height: 600px;          /* Not necessary -- for example only */
}
.sticky {
  position: -webkit-sticky; /* for Safari */
  position: sticky;
  top: 0;
  align-self: flex-start; /* <-- this is the fix */
  background-color: red;  /* Not necessary -- for example only */
}

<div class="flexbox-wrapper">
  <div class="regular">
    This is the regular box
  </div>
  <div class="sticky">
    This is the sticky box
  </div>
</div>

JSFiddle showing the solution


问:
UNICODE_STRING to ANSI_STRING conversion with RtlUnicodeStringToAnsiString
The documentation on RtlUnicodeStringToAnsiString is rather vague about its possible failures - by vague I mean it doesn't say anything about them.

I'm not exactly sure how/if it deals with different encodings, or if my understanding is so flawed that it doesn't even come into the equation, but let's assume input is UTF-16 for argument's sake.

If all the characters are within the ASCII range then there is no problem, they can just get truncated and lose the high order byte - The first 128 Unicode code points are the ASCII characters and UTF-16 encodes U+0000 to U+D7FF as numerically equal to the code points.[1][2]

Note: UNICODE_STRING has a WCHAR* Buffer, and ANSI_STRING a CHAR* Buffer, as may be expected.

[Skipping over 129-255 and locales/codepages]

What happens with characters above 255? There is an RtlUnicodeToUTF8N function so it's safe to assume it doesn't convert to UTF-8.

How about code points outside BMP (surrogate pairs and whatnot)?

I saw a function that does something like the code below:

```<code>char *pTarget = reinterpret_cast<char*>(char_str);
const WCHAR  *pSource = reinterpret_cast<const WCHAR*>(wchar_str);

for ( long i = 0; i < targetMaxSizeInBytes; i++ )
{
    *pTarget = static_cast<char>(*pSource);

    if (L'\0' == *pSource)
        break;

    pTarget++;
    pSource++;
}
</code>```

This would cause problems with any non-ASCII characters, correct?

Update:

From RbMm's answer:

RtlUnicodeStringToAnsiString is shell over RtlUnicodeToMultiByteN routine

I get a little more information:

Like RtlUnicodeToMultiByteSize, RtlUnicodeToMultiByteN supports only precomposed Unicode characters that are mapped to the current system ANSI code page installed at system boot.

WideCharToMultiByte has an option to be notified if a default character is used in the conversion for a character that cannot be represented in the specified code page:

lpUsedDefaultChar [out, optional]

Pointer to a flag that indicates if the function has used a default character in the conversion. The flag is set to TRUE if one or more characters in the source string cannot be represented in the specified code page. Otherwise, the flag is set to FALSE. This parameter can be set to NULL.

However, it seems RtlUnicodeToMultiByteN, and therefore RtlUnicodeStringToAnsiString, simply don't support characters outside the current code page?

I tried a few characters and got seemingly random conversions (see below) - more importantly, I got STATUS_SUCCESS returned.

```<code>U+03A3 Σ -> 0n83 'S'
U+03A4 Τ -> 0n63 '?'
U+03A5 Υ -> 0n63 '?'
U+03A6 Φ -> 0n70 'F'
</code>```

答:
RtlUnicodeStringToAnsiString is shell over RtlUnicodeToMultiByteN routine

The RtlUnicodeToMultiByteN routine translates the specified Unicode
  string into a new character string, using the current system ANSI
  code page (ACP). The translated string is not necessarily from a
  multibyte character set.

so any of this routine have the same conversion as WideCharToMultiByte with CP_ACP

also exist next routines:

RtlUnicodeStringToOemString - shell over RtlUnicodeToOemN routine

The RtlUnicodeToOemN routine translates a given Unicode string to
  an OEM string, using the current system OEM code page.

so this routines have the same conversion as WideCharToMultiByte with CP_OEMCP

for UTF-8 convertions exist RtlUnicodeToUTF8N (converts a Unicode string to a UTF-8 string) and RtlUTF8ToUnicodeN (converts a UTF-8 string to a Unicode string. )

for custom code page you can use undocumented api

```<code>NTSYSAPI
NTSTATUS
NTAPI
RtlCustomCPToUnicodeN(
    _In_ PCPTABLEINFO CustomCP,
    _Out_writes_bytes_to_(MaxBytesInUnicodeString, *BytesInUnicodeString) PWCH UnicodeString,
    _In_ ULONG MaxBytesInUnicodeString,
    _Out_opt_ PULONG BytesInUnicodeString,
    _In_reads_bytes_(BytesInCustomCPString) PCH CustomCPString,
    _In_ ULONG BytesInCustomCPString
    );
</code>```

here key point in initialize CPTABLEINFO, so you can use any USHORT  CodePage; here

Body:
The documentation on RtlUnicodeStringToAnsiString is rather vague about its possible failures - by vague I mean it doesn't say anything about them.

I'm not exactly sure how/if it deals with different encodings, or if my understanding is so flawed that it doesn't even come into the equation, but let's assume input is UTF-16 for argument's sake.

If all the characters are within the ASCII range then there is no problem, they can just get truncated and lose the high order byte - The first 128 Unicode code points are the ASCII characters and UTF-16 encodes U+0000 to U+D7FF as numerically equal to the code points.[1][2]

Note: UNICODE_STRING has a WCHAR* Buffer, and ANSI_STRING a CHAR* Buffer, as may be expected.

[Skipping over 129-255 and locales/codepages]

What happens with characters above 255? There is an RtlUnicodeToUTF8N function so it's safe to assume it doesn't convert to UTF-8.

How about code points outside BMP (surrogate pairs and whatnot)?

I saw a function that does something like the code below:

char *pTarget = reinterpret_cast<char*>(char_str);
const WCHAR  *pSource = reinterpret_cast<const WCHAR*>(wchar_str);

for ( long i = 0; i < targetMaxSizeInBytes; i++ )
{
    *pTarget = static_cast<char>(*pSource);

    if (L'\0' == *pSource)
        break;

    pTarget++;
    pSource++;
}

This would cause problems with any non-ASCII characters, correct?

Update:

From RbMm's answer:

RtlUnicodeStringToAnsiString is shell over RtlUnicodeToMultiByteN routine

I get a little more information:

Like RtlUnicodeToMultiByteSize, RtlUnicodeToMultiByteN supports only precomposed Unicode characters that are mapped to the current system ANSI code page installed at system boot.

WideCharToMultiByte has an option to be notified if a default character is used in the conversion for a character that cannot be represented in the specified code page:

lpUsedDefaultChar [out, optional]

Pointer to a flag that indicates if the function has used a default character in the conversion. The flag is set to TRUE if one or more characters in the source string cannot be represented in the specified code page. Otherwise, the flag is set to FALSE. This parameter can be set to NULL.

However, it seems RtlUnicodeToMultiByteN, and therefore RtlUnicodeStringToAnsiString, simply don't support characters outside the current code page?

I tried a few characters and got seemingly random conversions (see below) - more importantly, I got STATUS_SUCCESS returned.

U+03A3 Σ -> 0n83 'S'
U+03A4 Τ -> 0n63 '?'
U+03A5 Υ -> 0n63 '?'
U+03A6 Φ -> 0n70 'F'

Body:
RtlUnicodeStringToAnsiString is shell over RtlUnicodeToMultiByteN routine

The RtlUnicodeToMultiByteN routine translates the specified Unicode
  string into a new character string, using the current system ANSI
  code page (ACP). The translated string is not necessarily from a
  multibyte character set.

so any of this routine have the same conversion as WideCharToMultiByte with CP_ACP

also exist next routines:

RtlUnicodeStringToOemString - shell over RtlUnicodeToOemN routine

The RtlUnicodeToOemN routine translates a given Unicode string to
  an OEM string, using the current system OEM code page.

so this routines have the same conversion as WideCharToMultiByte with CP_OEMCP

for UTF-8 convertions exist RtlUnicodeToUTF8N (converts a Unicode string to a UTF-8 string) and RtlUTF8ToUnicodeN (converts a UTF-8 string to a Unicode string. )

for custom code page you can use undocumented api

NTSYSAPI
NTSTATUS
NTAPI
RtlCustomCPToUnicodeN(
    _In_ PCPTABLEINFO CustomCP,
    _Out_writes_bytes_to_(MaxBytesInUnicodeString, *BytesInUnicodeString) PWCH UnicodeString,
    _In_ ULONG MaxBytesInUnicodeString,
    _Out_opt_ PULONG BytesInUnicodeString,
    _In_reads_bytes_(BytesInCustomCPString) PCH CustomCPString,
    _In_ ULONG BytesInCustomCPString
    );

here key point in initialize CPTABLEINFO, so you can use any USHORT  CodePage; here