问:
DynamoDB Pagination via Boto3, NextToken is not present but LastEvaluatedKey is?
The documentation for boto3 and dynamodb paginators specify that NextToken should be returned when paging, and you would then include that token in the next query for StartingToken to resume a paging session (as would happen when accessing information via a RESTful API).

However, my testing shows that it doesn't return NextToken in the results, but rather LastEvaluatedKey. I was thinking I could use LastEvaluatedKey as the token, but that doesn't work?

```<code>paginator = client.get_paginator('scan')
page_iterator = paginator.paginate(TableName='test1', PaginationConfig={'PageSize': 1 , 'MaxItems': 5000,  'MaxSize': 1 })

    for page in page_iterator:
        print(page)
        break
</code>```

I would expect the page object returned from the page_iterator to include NextToken Key but it does not?

```<code>{'Items': [{'PK': {'S': '99'}, 'SK': {'S': '99'}, 'data': {'S': 'Test Item 99'}}], 'Count': 1, 'ScannedCount': 1, 'LastEvaluatedKey': {'PK': {'S': '99'}, 'SK': {'S': '99'}}, 'ResponseMetadata': {'RequestId': 'DUE559L8KVKVH8H7G0G2JH0LUNVV4KQNSO5AEMVJF66Q9ASUAAJG', 'HTTPStatusCode': 200, 'HTTPHeaders': {'server': 'Server', 'date': 'Mon, 27 May 2019 14:22:09 GMT', 'content-type': 'application/x-amz-json-1.0', 'content-length': '153', 'connection': 'keep-alive', 'x-amzn-requestid': 'DUE559L8KVKVH8H7G0G2JH0LUNVV4KQNSO5AEMVJF66Q9ASUAAJG', 'x-amz-crc32': '3759060959'}, 'RetryAttempts': 0}}
</code>```

What am I missing?

UPDATE: Somehow related to this? How to use Boto3 pagination

答:
There are a few ways to address this using the boto3 scan paginator.

The first option is to call build_full_result like so:

```<code>result = paginator.paginate(TableName="your_table", PaginationConfig={"MaxItems":10, "PageSize": 10}).build_full_result()
</code>```

That returns a response with 10 items, and 'NextToken' is populated provided there are more than 10 items. This is probably the simplest way, you can just treat the MaxItems as your returned page size and if 'NextToken' is empty you are at the end of the scan.

I noticed if you don't specify a page size the results are the same, but the consumed capacity and 'ScannedCount' are higher.

Another way is to do the encoding of the 'StartingToken' using the TokenEncoder in botocore.paginate directly.

If the initial call to the paginator is like:

```<code>pagination_config = {
    "MaxItems": 5000,
    "PageSize": 10,
}

scan_iterator = scan_paginator.paginate(
    TableName="your_table_name",
    PaginationConfig=pagination_config
)
</code>```

The paged results will be as the question describes. The first 10 results will be returned in the first page, and 'NextToken' isn't specified but 'LastEvaluatedKey' is.

To use it, encode the returned 'LastEvaluatedKey' as the 'ExclusiveStartKey' and pass that into as the 'StartingToken' in the pagination config.

```<code>from botocore.paginate import TokenEncoder
encoder = TokenEncoder()
for page in scan_iterator:
    if "LastEvaluatedKey" in page:
            encoded_token = encoder.encode({"ExclusiveStartKey": page["LastEvaluatedKey"]})
</code>```

Then:

```<code>pagination_config = {
    "MaxItems": 500,
    "PageSize": 10,
    "StartingToken": encoded_token
}
</code>```

The reason to encode the primary key as the 'ExclusiveStartKey' is that it's what the actual scan API expects. Essentially the paginators are encoding / decoding the 'LastEvaluatedKey' and 'ExclusiveStartKey' into the 'NextToken' and 'StartingToken' values. If you do a base64 decode of the 'NextToken' returned when doing build_full_result you'll see that it is also uses the 'ExclusiveStartKey'.

Body:
The documentation for boto3 and dynamodb paginators specify that NextToken should be returned when paging, and you would then include that token in the next query for StartingToken to resume a paging session (as would happen when accessing information via a RESTful API).

However, my testing shows that it doesn't return NextToken in the results, but rather LastEvaluatedKey. I was thinking I could use LastEvaluatedKey as the token, but that doesn't work?

paginator = client.get_paginator('scan')
page_iterator = paginator.paginate(TableName='test1', PaginationConfig={'PageSize': 1 , 'MaxItems': 5000,  'MaxSize': 1 })

    for page in page_iterator:
        print(page)
        break

I would expect the page object returned from the page_iterator to include NextToken Key but it does not?

{'Items': [{'PK': {'S': '99'}, 'SK': {'S': '99'}, 'data': {'S': 'Test Item 99'}}], 'Count': 1, 'ScannedCount': 1, 'LastEvaluatedKey': {'PK': {'S': '99'}, 'SK': {'S': '99'}}, 'ResponseMetadata': {'RequestId': 'DUE559L8KVKVH8H7G0G2JH0LUNVV4KQNSO5AEMVJF66Q9ASUAAJG', 'HTTPStatusCode': 200, 'HTTPHeaders': {'server': 'Server', 'date': 'Mon, 27 May 2019 14:22:09 GMT', 'content-type': 'application/x-amz-json-1.0', 'content-length': '153', 'connection': 'keep-alive', 'x-amzn-requestid': 'DUE559L8KVKVH8H7G0G2JH0LUNVV4KQNSO5AEMVJF66Q9ASUAAJG', 'x-amz-crc32': '3759060959'}, 'RetryAttempts': 0}}

What am I missing?

UPDATE: Somehow related to this? How to use Boto3 pagination

Body:
There are a few ways to address this using the boto3 scan paginator.

The first option is to call build_full_result like so:

result = paginator.paginate(TableName="your_table", PaginationConfig={"MaxItems":10, "PageSize": 10}).build_full_result()

That returns a response with 10 items, and 'NextToken' is populated provided there are more than 10 items. This is probably the simplest way, you can just treat the MaxItems as your returned page size and if 'NextToken' is empty you are at the end of the scan.

I noticed if you don't specify a page size the results are the same, but the consumed capacity and 'ScannedCount' are higher.

Another way is to do the encoding of the 'StartingToken' using the TokenEncoder in botocore.paginate directly.

If the initial call to the paginator is like:

pagination_config = {
    "MaxItems": 5000,
    "PageSize": 10,
}

scan_iterator = scan_paginator.paginate(
    TableName="your_table_name",
    PaginationConfig=pagination_config
)

The paged results will be as the question describes. The first 10 results will be returned in the first page, and 'NextToken' isn't specified but 'LastEvaluatedKey' is.

To use it, encode the returned 'LastEvaluatedKey' as the 'ExclusiveStartKey' and pass that into as the 'StartingToken' in the pagination config.

from botocore.paginate import TokenEncoder
encoder = TokenEncoder()
for page in scan_iterator:
    if "LastEvaluatedKey" in page:
            encoded_token = encoder.encode({"ExclusiveStartKey": page["LastEvaluatedKey"]})

Then:

pagination_config = {
    "MaxItems": 500,
    "PageSize": 10,
    "StartingToken": encoded_token
}

The reason to encode the primary key as the 'ExclusiveStartKey' is that it's what the actual scan API expects. Essentially the paginators are encoding / decoding the 'LastEvaluatedKey' and 'ExclusiveStartKey' into the 'NextToken' and 'StartingToken' values. If you do a base64 decode of the 'NextToken' returned when doing build_full_result you'll see that it is also uses the 'ExclusiveStartKey'.


来源: stackexchange

问:
How to retrieve button position?
I've created a Relative layout that will change a button position when I touch it. Using OnTouchListener. But I want when I release the button (ACTION_UP), it go to it's own position before this operation. Can anyone help me out please?

My code : (inside on Create)

...

```<code>this.relative_layout.setOnTouchListener(new OnTouchListener()
            {

            @Override
            public boolean onTouch(View view, MotionEvent event)
            {
                // TODO: Implement this method
                if(event.getAction() == event.ACTION_MOVE)
                {
                    float x = event.getX();
                    float y = event.getY();
                    my_button.setX(x);
                    my_button.setY(y);
                } else if(event.getAction() == event.ACTION_UP)
                /* here's the issue that I'm
                 * asking for help about
                 * What to do to return the button position back
                 * Like it was? */
                    return true;
            }

        });
</code>```

答:
According to the doc, setX does:

Sets the visual x position of this view, in pixels. This is
  equivalent to setting the translationX property to be the difference
  between the x value passed in and the current left property.

So to reverse that, use setTranslationX(0);

Same thing for the Y-  setTranslationY(0);

ContentLicense: CC BY-SA 4.0

Title: How to retrieve button position?

Body:
I've created a Relative layout that will change a button position when I touch it. Using OnTouchListener. But I want when I release the button (ACTION_UP), it go to it's own position before this operation. Can anyone help me out please?

My code : (inside on Create)

...

this.relative_layout.setOnTouchListener(new OnTouchListener()
            {

            @Override
            public boolean onTouch(View view, MotionEvent event)
            {
                // TODO: Implement this method
                if(event.getAction() == event.ACTION_MOVE)
                {
                    float x = event.getX();
                    float y = event.getY();
                    my_button.setX(x);
                    my_button.setY(y);
                } else if(event.getAction() == event.ACTION_UP)
                /* here's the issue that I'm
                 * asking for help about
                 * What to do to return the button position back
                 * Like it was? */
                    return true;
            }

        });


问:
MQTT connection creation and subscribe
I'm setting up a new mqtt conection in my app but there is a problem when i would like to create the main connection of mqtt.

I'm using mqtt.js.

I've tried all what is done in MQTT documentation but nothing happens..

```<code>mqttFunction(){
  var mqtt = require('mqtt');
  var client = mqtt.connect([{host: 'localhost', port: '1883'},]);

  client.subscribe('presence')
  client.on('message', function (topic, message) {
  console.log(message);
});
}
</code>```

I expect the output of the mqtt broker to be 'ON' when i asked it to respond.
The error is: ERROR ReferenceError: process is not defined

答:
The documentation you followed is intended for Node.js and various other back-end JavaScript frameworks. Even though it uses NPM, Ionic ultimately produces a front-end framework, and its applications run a bit differently.

For example, Ionic programs may not have a global process variable like Node.js. mqtt.js expects this variable, with code like:

if (commist.parse(process.argv.slice(2)) !== null){...}

You could declare a process object, and get past this particular error. Other obstacles could come up.

var process = {env : {NODE_ENV: 'production'}}

If there are still issues with that, you could try the instructions for browser usage, which point to a specially compiled version, like https://unpkg.com/mqtt@3.0.0/dist/mqtt.min.js. I have had less luck with mqtt.js in the browser, and you may want an alternative like web-mqtt-cient / Paho if more complex connections are involved.

Title: MQTT connection creation and subscribe

Body:
I'm setting up a new mqtt conection in my app but there is a problem when i would like to create the main connection of mqtt.

I'm using mqtt.js.

I've tried all what is done in MQTT documentation but nothing happens..

mqttFunction(){
  var mqtt = require('mqtt');
  var client = mqtt.connect([{host: 'localhost', port: '1883'},]);

  client.subscribe('presence')
  client.on('message', function (topic, message) {
  console.log(message);
});
}

I expect the output of the mqtt broker to be 'ON' when i asked it to respond.
The error is: ERROR ReferenceError: process is not defined


问:
How can i send the Map Object in multipart request in flutter
Here I am trying to send the Object Map in the multipart request but my request is going as a string, not in JSON format please suggest me to do correct request. Thanks in advance.

I have tried the multipart request but my request should be in correct form..

```<code>var getApiUrl = 'http://malik-env-test.ap-south-1.elasticbeanstalk.com/webapi/post/create';

  Map userData = {

    "creator": {
      "creatorId": "298",
      "createDate": "2018-12-21 20:44:45.8"
    },
    "info": "$campusInfo",
    "title": "$eventName",
    "postCampusId": "5642"

  };

</code>```

```<code>Uri uri = Uri.parse(getApiUrl);
   http.MultipartRequest request = new http.MultipartRequest('POST', uri);
   request.fields['creator'] = userData['creator'];
   request.fields['info'] = '$campusInfo';
   request.fields['title'] = '$eventName';
   request.fields['postCampusId'] = '5642';
   request.files.add(await http.MultipartFile.fromPath('image_file1', imagePath, contentType: new MediaType('application', 'x-tar')));
//   var body = json.encode(request);
   print(request);
   http.StreamedResponse response = await request.send();
   String jsonData = response.toString();
   print(jsonData);ddd
</code>```

答:
Try:

```<code>request.fields['userData'] = json.encode(userData);
</code>```

You need to find out from the API spec or server owner what field name to use for the json. I've assumed userData.

If you want control over the media type, encoding, etc, add it as a file like this:

```<code>  request.files.add(
    http.MultipartFile.fromBytes(
      'the_form_field name',
      utf8.encode(json.encode(userData)),
      contentType: MediaType(
        'application',
        'json',
        {'charset': 'utf-8'},
      ),
    ),
  );
</code>```

Body:
Here I am trying to send the Object Map in the multipart request but my request is going as a string, not in JSON format please suggest me to do correct request. Thanks in advance.

I have tried the multipart request but my request should be in correct form..

var getApiUrl = 'http://malik-env-test.ap-south-1.elasticbeanstalk.com/webapi/post/create';

  Map userData = {

    "creator": {
      "creatorId": "298",
      "createDate": "2018-12-21 20:44:45.8"
    },
    "info": "$campusInfo",
    "title": "$eventName",
    "postCampusId": "5642"

  };

Uri uri = Uri.parse(getApiUrl);
   http.MultipartRequest request = new http.MultipartRequest('POST', uri);
   request.fields['creator'] = userData['creator'];
   request.fields['info'] = '$campusInfo';
   request.fields['title'] = '$eventName';
   request.fields['postCampusId'] = '5642';
   request.files.add(await http.MultipartFile.fromPath('image_file1', imagePath, contentType: new MediaType('application', 'x-tar')));
//   var body = json.encode(request);
   print(request);
   http.StreamedResponse response = await request.send();
   String jsonData = response.toString();
   print(jsonData);ddd

Body:
Try:

request.fields['userData'] = json.encode(userData);

You need to find out from the API spec or server owner what field name to use for the json. I've assumed userData.

If you want control over the media type, encoding, etc, add it as a file like this:

  request.files.add(
    http.MultipartFile.fromBytes(
      'the_form_field name',
      utf8.encode(json.encode(userData)),
      contentType: MediaType(
        'application',
        'json',
        {'charset': 'utf-8'},
      ),
    ),
  );


问:
How To Index Range Of 2-D Numpy Array From Different Start Points Sourced From Other Array
I am attempting to extract out and perform math on the subset of one numpy array that is of shape (3,32), the subset of data I am attempting to extract out is that of shape (3,9) and the ranges of this data originate at the indices contained in another array size (3). As an example, I have a data set of values from three channels operating in the time domain and I extract the index of the max value of each channel into an array

a = np.random.randint(20,size = (3,32))
a
array([[18,  3, 10,  6, 12,  1, 10,  8,  4, 11, 13, 14,  9,  9, 10,  2,
         9,  0,  0, 16, 14, 19,  1, 19, 14, 19, 19,  2, 14,  0,  4, 18],
       [ 9, 19,  2, 12,  0, 14, 18,  7,  3,  0,  7,  3, 12, 19,  4,  2,
         5,  9,  2, 11, 15, 19, 16, 17,  3,  4, 17,  5,  6,  1,  2, 17],
       [ 0, 11, 18,  8,  9,  2,  9, 15,  9,  6,  0,  8,  9, 16,  9,  6,
         1, 19,  1,  9, 12,  8,  0,  0,  7, 15,  3, 14, 15,  8, 10, 19]])
b = np.argmax(a,1)
b
array([21,  1, 17], dtype=int64)
```

<p>my goal at this point is to derive a new array consisting of the three values from each of the indexes specified.  For instance I would be looking to extract out :</p>

<pre class="lang-py prettyprint-override"><code>[21,22,23] from a[0]
[1,2,3] from a[1]
[17,18,19] from a[2]
</code>```

all into a new array of size [3,3]

I've been able to achieve this using loops already but I suspect that there is a more efficient way of producing this result without loops (speed is a bit of an issue with this application).  I have been able to effect a similar result by manually populating a smaller matrix manually ...

c = np.asarray([[1,2,3],[2,3,4],[3,4,5]])
a[np.arange(3)[:,None],c]
array([[ 3, 10,  6],
       [ 2, 12,  0],
       [ 8,  9,  2]])
```

<p>However, given the dynamic nature of this application I would like to write this such that it can be dynamically scaled (range of indeces out to 9 values beyond the root index, etc).  I just don't know if there is such a way to do this.  I have used syntax similar to the following in an effort to slice the array ...</p>

<pre class="lang-py prettyprint-override"><code>a[np.arange(3)[:,None],b[:]:(b[:] + 2)]
</code>```

resulting in error messages in the nature of ...

builtins.TypeError: only integer scalar arrays can be converted to a scalar index
```

答:
Since you say you cannot overflow, this gets much less tricky.  In general, since you have your starting indices, you can use basic broadcasting to create an (n, 3) shape array with your indices, and use take_along_axis to pull those elements from the original array.

```<code>np.take_along_axis(a, b[:, None] + np.arange(3), axis=1)
</code>```

```<code>array([[19,  1, 19],
       [19,  2, 12],
       [19,  1,  9]])
</code>```

Body:
I am attempting to extract out and perform math on the subset of one numpy array that is of shape (3,32), the subset of data I am attempting to extract out is that of shape (3,9) and the ranges of this data originate at the indices contained in another array size (3). As an example, I have a data set of values from three channels operating in the time domain and I extract the index of the max value of each channel into an array

a = np.random.randint(20,size = (3,32))
a
array([[18,  3, 10,  6, 12,  1, 10,  8,  4, 11, 13, 14,  9,  9, 10,  2,
         9,  0,  0, 16, 14, 19,  1, 19, 14, 19, 19,  2, 14,  0,  4, 18],
       [ 9, 19,  2, 12,  0, 14, 18,  7,  3,  0,  7,  3, 12, 19,  4,  2,
         5,  9,  2, 11, 15, 19, 16, 17,  3,  4, 17,  5,  6,  1,  2, 17],
       [ 0, 11, 18,  8,  9,  2,  9, 15,  9,  6,  0,  8,  9, 16,  9,  6,
         1, 19,  1,  9, 12,  8,  0,  0,  7, 15,  3, 14, 15,  8, 10, 19]])
b = np.argmax(a,1)
b
array([21,  1, 17], dtype=int64)

my goal at this point is to derive a new array consisting of the three values from each of the indexes specified.  For instance I would be looking to extract out :

[21,22,23] from a[0]
[1,2,3] from a[1]
[17,18,19] from a[2]

all into a new array of size [3,3]

I've been able to achieve this using loops already but I suspect that there is a more efficient way of producing this result without loops (speed is a bit of an issue with this application).  I have been able to effect a similar result by manually populating a smaller matrix manually ...

c = np.asarray([[1,2,3],[2,3,4],[3,4,5]])
a[np.arange(3)[:,None],c]
array([[ 3, 10,  6],
       [ 2, 12,  0],
       [ 8,  9,  2]])

However, given the dynamic nature of this application I would like to write this such that it can be dynamically scaled (range of indeces out to 9 values beyond the root index, etc).  I just don't know if there is such a way to do this.  I have used syntax similar to the following in an effort to slice the array ...

a[np.arange(3)[:,None],b[:]:(b[:] + 2)]

resulting in error messages in the nature of ...

builtins.TypeError: only integer scalar arrays can be converted to a scalar index

Body:
Since you say you cannot overflow, this gets much less tricky.  In general, since you have your starting indices, you can use basic broadcasting to create an (n, 3) shape array with your indices, and use take_along_axis to pull those elements from the original array.

np.take_along_axis(a, b[:, None] + np.arange(3), axis=1)

array([[19,  1, 19],
       [19,  2, 12],
       [19,  1,  9]])


问:
SQL distinct field combination disregard the position
Hi I have a SQL question:

Table: Flight

```<code>Origin  Destination
--------------------
Boston    LA
LA        Bostion
Newyork   LA
DC        Newyork
</code>```

How could I select the distinct combination of the fight path if I do not care origin or destination: (Boston to LA) = (LA to Boston)

答:
```<code>select distinct a1.f1,a1.f2 from
(select a.*,row_number() over() rn
from al_ofs_maps.flights a) a1
inner join
(select a.*,row_number() over() rn
from al_ofs_maps.flights a) a2
on a1.f1=a2.f2 and a1.f2=a2.f1
and a1.rn < a2.rn
union
select distinct  a.*
from al_ofs_maps.flights a
left outer join al_ofs_maps.flights b
on a.f1 = b.f2 and a.f2=b.f1
where b.f1 is null
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Hi I have a SQL question:

Table: Flight

Origin  Destination
--------------------
Boston    LA
LA        Bostion
Newyork   LA
DC        Newyork

How could I select the distinct combination of the fight path if I do not care origin or destination: (Boston to LA) = (LA to Boston)


问:
How can I show the differences between two programs?
I am giving a programming talk. Rather than use slides, I am presenting a sequence of incrementally longer programs, stored in filenames 0001.py, 0002.py, etc.

The code in each program introduces just one or a few lines of code as a modification to the preceding one.

I intend to present solely using emacs. I am familiar with ediff, but it would be a bit of a pain to use it live during a talk (as there are about 50 small programs, with one minute to introduce each increment).

Does there exist an emacs package that would allow me to split the window and to highlight what is actually different between (n).py and (n+1).py. (I'm using .py for concreteness, but hopefully the solution would work for any text file.)

I am asking here rather than on https://emacs.stackexchange.com because I will be happy with a solution using emacs, git, or any combination that I can string together to give a live demo, especially with the ability to modify the code live while answering questions.

Update

As phils suggests, M-x compare-windows almost solves this issue, but:

It would be nice if it works correctly regardless of the current position of the cursor in the two buffers.

It would be nice if all changes appear in one view, rather than iterating over the diffs. The point is to say "see, in the program on the right I've added just this line and that line, and look at all that that program can do compared to the previous one."

Update 2

In other words, how do I generate what is done manually in the HTML below to show the differences side-by-side?

.myflex {
  display: flex;
  flex-direction: row;
}

.before,
.after {
  border: 1px solid black;
  padding: 20px;
  margin: 20px;
  border-radius: 2px;
}

.pink {
  background-color: pink;
}

.green {
  background-color: PaleGreen;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="myflex">
  <div class="before">
    ```
And so without particularly analyzing all the contiguous sections of a
cone and of the ranks of an army, or the ranks and positions in any
while the less their direct participation in the action itself, the more
they command and the fewer of them there are; rising in this way from
the lowest ranks to the man at the top, who takes the least direct share
in the action and directs his activity chiefly to commanding.
        ```
  </div>
  <div class="after">
    ```
We see a law by which men, to take associated action, combine
in such relations that the more directly they participate in performing
the action the less they can command and the more numerous they are,
while the less their direct participation in the action itself, the more
they command and the fewer of them there are; rising in this way from
the lowest ranks to the man at the top, who takes the least direct share
in the action and directs his activity chiefly to commanding.
        ```
  </div>
</div></code>```

Sequel

(I'm only adding this sequel here because phils generously volunteered to answer more than I was initially asking for.)

Consider the program (in some imaginary language, stored in a .txt file):

```<code>hello
</code>```

and consider that we insert a keyword that requires indentation:

```<code>repeat:
    hello
</code>```

Now when we show the two programs in split-window, it would be nice if the hi is not highlighted, despite that the two lines differ by indentation; only the repeat: is.

The idea is that we'd be adding some loop operator and do not wish the gaze of the listener to go to either the indentation or to the entire line, only to the operator.

In other words, when displaying the difference, we would ideally highlight the repeat line, but neither hello nor the indentation preceding it.

答:
I suspect that some existing diff functionality can do this and so there'll be a better answer, but I've hacked the following together using compare-windows.

(defun my-compare-windows-complete (&optional ignore-whitespace)
  "Highlight all differences between two windows.

With a prefix argument, do not highlight whitespace-only differences.
\(This does not prevent the highlighting of whitespace that is part of
a difference which includes non-whitespace characters.)

To remove the highlighting, use \\[compare-windows-dehighlight]."
  (interactive "P")
  (require 'cl-lib)
  (require 'compare-w)
  (compare-windows-dehighlight)
  (let ((w1 (get-buffer-window))
        (w2 (funcall compare-windows-get-window-function)))
    (cl-letf ((w1p (window-point w1))
              (w2p (window-point w2))
              (compare-windows-highlight 'persistent)
              ((symbol-function 'compare-windows-dehighlight) #'ignore)
              ((symbol-function 'ding) (lambda () (error "done"))))
      (with-selected-window w1
        (goto-char (point-min)))
      (with-selected-window w2
        (goto-char (point-min)))
      (ignore-errors
        (while (compare-windows ignore-whitespace)))
      ;; Highlight any non-matching remainder in both buffers.
      (let ((b1 (window-buffer w1))
            (b2 (window-buffer w2))
            (p1 (window-point w1))
            (p2 (window-point w2))
            (max1 (with-selected-window w1 (point-max)))
            (max2 (with-selected-window w2 (point-max))))
        (compare-windows-highlight p1 max1 b1 w1 p2 max2 b2 w2))
      (set-window-point w1 w1p)
      (set-window-point w2 w2p))))
```

You can use M-x compare-windows-dehighlight afterwards to remove the highlighting.

The faces used for highlighting are:

compare-windows-removed (inheriting from diff-removed)

compare-windows-added (inheriting from diff-added)

Body:
I am giving a programming talk. Rather than use slides, I am presenting a sequence of incrementally longer programs, stored in filenames 0001.py, 0002.py, etc.

The code in each program introduces just one or a few lines of code as a modification to the preceding one.

I intend to present solely using emacs. I am familiar with ediff, but it would be a bit of a pain to use it live during a talk (as there are about 50 small programs, with one minute to introduce each increment).

Does there exist an emacs package that would allow me to split the window and to highlight what is actually different between (n).py and (n+1).py. (I'm using .py for concreteness, but hopefully the solution would work for any text file.)

I am asking here rather than on https://emacs.stackexchange.com because I will be happy with a solution using emacs, git, or any combination that I can string together to give a live demo, especially with the ability to modify the code live while answering questions.

Update

As phils suggests, M-x compare-windows almost solves this issue, but:

It would be nice if it works correctly regardless of the current position of the cursor in the two buffers.

It would be nice if all changes appear in one view, rather than iterating over the diffs. The point is to say "see, in the program on the right I've added just this line and that line, and look at all that that program can do compared to the previous one."

Update 2

In other words, how do I generate what is done manually in the HTML below to show the differences side-by-side?

.myflex {
  display: flex;
  flex-direction: row;
}

.before,
.after {
  border: 1px solid black;
  padding: 20px;
  margin: 20px;
  border-radius: 2px;
}

.pink {
  background-color: pink;
}

.green {
  background-color: PaleGreen;
}

And so without particularly analyzing all the contiguous sections of a
cone and of the ranks of an army, or the ranks and positions in any
while the less their direct participation in the action itself, the more
they command and the fewer of them there are; rising in this way from
the lowest ranks to the man at the top, who takes the least direct share
in the action and directs his activity chiefly to commanding.

We see a law by which men, to take associated action, combine
in such relations that the more directly they participate in performing
the action the less they can command and the more numerous they are,
while the less their direct participation in the action itself, the more
they command and the fewer of them there are; rising in this way from
the lowest ranks to the man at the top, who takes the least direct share
in the action and directs his activity chiefly to commanding.

Sequel

(I'm only adding this sequel here because phils generously volunteered to answer more than I was initially asking for.)

Consider the program (in some imaginary language, stored in a .txt file):

hello

and consider that we insert a keyword that requires indentation:

repeat:
    hello

Now when we show the two programs in split-window, it would be nice if the hi is not highlighted, despite that the two lines differ by indentation; only the repeat: is.

The idea is that we'd be adding some loop operator and do not wish the gaze of the listener to go to either the indentation or to the entire line, only to the operator.

In other words, when displaying the difference, we would ideally highlight the repeat line, but neither hello nor the indentation preceding it.

Body:
I suspect that some existing diff functionality can do this and so there'll be a better answer, but I've hacked the following together using compare-windows.

(defun my-compare-windows-complete (&optional ignore-whitespace)
  "Highlight all differences between two windows.

With a prefix argument, do not highlight whitespace-only differences.
\(This does not prevent the highlighting of whitespace that is part of
a difference which includes non-whitespace characters.)

To remove the highlighting, use \\[compare-windows-dehighlight]."
  (interactive "P")
  (require 'cl-lib)
  (require 'compare-w)
  (compare-windows-dehighlight)
  (let ((w1 (get-buffer-window))
        (w2 (funcall compare-windows-get-window-function)))
    (cl-letf ((w1p (window-point w1))
              (w2p (window-point w2))
              (compare-windows-highlight 'persistent)
              ((symbol-function 'compare-windows-dehighlight) #'ignore)
              ((symbol-function 'ding) (lambda () (error "done"))))
      (with-selected-window w1
        (goto-char (point-min)))
      (with-selected-window w2
        (goto-char (point-min)))
      (ignore-errors
        (while (compare-windows ignore-whitespace)))
      ;; Highlight any non-matching remainder in both buffers.
      (let ((b1 (window-buffer w1))
            (b2 (window-buffer w2))
            (p1 (window-point w1))
            (p2 (window-point w2))
            (max1 (with-selected-window w1 (point-max)))
            (max2 (with-selected-window w2 (point-max))))
        (compare-windows-highlight p1 max1 b1 w1 p2 max2 b2 w2))
      (set-window-point w1 w1p)
      (set-window-point w2 w2p))))

You can use M-x compare-windows-dehighlight afterwards to remove the highlighting.

The faces used for highlighting are:

compare-windows-removed (inheriting from diff-removed)

compare-windows-added (inheriting from diff-added)


问:
Matrix mirroring/transformation in Python
I'm looking for a Python function which, given the 2d array A, will output B:

```<code>A = [[a, b, c],
     [d, e, f],
     [g, h, i]]

B = [[a, d, g],
     [b, e, h],
     [c, f, i]]
</code>```

i.e. the first row becomes the first column, the second row becomes the second column etc.

Thanks.

Body:
I'm looking for a Python function which, given the 2d array A, will output B:

A = [[a, b, c],
     [d, e, f],
     [g, h, i]]

B = [[a, d, g],
     [b, e, h],
     [c, f, i]]

i.e. the first row becomes the first column, the second row becomes the second column etc.

Thanks.

Body:
A = [[a, b, c],
     [d, e, f],
     [g, h, i]]

B = zip(*A)


问:
Pass a lambda expression in place of iComparator in VB.Net
I have the following C# expression

```<code>var orderedMatches = matches.OrderBy((t1, t2) => t1.Item1 - t2.Item1).ToList();
</code>```

And am trying to translate to VB with Option Strict On, most translators produce something like below

```<code>Dim orderedMatches As List(Of Tuple(Of Integer, String)) = matches.OrderBy(Function(t1 As Tuple(Of Integer, String), t2 As Object) t1.Item1 - t2.Item1).ToList()
</code>```

Or just below and neither one compiles.

```<code>Dim orderedMatches As List(Of Tuple(Of Integer, String)) = matches.OrderBy(Function(t1, t2) t1.Item1 - t2.Item1).ToList()
</code>```

I have tried multiple converters and also setting Option Strict Off and setting T1 and T2 to Object.
The usual error is

```<code>BC36532 Nested function does not have the same signature as delegate 'Func(Of Tuple(Of Integer, String), Object)'
</code>```

OrderBy is defined as

```<code>Public Shared Function OrderBy(Of TSource, TKey)(source As IEnumerable(Of TSource), keySelector As Func(Of TSource, TKey)) As IOrderedEnumerable(Of TSource)
</code>```

or

```<code>Public Shared Function OrderBy(Of TSource, TKey)(source As IEnumerable(Of TSource), keySelector As Func(Of TSource, TKey), comparer As IComparer(Of TKey)) As IOrderedEnumerable(Of TSource)
</code>```

I need to code to compile with errors preferably with Option Strict On

答:
The syntax in VB.NET is like this:

```<code>Dim orderedMatches = matches.OrderBy(Function(x, y) x.Item1 - y.Item1).ToList()
</code>```

although your sort logic is buggy and crashes in my example with Int32.MinValues and Int32.MaxValues because of arithmetic overflows. A solid implementation could look like this:

```<code>Dim orderedMatches = matches.OrderBy(Function(x, y)
                                            If (x.Item1 < y.Item1) Then Return -1
                                            If (y.Item1 < x.Item1) Then Return 1
                                            Return 0
                                        End Function).ToList()
</code>```

Both examples above only work if there is somewhere an OrderBy extension method defined and imported (in C# as well as VB.NET), that works like this:

```<code><Extension>
Public Module BubbleSortLambda

    <Extension>
    Public Function OrderBy(Of T)(collection As IEnumerable(Of T), logic As Func(Of T, T, Int32)) As IEnumerable(Of T)
        If (collection Is Nothing) Then Throw New NullReferenceException() 'To simulate instance method behavior
        If (logic Is Nothing) Then logic = Function(x, y) 0
        Dim myComparer As New GenericComparer(Of T)(logic)
        Dim myArray As T() = collection.ToArray()
        Array.Sort(myArray, myComparer)
        Return myArray
    End Function

    Private Class GenericComparer(Of T)
        Implements IComparer(Of T)

        'Private Fields
        Private ReadOnly _SortLogic As Func(Of T, T, Int32)

        'Constructors

        Public Sub New(sortLogic As Func(Of T, T, Int32))
            If (sortLogic Is Nothing) Then Throw New ArgumentNullException(NameOf(sortLogic))
            _SortLogic = sortLogic
        End Sub

        'Public Methods
        Public Function Compare(x As T, y As T) As Int32 Implements IComparer(Of T).Compare
            'Handle null
            If (x Is Nothing) Then
                If (y Is Nothing) Then Return 0
                Return -1
            End If
            If (y Is Nothing) Then Return 1
            'Invoke logic
            Return _SortLogic(x, y)
        End Function

    End Class

End Module
</code>```

Body:
I have the following C# expression

var orderedMatches = matches.OrderBy((t1, t2) => t1.Item1 - t2.Item1).ToList();

And am trying to translate to VB with Option Strict On, most translators produce something like below

Dim orderedMatches As List(Of Tuple(Of Integer, String)) = matches.OrderBy(Function(t1 As Tuple(Of Integer, String), t2 As Object) t1.Item1 - t2.Item1).ToList()

Or just below and neither one compiles.

Dim orderedMatches As List(Of Tuple(Of Integer, String)) = matches.OrderBy(Function(t1, t2) t1.Item1 - t2.Item1).ToList()

I have tried multiple converters and also setting Option Strict Off and setting T1 and T2 to Object.
The usual error is

BC36532 Nested function does not have the same signature as delegate 'Func(Of Tuple(Of Integer, String), Object)'

OrderBy is defined as

Public Shared Function OrderBy(Of TSource, TKey)(source As IEnumerable(Of TSource), keySelector As Func(Of TSource, TKey)) As IOrderedEnumerable(Of TSource)

or

Public Shared Function OrderBy(Of TSource, TKey)(source As IEnumerable(Of TSource), keySelector As Func(Of TSource, TKey), comparer As IComparer(Of TKey)) As IOrderedEnumerable(Of TSource)

I need to code to compile with errors preferably with Option Strict On

Body:
The syntax in VB.NET is like this:

Dim orderedMatches = matches.OrderBy(Function(x, y) x.Item1 - y.Item1).ToList()

although your sort logic is buggy and crashes in my example with Int32.MinValues and Int32.MaxValues because of arithmetic overflows. A solid implementation could look like this:

Dim orderedMatches = matches.OrderBy(Function(x, y)
                                            If (x.Item1 < y.Item1) Then Return -1
                                            If (y.Item1 < x.Item1) Then Return 1
                                            Return 0
                                        End Function).ToList()

Both examples above only work if there is somewhere an OrderBy extension method defined and imported (in C# as well as VB.NET), that works like this:

<Extension>
Public Module BubbleSortLambda

    <Extension>
    Public Function OrderBy(Of T)(collection As IEnumerable(Of T), logic As Func(Of T, T, Int32)) As IEnumerable(Of T)
        If (collection Is Nothing) Then Throw New NullReferenceException() 'To simulate instance method behavior
        If (logic Is Nothing) Then logic = Function(x, y) 0
        Dim myComparer As New GenericComparer(Of T)(logic)
        Dim myArray As T() = collection.ToArray()
        Array.Sort(myArray, myComparer)
        Return myArray
    End Function

    Private Class GenericComparer(Of T)
        Implements IComparer(Of T)

        'Private Fields
        Private ReadOnly _SortLogic As Func(Of T, T, Int32)

        'Constructors

        Public Sub New(sortLogic As Func(Of T, T, Int32))
            If (sortLogic Is Nothing) Then Throw New ArgumentNullException(NameOf(sortLogic))
            _SortLogic = sortLogic
        End Sub

        'Public Methods
        Public Function Compare(x As T, y As T) As Int32 Implements IComparer(Of T).Compare
            'Handle null
            If (x Is Nothing) Then
                If (y Is Nothing) Then Return 0
                Return -1
            End If
            If (y Is Nothing) Then Return 1
            'Invoke logic
            Return _SortLogic(x, y)
        End Function

    End Class

End Module


问:
python pandas - set column value of column based on index and or ID of concatenated dataframes
I have a concatenated dataframe of at least two concatenated dataframes:

```<code>i.e.
df1
  Name | Type | ID
0 Joe     A     1
1 Fred    B     2
2 Mike   Both   3
3 Frank  Both   4

df2
  Name | Type | ID
0 Bill   Both    1
1 Jill   Both    2
2 Mill   B       3
3 Hill   A       4

ConcatDf:
  Name | Type | ID
0 Joe     A     1
1 Fred    B     2
2 Mike   Both   3
3 Frank  Both   4
0 Bill   Both   1
1 Jill   Both   2
2 Mill   B      3
3 Hill   A      4
</code>```

Suppose after they are concatenated, I'd like to set Type for all records from df1 to C and all records from df2 to B. Is this possible?

The indices of the dataframes can be vastly different sizes.

Thanks in advance.

答:
```<code>df3 = pd.concat([df1,df2], keys = (1,2))

df3.loc[(1), 'Type'] == 'C'
</code>```

When you concat you can assign the df's keys. This will create a multi-index with the keys separating the concatonated df's. Then when you use .loc with keys you can use( around the key to call the group. In the code above we would change all the Types of df1 (which has a key of 1) to C.

Body:
I have a concatenated dataframe of at least two concatenated dataframes:

i.e.
df1
  Name | Type | ID
0 Joe     A     1
1 Fred    B     2
2 Mike   Both   3
3 Frank  Both   4

df2
  Name | Type | ID
0 Bill   Both    1
1 Jill   Both    2
2 Mill   B       3
3 Hill   A       4

ConcatDf:
  Name | Type | ID
0 Joe     A     1
1 Fred    B     2
2 Mike   Both   3
3 Frank  Both   4
0 Bill   Both   1
1 Jill   Both   2
2 Mill   B      3
3 Hill   A      4

Suppose after they are concatenated, I'd like to set Type for all records from df1 to C and all records from df2 to B. Is this possible?

The indices of the dataframes can be vastly different sizes.

Thanks in advance.

Body:
df3 = pd.concat([df1,df2], keys = (1,2))

df3.loc[(1), 'Type'] == 'C'

When you concat you can assign the df's keys. This will create a multi-index with the keys separating the concatonated df's. Then when you use .loc with keys you can use( around the key to call the group. In the code above we would change all the Types of df1 (which has a key of 1) to C.


问:
Object Cell/Range doesn't support .Font property in VBA
I'm trying to colour code cells to give the user a warning about which cell's data is incorrect before running a calculation. Currently throwing a:

run time error 438 object doesn't support property

when trying to run through all the data.

Basically creating a worksheet to allow the user to input some data on a consist, then based off some back end data/restrictions, spit out an answer of what they can/can't do. I've got a level of error checking already in the initial code as the user inputs data (basically to try and encourage them to make sure the data they're inputting is valid before they try and run the calculation) and this works fine using a Worksheet_Change subroutine which can loop through all cells one at a time (within the target range) no worries.

If I try replicate this (using a named range instead of the Target cells from the change function) it seems to do one of two things: it will try and send through a range of cells, rather than individual cells and fail when it tries to match data from the "cells" rather than the single cell it should be trying to match, OR it will throw the 438 error when it tries to colour it in.

Private Sub CommandButton1_Click()
    Dim ErrorWagonPack As Boolean, ErrorCellsNotEmpty As Boolean, WagonPack As Integer, cel As Range, Target As Range

    ErrorWagonPack = False
    ErrorCellsNotEmpty = False
    Set Target = Application.Range("ConsistInput")

    For Each cel In Target 'issue is here somewhere I think. It's related to how the cel is created and as such what properties it can have
        Application.EnableEvents = False
        WagonPack = 0
        If Len(cel.Value) > 0 Then
            WagonPack = Application.Index(Application.Range("WagonData"), Application.Match(cel.Value, Application.Range("WagonData").Columns(1), 0), 4)
            If cel.Offset(0, 1).Value Mod WagonPack > 0 Then
                ErrorWagonPack = True
                cel.Font.ColourIndex = RGB(156, 0, 6) '438 error here
                cel.Interior.ColourIndex = RGB(255, 199, 206) '438 error here too
            End If
        End If
    Next cel

If ErrorWagonPack = True Or ErrorCellsNotEmpty = True Then
    Exit Sub
End If

'calculate stuff
Application.EnableEvents = True
End Sub
```

Ideally I'd like to get to a point where I run the code, colour the cells causing issues/with incorrect data, then if doesn't throw any error variables, run the calculation but the 438 error seems to be the sticking point. I'm almost willing to bet it's something simple I'm just missing but can't figure it out. Probably doesn't help I'm still pretty green with VBA.

答:
The .ColorIndex property is between 1 and 56:

```<code>Sub TestMe()

    Dim cel As Range
    Set cel = Worksheets(1).Range("A1")
    cel.Interior.ColorIndex = 1
    cel.Font.ColorIndex = 20

End Sub
</code>```

The 2 RGB values go way further than 56:

```<code>Sub TestMe()

    Debug.Print RGB(156, 0, 6)          '393372
    Debug.Print RGB(255, 199, 206)      '13551615

End Sub
</code>```

Thus, the only values to be safely used are the 56 red values, between:

cel.Font.ColorIndex = RGB(56, 0, 0)

and

cel.Font.ColorIndex = RGB(1, 0, 0)

As an alternative, without using ColorIndex the Range().Font.Color supports the complete RGB values:

```<code>Range("A1").Font.Color = RGB(100, 20, 255)
</code>```

Body:
I'm trying to colour code cells to give the user a warning about which cell's data is incorrect before running a calculation. Currently throwing a:

run time error 438 object doesn't support property

when trying to run through all the data.

Basically creating a worksheet to allow the user to input some data on a consist, then based off some back end data/restrictions, spit out an answer of what they can/can't do. I've got a level of error checking already in the initial code as the user inputs data (basically to try and encourage them to make sure the data they're inputting is valid before they try and run the calculation) and this works fine using a Worksheet_Change subroutine which can loop through all cells one at a time (within the target range) no worries.

If I try replicate this (using a named range instead of the Target cells from the change function) it seems to do one of two things: it will try and send through a range of cells, rather than individual cells and fail when it tries to match data from the "cells" rather than the single cell it should be trying to match, OR it will throw the 438 error when it tries to colour it in.

Private Sub CommandButton1_Click()
    Dim ErrorWagonPack As Boolean, ErrorCellsNotEmpty As Boolean, WagonPack As Integer, cel As Range, Target As Range

    ErrorWagonPack = False
    ErrorCellsNotEmpty = False
    Set Target = Application.Range("ConsistInput")

    For Each cel In Target 'issue is here somewhere I think. It's related to how the cel is created and as such what properties it can have
        Application.EnableEvents = False
        WagonPack = 0
        If Len(cel.Value) > 0 Then
            WagonPack = Application.Index(Application.Range("WagonData"), Application.Match(cel.Value, Application.Range("WagonData").Columns(1), 0), 4)
            If cel.Offset(0, 1).Value Mod WagonPack > 0 Then
                ErrorWagonPack = True
                cel.Font.ColourIndex = RGB(156, 0, 6) '438 error here
                cel.Interior.ColourIndex = RGB(255, 199, 206) '438 error here too
            End If
        End If
    Next cel

If ErrorWagonPack = True Or ErrorCellsNotEmpty = True Then
    Exit Sub
End If

'calculate stuff
Application.EnableEvents = True
End Sub

Ideally I'd like to get to a point where I run the code, colour the cells causing issues/with incorrect data, then if doesn't throw any error variables, run the calculation but the 438 error seems to be the sticking point. I'm almost willing to bet it's something simple I'm just missing but can't figure it out. Probably doesn't help I'm still pretty green with VBA.

Body:
The .ColorIndex property is between 1 and 56:

Sub TestMe()

    Dim cel As Range
    Set cel = Worksheets(1).Range("A1")
    cel.Interior.ColorIndex = 1
    cel.Font.ColorIndex = 20

End Sub

The 2 RGB values go way further than 56:

Sub TestMe()

    Debug.Print RGB(156, 0, 6)          '393372
    Debug.Print RGB(255, 199, 206)      '13551615

End Sub

Thus, the only values to be safely used are the 56 red values, between:

cel.Font.ColorIndex = RGB(56, 0, 0)

and

cel.Font.ColorIndex = RGB(1, 0, 0)

As an alternative, without using ColorIndex the Range().Font.Color supports the complete RGB values:

Range("A1").Font.Color = RGB(100, 20, 255)


问:
Use sfinae to single out preferred variadic constructor
I'm trying to write a policy-based class that forwards arguments to its unique super class, but also optionally takes some arguments of its own. The problem I'm facing is, the compiler seems to unconditionally prefer the second constructor below in the face of an implicit conversion - with only the parameter pack - over the first, which is the one I prefer.

#include <utility>
#include <iostream>

template <class Super>
struct Base : public Super {
  // 1
  template <typename... Args,
            typename = std::enable_if_t<std::is_constructible_v<Super, Args&&...>>>
  explicit Base(unsigned long count, Args&&... args)
    : Super(std::forward<Args>(args)...), count(count) {}

  // 2
  template <typename... Args,
            typename = std::enable_if_t<std::is_constructible_v<Super, Args&&...>>>
  explicit Base(Args&&... args) : Super(std::forward<Args>(args)...), count(0) {}

  unsigned long count;
};

struct A {
  explicit A(unsigned long id) {}
  A() {}
};

struct B {
  explicit B(const char* cstring) {}
  explicit B(unsigned long id, const char* cstring) {}
  explicit B(unsigned long id, A a) {}
  B() {}
};

int main() {
  auto a1 = Base(7);             // selects 2, but I want 1
  auto a2 = Base(7ul);           // selects 1
  auto a3 = Base(7, 10);         // selects 1
  auto b1 = Base(4);             // selects 1
  auto b2 = Base("0440");        // selects 2
  auto b3 = Base(4, "0440");     // selects 2, but I want 1
  auto b4 = Base(4, 4, "0440");  // selects 1
  auto b5 = Base(4, A());        // selects 2
  std::printf("%lu %lu %lu\n", a1.count, a2.count, a3.count);
  std::printf("%lu %lu %lu %lu %lu\n", b1.count, b2.count, b3.count, b4.count, b5.count);
  return 0;
}
```

The output is 0 7 7 on the first line, but I want 7 7 7, i.e. Base(7) should select the first constructor, not the second. Idem for b3.

The sfinae on the constructors let the compiler choose 1 when 2 doesn't match the arguments, but I want it to select constructor 1 every time it matches. In the a1 case, the implicit conversion of 7 from int to unsigned long is forcing a choice of constructor 2, which I also don't understand why.

How do I go about solving this?

答:
Let's collect requirements:

First argument implicitly convertible to unsigned long, rest can construct base => do that.

Does not fit 1, and arguments can construct base => do that.

```<code>struct Base : Super {
    // This one should be preferred:
    template <class... Args, class = std::enable_if_t<std::is_constructible_v<Super, Args...>>>
    explicit Base(unsigned long count = 0, Args&&... args)
    : Super(std::forward<Args>(args))
    , count(count) {
    }

    // Only if the first is non-viable:
    template <class U, class... Args, class = std::enable_if_t<
        !(std::is_convertible_v<U, unsigned long> && std::is_constructible_v<Super, Args...>)
        && std::is_constructible_v<Super, U, Args>>>
    explicit Base(U&& u, Args&&... args)
    : Base(0, std::forward<U>(u), std::forward<Args>(args)...) {
    }
    unsigned long count;
};
</code>```

Beware that both templated ctors are candidates for implicit conversions. Putting explicit where needed left as an exercise for the reader.

If there were more alternatives to be considered, tag-dispatching would be advisable:

```<code>template <std::size_t N> struct priority : priority<N - 1> {};
template <> struct priority<0> {};

template <class... Ts>
static constexpr bool has_priority_v = (std::is_base_of_v<priority<0>, std::decay_t<Ts>> || ...);

class Base : Super {
    template <class UL, class... Ts, class = std::enable_if_t<
        std::is_convertible_v<UL, unsigned long> && std::is_constructible_v<Super, Ts...>>>
    Base(priority<1>, UL&& count, Ts&&... ts)
    : Super(std::forward<Ts>(ts)...), count(count)
    {}

    template <class... Ts, class = std::enable_if_t<std::is_constructible_v<Super, Ts...>>>
    Base(priority<0>, Ts&&... ts)
    : Base(priority<1>(), std::forward<Ts>(ts)...)
    {}
public:
    template <class... Ts, class = std::enable_if_t<
        !has_priority<Ts...> && std::is_constructible_v<Base, priority<>, Ts...>>>
    explicit Base(Ts&&... ts)
    : Base(priority<1>(), std::forward<Ts>(ts)...)
    {}
</code>```

Body:
I'm trying to write a policy-based class that forwards arguments to its unique super class, but also optionally takes some arguments of its own. The problem I'm facing is, the compiler seems to unconditionally prefer the second constructor below in the face of an implicit conversion - with only the parameter pack - over the first, which is the one I prefer.

#include <utility>
#include <iostream>

template <class Super>
struct Base : public Super {
  // 1
  template <typename... Args,
            typename = std::enable_if_t<std::is_constructible_v<Super, Args&&...>>>
  explicit Base(unsigned long count, Args&&... args)
    : Super(std::forward<Args>(args)...), count(count) {}

  // 2
  template <typename... Args,
            typename = std::enable_if_t<std::is_constructible_v<Super, Args&&...>>>
  explicit Base(Args&&... args) : Super(std::forward<Args>(args)...), count(0) {}

  unsigned long count;
};

struct A {
  explicit A(unsigned long id) {}
  A() {}
};

struct B {
  explicit B(const char* cstring) {}
  explicit B(unsigned long id, const char* cstring) {}
  explicit B(unsigned long id, A a) {}
  B() {}
};

int main() {
  auto a1 = Base(7);             // selects 2, but I want 1
  auto a2 = Base(7ul);           // selects 1
  auto a3 = Base(7, 10);         // selects 1
  auto b1 = Base(4);             // selects 1
  auto b2 = Base("0440");        // selects 2
  auto b3 = Base(4, "0440");     // selects 2, but I want 1
  auto b4 = Base(4, 4, "0440");  // selects 1
  auto b5 = Base(4, A());        // selects 2
  std::printf("%lu %lu %lu\n", a1.count, a2.count, a3.count);
  std::printf("%lu %lu %lu %lu %lu\n", b1.count, b2.count, b3.count, b4.count, b5.count);
  return 0;
}

The output is 0 7 7 on the first line, but I want 7 7 7, i.e. Base(7) should select the first constructor, not the second. Idem for b3.

The sfinae on the constructors let the compiler choose 1 when 2 doesn't match the arguments, but I want it to select constructor 1 every time it matches. In the a1 case, the implicit conversion of 7 from int to unsigned long is forcing a choice of constructor 2, which I also don't understand why.

How do I go about solving this?

Body:
Let's collect requirements:

First argument implicitly convertible to unsigned long, rest can construct base => do that.

Does not fit 1, and arguments can construct base => do that.

struct Base : Super {
    // This one should be preferred:
    template <class... Args, class = std::enable_if_t<std::is_constructible_v<Super, Args...>>>
    explicit Base(unsigned long count = 0, Args&&... args)
    : Super(std::forward<Args>(args))
    , count(count) {
    }

    // Only if the first is non-viable:
    template <class U, class... Args, class = std::enable_if_t<
        !(std::is_convertible_v<U, unsigned long> && std::is_constructible_v<Super, Args...>)
        && std::is_constructible_v<Super, U, Args>>>
    explicit Base(U&& u, Args&&... args)
    : Base(0, std::forward<U>(u), std::forward<Args>(args)...) {
    }
    unsigned long count;
};

Beware that both templated ctors are candidates for implicit conversions. Putting explicit where needed left as an exercise for the reader.

If there were more alternatives to be considered, tag-dispatching would be advisable:

template <std::size_t N> struct priority : priority<N - 1> {};
template <> struct priority<0> {};

template <class... Ts>
static constexpr bool has_priority_v = (std::is_base_of_v<priority<0>, std::decay_t<Ts>> || ...);

class Base : Super {
    template <class UL, class... Ts, class = std::enable_if_t<
        std::is_convertible_v<UL, unsigned long> && std::is_constructible_v<Super, Ts...>>>
    Base(priority<1>, UL&& count, Ts&&... ts)
    : Super(std::forward<Ts>(ts)...), count(count)
    {}

    template <class... Ts, class = std::enable_if_t<std::is_constructible_v<Super, Ts...>>>
    Base(priority<0>, Ts&&... ts)
    : Base(priority<1>(), std::forward<Ts>(ts)...)
    {}
public:
    template <class... Ts, class = std::enable_if_t<
        !has_priority<Ts...> && std::is_constructible_v<Base, priority<>, Ts...>>>
    explicit Base(Ts&&... ts)
    : Base(priority<1>(), std::forward<Ts>(ts)...)
    {}


问:
What endpoint would be suitable for answering a question in REST design
What endpoint would be suitable for answering a question.

I thought using

```<code> post /questions/{id}
</code>```

It's not self explanatory. Using posting to "/question/2" is hard to imagine that it is answering a question.

I thought about using

```<code> post  /questions/{id}/answers
</code>```

Question and answers do not map to models or tables in my system, if that is relevant. I use another api to access the question. My application is serving as a hub.

答:
REST doesn't care what spelling you use for your URI.  /cbcaf573-4f34-40ae-a91b-f097adfac495 is a perfectly satisfactory URI.  The various spelling conventions that you see should have roughly the same weight as variable naming in your local coding standard; it may make it easier for people to understand what is going on, but the machines don't care.

What you do normally want to pay some attention to: which resource's representation is going to change as a consequence of the request.  If the representation of /questions/{id} is normally going to include all of the answers in it, then you'll normally want to POST the answer to questions/{id}.  If the representation of the question just includes a link to answers, then you'll normally want to POST to the same URI as the link.

The motivation for this is that HTTP's cache invalidation rules are all based on the target uri of the unsafe request.

Using the cache invalidation style isn't required, however.  For example, on this question here: it's URI is

https://stackoverflow.com/questions/56349556/what-endpoint-would-be-suitable-for-answering-a-question-in-rest-design

But when I submit an answer, the POST request with my form data is sent to

https://stackoverflow.com/questions/56349556/answer/submit

And on successful save of my answer, I get a client side redirect to

https://stackoverflow.com/questions/56349556/what-endpoint-would-be-suitable-for-answering-a-question-in-rest-design/56350857#56350857

And that works too - my browser doesn't have any trouble figuring out how to create the requests that it needs to follow the submission protocol.

Body:
What endpoint would be suitable for answering a question.

I thought using

 post /questions/{id}

It's not self explanatory. Using posting to "/question/2" is hard to imagine that it is answering a question.

I thought about using

 post  /questions/{id}/answers

Question and answers do not map to models or tables in my system, if that is relevant. I use another api to access the question. My application is serving as a hub.


问:
How do I add a Fragment tag to a newly created instance?
How would I add a tag to a newly created instance?

```<code>case 0:
 return FragmentNotifications.newInstance(notifications, mCurrentTime);
</code>```

The new instance:

```<code>    public static FragmentNotifications
                 newInstance(String notificationsArray, long currentTime){

        FragmentNotifications fragment = new FragmentNotifications();
        return fragment;
    }
</code>```

How would I assign a name to the fragment created with viewpager?

```<code>@Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return
             FragmentNotifications.newInstance(notifications, mCurrentTime);
            case 1:
                return FragmentMessages.newInstance(messages,
              mCurrentTime);
            case 2:
                return new FragmentProfile();
            default:
                return null;

        }

    }
</code>```

答:
Answer & Credits to the person who found this method:

How to get existing fragments when using FragmentPagerAdapter

I got the tag name that is automatically generated by android api

```<code>@Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment createdFragment = (Fragment) super.instantiateItem(container, position);
// get the tags set by FragmentPagerAdapter
switch (position) {
    case 0:
        String firstTag = createdFragment.getTag();
        break;
    case 1:
        String secondTag = createdFragment.getTag();
        break;
}
// ... save the tags somewhere so you can reference them later
    return createdFragment;
}
</code>```

Make sure you use the getChildFragmentManager to reference it otherwise it returns null
I spent like 2 hours trying to find out why findFragmentByTag was returning null

Body:
How would I add a tag to a newly created instance?

case 0:
 return FragmentNotifications.newInstance(notifications, mCurrentTime);

The new instance:

    public static FragmentNotifications
                 newInstance(String notificationsArray, long currentTime){

        FragmentNotifications fragment = new FragmentNotifications();
        return fragment;
    }

How would I assign a name to the fragment created with viewpager?

@Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return
             FragmentNotifications.newInstance(notifications, mCurrentTime);
            case 1:
                return FragmentMessages.newInstance(messages,
              mCurrentTime);
            case 2:
                return new FragmentProfile();
            default:
                return null;

        }

    }

Body:
Answer & Credits to the person who found this method:

How to get existing fragments when using FragmentPagerAdapter

I got the tag name that is automatically generated by android api

@Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment createdFragment = (Fragment) super.instantiateItem(container, position);
// get the tags set by FragmentPagerAdapter
switch (position) {
    case 0:
        String firstTag = createdFragment.getTag();
        break;
    case 1:
        String secondTag = createdFragment.getTag();
        break;
}
// ... save the tags somewhere so you can reference them later
    return createdFragment;
}

Make sure you use the getChildFragmentManager to reference it otherwise it returns null
I spent like 2 hours trying to find out why findFragmentByTag was returning null


问:
How to draw dynamic line in RDLC Report
I'm try to generate dynamic line for column in RDLC report. Start and end point of line are not fixed, it depends upon data coming from database. I tried different code but no luck.

Please refer image for better understanding.

答:
The lines in SSRS can't be set dynamically. The closest you could get to this would be to use a Line Chart or Sparkline. These both typically go left to right, not down. So it would be very difficult to simulate what you show in the screenshot.

You could try making separate charts stacked vertically that look like they're connected, but I don't think you would be able to get those nice dots at the vertices if you can even get rid of all the padding. And objects can't overlap. So you can't even add images over spots that you want to. You also can't rotate charts.

Sorry for the vague answer, but I would hazard to say it's not possible to do exactly what you're showing there. Hopefully this at least helps explain why.

Title: How to draw dynamic line in RDLC Report


问:
How to change header of bootstrap4 django-tables2
I defined the table as below

```<code>class MyTable(tables.Table):
    class Meta:
        template_name = "django_tables2/bootstrap4.html"
        model = Mymodel
        attrs = {"class": "table table-hover"}
</code>```

I want to change the table head to make  appear light or dark gray, like this.

答:
try this one:</p>

```<code>attrs = {
        'class': 'table table-hover',
        'thead' : {
            'class': 'thead-dark'
        }
</code>```

Body:
I defined the table as below

class MyTable(tables.Table):
    class Meta:
        template_name = "django_tables2/bootstrap4.html"
        model = Mymodel
        attrs = {"class": "table table-hover"}

I want to change the table head to make  appear light or dark gray, like this.

Body:
try this one:

attrs = {
        'class': 'table table-hover',
        'thead' : {
            'class': 'thead-dark'
        }


问:
How to prevent user from scrolling while implementing swipeRefreshLayout?
In my app I have a recycler view with 20 - 30 items and I have the function to pull to refresh the content, and I want to prevent the user from scrolling the view while the refresh is in progress because it creates an error if the user ties to scroll and the regresh is in progress, but I'm really lost on how to do it :/</p>

```<code>eRecyclerView = findViewById(R.id.recycler_view);
        RecyclerView.LayoutManager eLayoutManager = new GridLayoutManager(this, 2);
        eRecyclerView.setLayoutManager(eLayoutManager);

 swipeRefreshLayout = findViewById(R.id.refreshSecondLevel);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
               loadNewContent();
               Handler delay = new Handler();
                delay.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        swipeRefreshLayout.setRefreshing(false);
                    }
                }, 3000);

            }
        });
</code>```

答:
You should override canScrollVertically method on your RecyclerView.LayoutManager:

```<code>public class ToggledScrollLayoutManager extends LinearLayoutManager {
    private boolean mIsScrollEnabled = true;

    public ToggledScrollLayoutManager(Context context) {
        super(context);
    }

    public void setScrollEnabled(boolean enabled) {
        this.mIsScrollEnabled = enabled;
    }

    @Override
    public boolean canScrollVertically() {
        return mIsScrollEnabled && super.canScrollVertically();
    }
}
</code>```

Then use it when user refreshed the page:

```<code>recyclerView = findViewById(R.id.recyclerView);
ToggledScrollLayoutManager layoutManager = new ToggledScrollLayoutManager();
recyclerView.setLayoutManager(layoutManager);

swipeRefreshLayout = findViewById(R.id.refreshSecondLevel);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
    @Override
        public void onRefresh() {
            loadNewContent();
            layoutManager.setScrollEnabled(false);
            Handler delay = new Handler();
            delay.postDelayed(new Runnable() {
                @Override
                public void run() {
                    swipeRefreshLayout.setRefreshing(false);
                    layoutManager.setScrollEnabled(true);
                }
            }, 3000);
        }
    }
});
</code>```

Body:
In my app I have a recycler view with 20 - 30 items and I have the function to pull to refresh the content, and I want to prevent the user from scrolling the view while the refresh is in progress because it creates an error if the user ties to scroll and the regresh is in progress, but I'm really lost on how to do it :/

eRecyclerView = findViewById(R.id.recycler_view);
        RecyclerView.LayoutManager eLayoutManager = new GridLayoutManager(this, 2);
        eRecyclerView.setLayoutManager(eLayoutManager);

 swipeRefreshLayout = findViewById(R.id.refreshSecondLevel);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
               loadNewContent();
               Handler delay = new Handler();
                delay.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        swipeRefreshLayout.setRefreshing(false);
                    }
                }, 3000);

            }
        });

Body:
You should override canScrollVertically method on your RecyclerView.LayoutManager:

public class ToggledScrollLayoutManager extends LinearLayoutManager {
    private boolean mIsScrollEnabled = true;

    public ToggledScrollLayoutManager(Context context) {
        super(context);
    }

    public void setScrollEnabled(boolean enabled) {
        this.mIsScrollEnabled = enabled;
    }

    @Override
    public boolean canScrollVertically() {
        return mIsScrollEnabled && super.canScrollVertically();
    }
}

Then use it when user refreshed the page:

recyclerView = findViewById(R.id.recyclerView);
ToggledScrollLayoutManager layoutManager = new ToggledScrollLayoutManager();
recyclerView.setLayoutManager(layoutManager);

swipeRefreshLayout = findViewById(R.id.refreshSecondLevel);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
    @Override
        public void onRefresh() {
            loadNewContent();
            layoutManager.setScrollEnabled(false);
            Handler delay = new Handler();
            delay.postDelayed(new Runnable() {
                @Override
                public void run() {
                    swipeRefreshLayout.setRefreshing(false);
                    layoutManager.setScrollEnabled(true);
                }
            }, 3000);
        }
    }
});


问:
Lucee - How to setup virtual sites and access the web administrator?
I'm using current Lucee on W2K16 with IIS.  I installed Lucee and created a test site (test.lucee.xyz), added that to my hosts file and can browse it locally and everything seems to work.

I now added a 2nd site.  Added through IIS as normal and then I edited

```<code>D:\lucee\tomcat\conf\server.xml
</code>```

For my 2nd site I added a host:

```<code><Host name="mango.tuitionrewards.com" appBase="webapps" unpackWARs="true" autoDeploy="true"  xmlValidation="false" xmlNamespaceAware="false">
   <Context path="" docBase="D:\webroot\luceetest.mysite.com" />
   <Alias>luceetest.mysite.com</Alias>
</Host>
</code>```

Saved that, restarted Lucee and now have a WEB-INF folder in the site root:

```<code>D:\webroot\luceetest.mysite.com\WEB-INF
</code>```

This site now works as well.

My question is it's my understanding that in the Lucee Administrator the Server tab is global, and the Web tab is specific to one site.  For me, when I go into the Administrator, the URLs are:

```<code>http://127.0.0.1:8888/lucee/admin/server.cfm?action=overview
http://127.0.0.1:8888/lucee/admin/web.cfm?action=overview
</code>```

How do I get the "web" Administrator to interact with the new site?  Also is it safe to remove the first test site (test.lucee.xyz)?

答:
If you installed Lucee using the Lucee Installer, and you selected the option to install mod_cfml and the BonCode Connector, all you need to do is create a site in IIS, and manage them like you normally would in IIS.

mod_cfml will dynamically create the site contexts in Tomcat for you at runtime. You can create the contexts in the server.xml if you want to (this will start those contexts during Tomcat's startup cycle instead of at runtime), but the end result is the same.

From there, you would access each site's web administrator from that site's URL:

```<code>https://luceetest.mysite.com/lucee/admin/web.cfm?action=overview
</code>```

Hope this helps!

Body:
I'm using current Lucee on W2K16 with IIS.  I installed Lucee and created a test site (test.lucee.xyz), added that to my hosts file and can browse it locally and everything seems to work.

I now added a 2nd site.  Added through IIS as normal and then I edited

D:\lucee\tomcat\conf\server.xml

For my 2nd site I added a host:

<Host name="mango.tuitionrewards.com" appBase="webapps" unpackWARs="true" autoDeploy="true"  xmlValidation="false" xmlNamespaceAware="false">
   <Context path="" docBase="D:\webroot\luceetest.mysite.com" />
   <Alias>luceetest.mysite.com</Alias>
</Host>

Saved that, restarted Lucee and now have a WEB-INF folder in the site root:

D:\webroot\luceetest.mysite.com\WEB-INF

This site now works as well.

My question is it's my understanding that in the Lucee Administrator the Server tab is global, and the Web tab is specific to one site.  For me, when I go into the Administrator, the URLs are:

http://127.0.0.1:8888/lucee/admin/server.cfm?action=overview
http://127.0.0.1:8888/lucee/admin/web.cfm?action=overview

How do I get the "web" Administrator to interact with the new site?  Also is it safe to remove the first test site (test.lucee.xyz)?

Body:
If you installed Lucee using the Lucee Installer, and you selected the option to install mod_cfml and the BonCode Connector, all you need to do is create a site in IIS, and manage them like you normally would in IIS.

mod_cfml will dynamically create the site contexts in Tomcat for you at runtime. You can create the contexts in the server.xml if you want to (this will start those contexts during Tomcat's startup cycle instead of at runtime), but the end result is the same.

From there, you would access each site's web administrator from that site's URL:

https://luceetest.mysite.com/lucee/admin/web.cfm?action=overview

Hope this helps!


问:
When using unittest.mock.patch, why is autospec not True by default?
When you patch a function using mock, you have the option to specify autospec as True:

If you set autospec=True then the mock with be created with a spec
  from the object being replaced. All attributes of the mock will also
  have the spec of the corresponding attribute of the object being
  replaced. Methods and functions being mocked will have their arguments
  checked and will raise a TypeError if they are called with the wrong
  signature.

(http://www.voidspace.org.uk/python/mock/patch.html)

I'm wondering why this isn't the default behaviour?  Surely we would almost always want to catch passing incorrect parameters to any function we patch?

答:
The action of autospeccing itself can execute code, for example via the invocation of descriptors.

```<code>>>> class A:
...     @property
...     def foo(self):
...         print("rm -rf /")
...
>>> a = A()
>>> with mock.patch("__main__.a", autospec=False) as m:
...     pass
...
>>> with mock.patch("__main__.a", autospec=True) as m:
...     pass
...
rm -rf /
</code>```

Therefore, this is a problematic feature to enable by default and
is opt-in only.

Body:
The action of autospeccing itself can execute code, for example via the invocation of descriptors.

>>> class A:
...     @property
...     def foo(self):
...         print("rm -rf /")
...
>>> a = A()
>>> with mock.patch("__main__.a", autospec=False) as m:
...     pass
...
>>> with mock.patch("__main__.a", autospec=True) as m:
...     pass
...
rm -rf /

Therefore, this is a problematic feature to enable by default and
is opt-in only.


答:
All you need is the matrix transpose. Here is an example</p>

```<code>import numpy as np

A = np.array([[1,2,3],
              [4,5,6],
              [7,8,9]])
B = A.T

# array([[1, 4, 7],
#        [2, 5, 8],
#        [3, 6, 9]])
</code>```

Title: Matrix mirroring/transformation in Python

Body:
I'm looking for a Python function which, given the 2d array A, will output B:

A = [[a, b, c],
     [d, e, f],
     [g, h, i]]

B = [[a, d, g],
     [b, e, h],
     [c, f, i]]

i.e. the first row becomes the first column, the second row becomes the second column etc.

Thanks.

Body:
All you need is the matrix transpose. Here is an example

import numpy as np

A = np.array([[1,2,3],
              [4,5,6],
              [7,8,9]])
B = A.T

# array([[1, 4, 7],
#        [2, 5, 8],
#        [3, 6, 9]])


Body:
Try this,

>>> A = np.array([[1,2,3],
              [4,5,6],
              [7,8,9]])

>>> [list(i) for i in zip(*A)]

[[1, 4, 7], [2, 5, 8], [3, 6, 9]] #output


问:
How to get the right format for dates in the previous month with Google Apps Script
Using Google Apps Script, I am getting the first and last date from the previous month and then change the format to GMT 'yyyy-MM-dd'

```<code>var todayDate = new Date();

    var lastDate = function getLastDate() {
      var d = todayDate;
      d.setDate(0);
        return Utilities.formatDate(d, 'GMT', 'yyyy-MM-dd');
    }

    var firstDate = function getFirstDate() {
     var e = todayDate;
        e.setMonth(e.getMonth() - 1);
      e.setDate(1);
      return Utilities.formatDate(e, 'GMT', 'yyyy-MM-dd');
    }
</code>```

But I get an error stating:

"Invalid value ' function getLastDate() { var d = todayDate; d.setDate(0); return Utilities.formatDate(e, "GMT", "yyyy-MM-dd"); } '. Values must match the following regular expression: '[0-9]{4}-[0-9]{2}-[0-9]{2}|today|yesterday|[0-9]+(daysAgo)'"

Can someone please help?

答:
If you want to get previous month and locale it into spanish, check this out..</p>

```<code>var previousMonth = (function() {
    var d = new Date();
    d.setMonth(d.getMonth() - 1);
    var getLastMonth = Utilities.formatDate(d,Session.getScriptTimeZone(),"MMMM");
    var translateMonthIntoSpanish = LanguageApp.translate (getLastMonth,'en','es');
    var titleCaseMonth = translateMonthIntoSpanish.charAt(0).toUpperCase() + translateMonthIntoSpanish.slice(1);
    return titleCaseMonth;
})();

Logger.log(previousMonth);
</code>```

Body:
Using Google Apps Script, I am getting the first and last date from the previous month and then change the format to GMT 'yyyy-MM-dd'

var todayDate = new Date();

    var lastDate = function getLastDate() {
      var d = todayDate;
      d.setDate(0);
        return Utilities.formatDate(d, 'GMT', 'yyyy-MM-dd');
    }

    var firstDate = function getFirstDate() {
     var e = todayDate;
        e.setMonth(e.getMonth() - 1);
      e.setDate(1);
      return Utilities.formatDate(e, 'GMT', 'yyyy-MM-dd');
    }

But I get an error stating:

"Invalid value ' function getLastDate() { var d = todayDate; d.setDate(0); return Utilities.formatDate(e, "GMT", "yyyy-MM-dd"); } '. Values must match the following regular expression: '[0-9]{4}-[0-9]{2}-[0-9]{2}|today|yesterday|[0-9]+(daysAgo)'"

Can someone please help?

Body:
If you want to get previous month and locale it into spanish, check this out..

var previousMonth = (function() {
    var d = new Date();
    d.setMonth(d.getMonth() - 1);
    var getLastMonth = Utilities.formatDate(d,Session.getScriptTimeZone(),"MMMM");
    var translateMonthIntoSpanish = LanguageApp.translate (getLastMonth,'en','es');
    var titleCaseMonth = translateMonthIntoSpanish.charAt(0).toUpperCase() + translateMonthIntoSpanish.slice(1);
    return titleCaseMonth;
})();

Logger.log(previousMonth);


问:
Edit and Continue broken on converted VS 2008-2010 project
I've looked through as many posts on broken EAC I can find but still can't find a solution.

I'm running VS2010 express on Win7 64bit now with XNA4.0 framework, I was running VS2008 express before on 32bit XP with XNA3.1 installed.

Did a conversion of the project, and EAC doesn't work. Gives me this error:
http://smars.se/misc/eac.jpg

It's the debug build, code is not optimized, x86 build, I've tried clearing all .user/.chachefile/.suo/bin/obj folders. When I create new projects EAC works. But I still can't get it working in my project.

Any ideas?

答:
Rather than trying to fix this, might I suggest that it would be quicker and easier to simply recreate your project file(s)?

If you open them up in a text editor, you can simply copy out the <ItemGroup> that has all your source files. Then create a fresh project with the XNA 4.0 template. Edit the new project file and paste over the <ItemGroup> with your source files.

Obviously you will need to go through and reset things like the default namespace, output assembly name, and so on.

If you wanted to get even cleverer you could copy more sections of the project file over. Or you could even diff the the broken project file with a fresh one to figure out what might be causing the problem.


问:
Renaming file extension using pathlib (python 3)
I am using windows 10 and winpython. I have a file with a .dwt extension (it is a text file). I want to change the extension of this file to .txt.

My code does not throw any errors, but it does not change the extension.

```<code>from pathlib import Path

filename = Path("E:\\seaborn_plot\\x.dwt")

print(filename)

filename_replace_ext = filename.with_suffix('.txt')

print(filename_replace_ext)
</code>```

Expected results are printed out (as shown below) in winpython's ipython window output:

E:\seaborn_plot\x.dwt

E:\seaborn_plot\x.txt

But when I look for a file with a renamed extension, the extension has not been changed, only the original file exists. I suspect windows file permissions.

答:
From the docs:

Path.rename(target)

Rename this file or directory to the given target. On Unix, if target exists and is a file, it will be replaced silently if the user has permission. target can be either a string or another path object.

pathlib — Object-oriented filesystem paths on docs.python.org

You could use it like this:

```<code>from pathlib import Path

filename = Path("E:\\seaborn_plot\\x.dwt")
filename_replace_ext = filename.with_suffix(".txt")
filename.rename(filename_replace_ext)
</code>```

Body:
I am using windows 10 and winpython. I have a file with a .dwt extension (it is a text file). I want to change the extension of this file to .txt.

My code does not throw any errors, but it does not change the extension.

from pathlib import Path

filename = Path("E:\\seaborn_plot\\x.dwt")

print(filename)

filename_replace_ext = filename.with_suffix('.txt')

print(filename_replace_ext)

Expected results are printed out (as shown below) in winpython's ipython window output:

E:\seaborn_plot\x.dwt

E:\seaborn_plot\x.txt

But when I look for a file with a renamed extension, the extension has not been changed, only the original file exists. I suspect windows file permissions.

Body:
From the docs:

Path.rename(target)

Rename this file or directory to the given target. On Unix, if target exists and is a file, it will be replaced silently if the user has permission. target can be either a string or another path object.

pathlib — Object-oriented filesystem paths on docs.python.org

You could use it like this:

from pathlib import Path

filename = Path("E:\\seaborn_plot\\x.dwt")
filename_replace_ext = filename.with_suffix(".txt")
filename.rename(filename_replace_ext)


问:
What is the relationship between Gallina and OCaml?
I learned that Coq is written in OCaml, but it has the specification language as Gallina. How are these two languages related besides they are all functional programming languages?</p>

答:
That's a bit of a loaded question.

Gallina could exist independently from OCaml, though, being a lambda calculus, it shares some construct and semantics with it, and, having been developed in the OCaml world, it also shares some concrete syntax. But OCaml could not have been suitable to take the place of Gallina.

Some similarities:

They share a lambda calculus-inspired, functional language.

They have similar algebraic data type declarations (though there are lots of differences in what is allowable and expressible).

Some (major) differences:

Gallina has dependent types, while OCaml has a type system that is close to a prenex-polymorphic System F with some subtyping... I'm not sure how to call it, but it is less expressive than dependent types in some ways, though it has some extra features absent from Gallina.

Gallina is total, meaning all functions must be syntactically well-behaved, either clearly terminating, or clearly making computational progress. OCaml is a more general purpose language where non-termination is fine.

Gallina is pure, while OCaml has side-effectful primitives.

Gallina is "functional only" if you will. OCaml has a notion of objects, some "imperative"-looking features (due to all the differences previously listed).

In fact, historically, ML (which OCaml is some variant of) was to LCF sort of what Ltac is to Gallina! :-D (oh boy, I might get some angry comments because of this note...)