问:
Change target of ajax post in razor page from api in controller to "code-behind" post handler in same razor page
I have the following ajax post on my index.cshtml razor page which works fine:

```<code>create: {
            url: "/api/LearningTasks/create",
            type: "POST",
            dataType: "json"
        },
</code>```

It sends the post to my controller and the code receiving works fine.  It looks like this:

```<code>[HttpPost]
    [Route("api/LearningTasks/create")]
    public async Task<ActionResult<LearningTask>> CreateLearningTask(LearningTask learningTask)
    {
        _context.LearningTasks.Add(learningTask);
        await _context.SaveChangesAsync();

        return CreatedAtAction("GetLearningTask", new { id = learningTask.Id }, learningTask);
    }
</code>```

I would like to change the target of my post so that it goes to the "code-behind" index.cshtml.cs.  The method that I would like to receive it looks like this:

```<code> public async Task<IActionResult> OnPostAsync()
    {
        // This is where I want to have the send the data for the create operation instead of to /api/LearningTasks/create
        _context.LearningTasks.Add(LearningTask);
        await _context.SaveChangesAsync();

        return null;
    }
</code>```

I have tried removing the line url: "/api/LearningTasks/create", and setting it to url: "",  but neither works.  Any help in figuring out how to do this would be greatly appreciated.

答:
Razor Pages are designed to be automatically protected from cross-site request forgery (CSRF/XSRF) attacks.

You should send the anti-forgery token in request header to the server using AJAX:

Add explicitly using @Html.AntiForgeryToken() ,it will add an input type hidden with name __RequestVerificationToken.

Send token in request header :

```<code>$.ajax({
    url: '/Index',
    type: 'POST',
    beforeSend: function (xhr) {
        xhr.setRequestHeader("XSRF-TOKEN",
            $('input:hidden[name="__RequestVerificationToken"]').val());
    },
})
.done(function (result) { })
</code>```

Configure the antiforgery service to look for the X-CSRF-TOKEN header :

```<code>services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
</code>```

Below article is for your reference :

Handle Ajax Requests in ASP.NET Core Razor Pages

Body:
I have the following ajax post on my index.cshtml razor page which works fine:

create: {
            url: "/api/LearningTasks/create",
            type: "POST",
            dataType: "json"
        },

It sends the post to my controller and the code receiving works fine.  It looks like this:

[HttpPost]
    [Route("api/LearningTasks/create")]
    public async Task<ActionResult<LearningTask>> CreateLearningTask(LearningTask learningTask)
    {
        _context.LearningTasks.Add(learningTask);
        await _context.SaveChangesAsync();

        return CreatedAtAction("GetLearningTask", new { id = learningTask.Id }, learningTask);
    }

I would like to change the target of my post so that it goes to the "code-behind" index.cshtml.cs.  The method that I would like to receive it looks like this:

 public async Task<IActionResult> OnPostAsync()
    {
        // This is where I want to have the send the data for the create operation instead of to /api/LearningTasks/create
        _context.LearningTasks.Add(LearningTask);
        await _context.SaveChangesAsync();

        return null;
    }

I have tried removing the line url: "/api/LearningTasks/create", and setting it to url: "",  but neither works.  Any help in figuring out how to do this would be greatly appreciated.

Body:
Razor Pages are designed to be automatically protected from cross-site request forgery (CSRF/XSRF) attacks.

You should send the anti-forgery token in request header to the server using AJAX:

Add explicitly using @Html.AntiForgeryToken() ,it will add an input type hidden with name __RequestVerificationToken.

Send token in request header :

$.ajax({
    url: '/Index',
    type: 'POST',
    beforeSend: function (xhr) {
        xhr.setRequestHeader("XSRF-TOKEN",
            $('input:hidden[name="__RequestVerificationToken"]').val());
    },
})
.done(function (result) { })

Configure the antiforgery service to look for the X-CSRF-TOKEN header :

services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");

Below article is for your reference :

Handle Ajax Requests in ASP.NET Core Razor Pages


来源: stackexchange

问:
Are Python PEPs implemented as proposed/amended or is there wiggle room?
I just noticed in PEP 3127 (the one that rationalised radix calculations on literals and int() arguments so that, for example, 010 is no longer a valid literal and must instead be 0o10 if octal is desired), that one particular part of the PEP was not implemented.

I refer specifically to the section quoted below:

Tokenizer exception handling

If an invalid token contains a leading "0", the exception error message should be more informative than the current "SyntaxError: invalid token". It should explain that decimal numbers may not have a leading zero, and that octal numbers require an "o" after the leading zero.

However, when I try to use this (now invalid) format, I still see the old (less informative) error, as per the following transcript:

```<code>MyPromptHere> python3
Python 3.6.8 (default, Oct  7 2019, 12:59:55)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> x = 010
  File "<stdin>", line 1
    x = 010
          ^
SyntaxError: invalid token

>>> int('010', 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 0: '010'

>>> _
</code>```

Now I don't really care about the fact that it's a weird error since I earn much of my remuneration from arcane errors :-) However, from what I understand, the PEPs go through revision processes even after they've been sponsored so I'm curious as to why either:

that part of the PEP wasn't implemented; or

the PEP wasnt revised to reflect reality of the implementation.

Or is this simply the usage of the word "should" having less force than the normal standards "required" terms like "shall" or "must"? I'm not sure of that since, as per the transcript above, "should" appears to be obeyed in the section dealing with int():

int() exception handling

The ValueError raised for any call to int() with a string should at least explicitly contain the base in the error message, e.g.: ValueError: invalid literal for base 8 int(): 09.

答:
This might be a python version difference for you.

```<code>Python 3.8.1 (default, Jan 13 2020, 22:28:48)
>>> 010
  File "<stdin>", line 1
SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers
</code>```

Also, in the "Open Issues" section of PEP 3127, it states

There are still some strong feelings that '0123' should be allowed as
  a literal decimal in Python 3.0. If this is the right thing to do,
  this can easily be covered in an additional PEP. This proposal only
  takes the first step of making '0123' not be a valid octal number, for
  reasons covered in the rationale.

To me, this means that there was no hard requirement to change the error message. It was a suggestion to be more informative which was eventually implemented at some point (see 3.8.1 output above).

ContentLicense: CC BY-SA 4.0

Body:
I just noticed in PEP 3127 (the one that rationalised radix calculations on literals and int() arguments so that, for example, 010 is no longer a valid literal and must instead be 0o10 if octal is desired), that one particular part of the PEP was not implemented.

I refer specifically to the section quoted below:

Tokenizer exception handling

If an invalid token contains a leading "0", the exception error message should be more informative than the current "SyntaxError: invalid token". It should explain that decimal numbers may not have a leading zero, and that octal numbers require an "o" after the leading zero.

However, when I try to use this (now invalid) format, I still see the old (less informative) error, as per the following transcript:

MyPromptHere> python3
Python 3.6.8 (default, Oct  7 2019, 12:59:55)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> x = 010
  File "<stdin>", line 1
    x = 010
          ^
SyntaxError: invalid token

>>> int('010', 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 0: '010'

>>> _

Now I don't really care about the fact that it's a weird error since I earn much of my remuneration from arcane errors :-) However, from what I understand, the PEPs go through revision processes even after they've been sponsored so I'm curious as to why either:

that part of the PEP wasn't implemented; or

the PEP wasnt revised to reflect reality of the implementation.

Or is this simply the usage of the word "should" having less force than the normal standards "required" terms like "shall" or "must"? I'm not sure of that since, as per the transcript above, "should" appears to be obeyed in the section dealing with int():

int() exception handling

The ValueError raised for any call to int() with a string should at least explicitly contain the base in the error message, e.g.: ValueError: invalid literal for base 8 int(): 09.

Body:
This might be a python version difference for you.

Python 3.8.1 (default, Jan 13 2020, 22:28:48)
>>> 010
  File "<stdin>", line 1
SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers

Also, in the "Open Issues" section of PEP 3127, it states

There are still some strong feelings that '0123' should be allowed as
  a literal decimal in Python 3.0. If this is the right thing to do,
  this can easily be covered in an additional PEP. This proposal only
  takes the first step of making '0123' not be a valid octal number, for
  reasons covered in the rationale.

To me, this means that there was no hard requirement to change the error message. It was a suggestion to be more informative which was eventually implemented at some point (see 3.8.1 output above).


问:
Generate Nested JSON Using R
I am trying to generate a nested JSON file using R, and am having difficulties in setting it up. I am admittedly very new to JSON, so conceptually I'm behind. I would appreciate any help- including advice on places (other than R) that would make this task easier.

I have 3 datasets I'm working with- all connected via keys. Essentially, my objective is to create a JSON file that contains patient objects, with nested encounters & within those encounters, nested claim lines.

Here's the set up in R:

```<code>patients <- data.frame (
                      PatientID = c('PID01','PID02'),
                      PatientName = c('John Doe','Jane Doe'),
                      PatientGroup = c('Group A','Group B')
                    )

encounters <- data.frame (
                          EncounterID = c('Enc01','Enc02','Enc03','Enc04','Enc05'),
                          PatientID = c('PID01','PID01','PID02','PID02','PID02'),
                          EncounterType = c('Outpatient','Outpatient','Inpatient','Outpatient','SNF')
                         )

encounterLines <- data.frame (
                              EncounterID = c(rep('Enc01',5),rep('Enc04',2)),
                              RevCodes = c('001','100','200','300','400','001','100'),
                              ClaimLine = c(seq(1:5),seq(1:2))
                              )

 ----------------------------------------
 PatientID   PatientName   PatientGroup
----------- ------------- --------------
   PID01      John Doe       Group A

   PID02      Jane Doe       Group B
----------------------------------------

-----------------------------------------
 EncounterID   PatientID   EncounterType
------------- ----------- ---------------
    Enc01        PID01      Outpatient

    Enc02        PID01      Outpatient

    Enc03        PID02       Inpatient

    Enc04        PID02      Outpatient

    Enc05        PID02          SNF
-----------------------------------------

------------------------------------
 EncounterID   RevCodes   ClaimLine
------------- ---------- -----------
    Enc01        001          1

    Enc01        100          2

    Enc01        200          3

    Enc01        300          4

    Enc01        400          5

    Enc04        001          1

    Enc04        100          2
------------------------------------
</code>```

The JSON output I'm looking for is as follows. I've tried using jsonlite but I can't seem to get any real traction:

```<code>[
    {
        "PatientID": "PID01",
        "PatientName": "John Doe",
        "PatientGroup": "Group A",
        "Encounters": [
            {
                "EncounterID": "Enc01",
                "EncounterType": "Outpatient",
                "ClaimLines": [
                    {
                        "ClaimLine": 1,
                        "RevenueCode": "001"
                    },
                    {
                        "ClaimLine": 2,
                        "RevenueCode": "100"
                    },
                    {
                        "ClaimLine": 3,
                        "RevenueCode": "200"
                    },
                    {
                        "ClaimLine": 4,
                        "RevenueCode": "300"
                    },
                    {
                        "ClaimLine": 5,
                        "RevenueCode": "400"
                    }
                ]
            },
            {
                "EncounterID": "Enc02",
                "EncounterType": "Outpatient"
            }
        ]
    },
    {
        "PatientID": "PID02",
        "PatientName": "Jane Doe",
        "PatientGroup": "Group B",
        "Encounters": [
            {
                "EncounterID": "Enc03",
                "EncounterType": "Inpatient"
            },
            {
                "EncounterID": "Enc04",
                "EncounterType": "Outpatient",
                "ClaimLines": [
                    {
                        "ClaimLine": 1,
                        "RevenueCode": "001"
                    },
                    {
                        "ClaimLine": 2,
                        "RevenueCode": "100"
                    }
                ]
            },
            {
                "EncounterID": "Enc05",
                "EncounterType": "SNF"
            }
        ]
    }
]
</code>```

Any/all help would be GREATLY appreciated. As I mentioned before, I'm not opposed to using tools outside R.

Thanks!

答:
A couple of data.table joins and you can get there too

library(data.table)
setDT( patients )
setDT( encounters )
setDT( encounterLines )

## do a 'left-join' by putting
## encounterLines onto encounters
dt_encounters <- encounterLines[
  encounters
  , on = "EncounterID"
  , nomatch = NA       ## indicates left-join
]

## make a list-column (required for JSON)
dt_encounters <- dt_encounters[
  , .(ClaimLines = list(.SD))
  , by = .(EncounterID, EncounterType, PatientID)
]

## do a 'left-join' by putting
## encounters onto patients
dt_patients <- dt_encounters[
  patients
  , on = "PatientID"
  , nomatch = NA
]

## make a list-column (required for JSON)
dt_patients <- dt_patients[
  , .(Encounters = list(.SD))
  , by = .(PatientID, PatientName, PatientGroup)
]
```

<pre class="lang-r prettyprint-override"><code>toJSON( dt_patients, pretty = TRUE )

[
  {
    "PatientID": "PID01",
    "PatientName": "John Doe",
    "PatientGroup": "Group A",
    "Encounters": [
      {
        "EncounterID": "Enc01",
        "EncounterType": "Outpatient",
        "ClaimLines": [
          {
            "RevCodes": "001",
            "ClaimLine": 1
          },
          {
            "RevCodes": "100",
            "ClaimLine": 2
          },
          {
            "RevCodes": "200",
            "ClaimLine": 3
          },
          {
            "RevCodes": "300",
            "ClaimLine": 4
          },
          {
            "RevCodes": "400",
            "ClaimLine": 5
          }
        ]
      },
      {
        "EncounterID": "Enc02",
        "EncounterType": "Outpatient",
        "ClaimLines": [
          {}
        ]
      }
    ]
  },
  {
    "PatientID": "PID02",
    "PatientName": "Jane Doe",
    "PatientGroup": "Group B",
    "Encounters": [
      {
        "EncounterID": "Enc03",
        "EncounterType": "Inpatient",
        "ClaimLines": [
          {}
        ]
      },
      {
        "EncounterID": "Enc04",
        "EncounterType": "Outpatient",
        "ClaimLines": [
          {
            "RevCodes": "001",
            "ClaimLine": 1
          },
          {
            "RevCodes": "100",
            "ClaimLine": 2
          }
        ]
      },
      {
        "EncounterID": "Enc05",
        "EncounterType": "SNF",
        "ClaimLines": [
          {}
        ]
      }
    ]
  }
]

</code>```

Title: Generate Nested JSON Using R

Body:
I am trying to generate a nested JSON file using R, and am having difficulties in setting it up. I am admittedly very new to JSON, so conceptually I'm behind. I would appreciate any help- including advice on places (other than R) that would make this task easier.

I have 3 datasets I'm working with- all connected via keys. Essentially, my objective is to create a JSON file that contains patient objects, with nested encounters & within those encounters, nested claim lines.

Here's the set up in R:

patients <- data.frame (
                      PatientID = c('PID01','PID02'),
                      PatientName = c('John Doe','Jane Doe'),
                      PatientGroup = c('Group A','Group B')
                    )

encounters <- data.frame (
                          EncounterID = c('Enc01','Enc02','Enc03','Enc04','Enc05'),
                          PatientID = c('PID01','PID01','PID02','PID02','PID02'),
                          EncounterType = c('Outpatient','Outpatient','Inpatient','Outpatient','SNF')
                         )

encounterLines <- data.frame (
                              EncounterID = c(rep('Enc01',5),rep('Enc04',2)),
                              RevCodes = c('001','100','200','300','400','001','100'),
                              ClaimLine = c(seq(1:5),seq(1:2))
                              )

 ----------------------------------------
 PatientID   PatientName   PatientGroup
----------- ------------- --------------
   PID01      John Doe       Group A

   PID02      Jane Doe       Group B
----------------------------------------

-----------------------------------------
 EncounterID   PatientID   EncounterType
------------- ----------- ---------------
    Enc01        PID01      Outpatient

    Enc02        PID01      Outpatient

    Enc03        PID02       Inpatient

    Enc04        PID02      Outpatient

    Enc05        PID02          SNF
-----------------------------------------

------------------------------------
 EncounterID   RevCodes   ClaimLine
------------- ---------- -----------
    Enc01        001          1

    Enc01        100          2

    Enc01        200          3

    Enc01        300          4

    Enc01        400          5

    Enc04        001          1

    Enc04        100          2
------------------------------------

The JSON output I'm looking for is as follows. I've tried using jsonlite but I can't seem to get any real traction:

[
    {
        "PatientID": "PID01",
        "PatientName": "John Doe",
        "PatientGroup": "Group A",
        "Encounters": [
            {
                "EncounterID": "Enc01",
                "EncounterType": "Outpatient",
                "ClaimLines": [
                    {
                        "ClaimLine": 1,
                        "RevenueCode": "001"
                    },
                    {
                        "ClaimLine": 2,
                        "RevenueCode": "100"
                    },
                    {
                        "ClaimLine": 3,
                        "RevenueCode": "200"
                    },
                    {
                        "ClaimLine": 4,
                        "RevenueCode": "300"
                    },
                    {
                        "ClaimLine": 5,
                        "RevenueCode": "400"
                    }
                ]
            },
            {
                "EncounterID": "Enc02",
                "EncounterType": "Outpatient"
            }
        ]
    },
    {
        "PatientID": "PID02",
        "PatientName": "Jane Doe",
        "PatientGroup": "Group B",
        "Encounters": [
            {
                "EncounterID": "Enc03",
                "EncounterType": "Inpatient"
            },
            {
                "EncounterID": "Enc04",
                "EncounterType": "Outpatient",
                "ClaimLines": [
                    {
                        "ClaimLine": 1,
                        "RevenueCode": "001"
                    },
                    {
                        "ClaimLine": 2,
                        "RevenueCode": "100"
                    }
                ]
            },
            {
                "EncounterID": "Enc05",
                "EncounterType": "SNF"
            }
        ]
    }
]

Any/all help would be GREATLY appreciated. As I mentioned before, I'm not opposed to using tools outside R.

Thanks!

Body:
A couple of data.table joins and you can get there too

library(data.table)
setDT( patients )
setDT( encounters )
setDT( encounterLines )

## do a 'left-join' by putting
## encounterLines onto encounters
dt_encounters <- encounterLines[
  encounters
  , on = "EncounterID"
  , nomatch = NA       ## indicates left-join
]

## make a list-column (required for JSON)
dt_encounters <- dt_encounters[
  , .(ClaimLines = list(.SD))
  , by = .(EncounterID, EncounterType, PatientID)
]

## do a 'left-join' by putting
## encounters onto patients
dt_patients <- dt_encounters[
  patients
  , on = "PatientID"
  , nomatch = NA
]

## make a list-column (required for JSON)
dt_patients <- dt_patients[
  , .(Encounters = list(.SD))
  , by = .(PatientID, PatientName, PatientGroup)
]

toJSON( dt_patients, pretty = TRUE )

[
  {
    "PatientID": "PID01",
    "PatientName": "John Doe",
    "PatientGroup": "Group A",
    "Encounters": [
      {
        "EncounterID": "Enc01",
        "EncounterType": "Outpatient",
        "ClaimLines": [
          {
            "RevCodes": "001",
            "ClaimLine": 1
          },
          {
            "RevCodes": "100",
            "ClaimLine": 2
          },
          {
            "RevCodes": "200",
            "ClaimLine": 3
          },
          {
            "RevCodes": "300",
            "ClaimLine": 4
          },
          {
            "RevCodes": "400",
            "ClaimLine": 5
          }
        ]
      },
      {
        "EncounterID": "Enc02",
        "EncounterType": "Outpatient",
        "ClaimLines": [
          {}
        ]
      }
    ]
  },
  {
    "PatientID": "PID02",
    "PatientName": "Jane Doe",
    "PatientGroup": "Group B",
    "Encounters": [
      {
        "EncounterID": "Enc03",
        "EncounterType": "Inpatient",
        "ClaimLines": [
          {}
        ]
      },
      {
        "EncounterID": "Enc04",
        "EncounterType": "Outpatient",
        "ClaimLines": [
          {
            "RevCodes": "001",
            "ClaimLine": 1
          },
          {
            "RevCodes": "100",
            "ClaimLine": 2
          }
        ]
      },
      {
        "EncounterID": "Enc05",
        "EncounterType": "SNF",
        "ClaimLines": [
          {}
        ]
      }
    ]
  }
]


问:
URL rewriting is rewriting ALL my files with two segments
This is my rule in web config

```<code><rule name="rewrite">
  <match url="^([^/]+)/([^/]+)?$" />
<action type="Rewrite" url="/review.aspx?c={R:1}&t={R:2}" appendQueryString="false" />
</rule>
</code>```

Which successfully turns review.aspx?c=value&t=value into /value/value

My problem now is, my /css/style.css now loads as review.aspx

Is there a way to stop this? Not only with CSS, but with all instances?

答:
Because of the match pattern, you may need to add an exclusion, something like:</p>

```<code><conditions logicalGrouping="MatchAll">
    <add input="{REQUEST_URI}" pattern="\.js|\.css|\.jpg" negate="true" />
</conditions>
</code>```

Body:
This is my rule in web config

<rule name="rewrite">
  <match url="^([^/]+)/([^/]+)?$" />
<action type="Rewrite" url="/review.aspx?c={R:1}&t={R:2}" appendQueryString="false" />
</rule>

Which successfully turns review.aspx?c=value&t=value into /value/value

My problem now is, my /css/style.css now loads as review.aspx

Is there a way to stop this? Not only with CSS, but with all instances?

Body:
Because of the match pattern, you may need to add an exclusion, something like:

<conditions logicalGrouping="MatchAll">
    <add input="{REQUEST_URI}" pattern="\.js|\.css|\.jpg" negate="true" />
</conditions>


问:
grails file upload
Hey. I need to upload some files (images/pdf/pp) to my SQLS Database and thereafter, download it again. I'm not sure what is the best solution - store it as bytes, or store it as file (not sure if possible). I need later to databind multiple domain classes together with that file upload.

Any help would be very much apreciated,
JM

答:
saving files in the file system or in the DB is a general question which is asked here several times.

check this: Store images(jpg,gif,png) in filesystem or DB?

I recommend to save the files in the file system and just save the path in the DB.
(if you want to work with google app-engine though you have to save the file as byte array in the DB as saving files in the file system is not possible with google app-engine)

To upload file with grails check this: http://www.grails.org/Controllers+-+File+Uploads

ContentLicense: CC BY-SA 3.0

Title: grails file upload


问:
SubtleCrypto.wrapKey usage: can exportKey but not wrapKey?
I'm trying to wrap an RSA private key using an AES-256 key-wrapping key, using the SubtleCrypto API.  I've managed to make the RSA keys and key-wrapping AES key (plus another symmetric AES key) using generateKey, but wrapKey fails on the RSA private key.

I can successfully export and then import the RSA private key, and I can successfully wrap and unwrap a general-purpose AES key.  But I get a "data provide to an operation does not meet requirements" error when trying to wrap the RSA private key, and I don't understand what I'm doing wrong.

HTML file for testing:

```<code><!DOCTYPE html>
<html lang="eng-US">
  <head>
    <meta charset="UTF-8">
    <title>Test WebCrypto.subtle</title>
  </head>
  <body>
    <h1>Test WebCrypto.subtle Functions</h1>
    <div id="output">
    </div>
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.js"></script>
    <script type="text/javascript">
     function TestCrypto( ) {
       $('#output').append( 'Starting test...<br/>' );
       let info = {};

       window.test_result = info;

       let seq = crypto.subtle.generateKey( { name: 'RSA-OAEP',
                                              modulusLength: 1024,
                                              publicExponent: new Uint8Array( [ 1, 0, 1 ] ),
                                              hash: 'SHA-256' },
                                            true,   // extractable
                                            [ 'encrypt', 'decrypt' ] )
                       .then( (rsaKey) =>
                         {
                           <span class="math-container">$('#output').append( 'Created RSA key<br/>' );
                           info.RSA = rsaKey;
                           return crypto.subtle.generateKey( { name: 'AES-GCM',
                                                               length: 256 },
                                                             true,
                                                             [ 'encrypt', 'decrypt' ] )
                         } )
                       .then( (symKey) =>
                         {
                           $('#output').append( 'Created symmetric AES key<br/>' );
                           info.AES = symKey;
                           return crypto.subtle.generateKey( { name: 'AES-KW',
                                                               length: 256 },
                                                             true,
                                                             [ 'wrapKey', 'unwrapKey' ] )
                         } )
                       .then( (kek) =>
                         {
                           $('#output').append( 'Created key-encryption AES key<br/>' );
                           info.KEK = kek;
                           return crypto.subtle.exportKey( 'pkcs8',
                                                           info.RSA.privateKey );
                         } )
                       .then( (expPrivKey) =>
                         {
                           $('#output').append( 'Exported RSA private key<br/>' );
                           info.exportedPrivateKey = expPrivKey;
                           return crypto.subtle.importKey( 'pkcs8',
                                                           info.exportedPrivateKey,
                                                           { name: 'RSA-OAEP',
                                                             hash: 'SHA-256' },
                                                           true,
                                                           [ 'decrypt', 'unwrapKey' ] );
                         } )
                       .then( (impPrivKey) =>
                         {
                           $('#output').append( 'Imported RSA private key<br/>' );
                           info.importedPrivateKey = impPrivKey;
                           /* Wrapping & unwrapping an AES key works...
                           return crypto.subtle.wrapKey( 'raw',
                                                         info.AES,
                                                         info.KEK,
                                                         'AES-KW' );
                            */
                           /* Wrapping & unwrapping an RSA key doesn't work... */
                           return crypto.subtle.wrapKey( 'pkcs8',
                                                         info.RSA.privateKey,
                                                         info.KEK,
                                                         'AES-KW' );
                         } )
                       .then( (wrappedKey) =>
                         {
                           $('#output').append( 'Wrapped a key<br/>' );
                           info.wrappedKey = wrappedKey;
                           /*
                           return crypto.subtle.unwrapKey( 'raw',
                                                           info.wrappedKey,
                                                           info.KEK,
                                                           'AES-KW',
                                                           { name: 'AES-GCM',
                                                             length: 256 },
                                                           true,
                                                           [ 'encrypt', 'decrypt' ] );
                           */
                           return crypto.subtle.unwrapKey( 'pkcs8',
                                                           info.wrappedPrivateKey,
                                                           info.KEK,
                                                           'AES-KW',
                                                           { name: 'RSA-OAEP',
                                                             // These items shouldn't be needed, but don't help
                                                             // even if you add them.
                                                             // modulusLength: 1024,
                                                             // publicExponent: new Uint8Array( [ 1, 0, 1 ] ),
                                                             hash: 'SHA-256' },
                                                           true,
                                                           [ 'decrypt', 'unwrapKey' ] );
                         } )
                       .then( (unwrappedKey) =>
                         {
                           $('#output').append( 'Unwrapped the key<br/>' );
                           info.unwrappedKey = unwrappedKey;
                           $('#output').append( 'Testing complete, check console for results<br/>' );
                           console.log( info );
                           window.test_result = info;
                           return info;
                         } )
                       .catch( (e) =>
                         {
                           $</span>('#output').append( 'Key testing failed<br/>' )
                                       .append( e.toString( ) )
                                       .append( '<br/>' );
                         } );
     }

     $(document).ready( TestCrypto );
    </script>
  </body>
</html>
</code>```

答:
After a lot of testing and re-reading docs, I found the section that solves this problem:

One advantage of using AES-KW over another AES mode such as AES-GCM is
  that AES-KW does not require an initialization vector. To use
  AES-KW, the input must be a multiple of 64 bits.

OwnerDisplayName: Dave M.

Body:
I'm trying to wrap an RSA private key using an AES-256 key-wrapping key, using the SubtleCrypto API.  I've managed to make the RSA keys and key-wrapping AES key (plus another symmetric AES key) using generateKey, but wrapKey fails on the RSA private key.

I can successfully export and then import the RSA private key, and I can successfully wrap and unwrap a general-purpose AES key.  But I get a "data provide to an operation does not meet requirements" error when trying to wrap the RSA private key, and I don't understand what I'm doing wrong.

HTML file for testing:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Test WebCrypto.subtle</title>

Test WebCrypto.subtle Functions


问:
VBA - Do Loop (nested)
I'm writing a macro that will break up records into separate batches once the dollar amount reaches 1 billion.

Workbook Values

```<code>Values:
A1: 450M
A2: 450M
A3: 400M
A4: 400M
A5: 100M
A6: 300M
*continue until end of range*
</code>```

For F1 and F2, they'll be a part of batch 1. For cells F3:F5, they'll be in batch 2. F6 breaks into a new batch.

Desired Results:

```<code>A1: 450M; B1: Batch 1
A2: 450M; B2: Batch 1
A3: 400M; B3: Batch 2
A4: 400M; B4: Batch 2
A5: 100M; B5: Batch 2
A6: 300M; B6: Batch 3
*continue until end of range*
</code>```

What VBA Loop should I use to do this?

```<code>Sub Determine_Batches()
    Dim Ws As Worksheet
    Dim vDB, vR(), vS() 'vDB will be the Row Count while vR() will be the array?
    Dim i As Long, n As Long
    Dim Cnt As Long 'This inserts the row we're working on into the array
    Dim TotalDrCr As Currency

    Set Ws = ActiveSheet
    With Ws
        'Get the Count of Cells we're reviewing
        vDB = .Range("I2", .Range("I" & Rows.Count).End(xlUp))
        'Debug.Print vDB
    End With

    n = UBound(vDB, 1) 'Declare the Upperbound -> vDB= Ending Row , 1= Starting Row
    ReDim vR(1 To n, 1 To 1) 'The Array that will hold the Batch #'s on each row
    ReDim vS(1 To n, 1 To 1) 'The Array that will show us the Running Total's on each row
        vR(1, 1) = "Batch 1" 'This declares the starting Batch # - This would be a place to obtain the first batch # from Accounting

    'Declarations
        i = 1 'Declare the starting Row and populate values
        Cnt = 1 'This declares the start of the count
        TotalDrCr = vDB(1, 1) 'This declares the sum
        vR(i, 1) = "Batch " & Cnt '-> I found this needed to be added as J2 wasn't being populated
        vS(i, 1) = TotalDrCr

        'Track in the immediate window
        Debug.Print "J" & i & "-" & vR(i, 1) & "-" & TotalDrCr & "-" & vS(i, 1)

    'The all powerful loop
    For i = 2 To n
        'Change the Batch Count to Manual Split out
        'This isn't working, probably because of the above
        If vDB(i, 1) > 10 ^ 9 Then
        vR(i, 1) = "Manual"
        End If

        TotalDrCr = TotalDrCr + vDB(i, 1) 'Get the Total Debit and Credit Amount
        If TotalDrCr > 500000000 Then ' Condition to meet to add +1 to the batch, moving us forward
           Cnt = Cnt + 1 'Move the counter forward
           TotalDrCr = vDB(i, 1) 'this inserts the total
           vR(i, 1) = "Batch " & Cnt 'Add +1 to the batch # if DrCr sum exceeds 1 billion
           vS(i, 1) = TotalDrCr
        ElseIf TotalDrCr < 10 ^ 9 Then
            vS(i, 1) = TotalDrCr
        End If

        vR(i, 1) = "Batch " & Cnt 'Commit the cell and batch # to the array
            Debug.Print "J" & i & "-" & vR(i, 1) & "-" & TotalDrCr & "-" & vS(i, 1)
    Next i

    'This prints out the results of the array to our worksheet
    Ws.Range("J2").Resize(n) = vR 'Print out the array to J2 to n/ or end of the range
    Ws.Range("K2").Resize(n) = vS
End Sub
</code>```

答:
Try</p>

```<code>Sub test()

    Dim Ws As Worksheet
    Dim vDB, vR()
    Dim i As Long, n As Long
    Dim Cnt As Long
    Dim Total As Currency

    Set Ws = ActiveSheet
    With Ws
        vDB = .Range("a1", .Range("a" & Rows.Count).End(xlUp))
    End With

    n = UBound(vDB, 1)
    ReDim vR(1 To n, 1 To 1)

    vR(1, 1) = "Batch 1"
    Total = vDB(1, 1)
    Cnt = 1
    For i = 2 To n
        Total = Total + vDB(i, 1)
        If Total > 10 ^ 9 Then
           Cnt = Cnt + 1
           Total = vDB(i, 1)
           vR(i, 1) = "Batch " & Cnt
        End If
        vR(i, 1) = "Batch " & Cnt
    Next i

    Ws.Range("b1").Resize(n) = vR
End Sub
</code>```

Title: VBA - Do Loop (nested)

Body:
I'm writing a macro that will break up records into separate batches once the dollar amount reaches 1 billion.

Workbook Values

Values:
A1: 450M
A2: 450M
A3: 400M
A4: 400M
A5: 100M
A6: 300M
*continue until end of range*

For F1 and F2, they'll be a part of batch 1. For cells F3:F5, they'll be in batch 2. F6 breaks into a new batch.

Desired Results:

A1: 450M; B1: Batch 1
A2: 450M; B2: Batch 1
A3: 400M; B3: Batch 2
A4: 400M; B4: Batch 2
A5: 100M; B5: Batch 2
A6: 300M; B6: Batch 3
*continue until end of range*

What VBA Loop should I use to do this?

Sub Determine_Batches()
    Dim Ws As Worksheet
    Dim vDB, vR(), vS() 'vDB will be the Row Count while vR() will be the array?
    Dim i As Long, n As Long
    Dim Cnt As Long 'This inserts the row we're working on into the array
    Dim TotalDrCr As Currency

    Set Ws = ActiveSheet
    With Ws
        'Get the Count of Cells we're reviewing
        vDB = .Range("I2", .Range("I" & Rows.Count).End(xlUp))
        'Debug.Print vDB
    End With

    n = UBound(vDB, 1) 'Declare the Upperbound -> vDB= Ending Row , 1= Starting Row
    ReDim vR(1 To n, 1 To 1) 'The Array that will hold the Batch #'s on each row
    ReDim vS(1 To n, 1 To 1) 'The Array that will show us the Running Total's on each row
        vR(1, 1) = "Batch 1" 'This declares the starting Batch # - This would be a place to obtain the first batch # from Accounting

    'Declarations
        i = 1 'Declare the starting Row and populate values
        Cnt = 1 'This declares the start of the count
        TotalDrCr = vDB(1, 1) 'This declares the sum
        vR(i, 1) = "Batch " & Cnt '-> I found this needed to be added as J2 wasn't being populated
        vS(i, 1) = TotalDrCr

        'Track in the immediate window
        Debug.Print "J" & i & "-" & vR(i, 1) & "-" & TotalDrCr & "-" & vS(i, 1)

    'The all powerful loop
    For i = 2 To n
        'Change the Batch Count to Manual Split out
        'This isn't working, probably because of the above
        If vDB(i, 1) > 10 ^ 9 Then
        vR(i, 1) = "Manual"
        End If

        TotalDrCr = TotalDrCr + vDB(i, 1) 'Get the Total Debit and Credit Amount
        If TotalDrCr > 500000000 Then ' Condition to meet to add +1 to the batch, moving us forward
           Cnt = Cnt + 1 'Move the counter forward
           TotalDrCr = vDB(i, 1) 'this inserts the total
           vR(i, 1) = "Batch " & Cnt 'Add +1 to the batch # if DrCr sum exceeds 1 billion
           vS(i, 1) = TotalDrCr
        ElseIf TotalDrCr < 10 ^ 9 Then
            vS(i, 1) = TotalDrCr
        End If

        vR(i, 1) = "Batch " & Cnt 'Commit the cell and batch # to the array
            Debug.Print "J" & i & "-" & vR(i, 1) & "-" & TotalDrCr & "-" & vS(i, 1)
    Next i

    'This prints out the results of the array to our worksheet
    Ws.Range("J2").Resize(n) = vR 'Print out the array to J2 to n/ or end of the range
    Ws.Range("K2").Resize(n) = vS
End Sub

Body:
Try

Sub test()

    Dim Ws As Worksheet
    Dim vDB, vR()
    Dim i As Long, n As Long
    Dim Cnt As Long
    Dim Total As Currency

    Set Ws = ActiveSheet
    With Ws
        vDB = .Range("a1", .Range("a" & Rows.Count).End(xlUp))
    End With

    n = UBound(vDB, 1)
    ReDim vR(1 To n, 1 To 1)

    vR(1, 1) = "Batch 1"
    Total = vDB(1, 1)
    Cnt = 1
    For i = 2 To n
        Total = Total + vDB(i, 1)
        If Total > 10 ^ 9 Then
           Cnt = Cnt + 1
           Total = vDB(i, 1)
           vR(i, 1) = "Batch " & Cnt
        End If
        vR(i, 1) = "Batch " & Cnt
    Next i

    Ws.Range("b1").Resize(n) = vR
End Sub


问:
How to set a text field up with c#
I am creating an ios app and in visual studio using storyboard. I have created a text field and I want to let the userName = what ever the user inputs. I am using c#. </p>

答:
You can create a textbox to achieve the user inputting.

Like the following:

```<code>string username = textBox1.Text;
</code>```

If you want to know more about how it work in an ios app, you can refer to Hello, iOS – Quickstart.

Title: How to set a text field up with c#

Body:
You can create a textbox to achieve the user inputting.

Like the following:

string username = textBox1.Text;

If you want to know more about how it work in an ios app, you can refer to Hello, iOS – Quickstart.


问:
One-To-Many relationship with navigation property only on one side?
I have perfectly fine one-to-many relationship between two tables: Play and Player:

```<code>public class Player
{
    public int PlayerId { get; set; }
    public string Name { get; set; }

    public ICollection<Play> Plays { get; set; }
}

public class Play
{
    public int PlayId { get; set; }

    public int PlayerId { get; set; }
    public Player Player { get; set; }
}

modelBuilder.Entity<Play>()
    .HasOne<Player>(p => p.Player)
    .WithMany(p => p.Plays)
    .OnDelete(DeleteBehavior.Cascade)
    .HasForeignKey(p => p.PlayerId)
    .IsRequired();
</code>```

Is it possible to omit navigation property on side? For example remove Plays collection from Player?

```<code>public class Player
{
    public int PlayerId { get; set; }
    public string Name { get; set; }
}
</code>```

I'm gonna have two specific questions:

Is it possible to do it at all?

Is it possible to do it, without relying on EF Core conventions - e.g. "Id" is a primary key etc...? (Meaning, having everything explicit, either in fluent API or as Annotations)

答:
Is it possible to omit navigation property on side? For example remove Plays collection from Player?

Absolutely possible. Write you entity configuration as follows:

```<code>modelBuilder.Entity<Play>()
    .HasOne<Player>(p => p.Player)
    .WithMany() // <-- Here it is
    .HasForeignKey(p => p.PlayerId)
    .OnDelete(DeleteBehavior.Cascade)
    .IsRequired();
</code>```

Is it possible to do it, without relying on EF Core conventions - e.g. "Id" is a primary key etc...? (Meaning, having everything explicit, either in fluent API or as Annotations)

No! Its not possible without Fluent API.

Body:
I have perfectly fine one-to-many relationship between two tables: Play and Player:

public class Player
{
    public int PlayerId { get; set; }
    public string Name { get; set; }

    public ICollection<Play> Plays { get; set; }
}

public class Play
{
    public int PlayId { get; set; }

    public int PlayerId { get; set; }
    public Player Player { get; set; }
}

modelBuilder.Entity<Play>()
    .HasOne<Player>(p => p.Player)
    .WithMany(p => p.Plays)
    .OnDelete(DeleteBehavior.Cascade)
    .HasForeignKey(p => p.PlayerId)
    .IsRequired();

Is it possible to omit navigation property on side? For example remove Plays collection from Player?

public class Player
{
    public int PlayerId { get; set; }
    public string Name { get; set; }
}

I'm gonna have two specific questions:

Is it possible to do it at all?

Is it possible to do it, without relying on EF Core conventions - e.g. "Id" is a primary key etc...? (Meaning, having everything explicit, either in fluent API or as Annotations)

Body:
Is it possible to omit navigation property on side? For example remove Plays collection from Player?

Absolutely possible. Write you entity configuration as follows:

modelBuilder.Entity<Play>()
    .HasOne<Player>(p => p.Player)
    .WithMany() // <-- Here it is
    .HasForeignKey(p => p.PlayerId)
    .OnDelete(DeleteBehavior.Cascade)
    .IsRequired();

Is it possible to do it, without relying on EF Core conventions - e.g. "Id" is a primary key etc...? (Meaning, having everything explicit, either in fluent API or as Annotations)

No! Its not possible without Fluent API.


问:
Sum multiple fields with select new and where raises error 'Model' does not have definition of 'Sum'
First timer to C# and want to see if i can change a query. Basically, I want an aggregated values of the two currency columns in one go. There are Car dealer, with each dealer having a list of cars in their possession. So I want to get list of car dealers along with a total cost of all the cars under them. For now what I am doing is I loop over each dealer, get the cars then loop the cars over summing each cars price, which sounds inefficient to me.

```<code>public object DealerObj(Dealer d)
{
    var cars = d.DealerCars.Select(cc => new { cc.Cost }).ToList();

    var totalCost decimal = 0;
    foreach (var car in cars){
        totalCost += car.Cost;
    }

    return new {
        d.DealerName,
        totalCost = totalCost
    }
}
</code>```

While I am getting the correct results, the query appears slower. Is there a way to do a Sum() on the results and avoid the loop, something like below

```<code>   var cars = d.DealerCars.Select(cc => new { total = cc.Sum(s=>s.Cost) });
</code>```

答:
It appears to me that you just need to do this:

```<code>public object DealerObj(Dealer d)
{
    return new
    {
        d.DealerName,
        totalCost = d.DealerCars.Sum(cc => cc.Cost),
    };
}
</code>```

It seems like a fairly pointless method. I would love to know how you are using the above code, espcially how you're turning the returned object into something useful.

Body:
First timer to C# and want to see if i can change a query. Basically, I want an aggregated values of the two currency columns in one go. There are Car dealer, with each dealer having a list of cars in their possession. So I want to get list of car dealers along with a total cost of all the cars under them. For now what I am doing is I loop over each dealer, get the cars then loop the cars over summing each cars price, which sounds inefficient to me.

public object DealerObj(Dealer d)
{
    var cars = d.DealerCars.Select(cc => new { cc.Cost }).ToList();

    var totalCost decimal = 0;
    foreach (var car in cars){
        totalCost += car.Cost;
    }

    return new {
        d.DealerName,
        totalCost = totalCost
    }
}

While I am getting the correct results, the query appears slower. Is there a way to do a Sum() on the results and avoid the loop, something like below

   var cars = d.DealerCars.Select(cc => new { total = cc.Sum(s=>s.Cost) });

Body:
It appears to me that you just need to do this:

public object DealerObj(Dealer d)
{
    return new
    {
        d.DealerName,
        totalCost = d.DealerCars.Sum(cc => cc.Cost),
    };
}

It seems like a fairly pointless method. I would love to know how you are using the above code, espcially how you're turning the returned object into something useful.


问:
Status Update using Nerilcrookes' OAuth extension to CakePHP HttpSocket returns "incorrect signature error"
I'm using Neilcrookes' OAuth extension to CakePHP HttpSocket ( http://www.neilcrookes.com/2010/04/12/cakephp-oauth-extension-to-httpsocket/ )

My request looks like:

```<code>Array (
    [method] => POST
    [uri] => Array (
        [host] => api.twitter.com
        [path] => 1/statuses/update.json
    )
    [auth] => Array (
        [method] => OAuth
        [oauth_token] => xxx
        [oauth_token_secret] => xxx
        [oauth_consumer_key] => xxx
        [oauth_consumer_secret] => xxx
    )
    [body] => Array (
        [status] => Hello World
    )
)
</code>```

I have the oauth_token and oauth_token_secret from the previous request from the user

response looks like {“request”:”\/1\/statuses\/update.json”,”error”:”Incorrect signature”}

Thanks in Advance

答: Just a wild guess: But could it be that your signature isn't correct?</p>

Body:
I'm using Neilcrookes' OAuth extension to CakePHP HttpSocket ( http://www.neilcrookes.com/2010/04/12/cakephp-oauth-extension-to-httpsocket/ )

My request looks like:

Array (
    [method] => POST
    [uri] => Array (
        [host] => api.twitter.com
        [path] => 1/statuses/update.json
    )
    [auth] => Array (
        [method] => OAuth
        [oauth_token] => xxx
        [oauth_token_secret] => xxx
        [oauth_consumer_key] => xxx
        [oauth_consumer_secret] => xxx
    )
    [body] => Array (
        [status] => Hello World
    )
)

I have the oauth_token and oauth_token_secret from the previous request from the user

response looks like {“request”:”\/1\/statuses\/update.json”,”error”:”Incorrect signature”}

Thanks in Advance


答:
This is an optimization called join elimination. Because t2.t2 us unique, the optimizer knows that every row retrieved from t1 can only ever retrieve one row from t2. Since there is nothing projected from t2, there is no need to perform the join.
If you do

```<code>select tid, t1 from v_1;
</code>```

you will see that we do not perform the join. However, if we project from t2, then the join is needed.

Title: why oracle optimizer not eliminate this case?

Body:
i am doubting about this case, but not clear why.

consider the following sql :

create table t1(tid int not null, t1 int not null);
create table t2(t2 int not null, tname varchar(30) null);
create unique index i_t2 on t2(t2);
create or replace view v_1 as
select t1.tid,t1.t1,max(t2.tname) as tname
from t1 left join t2
on t1.t1 = t2.t2
group by t1.tid,t1.t1;

then check the execution plan for select count(1) from v_1, the t2 is eliminated by the optimizer:

SQL> select count(1) from v_1;

Execution Plan
----------------------------------------------------------
Plan hash value: 3243658773

----------------------------------------------------------------------------------
| Id  | Operation            | Name      | Rows  | Bytes | Cost (%CPU)| Time     |
----------------------------------------------------------------------------------
|   0 | SELECT STATEMENT     |           |     1 |       |     3  (34)| 00:00:01 |
|   1 |  SORT AGGREGATE      |           |     1 |       |            |          |
|   2 |   VIEW               | VM_NWVW_0 |     1 |       |     3  (34)| 00:00:01 |
|   3 |    HASH GROUP BY     |           |     1 |    26 |     3  (34)| 00:00:01 |
|   4 |     TABLE ACCESS FULL| T1        |     1 |    26 |     2   (0)| 00:00:01 |
----------------------------------------------------------------------------------

but if the index i_t2 is dropped or recreated without unique attribute,

the table t2 is not eliminated in execution plan:

SQL> drop index i_t2;

Index dropped.

SQL> select count(1) from v_1;

Execution Plan
----------------------------------------------------------
Plan hash value: 2710188186

-----------------------------------------------------------------------------------
| Id  | Operation             | Name      | Rows  | Bytes | Cost (%CPU)| Time     |
-----------------------------------------------------------------------------------
|   0 | SELECT STATEMENT      |           |     1 |       |     5  (20)| 00:00:01 |
|   1 |  SORT AGGREGATE       |           |     1 |       |            |          |
|   2 |   VIEW                | VM_NWVW_0 |     1 |       |     5  (20)| 00:00:01 |
|   3 |    HASH GROUP BY      |           |     1 |    39 |     5  (20)| 00:00:01 |
|*  4 |     HASH JOIN OUTER   |           |     1 |    39 |     4   (0)| 00:00:01 |
|   5 |      TABLE ACCESS FULL| T1        |     1 |    26 |     2   (0)| 00:00:01 |
|   6 |      TABLE ACCESS FULL| T2        |     1 |    13 |     2   (0)| 00:00:01 |
-----------------------------------------------------------------------------------

it seems even if the index is removed,

the result of select count(1) from v_1 also equal to
select count(1) from (select tid,t1 from t1 group by tid,t1)

why the optimizer does not eliminate t2 in the second case?

is there any principle or actual data example discribing this?
thanks :)

Body:
This is an optimization called join elimination. Because t2.t2 us unique, the optimizer knows that every row retrieved from t1 can only ever retrieve one row from t2. Since there is nothing projected from t2, there is no need to perform the join.
If you do

select tid, t1 from v_1;

you will see that we do not perform the join. However, if we project from t2, then the join is needed.


问:
Why does option refuse to append to select element?
I'm trying to append an option to a select element from a function that is fired when a button is clicked but it isn't working. What am I doing wrong? It almost seems as if the element does not exist, because even empty() does not work. But if I check for its existence and show an alert, it returns that the element does exist. Here's my code.

function Add(ID) {
  var text = "";
  if (ID == "1") {
    text = "January";
  } else
  if (ID == "2") {
    text = "February"
  } else
  if (ID == "3") {
    text = "March";
  }
  $("#Month").append($("<option></option>").val(ID).html(text));
}
Add(1);
Add(3);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="Month"></select></code>```

答:
Your should change from ID == "1" to ID == 1. Because you are passing number instead of character or string.

Add(1);
Add(3);

function Add(ID) {
        var text = "";
        if (ID == 1) {
            text = "January";
        }
        else if (ID == 2) {
            text = "February"
        }else if (ID == 3){
            text = "March";
        }
        $("#Month").append($("<option></option>").val(ID).html(text));
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="Month">
  <option>--Please select--</option>
</select></code>```

Refactor code

var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
Add(1);
Add(3);

Add(0);
Add(13);
function Add(ID) {
        if(ID <= 0 || ID >= 13){
          console.log("ID: " + ID + " must in range 1 - 12");
          return;
        }
        $("#Month").append($("<option></option>").val(ID).html(months[ID - 1]));
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="Month">
  <option>--Please select--</option>
</select></code>```

Body:
I'm trying to append an option to a select element from a function that is fired when a button is clicked but it isn't working. What am I doing wrong? It almost seems as if the element does not exist, because even empty() does not work. But if I check for its existence and show an alert, it returns that the element does exist. Here's my code.

function Add(ID) {
  var text = "";
  if (ID == "1") {
    text = "January";
  } else
  if (ID == "2") {
    text = "February"
  } else
  if (ID == "3") {
    text = "March";
  }
  $("#Month").append($("<option></option>").val(ID).html(text));
}
Add(1);
Add(3);

<select id="Month"></select>

Body:
Your should change from ID == "1" to ID == 1. Because you are passing number instead of character or string.

Add(1);
Add(3);

function Add(ID) {
        var text = "";
        if (ID == 1) {
            text = "January";
        }
        else if (ID == 2) {
            text = "February"
        }else if (ID == 3){
            text = "March";
        }
        $("#Month").append($("<option></option>").val(ID).html(text));
    }

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="Month">
  <option>--Please select--</option>
</select>

Refactor code

var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
Add(1);
Add(3);

Add(0);
Add(13);
function Add(ID) {
        if(ID <= 0 || ID >= 13){
          console.log("ID: " + ID + " must in range 1 - 12");
          return;
        }
        $("#Month").append($("<option></option>").val(ID).html(months[ID - 1]));
    }

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="Month">
  <option>--Please select--</option>
</select>


问:
PHP / MySQL: Error after delete a row ta PHP page (filtered)
I have a problem with my delete function. Before that, I will brief to you about the flow of the system

1) At dashboard_engineer.php, there's 3 select options which is team, time from and time to.

2) user need to select 3 select option and press button "Search" to display the result.

3) The result will display at dashboard_engineer2.php.

4) The result will display all data rows and each row contains one delete button.

My problem is, after I click button delete, it was successful delete but the dashboard_engineer2.php page doesn't display the result that same as point 3 above. The result empty.

What I want is that, after delete, the dashboard_engineer2.php will display the remaining data rows that already filtered before. Below is my code.

dashboard_engineer.php

```<code><?php

    $smt = $conn->prepare("SELECT * FROM ot_team INNER JOIN ot_users ON ot_team.team_id = ot_users.team_id WHERE ot_users.roles_id = 7 AND ot_users.team_id <> 1 ORDER BY ot_users.fullname ASC");
    $smt->execute();
    $data = $smt->fetchAll();

?>

<form method = 'post' action = 'dashboard_engineer2.php' >
  <td width="40%">
    <select class="form-control"  name="team" id="team" required>
      <option value="">Please select...</option>
      <?php foreach ($data as $row2): ?>
      <option value= <?php echo $row2["team_id"]; ?> ><?php echo $row2["fullname"]; ?></option>
      <?php endforeach ?>
    </select>
  </td>
  <td width="1%"></td>
  <td width="20%"><input type="text" name="from" id="from" class="form-control" placeholder="From" required></td>
  <td width="1%"></td>
  <td width="20%"><input type="text" name="to" id="to" class="form-control" placeholder="To" required></td>
  <td width="1%"></td>
  <td width="10%"><button type="submit" value="Search" class="btn btn-primary" >Send</button><td>
</form>

<script>
$(document).ready(function(){
  $.datepicker.setDefaults({
    dateFormat: 'yy-mm-dd'
  });
  $(function(){
    $("#from").datepicker().attr("autocomplete", "off");;
    $("#to").datepicker().attr("autocomplete", "off");;
  });

});
</script>
</code>```

dashboard_engineer2.php

```<code><?php

    if(isset($_POST["from"], $_POST["to"], $_POST["team"])){

        $result = '';
        $query = "SELECT * FROM ot_report LEFT JOIN ot_users ON ot_report.badgeid = ot_users.badgeid WHERE ot_users.team_id = '".$_POST["team"]."' AND report_date BETWEEN '".$_POST["from"]."' AND '".$_POST["to"]."' ORDER BY ot_report.report_date DESC";
        $sql = $conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
        $sql -> execute();

        if($sql->rowCount() > 0){

        echo'

        <table class = "table-bordered" width = "100%">
        <thead>
        <tr>
        <th width = "10%"><input type="checkbox" id="checkAl"> All</th>
        <th width = "3%">id</th>
        <th width = "15%">Date</th>
        <th width = "30%">Task Name</th>
        <th width = "10%">Status</th>
        <th colspan = "2" width = "7%">Action</th>
        </tr>
        </thead>
        <tbody>';

            $i=0;

            while($row = $sql->fetch(PDO::FETCH_ASSOC)){

            $datereport = $row['report_date'];
            $datereport2 = strtotime($datereport);
            $report_date = date('d M Y', $datereport2);

            $report_id = $row["report_id"];

            echo'<tr>';
                echo '<td><input type="checkbox" id="checkItem" name="check[]" value='.$row['report_id'].'></td>';
                echo '<td>'.$report_id.'</td>';
                echo '<td>'.$report_date.'</td>';
                echo '<td>'.$row["task_name"].'</td>';
                echo '<td align="center"><strong>'.$row["report_status"].'</strong></td>';
                echo '<td align="center">';
                echo '<form action = "view_task/view_task.php" method = "post">';
                echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
                echo '<button type = "submit" class="btn-primary">View</button>';
                echo '</form>';

                echo "<form action = 'delete.php' method = 'post' onClick=\"return confirm('Do you want to remove team?')\">";
                echo '<input type = "hidden" name = "from" value = "'.$_POST["from"].'">';
                echo '<input type = "hidden" name = "to" value = "'.$_POST["to"].'">';
                echo '<input type = "hidden" name = "team" value = "'.$_POST["team"].'">';
                echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
                echo '<button type = "submit" class="btn-danger">Delete</button>';
                echo '</form>';

                echo '</td>';
            echo '</tr>';
            $i++;

            }
            echo '<tr>';
                echo '<td><p align="center"><button type="submit" class="btn-danger btn-sm" name="save">DELETE</button></p></td>';
            echo '</tr>';
            echo '</form>';

        }
        else
        {
            echo '
            <table class = "table-bordered" width = "100%">
            <thead>
            <tr>
            <th width = "5%">id</th>
            <th width = "12%">Date</th>
            <th width = "23%">Task Name</th>
            <th width = "10%">Status</th>
            <th width = "7%">Action</th>
            </tr>
            <tr>
            <td colspan="5">No report found</td>
            </tr>';
        }
        echo '</body></table></div></div>';

        }

?>
</code>```

delete.php

```<code>  <?php

        $report_id = $_POST['report_id'];

        $sql = "DELETE FROM ot_report WHERE report_id=:report_id";
        $query = $conn->prepare($sql);
        $query->execute(array(':report_id' => $report_id));

        header("Location: dashboard_engineer2.php");

  ?>
</code>```

Can anyone help me on how to fix this?

答:
You can try my code below , sorry if it is not run
delete.php

```<code>$from = $_POST["from"];
$to = $_POST["to"];
$team = $_POST["team"];
header("Location: dashboard_engineer2.php?from=$from&to=$to&team=$team");
</code>```

Then change condition seem like below.
dashboard_engineer2.php

```<code>
if(isset($_REQUEST["from"], $_REQUEST["to"], $_REQUEST["team"])){
</code>```

Hope it work well .

Body:
I have a problem with my delete function. Before that, I will brief to you about the flow of the system

1) At dashboard_engineer.php, there's 3 select options which is team, time from and time to.

2) user need to select 3 select option and press button "Search" to display the result.

3) The result will display at dashboard_engineer2.php.

4) The result will display all data rows and each row contains one delete button.

My problem is, after I click button delete, it was successful delete but the dashboard_engineer2.php page doesn't display the result that same as point 3 above. The result empty.

What I want is that, after delete, the dashboard_engineer2.php will display the remaining data rows that already filtered before. Below is my code.

dashboard_engineer.php

<?php

    $smt = $conn->prepare("SELECT * FROM ot_team INNER JOIN ot_users ON ot_team.team_id = ot_users.team_id WHERE ot_users.roles_id = 7 AND ot_users.team_id <> 1 ORDER BY ot_users.fullname ASC");
    $smt->execute();
    $data = $smt->fetchAll();

?>

<form method = 'post' action = 'dashboard_engineer2.php' >

    <select class="form-control"  name="team" id="team" required>
      <option value="">Please select...</option>
      <?php foreach ($data as $row2): ?>
      <option value= <?php echo $row2["team_id"]; ?> ><?php echo $row2["fullname"]; ?></option>
      <?php endforeach ?>
    </select>

  <input type="text" name="from" id="from" class="form-control" placeholder="From" required>

  <input type="text" name="to" id="to" class="form-control" placeholder="To" required>

  <button type="submit" value="Search" class="btn btn-primary" >Send</button>
</form>

dashboard_engineer2.php

<?php

    if(isset($_POST["from"], $_POST["to"], $_POST["team"])){

        $result = '';
        $query = "SELECT * FROM ot_report LEFT JOIN ot_users ON ot_report.badgeid = ot_users.badgeid WHERE ot_users.team_id = '".$_POST["team"]."' AND report_date BETWEEN '".$_POST["from"]."' AND '".$_POST["to"]."' ORDER BY ot_report.report_date DESC";
        $sql = $conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
        $sql -> execute();

        if($sql->rowCount() > 0){

        echo'

        <input type="checkbox" id="checkAl"> All
        id
        Date
        Task Name
        Status
        Action

';

            $i=0;

            while($row = $sql->fetch(PDO::FETCH_ASSOC)){

            $datereport = $row['report_date'];
            $datereport2 = strtotime($datereport);
            $report_date = date('d M Y', $datereport2);

            $report_id = $row["report_id"];

            echo'
';
                echo '<input type="checkbox" id="checkItem" name="check[]" value='.$row['report_id'].'>	';
                echo ''.$report_id.'	';
                echo ''.$report_date.'	';
                echo ''.$row["task_name"].'	';
                echo ''.$row["report_status"].'	';
                echo '';
                echo '<form action = "view_task/view_task.php" method = "post">';
                echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
                echo '<button type = "submit" class="btn-primary">View</button>';
                echo '</form>';

                echo "<form action = 'delete.php' method = 'post' onClick=\"return confirm('Do you want to remove team?')\">";
                echo '<input type = "hidden" name = "from" value = "'.$_POST["from"].'">';
                echo '<input type = "hidden" name = "to" value = "'.$_POST["to"].'">';
                echo '<input type = "hidden" name = "team" value = "'.$_POST["team"].'">';
                echo '<input type = "hidden" name = "report_id" value = "'.$report_id.'">';
                echo '<button type = "submit" class="btn-danger">Delete</button>';
                echo '</form>';

                echo '	';
            echo '
';
            $i++;

            }
            echo '
';
                echo '
<button type="submit" class="btn-danger btn-sm" name="save">DELETE</button>
	';
            echo '
';
            echo '</form>';

        }
        else
        {
            echo '

            id
            Date
            Task Name
            Status
            Action

            No report found

';
        }
        echo '

';

        }

?>

delete.php

  <?php

        $report_id = $_POST['report_id'];

        $sql = "DELETE FROM ot_report WHERE report_id=:report_id";
        $query = $conn->prepare($sql);
        $query->execute(array(':report_id' => $report_id));

        header("Location: dashboard_engineer2.php");

  ?>

Can anyone help me on how to fix this?

Body:
You can try my code below , sorry if it is not run
delete.php

$from = $_POST["from"];
$to = $_POST["to"];
$team = $_POST["team"];
header("Location: dashboard_engineer2.php?from=$from&to=$to&team=$team");

Then change condition seem like below.
dashboard_engineer2.php

if(isset($_REQUEST["from"], $_REQUEST["to"], $_REQUEST["team"])){

Hope it work well .


问:
VBA Compile Error: Syntax Error for Saving Excel in PDF for Excel 2019
I'm getting a "Compile Error: Syntax Error" when running the code below using Excel 2019. It works with the older version Excel, but not on 2019. How can I fix this and what's causing it?

the error line

```<code>ReportSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _

        ThisWorkbook.Path & "\" & Cell, _

        Quality:=xlQualityStandard, IncludeDocProperties:=True, _

        IgnorePrintAreas:=True, OpenAfterPublish:=False
</code>```

The entire code

```<code>Option Explicit

Private Sub CommandButton1_Click()

Dim MyFolder As String, MyFile As String

Dim StartTime As Double

Dim MinutesElapsed As String

Dim Filename As String

Dim Cell As String

Dim Counter As Long

            If ThisWorkbook.Sheets("Sheet1").Range("C7").Value = vbNullString Then

            MsgBox "Enter Tab Name"

            Exit Sub

            End If

StartTime = Timer

            With Application.FileDialog(msoFileDialogFolderPicker)

               .AllowMultiSelect = False

               .Title = "Select a Folder"

               If .Show = True Then

               MyFolder = .SelectedItems(1)

               End If

               If .SelectedItems.Count = 0 Then Exit Sub

               Err.Clear

            End With

            'Turns settings off
            Application.ScreenUpdating = False

            Application.DisplayStatusBar = False

            Application.EnableEvents = False

            Application.Calculation = xlCalculationManual

            MyFile = Dir(MyFolder & "\", vbReadOnly)

Do While MyFile <> ""

        DoEvents

        On Error GoTo 0

        Workbooks.Open Filename:=MyFolder & "\" & MyFile, UpdateLinks:=False

Dim ReportSheet As Worksheet

Dim MySheet As String

Dim allColumns As Range

MySheet = ThisWorkbook.Sheets("Sheet1").Range("C7").Value

Set ReportSheet = Sheets(MySheet)

Set allColumns = ReportSheet.Columns("N:S")

        allColumns.Hidden = True

        With ReportSheet.PageSetup

         .Zoom = False

         .FitToPagesWide = 1    '.FitToPagesTall = 1

        End With

Filename = ActiveWorkbook.Name

Cell = Replace(Filename, ".xlsx", ".PDF")

    ReportSheet.Select

    ReportSheet.PageSetup.Orientation = xlLandscape

    ReportSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _

        ThisWorkbook.Path & "\" & Cell, _

        Quality:=xlQualityStandard, IncludeDocProperties:=True, _

        IgnorePrintAreas:=True, OpenAfterPublish:=False

Counter = Counter + 1

0

        Workbooks(MyFile).Close SaveChanges:=False

        MyFile = Dir

Loop

    'turns settings back on that you turned off before looping folders

        Application.ScreenUpdating = True

        Application.DisplayStatusBar = True

        Application.EnableEvents = True

        Application.Calculation = xlCalculationManual

MinutesElapsed = Format((Timer - StartTime) / 86400, "hh:mm:ss")

MsgBox "Successfully Converted " & Counter & " Files in " & MinutesElapsed & " minutes", vbInformation

End Sub
</code>```

答:
Leaving a blank line when you are using the line continuation _ character is not allowed in any Excel version (AFAIK)

The code giving you trouble should be:

```<code>ReportSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=ThisWorkbook.Path & "\" & Cell, _
                                Quality:=xlQualityStandard, IncludeDocProperties:=True, _
                                IgnorePrintAreas:=True, OpenAfterPublish:=False
</code>```

Try indenting your code properly and remove the extra lines.

Code:

```<code>Option Explicit

Private Sub CommandButton1_Click()

    Dim MyFolder As String, MyFile As String

    Dim StartTime As Double

    Dim MinutesElapsed As String

    Dim Filename As String

    Dim Cell As String

    Dim Counter As Long

    If ThisWorkbook.Sheets("Sheet1").Range("C7").Value = vbNullString Then

        MsgBox "Enter Tab Name"

        Exit Sub

    End If

    StartTime = Timer

    With Application.FileDialog(msoFileDialogFolderPicker)

        .AllowMultiSelect = False

        .Title = "Select a Folder"

        If .Show = True Then

            MyFolder = .SelectedItems(1)

        End If

        If .SelectedItems.Count = 0 Then Exit Sub

        Err.Clear

    End With

    'Turns settings off
    Application.ScreenUpdating = False

    Application.DisplayStatusBar = False

    Application.EnableEvents = False

    Application.Calculation = xlCalculationManual

    MyFile = Dir(MyFolder & "\", vbReadOnly)

    Do While MyFile <> ""

        DoEvents

        On Error GoTo 0

        Workbooks.Open Filename:=MyFolder & "\" & MyFile, UpdateLinks:=False

        Dim ReportSheet As Worksheet

        Dim MySheet As String

        Dim allColumns As Range

        MySheet = ThisWorkbook.Sheets("Sheet1").Range("C7").Value

        Set ReportSheet = Sheets(MySheet)

        Set allColumns = ReportSheet.Columns("N:S")

        allColumns.Hidden = True

        With ReportSheet.PageSetup

            .Zoom = False

            .FitToPagesWide = 1                  '.FitToPagesTall = 1

        End With

        Filename = ActiveWorkbook.Name

        Cell = Replace(Filename, ".xlsx", ".PDF")

        ReportSheet.Select

        ReportSheet.PageSetup.Orientation = xlLandscape

        ReportSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=ThisWorkbook.Path & "\" & Cell, _
                                        Quality:=xlQualityStandard, IncludeDocProperties:=True, _
                                        IgnorePrintAreas:=True, OpenAfterPublish:=False

        Counter = Counter + 1

        Workbooks(MyFile).Close SaveChanges:=False

        MyFile = Dir

    Loop

    'turns settings back on that you turned off before looping folders

    Application.ScreenUpdating = True

    Application.DisplayStatusBar = True

    Application.EnableEvents = True

    Application.Calculation = xlCalculationManual

    MinutesElapsed = Format((Timer - StartTime) / 86400, "hh:mm:ss")

    MsgBox "Successfully Converted " & Counter & " Files in " & MinutesElapsed & " minutes", vbInformation

End Sub
</code>```

Side note: Didn't review other parts of your code

Body:
I'm getting a "Compile Error: Syntax Error" when running the code below using Excel 2019. It works with the older version Excel, but not on 2019. How can I fix this and what's causing it?

the error line

ReportSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _

        ThisWorkbook.Path & "\" & Cell, _

        Quality:=xlQualityStandard, IncludeDocProperties:=True, _

        IgnorePrintAreas:=True, OpenAfterPublish:=False

The entire code

Option Explicit

Private Sub CommandButton1_Click()

Dim MyFolder As String, MyFile As String

Dim StartTime As Double

Dim MinutesElapsed As String

Dim Filename As String

Dim Cell As String

Dim Counter As Long

            If ThisWorkbook.Sheets("Sheet1").Range("C7").Value = vbNullString Then

            MsgBox "Enter Tab Name"

            Exit Sub

            End If

StartTime = Timer

            With Application.FileDialog(msoFileDialogFolderPicker)

               .AllowMultiSelect = False

               .Title = "Select a Folder"

               If .Show = True Then

               MyFolder = .SelectedItems(1)

               End If

               If .SelectedItems.Count = 0 Then Exit Sub

               Err.Clear

            End With

            'Turns settings off
            Application.ScreenUpdating = False

            Application.DisplayStatusBar = False

            Application.EnableEvents = False

            Application.Calculation = xlCalculationManual

            MyFile = Dir(MyFolder & "\", vbReadOnly)

Do While MyFile <> ""

        DoEvents

        On Error GoTo 0

        Workbooks.Open Filename:=MyFolder & "\" & MyFile, UpdateLinks:=False

Dim ReportSheet As Worksheet

Dim MySheet As String

Dim allColumns As Range

MySheet = ThisWorkbook.Sheets("Sheet1").Range("C7").Value

Set ReportSheet = Sheets(MySheet)

Set allColumns = ReportSheet.Columns("N:S")

        allColumns.Hidden = True

        With ReportSheet.PageSetup

         .Zoom = False

         .FitToPagesWide = 1    '.FitToPagesTall = 1

        End With

Filename = ActiveWorkbook.Name

Cell = Replace(Filename, ".xlsx", ".PDF")

    ReportSheet.Select

    ReportSheet.PageSetup.Orientation = xlLandscape

    ReportSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _

        ThisWorkbook.Path & "\" & Cell, _

        Quality:=xlQualityStandard, IncludeDocProperties:=True, _

        IgnorePrintAreas:=True, OpenAfterPublish:=False

Counter = Counter + 1

0

        Workbooks(MyFile).Close SaveChanges:=False

        MyFile = Dir

Loop

    'turns settings back on that you turned off before looping folders

        Application.ScreenUpdating = True

        Application.DisplayStatusBar = True

        Application.EnableEvents = True

        Application.Calculation = xlCalculationManual

MinutesElapsed = Format((Timer - StartTime) / 86400, "hh:mm:ss")

MsgBox "Successfully Converted " & Counter & " Files in " & MinutesElapsed & " minutes", vbInformation

End Sub

Body:
Leaving a blank line when you are using the line continuation _ character is not allowed in any Excel version (AFAIK)

The code giving you trouble should be:

ReportSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=ThisWorkbook.Path & "\" & Cell, _
                                Quality:=xlQualityStandard, IncludeDocProperties:=True, _
                                IgnorePrintAreas:=True, OpenAfterPublish:=False

Try indenting your code properly and remove the extra lines.

Code:

Option Explicit

Private Sub CommandButton1_Click()

    Dim MyFolder As String, MyFile As String

    Dim StartTime As Double

    Dim MinutesElapsed As String

    Dim Filename As String

    Dim Cell As String

    Dim Counter As Long

    If ThisWorkbook.Sheets("Sheet1").Range("C7").Value = vbNullString Then

        MsgBox "Enter Tab Name"

        Exit Sub

    End If

    StartTime = Timer

    With Application.FileDialog(msoFileDialogFolderPicker)

        .AllowMultiSelect = False

        .Title = "Select a Folder"

        If .Show = True Then

            MyFolder = .SelectedItems(1)

        End If

        If .SelectedItems.Count = 0 Then Exit Sub

        Err.Clear

    End With

    'Turns settings off
    Application.ScreenUpdating = False

    Application.DisplayStatusBar = False

    Application.EnableEvents = False

    Application.Calculation = xlCalculationManual

    MyFile = Dir(MyFolder & "\", vbReadOnly)

    Do While MyFile <> ""

        DoEvents

        On Error GoTo 0

        Workbooks.Open Filename:=MyFolder & "\" & MyFile, UpdateLinks:=False

        Dim ReportSheet As Worksheet

        Dim MySheet As String

        Dim allColumns As Range

        MySheet = ThisWorkbook.Sheets("Sheet1").Range("C7").Value

        Set ReportSheet = Sheets(MySheet)

        Set allColumns = ReportSheet.Columns("N:S")

        allColumns.Hidden = True

        With ReportSheet.PageSetup

            .Zoom = False

            .FitToPagesWide = 1                  '.FitToPagesTall = 1

        End With

        Filename = ActiveWorkbook.Name

        Cell = Replace(Filename, ".xlsx", ".PDF")

        ReportSheet.Select

        ReportSheet.PageSetup.Orientation = xlLandscape

        ReportSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=ThisWorkbook.Path & "\" & Cell, _
                                        Quality:=xlQualityStandard, IncludeDocProperties:=True, _
                                        IgnorePrintAreas:=True, OpenAfterPublish:=False

        Counter = Counter + 1

        Workbooks(MyFile).Close SaveChanges:=False

        MyFile = Dir

    Loop

    'turns settings back on that you turned off before looping folders

    Application.ScreenUpdating = True

    Application.DisplayStatusBar = True

    Application.EnableEvents = True

    Application.Calculation = xlCalculationManual

    MinutesElapsed = Format((Timer - StartTime) / 86400, "hh:mm:ss")

    MsgBox "Successfully Converted " & Counter & " Files in " & MinutesElapsed & " minutes", vbInformation

End Sub

Side note: Didn't review other parts of your code


问:
Multicell LSTM RNN returns nan training error
I'm trying to train this Multi Cell RNN network (for training, you can ignore the m_t+1 -> m_t part)

that uses 4 LSTM cell layers. Encoder and Decoder are just fully connected layers.
 G_t and m_t are groups of floats of size 6, 69 respectively. P_t, m_t+1 are also that size as well. The time step of this RNN is 48.
But for somewhat reason, my training won't work AT ALL. I am dying to know what's wrong with my code.

The cost function looks like this

```<code>n_steps = 48
n_neurons = 512
n_layers = 4
NUM_OF_INPUTS = 6 + 69
NUM_OF_OUTPUTS = 6 + 69
EPOCHS = 50
sample_size = 12494
batch_size = 128
total_batch = int(sample_size / batch_size)
global_step = tf.Variable(0, trainable=False)
prop_valid = 0.1
time_stamp = 48

def mini_batch(data, bs, i):
    return data[i*bs : i*bs+bs,:,:]

#Both X_data_np and Y_data_np are three dimensional, which is the required dimension for the inputs of tf.nn.dynamic_rnn
X_data_np = np.load('X_data.npy')
Y_data_np = np.load('Y_data.npy')
data = np.concatenate([X_data_np, Y_data_np], axis=-1)
np.random.shuffle(data)
#standardize data
mean = np.mean(data)
data = data - mean
std = np.std(data)
data = data / std

train_size = int(sample_size * (1 - prop_valid))
valid_size = int((sample_size - train_size))

train_input = data[:train_size, :, :NUM_OF_INPUTS]
train_label = data[:train_size, :, NUM_OF_INPUTS:]
valid_input = data[train_size:train_size + valid_size, :,:NUM_OF_INPUTS]
valid_label = data[train_size:train_size + valid_size, :,NUM_OF_INPUTS:]

X = tf.placeholder(tf.float32, [None, n_steps, NUM_OF_INPUTS])
Y = tf.placeholder(tf.float32, [None, n_steps, NUM_OF_OUTPUTS])
encoded_inputs = tf.layers.dense(X, 256)
layers = [tf.contrib.rnn.LSTMCell(num_units = n_neurons, activation=tf.nn.tanh) for layer in range(n_layers)]
multi_layer_cell = tf.contrib.rnn.MultiRNNCell(layers)
outputs, _ = tf.nn.dynamic_rnn(multi_layer_cell, encoded_inputs, dtype=tf.float32)
prediction = tf.layers.dense(outputs, NUM_OF_OUTPUTS)

Y = tf.placeholder(tf.float32, [None, n_steps, NUM_OF_OUTPUTS]) #(?, 48, 75)
distance = tf.norm(prediction[:,:,6:75] - Y[:,:,6:75], axis = 2)  # (?, 48)
distance_square = tf.square(distance)
#Add all the sum
reduced_distance = tf.math.reduce_sum(distance_square, axis= 1)  # (?, )
#Mean of all mini batch data
train_loss = tf.math.reduce_mean(reduced_distance, axis= 0) # ()

learning_rate = 0.001
trainOptimizer = tf.train.AdamOptimizer(learning_rate).minimize(train_loss, global_step=global_step)

sess = tf.Session()
tf.global_variables_initializer().run(session=sess)

for epoch in range(EPOCHS):
    for batch_idx in range(total_batch):
        train_batch_input = mini_batch(train_input, batch_size, batch_idx)
        train_batch_label = mini_batch(train_label, batch_size, batch_idx)
        _, loss= sess.run([trainOptimizer, train_loss], feed_dict={X:train_batch_input,Y:train_batch_label})
    if (epoch+1) % 10 == 0:
        prediction2 = sess.run(prediction, feed_dict={X:valid_input})
        valid_error = np.mean(np.sum(np.square(np.linalg.norm(prediction2[:,:,6:75] - valid_label[:,:,6:75], axis = 2)), axis = 1), axis = 0)
        print("Epoch: %05d tL: %.4f vE: %.4f" % (epoch+1, loss, valid_error))
</code>```

The result is as follows

```<code>Epoch: 00010 tL: nan vE: 4.3044
Epoch: 00020 tL: nan vE: 4.3114
Epoch: 00030 tL: nan vE: 4.2962
Epoch: 00040 tL: nan vE: 4.3009
Epoch: 00050 tL: nan vE: 4.2899
</code>```

the training loss is always nan no matter how small the training data is, so I think the fundamental problem is in my code where I train it. The validation error is NOT nan so the data itself contains no nan I suppose.
Is there a critical issue I'm not addressing in my code? Any help would be appreciated! Thanks in advance.

答:
The reason why validation error showed a normal value and training error did not was because I was making mini batches that hold nan values.

Apparently

```<code>sample_size = 12494
batch_size = 128
total_batch = int(sample_size / batch_size)
train_size = int(sample_size * (1 - prop_valid))
</code>```

and

```<code>for batch_idx in range(total_batch):
    train_batch_input = mini_batch(train_input, batch_size, batch_idx)
    train_batch_label = mini_batch(train_label, batch_size, batch_idx)
</code>```

did not make sense. total_batch should have been int(train_size / batch_size)

It was really hard to find this cause numpy does not return any error when array slicing is out of bounds.

Anyway, hope it helps people with similar issues in the future!

Body:
I'm trying to train this Multi Cell RNN network (for training, you can ignore the m_t+1 -> m_t part)

that uses 4 LSTM cell layers. Encoder and Decoder are just fully connected layers.
 G_t and m_t are groups of floats of size 6, 69 respectively. P_t, m_t+1 are also that size as well. The time step of this RNN is 48.
But for somewhat reason, my training won't work AT ALL. I am dying to know what's wrong with my code.

The cost function looks like this

n_steps = 48
n_neurons = 512
n_layers = 4
NUM_OF_INPUTS = 6 + 69
NUM_OF_OUTPUTS = 6 + 69
EPOCHS = 50
sample_size = 12494
batch_size = 128
total_batch = int(sample_size / batch_size)
global_step = tf.Variable(0, trainable=False)
prop_valid = 0.1
time_stamp = 48

def mini_batch(data, bs, i):
    return data[i*bs : i*bs+bs,:,:]

#Both X_data_np and Y_data_np are three dimensional, which is the required dimension for the inputs of tf.nn.dynamic_rnn
X_data_np = np.load('X_data.npy')
Y_data_np = np.load('Y_data.npy')
data = np.concatenate([X_data_np, Y_data_np], axis=-1)
np.random.shuffle(data)
#standardize data
mean = np.mean(data)
data = data - mean
std = np.std(data)
data = data / std

train_size = int(sample_size * (1 - prop_valid))
valid_size = int((sample_size - train_size))

train_input = data[:train_size, :, :NUM_OF_INPUTS]
train_label = data[:train_size, :, NUM_OF_INPUTS:]
valid_input = data[train_size:train_size + valid_size, :,:NUM_OF_INPUTS]
valid_label = data[train_size:train_size + valid_size, :,NUM_OF_INPUTS:]

X = tf.placeholder(tf.float32, [None, n_steps, NUM_OF_INPUTS])
Y = tf.placeholder(tf.float32, [None, n_steps, NUM_OF_OUTPUTS])
encoded_inputs = tf.layers.dense(X, 256)
layers = [tf.contrib.rnn.LSTMCell(num_units = n_neurons, activation=tf.nn.tanh) for layer in range(n_layers)]
multi_layer_cell = tf.contrib.rnn.MultiRNNCell(layers)
outputs, _ = tf.nn.dynamic_rnn(multi_layer_cell, encoded_inputs, dtype=tf.float32)
prediction = tf.layers.dense(outputs, NUM_OF_OUTPUTS)

Y = tf.placeholder(tf.float32, [None, n_steps, NUM_OF_OUTPUTS]) #(?, 48, 75)
distance = tf.norm(prediction[:,:,6:75] - Y[:,:,6:75], axis = 2)  # (?, 48)
distance_square = tf.square(distance)
#Add all the sum
reduced_distance = tf.math.reduce_sum(distance_square, axis= 1)  # (?, )
#Mean of all mini batch data
train_loss = tf.math.reduce_mean(reduced_distance, axis= 0) # ()

learning_rate = 0.001
trainOptimizer = tf.train.AdamOptimizer(learning_rate).minimize(train_loss, global_step=global_step)

sess = tf.Session()
tf.global_variables_initializer().run(session=sess)

for epoch in range(EPOCHS):
    for batch_idx in range(total_batch):
        train_batch_input = mini_batch(train_input, batch_size, batch_idx)
        train_batch_label = mini_batch(train_label, batch_size, batch_idx)
        _, loss= sess.run([trainOptimizer, train_loss], feed_dict={X:train_batch_input,Y:train_batch_label})
    if (epoch+1) % 10 == 0:
        prediction2 = sess.run(prediction, feed_dict={X:valid_input})
        valid_error = np.mean(np.sum(np.square(np.linalg.norm(prediction2[:,:,6:75] - valid_label[:,:,6:75], axis = 2)), axis = 1), axis = 0)
        print("Epoch: %05d tL: %.4f vE: %.4f" % (epoch+1, loss, valid_error))

The result is as follows

Epoch: 00010 tL: nan vE: 4.3044
Epoch: 00020 tL: nan vE: 4.3114
Epoch: 00030 tL: nan vE: 4.2962
Epoch: 00040 tL: nan vE: 4.3009
Epoch: 00050 tL: nan vE: 4.2899

the training loss is always nan no matter how small the training data is, so I think the fundamental problem is in my code where I train it. The validation error is NOT nan so the data itself contains no nan I suppose.
Is there a critical issue I'm not addressing in my code? Any help would be appreciated! Thanks in advance.

Body:
The reason why validation error showed a normal value and training error did not was because I was making mini batches that hold nan values.

Apparently

sample_size = 12494
batch_size = 128
total_batch = int(sample_size / batch_size)
train_size = int(sample_size * (1 - prop_valid))

and

for batch_idx in range(total_batch):
    train_batch_input = mini_batch(train_input, batch_size, batch_idx)
    train_batch_label = mini_batch(train_label, batch_size, batch_idx)

did not make sense. total_batch should have been int(train_size / batch_size)

It was really hard to find this cause numpy does not return any error when array slicing is out of bounds.

Anyway, hope it helps people with similar issues in the future!


问:
Htaccess configuration to start from sub-folder instead of root
I have a site www.domain.com , and i built my mvc framework for it.
.htaccess file content as following:

```<code>Options -Indexes

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l

RewriteRule ^(.+) index.php?url=$l [QSA,L]
</code>```

it makes me able to navigate like www.domain.com/home/index/ correctly, but i need to re-configure it to read from www.domain.com/site , instead of the end of domain.com ?!
any help ?

答:
add this line:

```<code>Redirect /index.html /public/
</code>```

and it will redirect to public folder , or change the word to any path you want.

Body:
I have a site www.domain.com , and i built my mvc framework for it.
.htaccess file content as following:

Options -Indexes

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l

RewriteRule ^(.+) index.php?url=$l [QSA,L]

it makes me able to navigate like www.domain.com/home/index/ correctly, but i need to re-configure it to read from www.domain.com/site , instead of the end of domain.com ?!
any help ?

Body:
add this line:

Redirect /index.html /public/

and it will redirect to public folder , or change the word to any path you want.


问:
how to clear the key buffer while using kbhit() and getch()
heu so I'm using the above stated windows functions which luckily are for windows 2000 and up, but in making a game on the console I've run into a problem: as soon as a key is pressed the console gets passed the kbhit() function no matter if a key is not pressed again...

is there some way I can clear the keyboard press buffer so you can't get passed kbhit without a new keypress?

If a new lib download is requires I guess I could... but I'm hoping for a windows standard way!

Thanks!!

答:
Whoever told you that kbhit() was a Windows function misinformed you.  kbhit(), getch() and their relatives are actually part of the (C language bindings to the) MS-DOS API.  Their presence in the runtime libraries for OS/2, Win32, and other C/C++ compilers is simply to be a porting aid for MS/PC/DR-DOS programs.  The library maps them onto whatever native mechanism exists for accessing the keyboard, if there is one at all, and usually only in the right way for TUI, not GUI, applications to access the keyboard.

If you're writing a new TUI application, don't use the MS-DOS API.  Use the proper, native, API for the platform that you're targetting, such as the Win32 Console API or the OS/2 Console API, or the POSIX General Terminal Interface (via ncurses or some such).

When you do, you'll read their documentation and find out how to perform a destructive "get" of the keyboard input after doing a non-destructive "peek".  Or indeed how to flush the buffer in its entirety if that is what you want to do.


问:
Replace NaN in pandas DataFrame with random strings without using fillna
I have a pandas DataFrame like below

```<code>      NAME      EMAIL      HEIGHT      WEIGHT

1     jlka       NaN        170          70

2     qwer     eee@ttt      180          80

3     ioff       NaN        175          75

4     iowu     iou@add      170          60
</code>```

And I want to replace NaN in 'EMAIL' column with random strings with no duplicates, which does not necessarily contain @.

I have tried to make a def which generates random strings but NaNs were replaced with the same random string since I used 'fillna' method after all.

It seems like, and as I saw other Q$As, def in fillna works only once and replace all the NaN with the same values or strings came out from the def.

Should I try 'for' sentence to replace them one by one?

Or is there a more Pythonic way to replace them?

答:
You could use pd.util.testing.rands_array, passing it the length of your desired string as the first (nchars) argument and the number of NaNs as the second (size) argument:

```<code>df.loc[df.EMAIL.isna(), "EMAIL"] = pd.util.testing.rands_array(10, sum(df.EMAIL.isnull()))

>>> df

   NAME       EMAIL  HEIGHT  WEIGHT
1  jlka  YxzVaC38uw     170      70
2  qwer     eee@ttt     180      80
3  ioff  33kyDArtip     175      75
4  iowu     iou@add     170      60
</code>```

pd.util.testing.rand_array could be replaced with any function that returns a list or array with a specific size.

Body:
I have a pandas DataFrame like below

      NAME      EMAIL      HEIGHT      WEIGHT

1     jlka       NaN        170          70

2     qwer     eee@ttt      180          80

3     ioff       NaN        175          75

4     iowu     iou@add      170          60

And I want to replace NaN in 'EMAIL' column with random strings with no duplicates, which does not necessarily contain @.

I have tried to make a def which generates random strings but NaNs were replaced with the same random string since I used 'fillna' method after all.

It seems like, and as I saw other Q$As, def in fillna works only once and replace all the NaN with the same values or strings came out from the def.

Should I try 'for' sentence to replace them one by one?

Or is there a more Pythonic way to replace them?

Body:
You could use pd.util.testing.rands_array, passing it the length of your desired string as the first (nchars) argument and the number of NaNs as the second (size) argument:

df.loc[df.EMAIL.isna(), "EMAIL"] = pd.util.testing.rands_array(10, sum(df.EMAIL.isnull()))

>>> df

   NAME       EMAIL  HEIGHT  WEIGHT
1  jlka  YxzVaC38uw     170      70
2  qwer     eee@ttt     180      80
3  ioff  33kyDArtip     175      75
4  iowu     iou@add     170      60

pd.util.testing.rand_array could be replaced with any function that returns a list or array with a specific size.


问:
How do I use brew installed Python as the default Python?
I try to switch to Homebrew (after using fink and macport) on Mac OS X 10.6.2. I have installed python 2.7 with

```<code>brew install python
</code>```

The problem is that, contrary to Macport, it seems that there is no python_select utility, and my default mac python is always default

```<code>which python
</code>```

give me

```<code>/usr/bin/python
</code>```

and /usr/bin/python is not a symlink

How can I do to make python brew flavour to be my default python ?

答:
If you are fish shell

echo 'set -g fish_user_paths "/usr/local/opt/python/libexec/bin" $fish_user_paths' >> ~/.config/fish/config.fish
```

Body:
I try to switch to Homebrew (after using fink and macport) on Mac OS X 10.6.2. I have installed python 2.7 with

brew install python

The problem is that, contrary to Macport, it seems that there is no python_select utility, and my default mac python is always default

which python

give me

/usr/bin/python

and /usr/bin/python is not a symlink

How can I do to make python brew flavour to be my default python ?