问:
How to parse a BIG JSON file in python
I am working with a very big dataset and I got a problem that could not find any answer for that.
I am trying to parse the data from JSON and here is what I did for a piece of data from the whole dataset and works:

```<code>import json

s = set()

with open("data.raw", "r") as f:

    for line in f:
        d = json.loads(line)
</code>```

The confusing part is that when I apply this code on my main data (the size is about 200G) it shows the following error (without going out of memory):

```<code>    d = json.loads(line)
  File "C:\Users\Sathyanarayanan\AppData\Local\Programs\Python\Python35-32\lib\json\__init__.py", line 319, in loads
    return _default_decoder.decode(s)
  File "C:\Users\Sathyanarayanan\AppData\Local\Programs\Python\Python35-32\lib\json\decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\Sathyanarayanan\AppData\Local\Programs\Python\Python35-32\lib\json\decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 2 column 1 (char 1)
</code>```

The type(f) = TextIOWrapper if it helps... but this data type is also for the small dataset...

Here are few lines of my data to see the format:

```<code>{"MessageType": "SALES.CONTRACTS.SALESTATUSCHANGED", "Event": {"Id": {"Source": 1, "SourceId": "ZGA=-3-1-002-0801743-2330650"}, "RefInfo": {"TenantId": {"Id": "ZGA="}, "UserId": {"Id": "ZMKj"}, "SentUtc": "2013-01-14T20:17:57.9681547", "Source": 1}, "OldStatus": {"Status": 3, "AutoRemoveInfo": null}, "NewStatus": {"Status": 4, "AutoRemoveInfo": null}, "Items": {"Items": [{"Id": {"Id": 1193}, "Sku": {"Sku": "Con BM20"}, "Quantity": 1, "UnitPrice": {"amount": 11.92, "currency": 840}}], "FulfilledItems": []}, "ShippingInfo": {"Carrier": "", "Class": "", "Region": null, "Country": 0, "PostalCode": null, "Costs": null, "Charges": null}, "SaleDate": "2013-01-13T13:39:57", "PendingItems": null, "Kits": null, "Products": null, "OldSaleDate": "0001-01-01T00:00:00", "AdditionalSaleInfo": null}}
{"MessageType": "SALES.CONTRACTS.SALESHIPPINGINFOCHANGED", "Event": {"Id": {"Source": 1, "SourceId": "ZGA=-3-1-002-0801743-2330650"}, "RefInfo": {"TenantId": {"Id": "ZGA="}, "UserId": {"Id": "ZMKj"}, "SentUtc": "2013-01-14T20:17:57.9681547", "Source": 1}, "Status": {"Status": 4, "AutoRemoveInfo": null}, "Items": {"Items": [{"Id": {"Id": 1193}, "Sku": {"Sku": "Con BM20"}, "Quantity": 1, "UnitPrice": {"amount": 11.92, "currency": 840}}], "FulfilledItems": []}, "OldShippingInfo": {"Carrier": "", "Class": "", "Region": null, "Country": 0, "PostalCode": null, "Costs": null, "Charges": null}, "NewShippingInfo": {"Carrier": "USPS", "Class": "FIRST/RECTPARCEL", "Region": null, "Country": 0, "PostalCode": null, "Costs": null, "Charges": null}, "SaleDate": "0001-01-01T00:00:00", "PendingItems": null, "Kits": null, "Products": null, "OldSaleDate": "0001-01-01T00:00:00", "AdditionalSaleInfo": null}}
{"MessageType": "SALES.CONTRACTS.SALECREATED", "Event": {"Id": {"Source": 1, "SourceId": "ZGA=-3-1-002-4851828-6514632"}, "RefInfo": {"TenantId": {"Id": "ZGA="}, "UserId": {"Id": "ZMKj"}, "SentUtc": "2013-01-14T20:17:58.1402505", "Source": 1}, "Status": {"Status": 4, "AutoRemoveInfo": null}, "Items": {"Items": [{"Id": {"Id": 9223372036854775807}, "Sku": {"Sku": "NFL Blanket Seahawks"}, "Quantity": 1, "UnitPrice": {"amount": 22.99, "currency": 840}}], "FulfilledItems": []}, "ShippingInfo": {"Carrier": "USPS", "Class": "FIRST/RECTPARCEL", "Region": null, "Country": 0, "PostalCode": null, "Costs": null, "Charges": null}, "SaleDate": "2013-01-13T15:51:12", "Kits": null, "Products": null, "AdditionalSaleInfo": null}}
{"MessageType": "SALES.CONTRACTS.SALECREATED", "Event": {"Id": {"Source": 1, "SourceId": "ZGA=-3-1-102-3824485-2270645"}, "RefInfo": {"TenantId": {"Id": "ZGA="}, "UserId": {"Id": "ZMKj"}, "SentUtc": "2013-01-14T20:17:58.3436109", "Source": 1}, "Status": {"Status": 4, "AutoRemoveInfo": null}, "Items": {"Items": [{"Id": {"Id": 9223372036854775807}, "Sku": {"Sku": "NFL CD Wallet Chargers"}, "Quantity": 1, "UnitPrice": {"amount": 12.99, "currency": 840}}], "FulfilledItems": []}, "ShippingInfo": {"Carrier": "USPS", "Class": "FIRST/RECTPARCEL", "Region": null, "Country": 0, "PostalCode": null, "Costs": null, "Charges": null}, "SaleDate": "2013-01-12T02:49:58", "Kits": null, "Products": null, "AdditionalSaleInfo": null}}
</code>```

It is Json because I'm already parsing first 2000 lines and it works perfectly. But when I try to use the same procedure for the big file it shows the error from very first lines of the data.

答:
A good solution to read a big json dataset, it is to use a generator like yield in python, because 200G it is too big for your RAM if your json parser stored whole file in memory, step by step the memory is saved with an iterator.

You can use iterative JSON parser with Pythonic interface http://pypi.python.org/pypi/ijson/.

But here your file has .raw extension, it is not a json file.

To read that do:

```<code>import numpy as np

content = np.fromfile("data.raw", dtype=np.int16, sep="")
</code>```

But this solution can crash for big file.

If fact a .raw seems to a .csv file, then you can create your reader like that:

```<code>import csv

def read_big_file(filename):
    with open(filename, "rb") as csvfile:
         reader = csv.reader(csvfile)
         for row in reader:
             yield row
</code>```

Or like taht for a text file:

```<code>def read_big_file(filename):
    with open(filename, "r") as _file:
         for line in _file:
             yield line
</code>```

Use rb only if your file is binary.

Execute:

```<code>for line in read_big_file(filename):
    <treatment>
    <free memory after a size of chunk>
</code>```

I can precise my answer if you give the first lines of your file.

Title: How to parse a BIG JSON file in python

Body:
I am working with a very big dataset and I got a problem that could not find any answer for that.
I am trying to parse the data from JSON and here is what I did for a piece of data from the whole dataset and works:

import json

s = set()

with open("data.raw", "r") as f:

    for line in f:
        d = json.loads(line)

The confusing part is that when I apply this code on my main data (the size is about 200G) it shows the following error (without going out of memory):

    d = json.loads(line)
  File "C:\Users\Sathyanarayanan\AppData\Local\Programs\Python\Python35-32\lib\json\__init__.py", line 319, in loads
    return _default_decoder.decode(s)
  File "C:\Users\Sathyanarayanan\AppData\Local\Programs\Python\Python35-32\lib\json\decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\Sathyanarayanan\AppData\Local\Programs\Python\Python35-32\lib\json\decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 2 column 1 (char 1)

The type(f) = TextIOWrapper if it helps... but this data type is also for the small dataset...

Here are few lines of my data to see the format:

{"MessageType": "SALES.CONTRACTS.SALESTATUSCHANGED", "Event": {"Id": {"Source": 1, "SourceId": "ZGA=-3-1-002-0801743-2330650"}, "RefInfo": {"TenantId": {"Id": "ZGA="}, "UserId": {"Id": "ZMKj"}, "SentUtc": "2013-01-14T20:17:57.9681547", "Source": 1}, "OldStatus": {"Status": 3, "AutoRemoveInfo": null}, "NewStatus": {"Status": 4, "AutoRemoveInfo": null}, "Items": {"Items": [{"Id": {"Id": 1193}, "Sku": {"Sku": "Con BM20"}, "Quantity": 1, "UnitPrice": {"amount": 11.92, "currency": 840}}], "FulfilledItems": []}, "ShippingInfo": {"Carrier": "", "Class": "", "Region": null, "Country": 0, "PostalCode": null, "Costs": null, "Charges": null}, "SaleDate": "2013-01-13T13:39:57", "PendingItems": null, "Kits": null, "Products": null, "OldSaleDate": "0001-01-01T00:00:00", "AdditionalSaleInfo": null}}
{"MessageType": "SALES.CONTRACTS.SALESHIPPINGINFOCHANGED", "Event": {"Id": {"Source": 1, "SourceId": "ZGA=-3-1-002-0801743-2330650"}, "RefInfo": {"TenantId": {"Id": "ZGA="}, "UserId": {"Id": "ZMKj"}, "SentUtc": "2013-01-14T20:17:57.9681547", "Source": 1}, "Status": {"Status": 4, "AutoRemoveInfo": null}, "Items": {"Items": [{"Id": {"Id": 1193}, "Sku": {"Sku": "Con BM20"}, "Quantity": 1, "UnitPrice": {"amount": 11.92, "currency": 840}}], "FulfilledItems": []}, "OldShippingInfo": {"Carrier": "", "Class": "", "Region": null, "Country": 0, "PostalCode": null, "Costs": null, "Charges": null}, "NewShippingInfo": {"Carrier": "USPS", "Class": "FIRST/RECTPARCEL", "Region": null, "Country": 0, "PostalCode": null, "Costs": null, "Charges": null}, "SaleDate": "0001-01-01T00:00:00", "PendingItems": null, "Kits": null, "Products": null, "OldSaleDate": "0001-01-01T00:00:00", "AdditionalSaleInfo": null}}
{"MessageType": "SALES.CONTRACTS.SALECREATED", "Event": {"Id": {"Source": 1, "SourceId": "ZGA=-3-1-002-4851828-6514632"}, "RefInfo": {"TenantId": {"Id": "ZGA="}, "UserId": {"Id": "ZMKj"}, "SentUtc": "2013-01-14T20:17:58.1402505", "Source": 1}, "Status": {"Status": 4, "AutoRemoveInfo": null}, "Items": {"Items": [{"Id": {"Id": 9223372036854775807}, "Sku": {"Sku": "NFL Blanket Seahawks"}, "Quantity": 1, "UnitPrice": {"amount": 22.99, "currency": 840}}], "FulfilledItems": []}, "ShippingInfo": {"Carrier": "USPS", "Class": "FIRST/RECTPARCEL", "Region": null, "Country": 0, "PostalCode": null, "Costs": null, "Charges": null}, "SaleDate": "2013-01-13T15:51:12", "Kits": null, "Products": null, "AdditionalSaleInfo": null}}
{"MessageType": "SALES.CONTRACTS.SALECREATED", "Event": {"Id": {"Source": 1, "SourceId": "ZGA=-3-1-102-3824485-2270645"}, "RefInfo": {"TenantId": {"Id": "ZGA="}, "UserId": {"Id": "ZMKj"}, "SentUtc": "2013-01-14T20:17:58.3436109", "Source": 1}, "Status": {"Status": 4, "AutoRemoveInfo": null}, "Items": {"Items": [{"Id": {"Id": 9223372036854775807}, "Sku": {"Sku": "NFL CD Wallet Chargers"}, "Quantity": 1, "UnitPrice": {"amount": 12.99, "currency": 840}}], "FulfilledItems": []}, "ShippingInfo": {"Carrier": "USPS", "Class": "FIRST/RECTPARCEL", "Region": null, "Country": 0, "PostalCode": null, "Costs": null, "Charges": null}, "SaleDate": "2013-01-12T02:49:58", "Kits": null, "Products": null, "AdditionalSaleInfo": null}}

It is Json because I'm already parsing first 2000 lines and it works perfectly. But when I try to use the same procedure for the big file it shows the error from very first lines of the data.

Body:
A good solution to read a big json dataset, it is to use a generator like yield in python, because 200G it is too big for your RAM if your json parser stored whole file in memory, step by step the memory is saved with an iterator.

You can use iterative JSON parser with Pythonic interface http://pypi.python.org/pypi/ijson/.

But here your file has .raw extension, it is not a json file.

To read that do:

import numpy as np

content = np.fromfile("data.raw", dtype=np.int16, sep="")

But this solution can crash for big file.

If fact a .raw seems to a .csv file, then you can create your reader like that:

import csv

def read_big_file(filename):
    with open(filename, "rb") as csvfile:
         reader = csv.reader(csvfile)
         for row in reader:
             yield row

Or like taht for a text file:

def read_big_file(filename):
    with open(filename, "r") as _file:
         for line in _file:
             yield line

Use rb only if your file is binary.

Execute:

for line in read_big_file(filename):
    <treatment>
    <free memory after a size of chunk>

I can precise my answer if you give the first lines of your file.


来源: stackexchange

问:
ZMQ: Sync messages between APs
Multiple Access Points are in a network. They need to sync client data whenever a client connects to any one of the AP.

I've studied ZeroMQ documentation for REQ/REP, PUB/SUB and PUSH/PULL patterns. Not quite sure which pattern really works for the above requirement between PUSH/PULL and PUB/SUB.

In the documentation, it is mentioned that,

One socket may have many outgoing and many incoming connections.

How to achieve this using one of the above patterns so that the data among APs always in sync.

Points to be considered

APs join network arbitrarily.

If a client connects to an AP, it's data need to be stored in all APs.

ZeroMQs are for C language.

答:
You could look at the Harmony peer/peer pattern; it's discussed in the ZMQ guide. Access points could then send a client state message to all their peer access points every time a client connects. No single access point would be a "master" - they would be true peers.

Alternatively you could have one of the access points setting itself up as a "master" (a bound PULL socket), to which slave access points connect and send client data through a PUSH socket. The "master" would then send that data back out to the other access points on a PUB socket, with slave access points receiving that on a SUB socket. It's not a very elegant solution, the master has to handle the entire network's client data traffic, but it may be easier to use.

ContentLicense: CC BY-SA 3.0

Title: ZMQ: Sync messages between APs


问:
node js twilio send sms doesn't work
i have this function sendsms

```<code> var twiml = new MessagingResponse();

function sendsms() {
                  twiml.message("aaa");
                 console.log(twiml.toString());
                   }
</code>```

but when i call this function inside User.findone

```<code> User.findOne({}, function(err, user) {
                 if (condition) {
                     sendsms();
                 }
             })
</code>```

it log the twiml.toString successfully

but the sms is not sent

when i call outside user.findOne the sms is sent  successfully

```<code>sendsms()
</code>```

this is the routes to send sms

```<code>router.post('/sendSMS', function(req, res) {
    var phone = req.body.phone;

    User.findOne({}, function(err, user) {

            require('../config/sendSMS')(user, phone);

            res.status(200).json({ success: true, message: 'message sent successfully' });

        }

    });
</code>```

this is the route to get and replay to sms

```<code>router.post('/getSMS', function(req, res) {

    require('../config/getAndReplay')(req, res);

});
</code>```

答:
Twilio developer evangelist here.

The problem in your code is that you are mixing synchronous and asynchronous code.

User.findOne is an asynchronous call, so calling the getandreplay() function within the result callback will mean it happens after the response is completed in your route.

What I suggest is that you return the message that you want to reply with from getandreplay() and use that to form a response to the incoming request. Like this:

```<code>function getandreplay(node) {
    if (node.outs.length > 0) {
        if (node.outs.includes(req.body.Body.toLowerCase())) {
            for (var i = 0; i < node.output.length; i++) {
                var el = node.output[i];
                if (req.body.Body.toLowerCase() == el[0]) {
                    req.session.lastnode = getnode(el[1]);
                    if (getnode(el[1]).outs.length == 0) {
                        req.session.destroy();
                        User.findOneAndUpdate({}, { $push: { users: userPhone } }, { safe: true, upsert: true }, function(user, err) {});
                    }
                    return getnode(el[1]).msg;
                }
            }
        } else {
            return node.msg
        }
    }
}
</code>```

Then, when you call User.findOne() you get the result from getandreplay() and send that back as the response:

```<code>User.findOne({}, function(err, user) {
    if (!user.users.includes(userPhone)) {
        twiml.message(getandreplay(mynode));
    }
    res.writeHead(200, { 'Content-Type': 'text/xml' });
    res.end(twiml.toString());
});
</code>```

Note that here I am calling res.end within the callback function for User.findOne().

Let me know if this helps at all.

Title: node js twilio send sms doesn't work

Body:
i have this function sendsms

 var twiml = new MessagingResponse();

function sendsms() {
                  twiml.message("aaa");
                 console.log(twiml.toString());
                   }

but when i call this function inside User.findone

 User.findOne({}, function(err, user) {
                 if (condition) {
                     sendsms();
                 }
             })

it log the twiml.toString successfully

but the sms is not sent

when i call outside user.findOne the sms is sent  successfully

sendsms()

this is the routes to send sms

router.post('/sendSMS', function(req, res) {
    var phone = req.body.phone;

    User.findOne({}, function(err, user) {

            require('../config/sendSMS')(user, phone);

            res.status(200).json({ success: true, message: 'message sent successfully' });

        }

    });

this is the route to get and replay to sms

router.post('/getSMS', function(req, res) {

    require('../config/getAndReplay')(req, res);

});

Body:
Twilio developer evangelist here.

The problem in your code is that you are mixing synchronous and asynchronous code.

User.findOne is an asynchronous call, so calling the getandreplay() function within the result callback will mean it happens after the response is completed in your route.

What I suggest is that you return the message that you want to reply with from getandreplay() and use that to form a response to the incoming request. Like this:

function getandreplay(node) {
    if (node.outs.length > 0) {
        if (node.outs.includes(req.body.Body.toLowerCase())) {
            for (var i = 0; i < node.output.length; i++) {
                var el = node.output[i];
                if (req.body.Body.toLowerCase() == el[0]) {
                    req.session.lastnode = getnode(el[1]);
                    if (getnode(el[1]).outs.length == 0) {
                        req.session.destroy();
                        User.findOneAndUpdate({}, { $push: { users: userPhone } }, { safe: true, upsert: true }, function(user, err) {});
                    }
                    return getnode(el[1]).msg;
                }
            }
        } else {
            return node.msg
        }
    }
}

Then, when you call User.findOne() you get the result from getandreplay() and send that back as the response:

User.findOne({}, function(err, user) {
    if (!user.users.includes(userPhone)) {
        twiml.message(getandreplay(mynode));
    }
    res.writeHead(200, { 'Content-Type': 'text/xml' });
    res.end(twiml.toString());
});

Note that here I am calling res.end within the callback function for User.findOne().

Let me know if this helps at all.


问:
initialize a numpy array
Is there way to initialize a numpy array of a shape and add to it? I will explain what I need with a list example. If I want to create a list of objects generated in a loop, I can do:

```<code>a = []
for i in range(5):
    a.append(i)
</code>```

I want to do something similar with a numpy array. I know about vstack, concatenate etc. However, it seems these require two numpy arrays as inputs. What I need is:

```<code>big_array # Initially empty. This is where I don't know what to specify
for i in range(5):
    array i of shape = (2,4) created.
    add to big_array
</code>```

The big_array should have a shape (10,4). How to do this?

EDIT:

I want to add the following clarification. I am aware that I can define big_array = numpy.zeros((10,4)) and then fill it up. However, this requires specifying the size of big_array in advance. I know the size in this case, but what if I do not? When we use the .append function for extending the list in python, we don't need to know its final size in advance. I am wondering if something similar exists for creating a bigger array from smaller arrays, starting with an empty array.

答:
Introduced in numpy 1.8:

numpy.full

Return a new array of given shape and type, filled with fill_value.

Examples:

```<code>>>> import numpy as np
>>> np.full((2, 2), np.inf)
array([[ inf,  inf],
       [ inf,  inf]])
>>> np.full((2, 2), 10)
array([[10, 10],
       [10, 10]])
</code>```

Title: initialize a numpy array

Body:
Is there way to initialize a numpy array of a shape and add to it? I will explain what I need with a list example. If I want to create a list of objects generated in a loop, I can do:

a = []
for i in range(5):
    a.append(i)

I want to do something similar with a numpy array. I know about vstack, concatenate etc. However, it seems these require two numpy arrays as inputs. What I need is:

big_array # Initially empty. This is where I don't know what to specify
for i in range(5):
    array i of shape = (2,4) created.
    add to big_array

The big_array should have a shape (10,4). How to do this?

EDIT:

I want to add the following clarification. I am aware that I can define big_array = numpy.zeros((10,4)) and then fill it up. However, this requires specifying the size of big_array in advance. I know the size in this case, but what if I do not? When we use the .append function for extending the list in python, we don't need to know its final size in advance. I am wondering if something similar exists for creating a bigger array from smaller arrays, starting with an empty array.

Body:
Introduced in numpy 1.8:

numpy.full

Return a new array of given shape and type, filled with fill_value.

Examples:

>>> import numpy as np
>>> np.full((2, 2), np.inf)
array([[ inf,  inf],
       [ inf,  inf]])
>>> np.full((2, 2), 10)
array([[10, 10],
       [10, 10]])


问:
Upgrading Excel 2010 add-in to office 2016
When upgrading to Office 365 / Excel 2016, I found that it was extremely slow to open, and even slower to close:  Waiting 20-30 seconds to open to a blank workbook, and taking over a minute to close-down excel.

My investigations showed that the problem was an Office 2010 add-in.  The add-in is a custom one that I wrote a few years ago - it was created with the help of the CustomUIEditor tool (to allow me to create a Ribbon for my add-in) - i.e. it is a .XLAM add-in, not a COM one.

After lots of googling, I can't find much about add-in compatibility between Office 2010 and Office 365.  The CustomUIEditor that I used previously has not been updated in around 10 years, and I can't find a useful alternative.

Has anyone come across a similar issue before (and solved it?)  Do I need to recreate the add-in as a COM add-in?

答:
OK - thanks to Siddharth for taking the time to respond.  I managed to solve my Excel issue, and in the end it was unrelated to the add-in (even though disabling the add-in did improve the speed that Excel opened and closed).

The issue was related to a lot of old files in my %appdata%\roaming\microsoft\excel\ folder.  Lots of corrupted files that it was trying to read / write back when I opened or closed excel.  I deleted them and Excel is now working properly.


问:
How do I get rid of chart in all workbooks in vba?
I tried running this code to delete any charts before allowing the code to run but error of "Object doesn't support this method" keeps coming up. </p>

```<code>Dim wksht As Worksheets

Set Source_Workbook = ThisWorkbook

For Each wksht In Source_Workbook

   If ChartObjects.Count > 0 Then

      ChartObjects.Delete

   End If

Next wksht
</code>```

答:
This is the corrected code:</p>

```<code>Sub DeleteAllChartObjects()
  Dim wksht As Worksheet
  For Each wksht In ThisWorkbook.Worksheets
    If wksht.ChartObjects.count > 0 Then wksht.ChartObjects.Delete
  Next wksht
End Sub
</code>```

Body:
I tried running this code to delete any charts before allowing the code to run but error of "Object doesn't support this method" keeps coming up.

Dim wksht As Worksheets

Set Source_Workbook = ThisWorkbook

For Each wksht In Source_Workbook

   If ChartObjects.Count > 0 Then

      ChartObjects.Delete

   End If

Next wksht

Body:
This is the corrected code:

Sub DeleteAllChartObjects()
  Dim wksht As Worksheet
  For Each wksht In ThisWorkbook.Worksheets
    If wksht.ChartObjects.count > 0 Then wksht.ChartObjects.Delete
  Next wksht
End Sub


问:
UILongPressGestureRecognizer with SpriteKit
I'm trying to figure it out how to detect if a shapeNode has been pressed, specifically with the LongPress Gesture. Please take a look on the below code. Any idea what is wrong, why I can't see the "Found!" message?

```<code>class Test: SKScene {
    let longPressGesture = UILongPressGestureRecognizer()

    override func didMove(to view: SKView) {

        longPressGesture.addTarget(self, action: #selector(GameScene.longPress))
        self.view?.addGestureRecognizer(longPressGesture)

        let testPath = UIBezierPath(rect: CGRect(x: (view.scene?.frame.midX)!, y: (view.scene?.frame.midY)!, width: 2 * 50.0, height: 2 * 50.0)).cgPath

        let testNode = Node.init(path: testPath, nodeName: "TEST")
        testNode.fillColor = UIColor.brown
        testNode.position = CGPoint(x: (view.scene?.frame.midX)!, y: (view.scene?.frame.midY)!)

        self.addChild(testNode)
    }

    func longPress(_ sender: UILongPressGestureRecognizer) {
        let longPressLocation = sender.location(in: self.view)

        if sender.state == .began {
            for child in self.children {
                if let shapeNode = child as? SKShapeNode {
                    if shapeNode.contains(longPressLocation) {
                        print("Found!")
                    }
                }
            }
        } else if sender.state == .ended {
            print("ended")
        }
    }
}
</code>```

Many thanks for any help!

答:
You are currently calculating tap location in view's coordinate system. In order to work in scene's coordinate system (because SKShapeNode is added to a scene), you have to convert a tap location from view's coordinate system to scene's coordinate system, like this:

```<code>let longPressLocation = convertPoint(fromView: sender.location(in: self.view))
</code>```

Unrelated to original issue, but a good thing to keep in mind is that forced unwrapping is not that good idea most of the time (sometimes it helps while development phase though), and you should tend to access underlying values of an optionals in a safe way ( using if let syntax for example).

Body:
I'm trying to figure it out how to detect if a shapeNode has been pressed, specifically with the LongPress Gesture. Please take a look on the below code. Any idea what is wrong, why I can't see the "Found!" message?

class Test: SKScene {
    let longPressGesture = UILongPressGestureRecognizer()

    override func didMove(to view: SKView) {

        longPressGesture.addTarget(self, action: #selector(GameScene.longPress))
        self.view?.addGestureRecognizer(longPressGesture)

        let testPath = UIBezierPath(rect: CGRect(x: (view.scene?.frame.midX)!, y: (view.scene?.frame.midY)!, width: 2 * 50.0, height: 2 * 50.0)).cgPath

        let testNode = Node.init(path: testPath, nodeName: "TEST")
        testNode.fillColor = UIColor.brown
        testNode.position = CGPoint(x: (view.scene?.frame.midX)!, y: (view.scene?.frame.midY)!)

        self.addChild(testNode)
    }

    func longPress(_ sender: UILongPressGestureRecognizer) {
        let longPressLocation = sender.location(in: self.view)

        if sender.state == .began {
            for child in self.children {
                if let shapeNode = child as? SKShapeNode {
                    if shapeNode.contains(longPressLocation) {
                        print("Found!")
                    }
                }
            }
        } else if sender.state == .ended {
            print("ended")
        }
    }
}

Many thanks for any help!

Body:
You are currently calculating tap location in view's coordinate system. In order to work in scene's coordinate system (because SKShapeNode is added to a scene), you have to convert a tap location from view's coordinate system to scene's coordinate system, like this:

let longPressLocation = convertPoint(fromView: sender.location(in: self.view))

Unrelated to original issue, but a good thing to keep in mind is that forced unwrapping is not that good idea most of the time (sometimes it helps while development phase though), and you should tend to access underlying values of an optionals in a safe way ( using if let syntax for example).


问:
Bitmap gets mangled when I converted from System.Drawing.Bitmap object to cv::Mat
I have a WPF application that takes a screen shot of the running Handbrake executable using a class called ScreenCapture that I copied from stack overflow.

```<code>public class ScreenCapture
{
    [DllImport("user32.dll")]
    static extern int GetWindowRgn(IntPtr hWnd, IntPtr hRgn);

    //Region Flags - The return value specifies the type of the region that the function obtains. It can be one of the following values.
    const int ERROR = 0;
    const int NULLREGION = 1;
    const int SIMPLEREGION = 2;
    const int COMPLEXREGION = 3;

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool GetWindowRect(HandleRef hWnd, out RECT lpRect);

    [DllImport("gdi32.dll")]
    static extern IntPtr CreateRectRgn(int nLeftRect, int nTopRect, int nRightRect, int nBottomRect);

    [DllImport("user32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool PrintWindow(IntPtr hwnd, IntPtr hDC, uint nFlags);

    [StructLayout(LayoutKind.Sequential)]
    public struct RECT
    {
        public int Left, Top, Right, Bottom;

        public RECT(int left, int top, int right, int bottom)
        {
            Left = left;
            Top = top;
            Right = right;
            Bottom = bottom;
        }

        public RECT(System.Drawing.Rectangle r) : this(r.Left, r.Top, r.Right, r.Bottom) { }

        public int X
        {
            get { return Left; }
            set { Right -= (Left - value); Left = value; }
        }

        public int Y
        {
            get { return Top; }
            set { Bottom -= (Top - value); Top = value; }
        }

        public int Height
        {
            get { return Bottom - Top; }
            set { Bottom = value + Top; }
        }

        public int Width
        {
            get { return Right - Left; }
            set { Right = value + Left; }
        }

        public System.Drawing.Point Location
        {
            get { return new System.Drawing.Point(Left, Top); }
            set { X = value.X; Y = value.Y; }
        }

        public System.Drawing.Size Size
        {
            get { return new System.Drawing.Size(Width, Height); }
            set { Width = value.Width; Height = value.Height; }
        }

        public static implicit operator System.Drawing.Rectangle(RECT r)
        {
            return new System.Drawing.Rectangle(r.Left, r.Top, r.Width, r.Height);
        }

        public static implicit operator RECT(System.Drawing.Rectangle r)
        {
            return new RECT(r);
        }

        public static bool operator ==(RECT r1, RECT r2)
        {
            return r1.Equals(r2);
        }

        public static bool operator !=(RECT r1, RECT r2)
        {
            return !r1.Equals(r2);
        }

        public bool Equals(RECT r)
        {
            return r.Left == Left && r.Top == Top && r.Right == Right && r.Bottom == Bottom;
        }

        public override bool Equals(object obj)
        {
            if (obj is RECT)
                return Equals((RECT)obj);
            else if (obj is System.Drawing.Rectangle)
                return Equals(new RECT((System.Drawing.Rectangle)obj));
            return false;
        }

        public override int GetHashCode()
        {
            return ((System.Drawing.Rectangle)this).GetHashCode();
        }

        public override string ToString()
        {
            return string.Format(System.Globalization.CultureInfo.CurrentCulture, "{{Left={0},Top={1},Right={2},Bottom={3}}}", Left, Top, Right, Bottom);
        }
    }
    public Bitmap GetScreenshot(IntPtr ihandle)
    {
        IntPtr hwnd = ihandle;//handle here

        RECT rc;
        GetWindowRect(new HandleRef(null, hwnd), out rc);

        Bitmap bmp = new Bitmap(rc.Right - rc.Left, rc.Bottom - rc.Top, PixelFormat.Format32bppArgb);
        Graphics gfxBmp = Graphics.FromImage(bmp);
        IntPtr hdcBitmap;
        try
        {
            hdcBitmap = gfxBmp.GetHdc();
        }
        catch
        {
            return null;
        }
        bool succeeded = PrintWindow(hwnd, hdcBitmap, 0);
        gfxBmp.ReleaseHdc(hdcBitmap);
        if (!succeeded)
        {
            gfxBmp.FillRectangle(new SolidBrush(Color.Gray), new Rectangle(Point.Empty, bmp.Size));
        }
        IntPtr hRgn = CreateRectRgn(0, 0, 0, 0);
        GetWindowRgn(hwnd, hRgn);
        Region region = Region.FromHrgn(hRgn);//err here once
        if (!region.IsEmpty(gfxBmp))
        {
            gfxBmp.ExcludeClip(region);
            gfxBmp.Clear(Color.Transparent);
        }
        gfxBmp.Dispose();
        return bmp;
    }

    public void WriteBitmapToFile(string filename, Bitmap bitmap)
    {
        bitmap.Save(filename, ImageFormat.Bmp);
    }
</code>```

So when the button click handler below is called a screenshot of the handbrake window is taken.
I write it to the harddrive to make sure its ok:
handbrake screen shot.
I create an instance of a CLR class library ClassLibrary1::Class1 and call the method "DoSomething" passing it the System.Drawing.Bitmap object.

```<code>  private void button4_Click(object sender, RoutedEventArgs e)
  {
     string wName = "HandBrake";
     IntPtr hWnd = IntPtr.Zero;
     foreach (Process pList in Process.GetProcesses())
     {
        if (pList.MainWindowTitle.Contains(wName))
        {
           hWnd = pList.MainWindowHandle;

           var sc = new ScreenCapture();

           SetForegroundWindow(hWnd);
           var bitmap = sc.GetScreenshot(hWnd);

           sc.WriteBitmapToFile("handbrake.bmp", bitmap);

           Bitmap image1 = (Bitmap)System.Drawing.Image.FromFile("handbrake.bmp", true);

           ClassLibrary1.Class1 opencv = new ClassLibrary1.Class1();

           opencv.DoSomething(image1);
        }
     }
  }
</code>```

Inside DoSomething I attempt to convert the System.Drawing.Bitmap to a OpenCV class cv::Mat. I call cv::imwrite to make sure the bitmap is still ok, unfortunately somethings gone wrong: mangled handbrake screenshot

```<code>void Class1::DoSomething(Bitmap ^mybitmap)
{
cv::Mat *imgOriginal;
// Lock the bitmap's bits.
Rectangle rect = Rectangle(0, 0, mybitmap->Width, mybitmap->Height);
Imaging::BitmapData^ bmpData = mybitmap->LockBits(rect, Imaging::ImageLockMode::ReadWrite, mybitmap->PixelFormat);
try
{
  // Get the address of the first line.
  IntPtr ptr = bmpData->Scan0;

  // Declare an array to hold the bytes of the bitmap.
  // This code is specific to a bitmap with 24 bits per pixels.
  int bytes = Math::Abs(bmpData->Stride) * mybitmap->Height;
  array<Byte>^rgbValues = gcnew array<Byte>(bytes);

  // Copy the RGB values into the array.
  System::Runtime::InteropServices::Marshal::Copy(ptr, rgbValues, 0, bytes);

  imgOriginal = new cv::Mat(mybitmap->Height, mybitmap->Width, CV_8UC3, (void *)ptr, std::abs(bmpData->Stride));
  }
  finally { mybitmap->UnlockBits(bmpData); }//Remember to unlock!!!

  cv::imwrite("from_mat.bmp", *imgOriginal);
}
</code>```

Can anybody spot my error?

答:
Since your image is stretched horizontally, I'm betting that you have the wrong pixel format selected. (It's not stretched vertically, nor skewed diagonally, so the stride is correct.) CV_8UC3 specifies 24 bits per pixel, but I think that your BMP file is using 32 bits per pixel.

Switch your pixel format to CV_8UC4, or better yet, read the number of bits per pixel from the image and select the correct CV format based on that.

Side note: Since you're doing sc.WriteBitmapToFile() followed by opencv.DoSomething(Image.FromFile(), the entire bit about how you're capturing the screenshot is irrelevant. You're reading the bitmap from a file; that's all that matters.

Body:
I have a WPF application that takes a screen shot of the running Handbrake executable using a class called ScreenCapture that I copied from stack overflow.

public class ScreenCapture
{
    [DllImport("user32.dll")]
    static extern int GetWindowRgn(IntPtr hWnd, IntPtr hRgn);

    //Region Flags - The return value specifies the type of the region that the function obtains. It can be one of the following values.
    const int ERROR = 0;
    const int NULLREGION = 1;
    const int SIMPLEREGION = 2;
    const int COMPLEXREGION = 3;

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool GetWindowRect(HandleRef hWnd, out RECT lpRect);

    [DllImport("gdi32.dll")]
    static extern IntPtr CreateRectRgn(int nLeftRect, int nTopRect, int nRightRect, int nBottomRect);

    [DllImport("user32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool PrintWindow(IntPtr hwnd, IntPtr hDC, uint nFlags);

    [StructLayout(LayoutKind.Sequential)]
    public struct RECT
    {
        public int Left, Top, Right, Bottom;

        public RECT(int left, int top, int right, int bottom)
        {
            Left = left;
            Top = top;
            Right = right;
            Bottom = bottom;
        }

        public RECT(System.Drawing.Rectangle r) : this(r.Left, r.Top, r.Right, r.Bottom) { }

        public int X
        {
            get { return Left; }
            set { Right -= (Left - value); Left = value; }
        }

        public int Y
        {
            get { return Top; }
            set { Bottom -= (Top - value); Top = value; }
        }

        public int Height
        {
            get { return Bottom - Top; }
            set { Bottom = value + Top; }
        }

        public int Width
        {
            get { return Right - Left; }
            set { Right = value + Left; }
        }

        public System.Drawing.Point Location
        {
            get { return new System.Drawing.Point(Left, Top); }
            set { X = value.X; Y = value.Y; }
        }

        public System.Drawing.Size Size
        {
            get { return new System.Drawing.Size(Width, Height); }
            set { Width = value.Width; Height = value.Height; }
        }

        public static implicit operator System.Drawing.Rectangle(RECT r)
        {
            return new System.Drawing.Rectangle(r.Left, r.Top, r.Width, r.Height);
        }

        public static implicit operator RECT(System.Drawing.Rectangle r)
        {
            return new RECT(r);
        }

        public static bool operator ==(RECT r1, RECT r2)
        {
            return r1.Equals(r2);
        }

        public static bool operator !=(RECT r1, RECT r2)
        {
            return !r1.Equals(r2);
        }

        public bool Equals(RECT r)
        {
            return r.Left == Left && r.Top == Top && r.Right == Right && r.Bottom == Bottom;
        }

        public override bool Equals(object obj)
        {
            if (obj is RECT)
                return Equals((RECT)obj);
            else if (obj is System.Drawing.Rectangle)
                return Equals(new RECT((System.Drawing.Rectangle)obj));
            return false;
        }

        public override int GetHashCode()
        {
            return ((System.Drawing.Rectangle)this).GetHashCode();
        }

        public override string ToString()
        {
            return string.Format(System.Globalization.CultureInfo.CurrentCulture, "{{Left={0},Top={1},Right={2},Bottom={3}}}", Left, Top, Right, Bottom);
        }
    }
    public Bitmap GetScreenshot(IntPtr ihandle)
    {
        IntPtr hwnd = ihandle;//handle here

        RECT rc;
        GetWindowRect(new HandleRef(null, hwnd), out rc);

        Bitmap bmp = new Bitmap(rc.Right - rc.Left, rc.Bottom - rc.Top, PixelFormat.Format32bppArgb);
        Graphics gfxBmp = Graphics.FromImage(bmp);
        IntPtr hdcBitmap;
        try
        {
            hdcBitmap = gfxBmp.GetHdc();
        }
        catch
        {
            return null;
        }
        bool succeeded = PrintWindow(hwnd, hdcBitmap, 0);
        gfxBmp.ReleaseHdc(hdcBitmap);
        if (!succeeded)
        {
            gfxBmp.FillRectangle(new SolidBrush(Color.Gray), new Rectangle(Point.Empty, bmp.Size));
        }
        IntPtr hRgn = CreateRectRgn(0, 0, 0, 0);
        GetWindowRgn(hwnd, hRgn);
        Region region = Region.FromHrgn(hRgn);//err here once
        if (!region.IsEmpty(gfxBmp))
        {
            gfxBmp.ExcludeClip(region);
            gfxBmp.Clear(Color.Transparent);
        }
        gfxBmp.Dispose();
        return bmp;
    }

    public void WriteBitmapToFile(string filename, Bitmap bitmap)
    {
        bitmap.Save(filename, ImageFormat.Bmp);
    }

So when the button click handler below is called a screenshot of the handbrake window is taken.
I write it to the harddrive to make sure its ok:
handbrake screen shot.
I create an instance of a CLR class library ClassLibrary1::Class1 and call the method "DoSomething" passing it the System.Drawing.Bitmap object.

  private void button4_Click(object sender, RoutedEventArgs e)
  {
     string wName = "HandBrake";
     IntPtr hWnd = IntPtr.Zero;
     foreach (Process pList in Process.GetProcesses())
     {
        if (pList.MainWindowTitle.Contains(wName))
        {
           hWnd = pList.MainWindowHandle;

           var sc = new ScreenCapture();

           SetForegroundWindow(hWnd);
           var bitmap = sc.GetScreenshot(hWnd);

           sc.WriteBitmapToFile("handbrake.bmp", bitmap);

           Bitmap image1 = (Bitmap)System.Drawing.Image.FromFile("handbrake.bmp", true);

           ClassLibrary1.Class1 opencv = new ClassLibrary1.Class1();

           opencv.DoSomething(image1);
        }
     }
  }

Inside DoSomething I attempt to convert the System.Drawing.Bitmap to a OpenCV class cv::Mat. I call cv::imwrite to make sure the bitmap is still ok, unfortunately somethings gone wrong: mangled handbrake screenshot

void Class1::DoSomething(Bitmap ^mybitmap)
{
cv::Mat *imgOriginal;
// Lock the bitmap's bits.
Rectangle rect = Rectangle(0, 0, mybitmap->Width, mybitmap->Height);
Imaging::BitmapData^ bmpData = mybitmap->LockBits(rect, Imaging::ImageLockMode::ReadWrite, mybitmap->PixelFormat);
try
{
  // Get the address of the first line.
  IntPtr ptr = bmpData->Scan0;

  // Declare an array to hold the bytes of the bitmap.
  // This code is specific to a bitmap with 24 bits per pixels.
  int bytes = Math::Abs(bmpData->Stride) * mybitmap->Height;
  array<Byte>^rgbValues = gcnew array<Byte>(bytes);

  // Copy the RGB values into the array.
  System::Runtime::InteropServices::Marshal::Copy(ptr, rgbValues, 0, bytes);

  imgOriginal = new cv::Mat(mybitmap->Height, mybitmap->Width, CV_8UC3, (void *)ptr, std::abs(bmpData->Stride));
  }
  finally { mybitmap->UnlockBits(bmpData); }//Remember to unlock!!!

  cv::imwrite("from_mat.bmp", *imgOriginal);
}

Can anybody spot my error?


问:
data frame names as word in quotation mark
I have two part question, both concerns working with data frames names:

I want to concatenate two dfs names with separator, for example: df1 and df2 to be "df1_&_df2"

I want  make R to read data frame name as character in quotation marks so my df is called df1 and I in certain parts of my code I want it to be "df1".

When it come to 1st part I tried paste but it pasted entire data in both dfs and names concerns column names.

In the 2nd issue, being able to make R understand df name as quotation marked word is very handy in code for more complex charts, I simply put dfs into code and R makes chart title out of it. I understand there is very simple workaround here, I can create list of names manually  list=c("df1", "df2") and then just use function get in places where I need to refer to content of data frame instead of its name, but it seems little inconvenient in the long run. Is there any function in R which output is just df name? Something that looks like GiveMeName(df) and the output is "df"? (I wrote this in normal font intentionally, so no one would thought this is real function)

答:
For #1, you'll have to give a use case for me to understand your goal.

For #2, you can use deparse(substitute(df1)).  Here's an example:

```<code>plot_and_title <- function(df1) {
  data_name <- deparse(substitute(df1))
  plot(df1[[1]], df1[[2]], main = data_name)
}

plot_and_title(mtcars)
</code>```

Body:
For #1, you'll have to give a use case for me to understand your goal.

For #2, you can use deparse(substitute(df1)).  Here's an example:

plot_and_title <- function(df1) {
  data_name <- deparse(substitute(df1))
  plot(df1[[1]], df1[[2]], main = data_name)
}

plot_and_title(mtcars)


问:
Iterate through sub-directories in for loop in R
I have a large directory with 365 sub-directories that contain images for each day of the year. I created a function that I want to apply to each of the images within these sub directories. At the moment, this is what I have:

```<code>library(raster)
library(zebu)

#List all of the 365 sub-directories within my main directory
days <- list.files(full.names = F , recursive =F, pattern='*X2000*')

#Apply my function to each directory within "days"
for(j in 1:length(days)){

    named <- paste0("full_",j)

    in.list <- list.files(recursive = T, full.names = F)

    stitched <- mosaicList(in.list)

    writeRaster(stitched, path='D:/Scratch/DataConvert/Daymet_Data/Full/' ,
    filename=named, overwrite=TRUE)
}
</code>```

The goal of this loop is to apply the function "mosaicList" to the images within each sub-directory. The problem is, when the for loop runs, the object "in.list" contains the same sub-directories as "days" instead of listing the images within the sub-directories. As a result it tries to run my function for every sub-directory at the same time and I get the error

```<code>Error: cannot allocate vector of size 14.2 Gb
</code>```

I am new to R so I'm not quite sure where I've gone wrong. Does anyone have any insight into fixing this problem?

答:
There's an issue with the list.files in your loop:

```<code>in.list <- list.files(recursive = T, full.names = F)
</code>```

The default path parameter for list.files is ".", which is the current directory. Perhaps changing to:

```<code>in.list <- list.files(path=days[j], recursive = T, full.names = T)
</code>```

Will fix.

Body:
I have a large directory with 365 sub-directories that contain images for each day of the year. I created a function that I want to apply to each of the images within these sub directories. At the moment, this is what I have:

library(raster)
library(zebu)

#List all of the 365 sub-directories within my main directory
days <- list.files(full.names = F , recursive =F, pattern='*X2000*')

#Apply my function to each directory within "days"
for(j in 1:length(days)){

    named <- paste0("full_",j)

    in.list <- list.files(recursive = T, full.names = F)

    stitched <- mosaicList(in.list)

    writeRaster(stitched, path='D:/Scratch/DataConvert/Daymet_Data/Full/' ,
    filename=named, overwrite=TRUE)
}

The goal of this loop is to apply the function "mosaicList" to the images within each sub-directory. The problem is, when the for loop runs, the object "in.list" contains the same sub-directories as "days" instead of listing the images within the sub-directories. As a result it tries to run my function for every sub-directory at the same time and I get the error

Error: cannot allocate vector of size 14.2 Gb

I am new to R so I'm not quite sure where I've gone wrong. Does anyone have any insight into fixing this problem?

Body:
There's an issue with the list.files in your loop:

in.list <- list.files(recursive = T, full.names = F)

The default path parameter for list.files is ".", which is the current directory. Perhaps changing to:

in.list <- list.files(path=days[j], recursive = T, full.names = T)

Will fix.


问:
OData exception with especific string
I have a trouble when i try to search in a container. My code is it:

```<code>Dim strtextbox As String = "<p>This B2C tenant must be linked to an active Azure subscription for communication, support and billing. <a href='https://learn.microsoft.com/azure/active-directory-b2c/active-directory-b2c-how-to-enable-billing' target='_blank' aria-label='Learn More - This B2C tenant must be linked to an active Azure subscription for communication, support and billing.'>Learn More</a></p>\r\n<p><b>If your Subscription status is No Subscription, please link this B2C tenant to an Azure subscription,</b></p>\r\n<p>\r\n    <ol>\r\n        <li><a href='#menu/account'>Switch Directories</a> to the location of your target Azure subscription</li>\r\n        <li>Under Marketplace, search for and select 'B2C'</li>\r\n        <li>Select Create to link this B2C Tenant to a subscription</li>\r\n    </ol>\r\n</p>\r\n<p><b>If your Subscription status is Warned, Suspended or Deleted, navigate to the linked Subscription for more information,</b></p>\r\n<p>\r\n    <ol>\r\n        <li><a href='#menu/account'>Switch Directories</a> to the location of the Azure subscription linked to this B2C Tenant</li>\r\n        <li>Under All Resources click on your B2C Tenant resource</li>\r\n        <li>Under Essentials select your subscription and review Subscription status</li>\r\n    </ol>\r\n</p>"

Dim res = cont.Entity.Where(Function(b) String.Compare(b.FullSourceString, strtextbox, True) = 0)

For Each j As Entity in res

     do something
End For
</code>```

Well, the problem is with that string and others html large strings. The odata.client "An error ocurred while processing this request" throws me an exception. If i modify 2 or 3 things from the string, this works. The uri works fine with that strings. The problem i think is with OData protocol.

Some help?

Thanks in advance

答:
I believe you need to escape any single quotes by doubling them up.</p>

```<code>strtextbox = strtextbox.Replace("'", "''")
</code>```

Title: OData exception with especific string

Body:
I have a trouble when i try to search in a container. My code is it:

Dim strtextbox As String = "
This B2C tenant must be linked to an active Azure subscription for communication, support and billing. Learn More
\r\n
If your Subscription status is No Subscription, please link this B2C tenant to an Azure subscription,
\r\n
\r\n
\r\n
Switch Directories to the location of your target Azure subscription
\r\n
Under Marketplace, search for and select 'B2C'
\r\n
Select Create to link this B2C Tenant to a subscription
\r\n
\r\n
\r\n
If your Subscription status is Warned, Suspended or Deleted, navigate to the linked Subscription for more information,
\r\n
\r\n
\r\n
Switch Directories to the location of the Azure subscription linked to this B2C Tenant
\r\n
Under All Resources click on your B2C Tenant resource
\r\n
Under Essentials select your subscription and review Subscription status
\r\n
\r\n
"

Dim res = cont.Entity.Where(Function(b) String.Compare(b.FullSourceString, strtextbox, True) = 0)

For Each j As Entity in res

     do something
End For

Well, the problem is with that string and others html large strings. The odata.client "An error ocurred while processing this request" throws me an exception. If i modify 2 or 3 things from the string, this works. The uri works fine with that strings. The problem i think is with OData protocol.

Some help?

Thanks in advance

Body:
I believe you need to escape any single quotes by doubling them up.

strtextbox = strtextbox.Replace("'", "''")


问:
How can an array value be SIX chars long and echoing nothing (string(6) " ")?
This is really weird. Look what is on my screen right now :

```<code>$albumGenre : array(6) {
  [0]=>
  string(5) "Noise"
  [1]=>
  string(6) " "
  [2]=>
  string(5) "Blues"
  [3]=>
  string(5) "Blues"
  [4]=>
  string(5) "Blues"
  [5]=>
  string(5) "Blues"
}
</code>```

This is just the output of :

```<code>var_dump($albumGenre);
</code>```

Can you see where it says [1]=>  string(6) " " ??? How can it be that an array value is SIX chars long, but is only seen as " " ?

I know what this value is. It's an "Unknown" mp3 tag. Fine, it's unknow, I just want to get rid of it then. But I can't test for it, if PHP can't reliably tell me what the hell this array value really IS to HIM, see ?

I guess my question really is : How can I really know what's inside an array ? Is'nt var_dump($array) the correct way to know everything about $array ?

答:
Maybe there are 6 Whitespaces.

Repeating whitespaces will collapse to only one whitespace when displayed inside a browser-window.(except you use a ```-element)

ContentLicense: CC BY-SA 2.5

Body:
This is really weird. Look what is on my screen right now :

$albumGenre : array(6) {
  [0]=>
  string(5) "Noise"
  [1]=>
  string(6) " "
  [2]=>
  string(5) "Blues"
  [3]=>
  string(5) "Blues"
  [4]=>
  string(5) "Blues"
  [5]=>
  string(5) "Blues"
}

This is just the output of :

var_dump($albumGenre);

Can you see where it says [1]=>  string(6) " " ??? How can it be that an array value is SIX chars long, but is only seen as " " ?

I know what this value is. It's an "Unknown" mp3 tag. Fine, it's unknow, I just want to get rid of it then. But I can't test for it, if PHP can't reliably tell me what the hell this array value really IS to HIM, see ?

I guess my question really is : How can I really know what's inside an array ? Is'nt var_dump($array) the correct way to know everything about $array ?

Body:
Maybe there are 6 Whitespaces.

Repeating whitespaces will collapse to only one whitespace when displayed inside a browser-window.(except you use a <pre>-element)


问:
Given only vector of dates, expand data in between (unequal) date points
Other questions have centered around having a start and end date. (see the following for examples
Given start date and end date, reshape/expand data for each day between (each day on a row)
Expand rows by date range using start and end date

My question is different in that I only have one date column and I would like to convert the unequal date ranges to daily counts. This specific example created deals with number of workers on a job site at one time. Different crews of people come on different dates

A brief data frame provided is as follows:

```<code>dd <- data.frame(date=as.Date(c("1999-03-22","1999-03-29","1999-04-08")),work=c(43,95,92),cumwork=c(43,138,230))
</code>```

I would like the data to look like this:

```<code>dw <- data.frame(date=c(seq(as.Date("1999-03-22"),as.Date("1999-04-10"),by= "day")),
       work=c(rep(43,7),rep(95,10),rep(92,3)),
       cumwork=c(rep(43,7),rep(138,10),rep(230,3)))
</code>```

I have been stuck on this for some time. Any help would be appreciated!

UPDATE (7/5/2017): As pointed out by @Scarabee the dates in the dataframe 'dd' should be in date format. Have updated the code to reflect this

答:
A possible way:

First, create the sequence of dates you're interested in as a one-column dataframe:

```<code>v <- data.frame(date = seq(min(dd$date), as.Date("1999-04-10"), by="day"))
</code>```

Next, join with your original dataframe and fill the missing values, for instance using dplyr and zoo:

```<code>library(dplyr)
library(zoo)

v %>%
  left_join(dd, by = "date") %>%
  na.locf
</code>```

NB: I suppose that your dataframe dd actually contains dates (and not factors).

```<code>dd <- data.frame(date=as.Date(c("1999-03-22","1999-03-29","1999-04-08")),work=c(43,95,92),cumwork=c(43,138,230))
</code>```

Body:
Other questions have centered around having a start and end date. (see the following for examples
Given start date and end date, reshape/expand data for each day between (each day on a row)
Expand rows by date range using start and end date

My question is different in that I only have one date column and I would like to convert the unequal date ranges to daily counts. This specific example created deals with number of workers on a job site at one time. Different crews of people come on different dates

A brief data frame provided is as follows:

dd <- data.frame(date=as.Date(c("1999-03-22","1999-03-29","1999-04-08")),work=c(43,95,92),cumwork=c(43,138,230))

I would like the data to look like this:

dw <- data.frame(date=c(seq(as.Date("1999-03-22"),as.Date("1999-04-10"),by= "day")),
       work=c(rep(43,7),rep(95,10),rep(92,3)),
       cumwork=c(rep(43,7),rep(138,10),rep(230,3)))

I have been stuck on this for some time. Any help would be appreciated!

UPDATE (7/5/2017): As pointed out by @Scarabee the dates in the dataframe 'dd' should be in date format. Have updated the code to reflect this

Body:
A possible way:

First, create the sequence of dates you're interested in as a one-column dataframe:

v <- data.frame(date = seq(min(dd$date), as.Date("1999-04-10"), by="day"))

Next, join with your original dataframe and fill the missing values, for instance using dplyr and zoo:

library(dplyr)
library(zoo)

v %>%
  left_join(dd, by = "date") %>%
  na.locf

NB: I suppose that your dataframe dd actually contains dates (and not factors).

dd <- data.frame(date=as.Date(c("1999-03-22","1999-03-29","1999-04-08")),work=c(43,95,92),cumwork=c(43,138,230))


问:
Is it possible to select text boxes with javaScript in acrobat
I would like to be able to use the JavaScript function of one of my form inputs to be able to show or hide a text box. After a lot of research I can only find how to select and hide other form input methods.

here is what I have:

var supplyBudget = this.getField("Supply Budget").value;
if (supplyBudget == ""){
/*text box selector*/.style.display = 3;
}
else if (supplyBudget =="0"){
/*text box selector*/.style.display = 3;
}
else{
/*text box selector*/.style.display = 1;
}```

This runs when the user leaves the input field.

*edited code in accordance with  freginold's comment

答:
There are no "selectors" in Acrobat JavaScript. However, you can get the number of fields and then iterate to get the names in order to find the ones that are of interest. For example if I wanted to hide all fields where the name starts with "name", I might write...

```<code>for ( var i = 0; i < this.numFields; i++) {
    var field = this.getField(this.getNthFieldName(i));
    if ( field.name.indexOf("name") > -1 ) {
      field.display = display.hidden
    }
}
</code>```

In general, to hide a field use...

```<code>this.getField("myFieldName").display = display.hidden;
</code>```

To show a hidden field use...

```<code>this.getField("myFieldName").display = display.visible;
</code>```

Body:
I would like to be able to use the JavaScript function of one of my form inputs to be able to show or hide a text box. After a lot of research I can only find how to select and hide other form input methods.

here is what I have:

var supplyBudget = this.getField("Supply Budget").value;
if (supplyBudget == ""){
/*text box selector*/.style.display = 3;
}
else if (supplyBudget =="0"){
/*text box selector*/.style.display = 3;
}
else{
/*text box selector*/.style.display = 1;
}

This runs when the user leaves the input field.

*edited code in accordance with  freginold's comment

Body:
There are no "selectors" in Acrobat JavaScript. However, you can get the number of fields and then iterate to get the names in order to find the ones that are of interest. For example if I wanted to hide all fields where the name starts with "name", I might write...

for ( var i = 0; i < this.numFields; i++) {
    var field = this.getField(this.getNthFieldName(i));
    if ( field.name.indexOf("name") > -1 ) {
      field.display = display.hidden
    }
}

In general, to hide a field use...

this.getField("myFieldName").display = display.hidden;

To show a hidden field use...

this.getField("myFieldName").display = display.visible;


问:
Angular 2: check radio button on div click
i want to check radio button, get value and add class 'selected' to sectionBlock when user clicks on div

please help not getting how to do this in angular 2

selectPlant(){
    console.log('');
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="SectionContent">
    <div class="sectionBlock" (click)="selectPlant($event)"><input type="radio" class="plant" name="plant" value="AEP" /><span>AEP</span></div>
    <div class="sectionBlock" (click)="selectPlant($event)"><input type="radio" class="plant" name="plant" value="ELP" /><span>ELP</span></div>
    <div class="sectionBlock" (click)="selectPlant($event)"><input type="radio" class="plant" name="plant" value="HCL" /><span>HCL</span></div>
    <div class="sectionBlock" (click)="selectPlant($event)"><input type="radio" class="plant" name="plant" value="HCM" /><span>HCM</span></div>
    <div class="sectionBlock" (click)="selectPlant($event)"><input type="radio" class="plant" name="plant" value="HDA" /><span>HDA</span></div>
    <div class="sectionBlock" (click)="selectPlant($event)"><input type="radio" class="plant" name="plant" value="HMA" /><span>HMA</span></div>
    <div class="sectionBlock" (click)="selectPlant($event)"><input type="radio" class="plant" name="plant" value="HMI" /><span>HMI</span></div>
    <div class="sectionBlock" (click)="selectPlant($event)"><input type="radio" class="plant" name="plant" value="HSC" /><span>HSC</span></div>
    <div class="sectionBlock" (click)="selectPlant($event)"><input type="radio" class="plant" name="plant" value="MAP" /><span>MAP</span></div>
    <div class="sectionBlock" (click)="selectPlant($event)"><input type="radio" class="plant" name="plant" value="MMP" /><span>MMP</span></div>
    <div class="sectionBlock" (click)="selectPlant($event)"><input type="radio" class="plant" name="plant" value="PMC" /><span>PMC</span></div>
  </div></code>```

答:
Use directive ngClass when the radio is selected, you have something variable selectedInput

example with one

```<code>div [ngClass]="{'sectionBlock': selectedInput}" (click)="selectPlant('AEP')">
</code>```

Body:
i want to check radio button, get value and add class 'selected' to sectionBlock when user clicks on div

please help not getting how to do this in angular 2

selectPlant(){
    console.log('');
  }

<input type="radio" class="plant" name="plant" value="AEP" />AEP

<input type="radio" class="plant" name="plant" value="ELP" />ELP

<input type="radio" class="plant" name="plant" value="HCL" />HCL

<input type="radio" class="plant" name="plant" value="HCM" />HCM

<input type="radio" class="plant" name="plant" value="HDA" />HDA

<input type="radio" class="plant" name="plant" value="HMA" />HMA

<input type="radio" class="plant" name="plant" value="HMI" />HMI

<input type="radio" class="plant" name="plant" value="HSC" />HSC

<input type="radio" class="plant" name="plant" value="MAP" />MAP

<input type="radio" class="plant" name="plant" value="MMP" />MMP

<input type="radio" class="plant" name="plant" value="PMC" />PMC

Body:
Use directive ngClass when the radio is selected, you have something variable selectedInput

example with one

div [ngClass]="{'sectionBlock': selectedInput}" (click)="selectPlant('AEP')">


问:
Pandas: How to use LocIndexer?
I am trying to figure out how to use a Locindexer object to select a subset of a dataframe.

For example

var = df.loc(df['rating'] == 4)

Returns as

pandas.core.indexing._LocIndexer

How do I use a LocIndexer to select the a subset of my dataframe?

答:
Furthermore if you have selected the row with:

```<code>subset = df.loc[(df['rating'] == 4)]
</code>```

you can acces a special column of this row with

1.

```<code>df.loc[(df['rating'] == 4)]["column]
</code>```

2.

```<code>subset["column"]
</code>```

Title: Pandas: How to use LocIndexer?

Body:
Furthermore if you have selected the row with:

subset = df.loc[(df['rating'] == 4)]

you can acces a special column of this row with

1.

df.loc[(df['rating'] == 4)]["column]

2.

subset["column"]


问:
Drawing on top of multiple JButtons
So, I have multiple objects of the class Square, which is the subclass of JButton. I have an instance of the class Board, which contains a few instances of Square. What I want to do is when I press one of the buttons (squares), draw a shape (a circle) on top of it. For doing that, I have a boolean variable in the Square class, namely isClicked, that basically decides what has to be drawn in the paintComponent method.

The problem is that buttons start to behave in a weird way when I have a few of them. Surprisingly, if there is only one of them, there is no problem at all. At first, I had thought the problem might be related to threads, however, I put the main code into invokeLater method and that did not help at all.

I saw a solution using BufferedImage, but I would like to see if there is any possibility to solve the problem doing it my way.

Sorry for possibly not perfect English.

Square class:

```<code>public class Square extends JButton implements ActionListener {

private int number;
private boolean isClicked;

public Square(int x) {
    number = x;
    isClicked = false;
}

@Override
protected void paintComponent(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    if (!isClicked) {
        super.paintComponent(g);
    } else {
        System.out.println("EXECUTED for: " + number);
        g2d.drawOval(this.getX(), this.getY(), 100, 100);
    }
}

@Override
public void actionPerformed(ActionEvent e) {
    isClicked = !isClicked;
    System.out.println(isClicked + " " + number);
    repaint();
}

}
</code>```

Board class:

```<code>public class Board extends JPanel {

private static final int BOARD_WIDTH = (int) (TicTacToe.WIDTH * 0.7);
private static final int VERTICAL_LINE_LENGTH = (int) (TicTacToe.WIDTH * 0.5);
private static final int HORIZONTAL_LINE_LENGTH = (int) (TicTacToe.HEIGHT * 0.8);
private static final int STROKE_WIDTH = 5;

private Square[] squares;

public Board() {

}

public void addButtons() {
    squares = new Square[9];

    for (int i = 0; i < 3; i++) {
            Square square = new Square(i);
            square.setPreferredSize(new Dimension(30, 30));
            square.addActionListener(square);
            this.add(square);
            squares[i] = square;
            ((GridLayout)this.getLayout()).setHgap(30);
            ((GridLayout)this.getLayout()).setVgap(30);
    }
}

public Square[] getButtons() {
    return squares;
}

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;
    g2d.setStroke(new BasicStroke(STROKE_WIDTH));
    // Horiztontal lines
    g2d.drawLine(0, TicTacToe.HEIGHT / 3,
            BOARD_WIDTH, TicTacToe.HEIGHT / 3);
    g2d.drawLine(0, 2 * TicTacToe.HEIGHT / 3,
            BOARD_WIDTH, 2 * TicTacToe.HEIGHT / 3);
    // Vertical lines
    g2d.drawLine(BOARD_WIDTH / 3, 0, BOARD_WIDTH / 3,
            TicTacToe.HEIGHT);
    g2d.drawLine(2 * BOARD_WIDTH / 3, 0, 2 * BOARD_WIDTH / 3,
            TicTacToe.HEIGHT);

}
}
</code>```

Main method:

```<code>SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            Board board = new Board();
    board.setPreferredSize(new Dimension((int) (WIDTH * 0.7), HEIGHT));
    board.setLayout(new GridLayout(3, 3));
    board.addButtons();

    GameOptions opt = new GameOptions();
    opt.setPreferredSize(new Dimension((int) (WIDTH * 0.3), HEIGHT));

    JFrame frame = new JFrame("Tic Tac Toe");
    frame.setLayout(new FlowLayout());
    frame.add(board);
    frame.add(opt);

    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
        }
    });
</code>```

答:
Your use of getX() and getY() on the button's drawing code is completely wrong and does not belong. These methods return the location of the button relative to its container, and so while this might work for a button located at the upper left, it will fail for anything else since you'll end up drawing somewhere far away from the button itself, and so many of your drawings will never show.

You'd be much better off not extending JButton but instead simply swapping ImageIcons that display what you want drawn on the JButton. This is much simpler and much more idiot-proof. You set the button's icon by calling .setIcon(myImageIcon) on it, passing in the icon of choice.

But if you absolutely wanted to draw on the button, you'd do so without using getX() or getY(). You'd also probably want to use a JToggleButton as the parent class, since you're toggling state. For example, my MCVE:

```<code>import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.image.BufferedImage;
import javax.swing.*;

@SuppressWarnings("serial")
public class DrawButtonPanel extends JPanel {
    private static final int SIDE = 3;
    private static final int GAP = 5;
    private static final Color BG = Color.BLACK;

    public DrawButtonPanel() {
        setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
        setLayout(new GridLayout(SIDE, SIDE, GAP, GAP));
        setBackground(BG);
        for (int i = 0; i < SIDE * SIDE; i++) {
            // add(new DrawButton1());
            DrawButton2 drawButton2 = new DrawButton2(i);
            AbstractButton button = drawButton2.getButton();
            add(button);
        }
    }

    private static void createAndShowGui() {
        JFrame frame = new JFrame("Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new DrawButtonPanel());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

class DrawButton2 {
    private static final int PREF_W = 200;
    private static final int PREF_H = PREF_W;
    private static final int GAP = 20;
    private static final float STROKE_WIDTH = 15f;
    private static final Stroke BASIC_STROKE = new BasicStroke(STROKE_WIDTH);
    private static final Color COLOR = Color.RED;
    private static final Color BG = Color.LIGHT_GRAY;
    private AbstractButton button = new JToggleButton();
    private int index;

    public DrawButton2(int index) {
        this.index = index;
        button.setBorderPainted(false);
        button.setBorder(null);
        button.setIcon(createPlainIcon());
        button.setSelectedIcon(createSelectedIcon());

        button.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    System.out.println("Index: " + index);
                }
            }
        });
    }

    public int getIndex() {
        return index;
    }

    private Icon createPlainIcon() {
        BufferedImage img = new BufferedImage(PREF_W, PREF_H, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = img.createGraphics();
        g2d.setColor(new Color(0, 0, 0, 0));
        g2d.fillRect(0, 0, PREF_W, PREF_H);
        g2d.dispose();
        return new ImageIcon(img);
    }

    private Icon createSelectedIcon() {
        BufferedImage img = new BufferedImage(PREF_W, PREF_H, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = img.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setStroke(BASIC_STROKE);
        g2d.setColor(BG);
        g2d.fillRect(0, 0, PREF_W, PREF_H);
        g2d.setColor(COLOR);
        g2d.drawOval(GAP, GAP, PREF_W - 2 * GAP, PREF_H - 2 * GAP);
        g2d.dispose();
        return new ImageIcon(img);
    }

    public AbstractButton getButton() {
        return button;
    }

}

@SuppressWarnings("serial")
class DrawButton1 extends JToggleButton {
    private static final int PREF_W = 200;
    private static final int PREF_H = PREF_W;
    private static final int GAP = 20;
    private static final float STROKE_WIDTH = 15f;
    private static final Stroke BASIC_STROKE = new BasicStroke(STROKE_WIDTH);
    private static final Color COLOR = Color.RED;
    private static final Color BG = Color.LIGHT_GRAY;

    @Override
    public Dimension getPreferredSize() {
        if (isPreferredSizeSet()) {
            return super.getPreferredSize();
        }
        return new Dimension(PREF_W, PREF_H);
    }

    @Override
    protected void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D) g.create();
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setStroke(BASIC_STROKE);
        if (!isSelected()) {
            super.paintComponent(g);
        } else {
            g2d.setColor(BG);
            g2d.fillRect(0, 0, getWidth(), getHeight());
            g2d.setColor(COLOR);
            g2d.drawOval(GAP, GAP, getWidth() - 2 * GAP, getHeight() - 2 * GAP);
        }
        g2d.dispose(); // since we created a new one
    }
}
</code>```

Edited to show how to do this with JToggleButton and icons.

Title: Drawing on top of multiple JButtons

Body:
So, I have multiple objects of the class Square, which is the subclass of JButton. I have an instance of the class Board, which contains a few instances of Square. What I want to do is when I press one of the buttons (squares), draw a shape (a circle) on top of it. For doing that, I have a boolean variable in the Square class, namely isClicked, that basically decides what has to be drawn in the paintComponent method.

The problem is that buttons start to behave in a weird way when I have a few of them. Surprisingly, if there is only one of them, there is no problem at all. At first, I had thought the problem might be related to threads, however, I put the main code into invokeLater method and that did not help at all.

I saw a solution using BufferedImage, but I would like to see if there is any possibility to solve the problem doing it my way.

Sorry for possibly not perfect English.

Square class:

public class Square extends JButton implements ActionListener {

private int number;
private boolean isClicked;

public Square(int x) {
    number = x;
    isClicked = false;
}

@Override
protected void paintComponent(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    if (!isClicked) {
        super.paintComponent(g);
    } else {
        System.out.println("EXECUTED for: " + number);
        g2d.drawOval(this.getX(), this.getY(), 100, 100);
    }
}

@Override
public void actionPerformed(ActionEvent e) {
    isClicked = !isClicked;
    System.out.println(isClicked + " " + number);
    repaint();
}

}

Board class:

public class Board extends JPanel {

private static final int BOARD_WIDTH = (int) (TicTacToe.WIDTH * 0.7);
private static final int VERTICAL_LINE_LENGTH = (int) (TicTacToe.WIDTH * 0.5);
private static final int HORIZONTAL_LINE_LENGTH = (int) (TicTacToe.HEIGHT * 0.8);
private static final int STROKE_WIDTH = 5;

private Square[] squares;

public Board() {

}

public void addButtons() {
    squares = new Square[9];

    for (int i = 0; i < 3; i++) {
            Square square = new Square(i);
            square.setPreferredSize(new Dimension(30, 30));
            square.addActionListener(square);
            this.add(square);
            squares[i] = square;
            ((GridLayout)this.getLayout()).setHgap(30);
            ((GridLayout)this.getLayout()).setVgap(30);
    }
}

public Square[] getButtons() {
    return squares;
}

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;
    g2d.setStroke(new BasicStroke(STROKE_WIDTH));
    // Horiztontal lines
    g2d.drawLine(0, TicTacToe.HEIGHT / 3,
            BOARD_WIDTH, TicTacToe.HEIGHT / 3);
    g2d.drawLine(0, 2 * TicTacToe.HEIGHT / 3,
            BOARD_WIDTH, 2 * TicTacToe.HEIGHT / 3);
    // Vertical lines
    g2d.drawLine(BOARD_WIDTH / 3, 0, BOARD_WIDTH / 3,
            TicTacToe.HEIGHT);
    g2d.drawLine(2 * BOARD_WIDTH / 3, 0, 2 * BOARD_WIDTH / 3,
            TicTacToe.HEIGHT);

}
}

Main method:

SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            Board board = new Board();
    board.setPreferredSize(new Dimension((int) (WIDTH * 0.7), HEIGHT));
    board.setLayout(new GridLayout(3, 3));
    board.addButtons();

    GameOptions opt = new GameOptions();
    opt.setPreferredSize(new Dimension((int) (WIDTH * 0.3), HEIGHT));

    JFrame frame = new JFrame("Tic Tac Toe");
    frame.setLayout(new FlowLayout());
    frame.add(board);
    frame.add(opt);

    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
        }
    });

Body:
Your use of getX() and getY() on the button's drawing code is completely wrong and does not belong. These methods return the location of the button relative to its container, and so while this might work for a button located at the upper left, it will fail for anything else since you'll end up drawing somewhere far away from the button itself, and so many of your drawings will never show.

You'd be much better off not extending JButton but instead simply swapping ImageIcons that display what you want drawn on the JButton. This is much simpler and much more idiot-proof. You set the button's icon by calling .setIcon(myImageIcon) on it, passing in the icon of choice.

But if you absolutely wanted to draw on the button, you'd do so without using getX() or getY(). You'd also probably want to use a JToggleButton as the parent class, since you're toggling state. For example, my MCVE:

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.image.BufferedImage;
import javax.swing.*;

@SuppressWarnings("serial")
public class DrawButtonPanel extends JPanel {
    private static final int SIDE = 3;
    private static final int GAP = 5;
    private static final Color BG = Color.BLACK;

    public DrawButtonPanel() {
        setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
        setLayout(new GridLayout(SIDE, SIDE, GAP, GAP));
        setBackground(BG);
        for (int i = 0; i < SIDE * SIDE; i++) {
            // add(new DrawButton1());
            DrawButton2 drawButton2 = new DrawButton2(i);
            AbstractButton button = drawButton2.getButton();
            add(button);
        }
    }

    private static void createAndShowGui() {
        JFrame frame = new JFrame("Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new DrawButtonPanel());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

class DrawButton2 {
    private static final int PREF_W = 200;
    private static final int PREF_H = PREF_W;
    private static final int GAP = 20;
    private static final float STROKE_WIDTH = 15f;
    private static final Stroke BASIC_STROKE = new BasicStroke(STROKE_WIDTH);
    private static final Color COLOR = Color.RED;
    private static final Color BG = Color.LIGHT_GRAY;
    private AbstractButton button = new JToggleButton();
    private int index;

    public DrawButton2(int index) {
        this.index = index;
        button.setBorderPainted(false);
        button.setBorder(null);
        button.setIcon(createPlainIcon());
        button.setSelectedIcon(createSelectedIcon());

        button.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    System.out.println("Index: " + index);
                }
            }
        });
    }

    public int getIndex() {
        return index;
    }

    private Icon createPlainIcon() {
        BufferedImage img = new BufferedImage(PREF_W, PREF_H, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = img.createGraphics();
        g2d.setColor(new Color(0, 0, 0, 0));
        g2d.fillRect(0, 0, PREF_W, PREF_H);
        g2d.dispose();
        return new ImageIcon(img);
    }

    private Icon createSelectedIcon() {
        BufferedImage img = new BufferedImage(PREF_W, PREF_H, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = img.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setStroke(BASIC_STROKE);
        g2d.setColor(BG);
        g2d.fillRect(0, 0, PREF_W, PREF_H);
        g2d.setColor(COLOR);
        g2d.drawOval(GAP, GAP, PREF_W - 2 * GAP, PREF_H - 2 * GAP);
        g2d.dispose();
        return new ImageIcon(img);
    }

    public AbstractButton getButton() {
        return button;
    }

}

@SuppressWarnings("serial")
class DrawButton1 extends JToggleButton {
    private static final int PREF_W = 200;
    private static final int PREF_H = PREF_W;
    private static final int GAP = 20;
    private static final float STROKE_WIDTH = 15f;
    private static final Stroke BASIC_STROKE = new BasicStroke(STROKE_WIDTH);
    private static final Color COLOR = Color.RED;
    private static final Color BG = Color.LIGHT_GRAY;

    @Override
    public Dimension getPreferredSize() {
        if (isPreferredSizeSet()) {
            return super.getPreferredSize();
        }
        return new Dimension(PREF_W, PREF_H);
    }

    @Override
    protected void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D) g.create();
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setStroke(BASIC_STROKE);
        if (!isSelected()) {
            super.paintComponent(g);
        } else {
            g2d.setColor(BG);
            g2d.fillRect(0, 0, getWidth(), getHeight());
            g2d.setColor(COLOR);
            g2d.drawOval(GAP, GAP, getWidth() - 2 * GAP, getHeight() - 2 * GAP);
        }
        g2d.dispose(); // since we created a new one
    }
}

Edited to show how to do this with JToggleButton and icons.


问:
How to determine the date passing the Week Number and Day Number (Week) in java
I need to get the date by passing these parameters

year

week number (in a month) i.e. 1,2,3,4,5

day number (in a week) 0 (Sunday) to 6 (Saturday)

Month

I looked for a constructor in Calendar class but does not contain these parameters.

答:
To create date from year, week number and week's day use java.util.Calendar instance:

```<code>Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, 2017);
        cal.set(Calendar.WEEK_OF_YEAR, 26);
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
</code>```

To convert from Calendar to java.util.Date :

```<code>Date date = cal.getTime();
</code>```

To convert Date into java.time.LocalDateTime use :

```<code>LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
</code>```

Body:
To create date from year, week number and week's day use java.util.Calendar instance:

Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, 2017);
        cal.set(Calendar.WEEK_OF_YEAR, 26);
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);

To convert from Calendar to java.util.Date :

Date date = cal.getTime();

To convert Date into java.time.LocalDateTime use :

LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());


问:
JS Calendar two days short
I'm building a calendar using Javascript (Vue JS). I have this little method to help get the days in the month:

```<code>daysInYearMonth(y,m){
  return new Date(y, m, 0).getDate()
}
</code>```

If I console.log the above I get 31 as it's July. However, when it comes time to use this value:

```<code>this.days = [...Array(this.daysInYearMonth(this.year,
  this.month)).keys()]
}
</code>```

I console.log this.days and get 29 days, two short. If I simply try to add two then the other months are off. Here is my CodePen.

NOTE: I am intentionally not using Moment.js and even though I agree it's better, the team decided to go with only Vue and vanilla JS.

答:
First of all:

In return new Date(y, m, 0).getDate()
you should use m + 1, as 0 takes the last day of the previous month (see http://www.w3resource.com/javascript-exercises/javascript-date-exercise-3.php)

Secondly:

this.days is zero-based, but days in a month aren't. So, you count from 0-30 instead of 1-31.

I hope this helps you out. Greets

Title: JS Calendar two days short

Body:
I'm building a calendar using Javascript (Vue JS). I have this little method to help get the days in the month:

daysInYearMonth(y,m){
  return new Date(y, m, 0).getDate()
}

If I console.log the above I get 31 as it's July. However, when it comes time to use this value:

this.days = [...Array(this.daysInYearMonth(this.year,
  this.month)).keys()]
}

I console.log this.days and get 29 days, two short. If I simply try to add two then the other months are off. Here is my CodePen.

NOTE: I am intentionally not using Moment.js and even though I agree it's better, the team decided to go with only Vue and vanilla JS.


问:
Why is .insert not adding entry text into array (Python)
This part of my code is the problem: I want to add names to Name_List by entering text into the entry widget. Then use the "add" button to insert the item into Name_List by the function add_name.

```<code>import tkinter as tk
from tkinter import *

Name_List = []

...

class NamePage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self,parent)
        name=StringVar()
        name_entry= tk.Entry(self, text="Enter name:", textvariable=name)
        name_entry.pack()
        add_button= tk.Button(self, text="Add",
                              command=lambda: self.add_name(name))
        add_button.pack()
        To_Role_List= tk.Button(self, text="Assign Roles",
                                command=lambda: self.print_namelist())
        To_Role_List.pack()

    def add_name(self,name,i=0):
        Name_List.insert(i, name)
        print(Name_List)
        i+=1

    def print_namelist(self):
        for i in [0,len(Name_List)]:
            print (Name_List[i])

app=TOS_outline()
app.mainloop()
</code>```

My result, after entering the name "Alpha" into the Entry widget, appears to be this (using print of course):

```<code>[<tkinter.StringVar object at 0x03E7D650>]
</code>```

What do I need to change/fix?

答: You are passing the variable to .insert instead of its value. Name_List.insert(i, name) must be Name_List.insert(i, name.get()).

Body:
This part of my code is the problem: I want to add names to Name_List by entering text into the entry widget. Then use the "add" button to insert the item into Name_List by the function add_name.

import tkinter as tk
from tkinter import *

Name_List = []

...

class NamePage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self,parent)
        name=StringVar()
        name_entry= tk.Entry(self, text="Enter name:", textvariable=name)
        name_entry.pack()
        add_button= tk.Button(self, text="Add",
                              command=lambda: self.add_name(name))
        add_button.pack()
        To_Role_List= tk.Button(self, text="Assign Roles",
                                command=lambda: self.print_namelist())
        To_Role_List.pack()

    def add_name(self,name,i=0):
        Name_List.insert(i, name)
        print(Name_List)
        i+=1

    def print_namelist(self):
        for i in [0,len(Name_List)]:
            print (Name_List[i])

app=TOS_outline()
app.mainloop()

My result, after entering the name "Alpha" into the Entry widget, appears to be this (using print of course):

[<tkinter.StringVar object at 0x03E7D650>]

What do I need to change/fix?


问:
Hide a view when a dependent view is hidden in ConstraintLayout
Is it possible in ContraintLayout to hide/show a view when a dependent view is gone/visible?

Obviously it's possible by using CoordinatorLayout with a custom behavior or by using an wrapped layout, however the mentioned approaches involve additional layouts. I would like to see such an approach that doesn't introduce additional layouts

答:
You should be able to group the views together using the new "group" feature of ConstraintLayout 1.1.x. See this posting on Medium.

Groups, like the Guidelines, are widgets with size 0. But Group helps to apply some action to a set of widgets. The most common case, is to control a visibility of a collection of widgets.


问:
Why is F# compiler sometimes incorrectly generalizing functions?
I ran into some unexpected behavior from the F# compiler recently. I was able to find a workaround, but the original behavior baffles me and I wanted to see if anyone can help me understand what causes it.

A function that I had defined as non-generic was becoming generic, which interfered with the ability of the function to share state between multiple invocations. I simplified my use-case down to the following:

```<code>let nextId =
  let mutable i = 0
  let help (key:obj) =
    i <- i + 1
    i
  help
nextId "a" // returns 1
nextId "b" // also returns 1!!!!
</code>```

Why is nextId of type 'a -> int instead of obj -> int? Clearly the generalization is also responsible for the bug where it returns 1 repeatedly, but why is the generalization occurring in the first place?

Note that if I define it without naming the nested function, it works as expected in giving unique Ids:

```<code>let nextId =
  let mutable i = 0
  fun (key:obj) ->
    i <- i + 1
    i
nextId "a" // returns 1
nextId "b" // returns 2
</code>```

But even more mysterious, with this definition, F# Interactive can't decide whether nextId is an (obj -> int) or an ('a -> int). When I first define it I get

val nextId : (obj -> int)

but if I simply eval

```<code>nextId
</code>```

I get

val it : ('a -> int)

What's going on here and why does my simple function get automatically generalized?

答:
I agree that this is quite unexpected behaviour. I think the reason why F# performs the generalization is that it treats help (when returning it) as fun x -> help x. Calling a function that takes obj seems to be one case where the compiler performs generalization (because it knows that anything can be obj). The same generalization happens, for example, in:

```<code>let foo (o:obj) = 1
let g = fun z -> foo z
</code>```

Here, g becomes 'a -> int too, just like in your first version. I don't quite know why the compiler does this, but what you see can be explained by 1) treating help as fun x -> help x and 2) generalising on calls taking obj.

The other thing that is happening is how F# treats generic values - generic values are generally problematic in ML languages (that's what the whole "value restriction" business is about), but F# allows it in some limited cases - you can for example write:

```<code>let empty = []
</code>```

This defines a generic value of type 'a list. The caveat is that this gets compiled as a function that is called every time you access the empty value. I think your first nextId function gets compiled in the same way - so the body is evaluated each time you access it.

This probably does not answer the why but I hope it provides some more tips on how this is happening - and in what other cases the behaviour you're seeing might be sensible!

Body:
I ran into some unexpected behavior from the F# compiler recently. I was able to find a workaround, but the original behavior baffles me and I wanted to see if anyone can help me understand what causes it.

A function that I had defined as non-generic was becoming generic, which interfered with the ability of the function to share state between multiple invocations. I simplified my use-case down to the following:

let nextId =
  let mutable i = 0
  let help (key:obj) =
    i <- i + 1
    i
  help
nextId "a" // returns 1
nextId "b" // also returns 1!!!!

Why is nextId of type 'a -> int instead of obj -> int? Clearly the generalization is also responsible for the bug where it returns 1 repeatedly, but why is the generalization occurring in the first place?

Note that if I define it without naming the nested function, it works as expected in giving unique Ids:

let nextId =
  let mutable i = 0
  fun (key:obj) ->
    i <- i + 1
    i
nextId "a" // returns 1
nextId "b" // returns 2

But even more mysterious, with this definition, F# Interactive can't decide whether nextId is an (obj -> int) or an ('a -> int). When I first define it I get

val nextId : (obj -> int)

but if I simply eval

nextId

I get

val it : ('a -> int)

What's going on here and why does my simple function get automatically generalized?

Body:
I agree that this is quite unexpected behaviour. I think the reason why F# performs the generalization is that it treats help (when returning it) as fun x -> help x. Calling a function that takes obj seems to be one case where the compiler performs generalization (because it knows that anything can be obj). The same generalization happens, for example, in:

let foo (o:obj) = 1
let g = fun z -> foo z

Here, g becomes 'a -> int too, just like in your first version. I don't quite know why the compiler does this, but what you see can be explained by 1) treating help as fun x -> help x and 2) generalising on calls taking obj.

The other thing that is happening is how F# treats generic values - generic values are generally problematic in ML languages (that's what the whole "value restriction" business is about), but F# allows it in some limited cases - you can for example write:

let empty = []

This defines a generic value of type 'a list. The caveat is that this gets compiled as a function that is called every time you access the empty value. I think your first nextId function gets compiled in the same way - so the body is evaluated each time you access it.

This probably does not answer the why but I hope it provides some more tips on how this is happening - and in what other cases the behaviour you're seeing might be sensible!


问:
Rating prediction in non negative matrix factorization
I was following this blog http://www.quuxlabs.com/blog/2010/09/matrix-factorization-a-simple-tutorial-and-implementation-in-python/ (Also attaching the matrix here)for the rating prediction using matrix factorization . Initially we have a sparse user-movie matrix R .

We then apply the MF algorithm so as to create a new matrix R' which is the product of 2 matrix P(UxK) and Q(DxK) . We then "minimize" the error in the value given in R and R' .So far so good . But in the final step , when the matrix is filled up , I am not so convinced that these are the predicted values that the user will give . Here is the final matrix:

What is the basis of justification that these are in fact the "predicted" ratings . Also , I am planning to use the P matrix (UxK) as the user's latent features . Can we somehow "justify" that these are infact user's latent features ?

答:
The justification for using the  obtained vectors for each user as latent trait vectors is that using these values of the latent latent traits will minimize the error between the predicted ratings and the actual known ratings.

If you take a look at the predicted ratings and the known ratings in the two diagrams that you posted you can see that the difference between the two matrixes in the cells that are common to both is very small. Example: U1D4 is 1 in the first diagram and 0.98 in the second.

Since the features or user latent trait vector produces good  results on the known ratings we think that it would do a good job on predicting the unknown ratings. Of course, we use regularisation to avoid overfitting the training data, but that is the general idea.