问:
How to implement inheritance for POJO class
I have two different class with constructor but with similar pojo and i wanted to implement java inheritance as while running sonar code analysis gives me code duplicate

I have created the classes DaoException and ServiceException which has same pojo and wanted to have the pojo common to avoid code duplicate

```<code>public class DaoException extends Exception {

  private static final long serialVersionUID = 1L;

  private final int code;
  private String message;

  public DaoException(int code, String message) {

      this.code = code;
      this.message = message;
  }

  public DaoException(int code, Throwable throwable) {

      this.code = code;
      this.message = throwable.getMessage();
  }

  public int getCode() {

      return code;
  }

  public void setCode(int code) {

      this.code = code;
  }

  public String getMessage() {

      return message;
  }

  public void setMessage(String message) {

      this.message = message;
  }
}

</code>```

```<code>public class ServiceException extends Exception {

private static final long serialVersionUID = 1L;

private final int code;
private String message;

public ServiceException(int code, String message) {

    this.code = code;
    this.message = message;
}

public ServiceException(int code, Throwable throwable) {

    this.code = code;
    this.message = throwable.getMessage();
}

public int getCode() {

    return code;
}

public void setCode(int code) {

    this.code = code;
}

public String getMessage() {

    return message;
}

public void setMessage(String message) {

    this.message = message;
}
</code>```

}

Please advise.

答:
You can create a common parent class for ServiceException and DAOExecption . You can create your class GenericException , with all the details .
Then make ServiceException and DAOExecption extend this GenericException. Call the appropriate constructor of parent class from the child</p>

Body:
I have two different class with constructor but with similar pojo and i wanted to implement java inheritance as while running sonar code analysis gives me code duplicate

I have created the classes DaoException and ServiceException which has same pojo and wanted to have the pojo common to avoid code duplicate

public class DaoException extends Exception {

  private static final long serialVersionUID = 1L;

  private final int code;
  private String message;

  public DaoException(int code, String message) {

      this.code = code;
      this.message = message;
  }

  public DaoException(int code, Throwable throwable) {

      this.code = code;
      this.message = throwable.getMessage();
  }

  public int getCode() {

      return code;
  }

  public void setCode(int code) {

      this.code = code;
  }

  public String getMessage() {

      return message;
  }

  public void setMessage(String message) {

      this.message = message;
  }
}

public class ServiceException extends Exception {

private static final long serialVersionUID = 1L;

private final int code;
private String message;

public ServiceException(int code, String message) {

    this.code = code;
    this.message = message;
}

public ServiceException(int code, Throwable throwable) {

    this.code = code;
    this.message = throwable.getMessage();
}

public int getCode() {

    return code;
}

public void setCode(int code) {

    this.code = code;
}

public String getMessage() {

    return message;
}

public void setMessage(String message) {

    this.message = message;
}

}

Please advise.


来源: stackexchange

问:
Subquery must return a single row
When I start this query I got this error:

AnalysisException: Subquery must return a single row: (SELECT round(c1.feb15 + c1.nov15 + c1.dec15) FROM suivisousse.compteur2015)

Query:

```<code>SELECT
    c2.compteur,
    ((c1.feb15 + c1.nov15 + c1.dec15) * 100 /
         (SELECT ROUND(c1.feb15 + c1.nov15 + c1.dec15) FROM compteur2015))
FROM
    compteur2015 c1, compteur c2
WHERE
    c1.compteur = c2.compteur
GROUP BY
    c2.compteur
</code>```

答: Your inner select query select round(c1.feb15+c1.nov15+c1.dec15) from compteur2015 returning more than 1 record. Make sure there is only one valid record returned by your inner query.

ContentLicense: CC BY-SA 4.0

Title: Subquery must return a single row

Body:
When I start this query I got this error:

AnalysisException: Subquery must return a single row: (SELECT round(c1.feb15 + c1.nov15 + c1.dec15) FROM suivisousse.compteur2015)

Query:

SELECT
    c2.compteur,
    ((c1.feb15 + c1.nov15 + c1.dec15) * 100 /
         (SELECT ROUND(c1.feb15 + c1.nov15 + c1.dec15) FROM compteur2015))
FROM
    compteur2015 c1, compteur c2
WHERE
    c1.compteur = c2.compteur
GROUP BY
    c2.compteur


问:
How to combine select and group by clause with conditional where in Linq
I'am learning ASP.Net MVC with SQL Server Database and got stuck in Linq operation query. Can anyone help me to convert this SQL query to Linq, please ?</p>

```<code>SELECT ShipName, COUNT(*) AS ShipValues
FROM Invoinces GROUP BY ShipName HAVING COUNT(*) > 30
</code>```

答:
Try this</p>

```<code>var result = Invoinces.GroupBy(x => x.ShipName)
                      .Where(y => y.Count() > 30)
                      .Select(o => new {ShipName = o.ShipName, Count = o.Count()});
</code>```

Body:
I'am learning ASP.Net MVC with SQL Server Database and got stuck in Linq operation query. Can anyone help me to convert this SQL query to Linq, please ?

SELECT ShipName, COUNT(*) AS ShipValues
FROM Invoinces GROUP BY ShipName HAVING COUNT(*) > 30

Body:
Try this

var result = Invoinces.GroupBy(x => x.ShipName)
                      .Where(y => y.Count() > 30)
                      .Select(o => new {ShipName = o.ShipName, Count = o.Count()});


问:
Upload video to Amazon S3 via iOS
I am trying to upload videos to Amazon S3 via my iOS app. I'm struggling to use the documentation provided by AWS.

Firstly, what should the contentType be if I want to upload .mov videos to S3? I can't seem to find any documentation of the format of content I can upload.

Secondly, how do I pass my .mov video as a Data() object?

```<code>func uploadData() {

   let data: Data = Data() // Data to be uploaded

   let expression = AWSS3TransferUtilityMultiPartUploadExpression()
      expression.progressBlock = {(task, progress) in
         DispatchQueue.main.async(execute: {
           // Do something e.g. Update a progress bar.
        })
   }

   var completionHandler: AWSS3TransferUtilityMultiPartUploadCompletionHandlerBlock
   completionHandler = { (task, error) -> Void in
      DispatchQueue.main.async(execute: {
         // Do something e.g. Alert a user for transfer completion.
         // On failed uploads, `error` contains the error object.
      })
   }

   let transferUtility = AWSS3TransferUtility.default()

   transferUtility.uploadUsingMultiPart(data:data,
        bucket: "YourBucket",
        key: "YourFileName",
        contentType: "text/plain",
        expression: expression,
        completionHandler: completionHandler).continueWith {
           (task) -> AnyObject! in
               if let error = task.error {
                  print("Error: \(error.localizedDescription)")
               }

               if let _ = task.result {
                  // Do something with uploadTask.
               }
               return nil;
       }
}
</code>```

答:
Try This Function For Upload Image/Video in AWS</p>

```<code>public struct AWSConstant {
    static let COGNITO_POOL_ID = "us-west-2:4918c1f8-d173-4668-8891-d6892a147259"
    static let BUCKET_NAME = "spinach-cafe/main-image"
    static let baseUrl = "https://s3-us-west-2.amazonaws.com/"
}

func uploadVideoToAmazon(currentFileName: String, videoFileURL: URL, contentType: String = "image/jpeg", _ bucket: String?, progressBlock: @escaping (Float) -> () = { _ in }, callBack: @escaping (_ url: String) -> Void?, failedBlock: @escaping (Error?) -> () = { _ in }) {

    let myIdentityPoolId = AWSConstant.COGNITO_POOL_ID

    let credentialsProvider: AWSCognitoCredentialsProvider = AWSCognitoCredentialsProvider(regionType: .USWest2, identityPoolId: myIdentityPoolId)

    let endpoint = AWSEndpoint.init(region: .USWest2, service: .S3, useUnsafeURL: false)
    let configuration = AWSServiceConfiguration.init(region: .USWest2, endpoint: endpoint, credentialsProvider: credentialsProvider)
    AWSServiceManager.default().defaultServiceConfiguration = configuration

    var S3BucketName = AWSConstant.BUCKET_NAME
    if let bucketName = bucket {
        S3BucketName = bucketName
    }

    let remoteName = currentFileName

    let uploadRequest = AWSS3TransferManagerUploadRequest()
    uploadRequest?.body = videoFileURL
    uploadRequest?.key = remoteName
    uploadRequest?.bucket = S3BucketName
    uploadRequest?.contentType = contentType
    uploadRequest?.acl = .publicRead

    uploadRequests.append(uploadRequest)

    uploadRequest?.uploadProgress = { bytesSent, totalBytesSent, totalBytesExpectedToSend in
        DispatchQueue.main.async(execute: {
            print("\(totalBytesSent)/\(totalBytesExpectedToSend)")
        })
    }

    let transferManager = AWSS3TransferManager.default()

    // Perform file upload

    transferManager.upload(uploadRequest!).continueWith(block: { task -> Any? in

        if let error = task.error {
            print("Upload failed with error: (\(error.localizedDescription))")
        }

        if task.result != nil {
            let stringURL = "\(AWSConstant.baseUrl)\(S3BucketName)/\(currentFileName)"

            print("Uploaded to:\n\(stringURL)")

            // Remove locally stored file
            DispatchQueue.main.async() {
                callBack(stringURL)
            }

        }
        else {
            DispatchQueue.main.async() {
                failedBlock(task.error)
            }
            print("Unexpected empty result.")
        }
        return nil
    })
}
</code>```

Title: Upload video to Amazon S3 via iOS

Body:
I am trying to upload videos to Amazon S3 via my iOS app. I'm struggling to use the documentation provided by AWS.

Firstly, what should the contentType be if I want to upload .mov videos to S3? I can't seem to find any documentation of the format of content I can upload.

Secondly, how do I pass my .mov video as a Data() object?

func uploadData() {

   let data: Data = Data() // Data to be uploaded

   let expression = AWSS3TransferUtilityMultiPartUploadExpression()
      expression.progressBlock = {(task, progress) in
         DispatchQueue.main.async(execute: {
           // Do something e.g. Update a progress bar.
        })
   }

   var completionHandler: AWSS3TransferUtilityMultiPartUploadCompletionHandlerBlock
   completionHandler = { (task, error) -> Void in
      DispatchQueue.main.async(execute: {
         // Do something e.g. Alert a user for transfer completion.
         // On failed uploads, `error` contains the error object.
      })
   }

   let transferUtility = AWSS3TransferUtility.default()

   transferUtility.uploadUsingMultiPart(data:data,
        bucket: "YourBucket",
        key: "YourFileName",
        contentType: "text/plain",
        expression: expression,
        completionHandler: completionHandler).continueWith {
           (task) -> AnyObject! in
               if let error = task.error {
                  print("Error: \(error.localizedDescription)")
               }

               if let _ = task.result {
                  // Do something with uploadTask.
               }
               return nil;
       }
}

Body:
Try This Function For Upload Image/Video in AWS

public struct AWSConstant {
    static let COGNITO_POOL_ID = "us-west-2:4918c1f8-d173-4668-8891-d6892a147259"
    static let BUCKET_NAME = "spinach-cafe/main-image"
    static let baseUrl = "https://s3-us-west-2.amazonaws.com/"
}

func uploadVideoToAmazon(currentFileName: String, videoFileURL: URL, contentType: String = "image/jpeg", _ bucket: String?, progressBlock: @escaping (Float) -> () = { _ in }, callBack: @escaping (_ url: String) -> Void?, failedBlock: @escaping (Error?) -> () = { _ in }) {

    let myIdentityPoolId = AWSConstant.COGNITO_POOL_ID

    let credentialsProvider: AWSCognitoCredentialsProvider = AWSCognitoCredentialsProvider(regionType: .USWest2, identityPoolId: myIdentityPoolId)

    let endpoint = AWSEndpoint.init(region: .USWest2, service: .S3, useUnsafeURL: false)
    let configuration = AWSServiceConfiguration.init(region: .USWest2, endpoint: endpoint, credentialsProvider: credentialsProvider)
    AWSServiceManager.default().defaultServiceConfiguration = configuration

    var S3BucketName = AWSConstant.BUCKET_NAME
    if let bucketName = bucket {
        S3BucketName = bucketName
    }

    let remoteName = currentFileName

    let uploadRequest = AWSS3TransferManagerUploadRequest()
    uploadRequest?.body = videoFileURL
    uploadRequest?.key = remoteName
    uploadRequest?.bucket = S3BucketName
    uploadRequest?.contentType = contentType
    uploadRequest?.acl = .publicRead

    uploadRequests.append(uploadRequest)

    uploadRequest?.uploadProgress = { bytesSent, totalBytesSent, totalBytesExpectedToSend in
        DispatchQueue.main.async(execute: {
            print("\(totalBytesSent)/\(totalBytesExpectedToSend)")
        })
    }

    let transferManager = AWSS3TransferManager.default()

    // Perform file upload

    transferManager.upload(uploadRequest!).continueWith(block: { task -> Any? in

        if let error = task.error {
            print("Upload failed with error: (\(error.localizedDescription))")
        }

        if task.result != nil {
            let stringURL = "\(AWSConstant.baseUrl)\(S3BucketName)/\(currentFileName)"

            print("Uploaded to:\n\(stringURL)")

            // Remove locally stored file
            DispatchQueue.main.async() {
                callBack(stringURL)
            }

        }
        else {
            DispatchQueue.main.async() {
                failedBlock(task.error)
            }
            print("Unexpected empty result.")
        }
        return nil
    })
}


问:
objective c gets EXC_BAD_ACCESS error on completionhandler
i'm new to objective-c, please bear with me if i ask stupid questions :)
The following is part of code i have to start vpn tunnel, but keeps getting EXC_BAD_ACCESS error

```<code>- (void)startTunnelWithOptions:(NSDictionary *)options completionHandler:(void (^)(BOOL * error))completionHandler {

    vpnAdapter = [[OpenAdapter alloc] init];
    vpnAdapter.delegate = self;

    // get config

    config = [[NSDictionary alloc] init];

    NETunnelProviderProtocol *protocol = (NETunnelProviderProtocol *)self.protocolConfiguration;
    config = protocol.providerConfiguration;

    host = config[@"server"];

    // Load config data
    username = config[@"username"];
    password = config[@"password"];

    if(option != nil){
        [vpnAdapter connect:host user:username pass:password add:YES completionHandler:^(BOOL success){
           // return success;
            completionHandler(&success); // Thread 2: EXC_BAD_ACCESS (code=1, address=0xbcc68f020)
        }];

    }else{
        [vpnAdapter connect:host user:username pass:password add:NO completionHandler:^(BOOL success){

            completionHandler(&success);

        }];
    }
}
</code>```

here is connect method

```<code>- (void)connect: (NSString *) host user:(NSString *)username pass:(NSString *) password add:(Boolean) isAdd completionHandler:(void (^)(BOOL success)) completionHandler{

    dispatch_queue_attr_t attributes = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_UTILITY, 0);
    dispatch_queue_t connectQueue = dispatch_queue_create("me.ss-abramchuk.open-adapter.connection", attributes);
    dispatch_async(connectQueue, ^{
        // Call connect
        //int ret=1;
        NSArray* options = [NSArray arrayWithObjects:
                            @"--user", username,
                            host,
                            nil];

        if(isAdd){
            options = [NSArray arrayWithObjects:
                       @"--user", username,
                       @"--protocol", @"ad",
                       host,
                       nil];
        }
        //NSArray *paths = NSSearchPathForDirectoriesInDomains
        (NSDocumentDirectory, NSUserDomainMask, YES);
        //NSString *documentsDirectory = [paths objectAtIndex:0];

        NSMutableArray *arguments = [NSMutableArray arrayWithCapacity:1+[options count]];
        [arguments addObject:@"connect"];
        [arguments addObjectsFromArray:options];

        int argc = [arguments count];
        char **argv = (char **)malloc(sizeof(char*) * (argc + 1));

        [arguments enumerateObjectsUsingBlock:^(NSString *option, NSUInteger i, BOOL *stop) {
            const char * c_string = [option UTF8String];
            int length = (int)strlen(c_string);
            char *c_string_copy = (char *) malloc(sizeof(char) * (length + 1));
            strcpy(c_string_copy, c_string);
            argv[i] = c_string_copy;
        }];
        argv[argc] = NULL;
        const char *cfPass=[password UTF8String];
        int ret = self.vpnClient->start2connect(argc, argv, cfPass);
        BOOL result;
        if (ret!=0){
            result=false;
        }
        else {result = true;}
        completionHandler(result);
    });
}
</code>```

all of these are from networkextension and while debugging, i found int ret = self.vpnClient->start2connect(argc, argv, cfPass);
seems not returning any value.

however, i confirmed that the start2connect method does return int value
so for now, anyone can help explain what's wrong?

thanks

答:
The BOOL * is a pointer to a BOOL. We don’t use that pattern very often.  We use it where the block needs to update a BOOL property somewhere, e.g. in enumerateMatchesinString, where you can update the boolean that stop points to in order to stop the enumeration.

But this is a completion handler, so there’s no point in passing a pointer to the boolean (one that presumably was on the stack, inviting problems). Just pass the boolean itself, not a pointer to it.

I would suggest that instead of:

```<code>- (void)startTunnelWithOptions:(NSDictionary *)options completionHandler:(void (^)(BOOL * error))completionHandler {
    ...
    [vpnAdapter connect:host user:username pass:password add:YES completionHandler:^(BOOL success){
        completionHandler(&success);
    }];
    ...
}
</code>```

That you want:

```<code>- (void)startTunnelWithOptions:(NSDictionary *)options completionHandler:(void (^)(BOOL success))completionHandler {
    ...
    [vpnAdapter connect:host user:username pass:password add:YES completionHandler:^(BOOL success){
        completionHandler(success);
    }];
    ...
}
</code>```

Note the block parameter isn’t BOOL * error but rather BOOL success and when it calls the completionHandler, there’s not & before success.

If there’s some reason you needed to update the BOOL, then that’s a different matter, but it doesn’t make sense in the context of a completion handler.

Body:
i'm new to objective-c, please bear with me if i ask stupid questions :)
The following is part of code i have to start vpn tunnel, but keeps getting EXC_BAD_ACCESS error

- (void)startTunnelWithOptions:(NSDictionary *)options completionHandler:(void (^)(BOOL * error))completionHandler {

    vpnAdapter = [[OpenAdapter alloc] init];
    vpnAdapter.delegate = self;

    // get config

    config = [[NSDictionary alloc] init];

    NETunnelProviderProtocol *protocol = (NETunnelProviderProtocol *)self.protocolConfiguration;
    config = protocol.providerConfiguration;

    host = config[@"server"];

    // Load config data
    username = config[@"username"];
    password = config[@"password"];

    if(option != nil){
        [vpnAdapter connect:host user:username pass:password add:YES completionHandler:^(BOOL success){
           // return success;
            completionHandler(&success); // Thread 2: EXC_BAD_ACCESS (code=1, address=0xbcc68f020)
        }];

    }else{
        [vpnAdapter connect:host user:username pass:password add:NO completionHandler:^(BOOL success){

            completionHandler(&success);

        }];
    }
}

here is connect method

- (void)connect: (NSString *) host user:(NSString *)username pass:(NSString *) password add:(Boolean) isAdd completionHandler:(void (^)(BOOL success)) completionHandler{

    dispatch_queue_attr_t attributes = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_UTILITY, 0);
    dispatch_queue_t connectQueue = dispatch_queue_create("me.ss-abramchuk.open-adapter.connection", attributes);
    dispatch_async(connectQueue, ^{
        // Call connect
        //int ret=1;
        NSArray* options = [NSArray arrayWithObjects:
                            @"--user", username,
                            host,
                            nil];

        if(isAdd){
            options = [NSArray arrayWithObjects:
                       @"--user", username,
                       @"--protocol", @"ad",
                       host,
                       nil];
        }
        //NSArray *paths = NSSearchPathForDirectoriesInDomains
        (NSDocumentDirectory, NSUserDomainMask, YES);
        //NSString *documentsDirectory = [paths objectAtIndex:0];

        NSMutableArray *arguments = [NSMutableArray arrayWithCapacity:1+[options count]];
        [arguments addObject:@"connect"];
        [arguments addObjectsFromArray:options];

        int argc = [arguments count];
        char **argv = (char **)malloc(sizeof(char*) * (argc + 1));

        [arguments enumerateObjectsUsingBlock:^(NSString *option, NSUInteger i, BOOL *stop) {
            const char * c_string = [option UTF8String];
            int length = (int)strlen(c_string);
            char *c_string_copy = (char *) malloc(sizeof(char) * (length + 1));
            strcpy(c_string_copy, c_string);
            argv[i] = c_string_copy;
        }];
        argv[argc] = NULL;
        const char *cfPass=[password UTF8String];
        int ret = self.vpnClient->start2connect(argc, argv, cfPass);
        BOOL result;
        if (ret!=0){
            result=false;
        }
        else {result = true;}
        completionHandler(result);
    });
}

all of these are from networkextension and while debugging, i found int ret = self.vpnClient->start2connect(argc, argv, cfPass);
seems not returning any value.

however, i confirmed that the start2connect method does return int value
so for now, anyone can help explain what's wrong?

thanks

Body:
The BOOL * is a pointer to a BOOL. We don’t use that pattern very often.  We use it where the block needs to update a BOOL property somewhere, e.g. in enumerateMatchesinString, where you can update the boolean that stop points to in order to stop the enumeration.

But this is a completion handler, so there’s no point in passing a pointer to the boolean (one that presumably was on the stack, inviting problems). Just pass the boolean itself, not a pointer to it.

I would suggest that instead of:

- (void)startTunnelWithOptions:(NSDictionary *)options completionHandler:(void (^)(BOOL * error))completionHandler {
    ...
    [vpnAdapter connect:host user:username pass:password add:YES completionHandler:^(BOOL success){
        completionHandler(&success);
    }];
    ...
}

That you want:

- (void)startTunnelWithOptions:(NSDictionary *)options completionHandler:(void (^)(BOOL success))completionHandler {
    ...
    [vpnAdapter connect:host user:username pass:password add:YES completionHandler:^(BOOL success){
        completionHandler(success);
    }];
    ...
}

Note the block parameter isn’t BOOL * error but rather BOOL success and when it calls the completionHandler, there’s not & before success.

If there’s some reason you needed to update the BOOL, then that’s a different matter, but it doesn’t make sense in the context of a completion handler.


问:
How well do ASP.NET and MySQL work together?
What have your experiences been with asp.net and mysql?

Is it actually faster than mssql in terms of connection times etc?  Or is the library slower?

Is it suitable for a large scale type app?

答: I've had a pretty bad experience with the  MySQL and ASP.Net combo. Connection pooling does not seem work, regardless of connection string settings or Connector version. The connections just stack up until the server is out of connection, even though I close all connections. For low-traffic websites, the lack of pooling might not matter that much but if you have a high-traffic site, it will affect performance.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
how to reset a div to its original style with javascript
I am trying to "reset" box after several changes to its original state in javascript. I have used several addEventListener methods to change the appearance of a box in HTML, but am having trouble using a "reset" button to revert the box to its original appearance.</p>

```<code>document.getElementById('button1').addEventListener('click', function(){

  document.getElementById('box').style.height = '250px';

});

document.getElementById('button2').addEventListener('click', function(){

  document.getElementById('box').style.background = 'blue';

});

document.getElementById('button3').addEventListener('click', function(){

  document.getElementById('box').style.opacity = '0.1';

});

// This is where i need to reset the box

document.getElementById('button4').addEventListener('click', function(){
</code>```

答:
Here this will work.

const el = document.querySelector('.base');
document.addEventListener('click', ({
  target
}) => {
  if (target.matches('#btn1')) {
    el.classList.add('style1');
  }

  if (target.matches('#btn2')) {
    el.classList.add('style2');
  }

  if (target.matches('#btn3')) {
    el.classList.add('style3');
  }

  if (target.matches('#btn4')) {
   el.classList.remove('style1', 'style2', 'style3');
   el.classList.add('base');
  }

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.base {
  border: 1px solid red;
}

.style1 {
  border: 1px solid blue;
}

.style2 {
  font-weight: bold;
}

.style3 {
  color: green;
}</code>```

Test Div

      <button id="btn1">Button 1</button>
      <button id="btn2">Button 2</button>
      <button id="btn3">Button 3</button>
      <button id="btn4">Button 4 - Reset</button>

```

Body:
I am trying to "reset" box after several changes to its original state in javascript. I have used several addEventListener methods to change the appearance of a box in HTML, but am having trouble using a "reset" button to revert the box to its original appearance.

document.getElementById('button1').addEventListener('click', function(){

  document.getElementById('box').style.height = '250px';

});

document.getElementById('button2').addEventListener('click', function(){

  document.getElementById('box').style.background = 'blue';

});

document.getElementById('button3').addEventListener('click', function(){

  document.getElementById('box').style.opacity = '0.1';

});

// This is where i need to reset the box

document.getElementById('button4').addEventListener('click', function(){

Body:
Here this will work.

const el = document.querySelector('.base');
document.addEventListener('click', ({
  target
}) => {
  if (target.matches('#btn1')) {
    el.classList.add('style1');
  }

  if (target.matches('#btn2')) {
    el.classList.add('style2');
  }

  if (target.matches('#btn3')) {
    el.classList.add('style3');
  }

  if (target.matches('#btn4')) {
   el.classList.remove('style1', 'style2', 'style3');
   el.classList.add('base');
  }

});

.base {
  border: 1px solid red;
}

.style1 {
  border: 1px solid blue;
}

.style2 {
  font-weight: bold;
}

.style3 {
  color: green;
}

<div class="base">Test Div
  <div>
    <div>
      <button id="btn1">Button 1</button>
      <button id="btn2">Button 2</button>
      <button id="btn3">Button 3</button>
      <button id="btn4">Button 4 - Reset</button>
    </div>


问:
Twilio WhatsApp Sandbox How to get media URL MediaUrl0 (audio files)
I am using the Twilio Sandbox for WhatsApp and when I send an image the payload I receive in my webhook works fine, I can get the url of the image but doesn't work with audio files (voice messages).

I'm facing an issue with the audios, if I send a voice message from WhatsApp, the payload in my webhook does not include the audio url.

Here the payload:

```<code>{
  "SmsMessageSid": "SMf79a4b49251969d1c0cf25d7dXXXXXXX",
  "NumMedia": "0",
  "SmsSid": "SMf79a4b49251969d1c0cf25d7dXXXXXXX3",
  "SmsStatus": "received",
  "Body": "",
  "To": "whatsapp:+1415XXXXXXX",
  "NumSegments": "1",
  "MessageSid": "SMf79a4b49251969d1c0cf25d7dab11313",
  "AccountSid": "AC33e5010eecfa033d3c03aaa4faef5561",
  "From": "whatsapp:+52155XXXXXXXX",
  "ApiVersion": "2010-04-01"
}
</code>```

I expected the url media like this:

```<code> "MediaUrl0": "https://api.twilio.com/2010-04-01/Accounts/AC33e5010eecfa033d3c03aaa4faef5561/Messages/MM637c2240c42ae13b481451cdbde7072e/Media/ME2789cc6ce84b1d73d66eb9135bd3253a"
</code>```

答:
As stated in this answer, Whatsapp recordings have an issue and are not supported yet.

In another response, a Twilio dev evangelist says they're working on a solution.

Body:
I am using the Twilio Sandbox for WhatsApp and when I send an image the payload I receive in my webhook works fine, I can get the url of the image but doesn't work with audio files (voice messages).

I'm facing an issue with the audios, if I send a voice message from WhatsApp, the payload in my webhook does not include the audio url.

Here the payload:

{
  "SmsMessageSid": "SMf79a4b49251969d1c0cf25d7dXXXXXXX",
  "NumMedia": "0",
  "SmsSid": "SMf79a4b49251969d1c0cf25d7dXXXXXXX3",
  "SmsStatus": "received",
  "Body": "",
  "To": "whatsapp:+1415XXXXXXX",
  "NumSegments": "1",
  "MessageSid": "SMf79a4b49251969d1c0cf25d7dab11313",
  "AccountSid": "AC33e5010eecfa033d3c03aaa4faef5561",
  "From": "whatsapp:+52155XXXXXXXX",
  "ApiVersion": "2010-04-01"
}

I expected the url media like this:

 "MediaUrl0": "https://api.twilio.com/2010-04-01/Accounts/AC33e5010eecfa033d3c03aaa4faef5561/Messages/MM637c2240c42ae13b481451cdbde7072e/Media/ME2789cc6ce84b1d73d66eb9135bd3253a"


问:
Issue on trying to query GeoJson multipolygons in SQL Server 2016
I am trying to run a query (which I gleened from here) against GeoJson multipolygon data. It processes many of the spatial records but is stopping on a some.

I get the following error in the query messages:

Msg 6522, Level 16, State 1, Line 10

      A .NET Framework error occurred during execution of user-defined routine or aggregate "geography":

      System.FormatException: 24142: Expected "(" at position 15. The input has ",".

      System.FormatException:

      at Microsoft.SqlServer.Types.WellKnownTextReader.RecognizeToken(Char token)     at Microsoft.SqlServer.Types.WellKnownTextReader.ParseLineStringText()

      at Microsoft.SqlServer.Types.WellKnownTextReader.ParsePolygonText()

      at Microsoft.SqlServer.Types.WellKnownTextReader.ParseMultiPolygonText()

      at Microsoft.SqlServer.Types.WellKnownTextReader.ParseTaggedText(OpenGisType type)

      at Microsoft.SqlServer.Types.WellKnownTextReader.Read(OpenGisType type, Int32 srid)

      at Microsoft.SqlServer.Types.SqlGeography.ParseText(OpenGisType type, SqlChars taggedText, Int32 srid)

      at Microsoft.SqlServer.Types.SqlGeography.GeographyFromText(OpenGisType type, SqlChars taggedText, Int32 srid)

This is my statement with some test data:

```<code>declare @CountiesGeoJson nvarchar(max) = '{"type":"FeatureCollection","features":[
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "700", "COUNTYNS": "01498555", "GEOID": "51700", "NAME": "Newport News" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-76.622252, 37.142146], [-76.577819, 37.187025], [-76.591432, 37.214721], [-76.565092, 37.220645], [-76.458516, 37.100661], [-76.435519, 37.094882], [-76.451274, 37.076878], [-76.442269, 37.018448], [-76.424757, 37.025107], [-76.387711304409194, 36.989671332859004], [-76.411768, 36.962847], [-76.428869, 36.969947], [-76.464471, 37.027547], [-76.518242, 37.055351], [-76.536875, 37.083942], [-76.564219, 37.077507], [-76.618252, 37.119347], [-76.622252, 37.142146]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "620", "COUNTYNS": "01498424", "GEOID": "51620", "NAME": "Franklin" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-76.963021, 36.704696], [-76.912221, 36.698408], [-76.909672, 36.648175], [-76.962339, 36.667515], [-76.949327, 36.67873], [-76.968027, 36.682971], [-76.963021, 36.704696]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "595", "COUNTYNS": "01498422", "GEOID": "51595", "NAME": "Emporia" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-77.557359, 36.713166], [-77.510273, 36.718229], [-77.509246, 36.682998], [-77.556524, 36.674874], [-77.557359, 36.713166]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "670", "COUNTYNS": "01498428", "GEOID": "51670", "NAME": "Hopewell" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-77.334549, 37.312468], [-77.273379, 37.316116], [-77.253234, 37.295668], [-77.31081, 37.261451], [-77.328291, 37.271748], [-77.334549, 37.312468]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "510", "COUNTYNS": "01498415", "GEOID": "51510", "NAME": "Alexandria" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-77.140872, 38.826905], [-77.110799, 38.843446], [-77.087805, 38.827357], [-77.085609, 38.84419], [-77.044487611898006, 38.839598699716696], [-77.040372554526996, 38.785355394851003], [-77.143135, 38.805321], [-77.140872, 38.826905]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "059", "COUNTYNS": "01480119", "GEOID": "51059", "NAME": "Fairfax" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-77.53576, 38.847474], [-77.32828109319901, 39.057794871536501], [-77.246003, 39.024909], [-77.255703, 39.002409], [-77.234803, 38.97631], [-77.148179, 38.965002], [-77.119759, 38.934343], [-77.172276, 38.893245], [-77.194712, 38.899073], [-77.194234, 38.886146], [-77.149701, 38.87567], [-77.110799, 38.843446], [-77.140872, 38.826905], [-77.143135, 38.805321], [-77.040372554526996, 38.785355394851003], [-77.042298, 38.718515], [-77.122001, 38.685816], [-77.1302, 38.635017], [-77.204302, 38.617817], [-77.277032, 38.695026], [-77.355884, 38.725425], [-77.370878, 38.710433], [-77.442956, 38.803796], [-77.492801, 38.797821], [-77.50834, 38.841032], [-77.53576, 38.847474]], [[-77.334852, 38.853737], [-77.318689, 38.834651], [-77.27052, 38.840902], [-77.270597, 38.866075], [-77.334852, 38.853737]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "680", "COUNTYNS": "01498429", "GEOID": "51680", "NAME": "Lynchburg" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-79.26745, 37.44744], [-79.183302, 37.465908], [-79.120451, 37.398311], [-79.085244, 37.394743], [-79.214924, 37.33258], [-79.257188, 37.355608], [-79.231933, 37.394911], [-79.256628, 37.406573], [-79.244548, 37.419941], [-79.268727, 37.431028], [-79.26745, 37.44744]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "037", "COUNTYNS": "01492442", "GEOID": "51037", "NAME": "Charlotte" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-78.902227, 37.026799], [-78.824209, 37.205361], [-78.808198, 37.201852], [-78.778353, 37.228639], [-78.734351, 37.220256], [-78.681477, 37.24969], [-78.692432, 37.203673], [-78.644621, 37.194323], [-78.634927, 37.170064], [-78.583642, 37.140635], [-78.547128, 37.150431], [-78.480891, 37.085196], [-78.443644, 37.079371], [-78.493028, 36.89122], [-78.648541, 36.697909], [-78.691328, 36.741847], [-78.666145, 36.764363], [-78.682652, 36.797222], [-78.666995, 36.811822], [-78.686878, 36.824331], [-78.666125, 36.840482], [-78.671463, 36.857951], [-78.749727, 36.920065], [-78.727686, 36.937454], [-78.743891, 37.005439], [-78.756549, 37.00717], [-78.748358, 36.987057], [-78.774715, 36.980976], [-78.785452, 36.952783], [-78.817455, 36.98402], [-78.892702, 36.976694], [-78.902227, 37.026799]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "099", "COUNTYNS": "01480137", "GEOID": "51099", "NAME": "King George" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-77.330384, 38.334951], [-77.286201505089011, 38.347024428844499], [-77.240072, 38.331598], [-77.17934, 38.341915], [-77.138224, 38.367917], [-77.08481, 38.368297], [-77.043526, 38.400548], [-77.011827, 38.374554], [-77.030683, 38.311623], [-76.99767, 38.278047], [-77.044799, 38.260407], [-77.048482, 38.182444], [-77.073796, 38.141331], [-77.084596, 38.160231], [-77.115997, 38.149931], [-77.2143, 38.197029], [-77.254001, 38.18943], [-77.242001, 38.210729], [-77.251801, 38.229628], [-77.229757, 38.245208], [-77.275302, 38.247528], [-77.291402, 38.223729], [-77.290302, 38.238728], [-77.309419, 38.234737], [-77.345728, 38.26139], [-77.330384, 38.334951]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "161", "COUNTYNS": "01480165", "GEOID": "51161", "NAME": "Roanoke" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-80.261984, 37.340694], [-80.200161, 37.378568], [-80.147625, 37.382342], [-80.073985, 37.422305], [-79.865099, 37.328417], [-79.840367, 37.302681], [-79.858058, 37.267138], [-79.847082, 37.225468], [-79.962301, 37.137099], [-80.030562, 37.17481], [-80.088553, 37.160482], [-80.128119, 37.122912], [-80.172264, 37.108156], [-80.189835, 37.233476], [-80.25852, 37.308344], [-80.261984, 37.340694]], [[-80.088062, 37.282334], [-80.050761, 37.252635], [-80.033464, 37.26289], [-80.02883, 37.24365], [-79.998113, 37.252193], [-79.950384, 37.211274], [-79.924496, 37.224634], [-79.900048, 37.257297], [-79.909493, 37.278054], [-79.879276, 37.304047], [-79.974023, 37.335419], [-80.022226, 37.308338], [-80.033596, 37.324293], [-80.12049, 37.287053], [-80.088062, 37.282334]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "135", "COUNTYNS": "01493928", "GEOID": "51135", "NAME": "Nottoway" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-78.238161, 37.194822], [-78.231234, 37.29622], [-77.795926, 37.192592], [-77.805982, 37.175933], [-77.900254, 37.143885], [-77.889813, 36.988818], [-77.932749, 36.984246], [-77.968114, 36.987292], [-78.003639, 37.022756], [-78.082023, 37.011121], [-78.172207, 37.055963], [-78.170716, 37.076188], [-78.224286, 37.089685], [-78.239354, 37.120089], [-78.238161, 37.194822]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "683", "COUNTYNS": "01498430", "GEOID": "51683", "NAME": "Manassas" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-77.526457, 38.732466], [-77.475711, 38.781214], [-77.44751, 38.761115], [-77.451642, 38.738337], [-77.471425, 38.728152], [-77.507299, 38.740479], [-77.506167, 38.705741], [-77.526457, 38.732466]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "630", "COUNTYNS": "01498425", "GEOID": "51630", "NAME": "Fredericksburg" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-77.530283, 38.309175], [-77.506782, 38.325925], [-77.467053, 38.31866], [-77.447126, 38.284614], [-77.457837, 38.271108], [-77.492045, 38.273637], [-77.530283, 38.309175]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "610", "COUNTYNS": "01498423", "GEOID": "51610", "NAME": "Falls Church" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-77.194712, 38.899073], [-77.172276, 38.893245], [-77.149701, 38.87567], [-77.189719, 38.87801], [-77.194712, 38.899073]]]] } },
]}';
--DECLARE @@CountiesGeoJson nvarchar(max)
--SELECT @@CountiesGeoJson = BulkColumn
--FROM OPENROWSET
--(BULK 'C:\MapData\countiesEdited.json', SINGLE_CLOB)
--as JSON

--Insert Into [Tox].[dbo].[GeoCounties] (GEOID, GEO_NAME, FIPS_ST_CD, FIPS_CNTY_CD, RESOLUTION_ACCURACY, GEO_OBJECT)
select GEOID, GNAME, STATEFP, COUNTYFP, 10, Geo=fixed
from   openjson (@CountiesGeoJson, '$.features')
with
(
    GEOID char(5) '$.properties.GEOID',
    GNAME varchar(40) '$.properties.NAME',
    STATEFP char(2) '$.properties.STATEFP',
    COUNTYFP char(3) '$.properties.COUNTYFP',
    [type] Varchar(64) '$.geometry.type',
    [coordinates] nvarchar(max) '$.geometry.coordinates' as json
)
as GeoData
cross apply (
select
   stuff(
      (
        select concat(',  ', json_value(Value,'$[0]'),' ',json_value(Value,'$[1]'))
        from openjson(GeoData.coordinates,'$[0]')
        order by cast([key] as int)
        for xml path('')
      ),1,3,'') [path]
) PolygonData
OUTER APPLY (
    SELECT  STUFF(
        (
            SELECT CONCAT(',  ', polygon)
            FROM OPENJSON(GeoData.coordinates) as Poly
            CROSS APPLY OPENJSON(Poly.value) as Shape
            CROSS APPLY (
                SELECT '(' + stuff(
                (
                    select concat(',  ', json_value(Value,'$[0]'),' ',json_value(Value,'$[1]'))
                    from OPENJSON(Shape.value)
                    order by cast([key] as int)
                    for xml path('')
                ),1,3,'')+')' polygon
        ) Polygons
        for xml path('')
    ),1,3,'') multi
    WHERE LEN(Path) = 0
) MultigonData
cross apply (
    SELECT concat(upper(GeoData.[type]),'((',IsNull(NULLIF(path,''),multi),'))') WKT
) shapeDef
outer apply (
    select geography::STGeomFromText(WKT,4326).MakeValid()/*.ReorientObject()*/ as geom
) geography
outer apply (
    select CASE WHEN geom.EnvelopeAngle() > 90 THEN geom.ReorientObject() ELSE geom END as fixed
) fixes
</code>```

The query will run and produce some results but when it hits records where the NAME = 'Fairfax' and 'Roanoke', it stops with the above error.

Can anyone see the issue and know how to resolve this?

[EDIT 2019-05-31 17:35]
GeoJson Header:

```<code>{
  "type": "FeatureCollection",
  "name": "USCounty_Simplify_01",
  "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:EPSG::4269" } },
  "features": [
...
</code>```

Body:
I am trying to run a query (which I gleened from here) against GeoJson multipolygon data. It processes many of the spatial records but is stopping on a some.

I get the following error in the query messages:

Msg 6522, Level 16, State 1, Line 10

      A .NET Framework error occurred during execution of user-defined routine or aggregate "geography":

      System.FormatException: 24142: Expected "(" at position 15. The input has ",".

      System.FormatException:

      at Microsoft.SqlServer.Types.WellKnownTextReader.RecognizeToken(Char token)     at Microsoft.SqlServer.Types.WellKnownTextReader.ParseLineStringText()

      at Microsoft.SqlServer.Types.WellKnownTextReader.ParsePolygonText()

      at Microsoft.SqlServer.Types.WellKnownTextReader.ParseMultiPolygonText()

      at Microsoft.SqlServer.Types.WellKnownTextReader.ParseTaggedText(OpenGisType type)

      at Microsoft.SqlServer.Types.WellKnownTextReader.Read(OpenGisType type, Int32 srid)

      at Microsoft.SqlServer.Types.SqlGeography.ParseText(OpenGisType type, SqlChars taggedText, Int32 srid)

      at Microsoft.SqlServer.Types.SqlGeography.GeographyFromText(OpenGisType type, SqlChars taggedText, Int32 srid)

This is my statement with some test data:

declare @CountiesGeoJson nvarchar(max) = '{"type":"FeatureCollection","features":[
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "700", "COUNTYNS": "01498555", "GEOID": "51700", "NAME": "Newport News" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-76.622252, 37.142146], [-76.577819, 37.187025], [-76.591432, 37.214721], [-76.565092, 37.220645], [-76.458516, 37.100661], [-76.435519, 37.094882], [-76.451274, 37.076878], [-76.442269, 37.018448], [-76.424757, 37.025107], [-76.387711304409194, 36.989671332859004], [-76.411768, 36.962847], [-76.428869, 36.969947], [-76.464471, 37.027547], [-76.518242, 37.055351], [-76.536875, 37.083942], [-76.564219, 37.077507], [-76.618252, 37.119347], [-76.622252, 37.142146]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "620", "COUNTYNS": "01498424", "GEOID": "51620", "NAME": "Franklin" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-76.963021, 36.704696], [-76.912221, 36.698408], [-76.909672, 36.648175], [-76.962339, 36.667515], [-76.949327, 36.67873], [-76.968027, 36.682971], [-76.963021, 36.704696]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "595", "COUNTYNS": "01498422", "GEOID": "51595", "NAME": "Emporia" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-77.557359, 36.713166], [-77.510273, 36.718229], [-77.509246, 36.682998], [-77.556524, 36.674874], [-77.557359, 36.713166]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "670", "COUNTYNS": "01498428", "GEOID": "51670", "NAME": "Hopewell" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-77.334549, 37.312468], [-77.273379, 37.316116], [-77.253234, 37.295668], [-77.31081, 37.261451], [-77.328291, 37.271748], [-77.334549, 37.312468]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "510", "COUNTYNS": "01498415", "GEOID": "51510", "NAME": "Alexandria" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-77.140872, 38.826905], [-77.110799, 38.843446], [-77.087805, 38.827357], [-77.085609, 38.84419], [-77.044487611898006, 38.839598699716696], [-77.040372554526996, 38.785355394851003], [-77.143135, 38.805321], [-77.140872, 38.826905]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "059", "COUNTYNS": "01480119", "GEOID": "51059", "NAME": "Fairfax" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-77.53576, 38.847474], [-77.32828109319901, 39.057794871536501], [-77.246003, 39.024909], [-77.255703, 39.002409], [-77.234803, 38.97631], [-77.148179, 38.965002], [-77.119759, 38.934343], [-77.172276, 38.893245], [-77.194712, 38.899073], [-77.194234, 38.886146], [-77.149701, 38.87567], [-77.110799, 38.843446], [-77.140872, 38.826905], [-77.143135, 38.805321], [-77.040372554526996, 38.785355394851003], [-77.042298, 38.718515], [-77.122001, 38.685816], [-77.1302, 38.635017], [-77.204302, 38.617817], [-77.277032, 38.695026], [-77.355884, 38.725425], [-77.370878, 38.710433], [-77.442956, 38.803796], [-77.492801, 38.797821], [-77.50834, 38.841032], [-77.53576, 38.847474]], [[-77.334852, 38.853737], [-77.318689, 38.834651], [-77.27052, 38.840902], [-77.270597, 38.866075], [-77.334852, 38.853737]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "680", "COUNTYNS": "01498429", "GEOID": "51680", "NAME": "Lynchburg" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-79.26745, 37.44744], [-79.183302, 37.465908], [-79.120451, 37.398311], [-79.085244, 37.394743], [-79.214924, 37.33258], [-79.257188, 37.355608], [-79.231933, 37.394911], [-79.256628, 37.406573], [-79.244548, 37.419941], [-79.268727, 37.431028], [-79.26745, 37.44744]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "037", "COUNTYNS": "01492442", "GEOID": "51037", "NAME": "Charlotte" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-78.902227, 37.026799], [-78.824209, 37.205361], [-78.808198, 37.201852], [-78.778353, 37.228639], [-78.734351, 37.220256], [-78.681477, 37.24969], [-78.692432, 37.203673], [-78.644621, 37.194323], [-78.634927, 37.170064], [-78.583642, 37.140635], [-78.547128, 37.150431], [-78.480891, 37.085196], [-78.443644, 37.079371], [-78.493028, 36.89122], [-78.648541, 36.697909], [-78.691328, 36.741847], [-78.666145, 36.764363], [-78.682652, 36.797222], [-78.666995, 36.811822], [-78.686878, 36.824331], [-78.666125, 36.840482], [-78.671463, 36.857951], [-78.749727, 36.920065], [-78.727686, 36.937454], [-78.743891, 37.005439], [-78.756549, 37.00717], [-78.748358, 36.987057], [-78.774715, 36.980976], [-78.785452, 36.952783], [-78.817455, 36.98402], [-78.892702, 36.976694], [-78.902227, 37.026799]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "099", "COUNTYNS": "01480137", "GEOID": "51099", "NAME": "King George" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-77.330384, 38.334951], [-77.286201505089011, 38.347024428844499], [-77.240072, 38.331598], [-77.17934, 38.341915], [-77.138224, 38.367917], [-77.08481, 38.368297], [-77.043526, 38.400548], [-77.011827, 38.374554], [-77.030683, 38.311623], [-76.99767, 38.278047], [-77.044799, 38.260407], [-77.048482, 38.182444], [-77.073796, 38.141331], [-77.084596, 38.160231], [-77.115997, 38.149931], [-77.2143, 38.197029], [-77.254001, 38.18943], [-77.242001, 38.210729], [-77.251801, 38.229628], [-77.229757, 38.245208], [-77.275302, 38.247528], [-77.291402, 38.223729], [-77.290302, 38.238728], [-77.309419, 38.234737], [-77.345728, 38.26139], [-77.330384, 38.334951]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "161", "COUNTYNS": "01480165", "GEOID": "51161", "NAME": "Roanoke" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-80.261984, 37.340694], [-80.200161, 37.378568], [-80.147625, 37.382342], [-80.073985, 37.422305], [-79.865099, 37.328417], [-79.840367, 37.302681], [-79.858058, 37.267138], [-79.847082, 37.225468], [-79.962301, 37.137099], [-80.030562, 37.17481], [-80.088553, 37.160482], [-80.128119, 37.122912], [-80.172264, 37.108156], [-80.189835, 37.233476], [-80.25852, 37.308344], [-80.261984, 37.340694]], [[-80.088062, 37.282334], [-80.050761, 37.252635], [-80.033464, 37.26289], [-80.02883, 37.24365], [-79.998113, 37.252193], [-79.950384, 37.211274], [-79.924496, 37.224634], [-79.900048, 37.257297], [-79.909493, 37.278054], [-79.879276, 37.304047], [-79.974023, 37.335419], [-80.022226, 37.308338], [-80.033596, 37.324293], [-80.12049, 37.287053], [-80.088062, 37.282334]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "135", "COUNTYNS": "01493928", "GEOID": "51135", "NAME": "Nottoway" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-78.238161, 37.194822], [-78.231234, 37.29622], [-77.795926, 37.192592], [-77.805982, 37.175933], [-77.900254, 37.143885], [-77.889813, 36.988818], [-77.932749, 36.984246], [-77.968114, 36.987292], [-78.003639, 37.022756], [-78.082023, 37.011121], [-78.172207, 37.055963], [-78.170716, 37.076188], [-78.224286, 37.089685], [-78.239354, 37.120089], [-78.238161, 37.194822]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "683", "COUNTYNS": "01498430", "GEOID": "51683", "NAME": "Manassas" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-77.526457, 38.732466], [-77.475711, 38.781214], [-77.44751, 38.761115], [-77.451642, 38.738337], [-77.471425, 38.728152], [-77.507299, 38.740479], [-77.506167, 38.705741], [-77.526457, 38.732466]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "630", "COUNTYNS": "01498425", "GEOID": "51630", "NAME": "Fredericksburg" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-77.530283, 38.309175], [-77.506782, 38.325925], [-77.467053, 38.31866], [-77.447126, 38.284614], [-77.457837, 38.271108], [-77.492045, 38.273637], [-77.530283, 38.309175]]]] } },
{ "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "610", "COUNTYNS": "01498423", "GEOID": "51610", "NAME": "Falls Church" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-77.194712, 38.899073], [-77.172276, 38.893245], [-77.149701, 38.87567], [-77.189719, 38.87801], [-77.194712, 38.899073]]]] } },
]}';
--DECLARE @@CountiesGeoJson nvarchar(max)
--SELECT @@CountiesGeoJson = BulkColumn
--FROM OPENROWSET
--(BULK 'C:\MapData\countiesEdited.json', SINGLE_CLOB)
--as JSON

--Insert Into [Tox].[dbo].[GeoCounties] (GEOID, GEO_NAME, FIPS_ST_CD, FIPS_CNTY_CD, RESOLUTION_ACCURACY, GEO_OBJECT)
select GEOID, GNAME, STATEFP, COUNTYFP, 10, Geo=fixed
from   openjson (@CountiesGeoJson, '$.features')
with
(
    GEOID char(5) '$.properties.GEOID',
    GNAME varchar(40) '$.properties.NAME',
    STATEFP char(2) '$.properties.STATEFP',
    COUNTYFP char(3) '$.properties.COUNTYFP',
    [type] Varchar(64) '$.geometry.type',
    [coordinates] nvarchar(max) '$.geometry.coordinates' as json
)
as GeoData
cross apply (
select
   stuff(
      (
        select concat(',  ', json_value(Value,'$[0]'),' ',json_value(Value,'$[1]'))
        from openjson(GeoData.coordinates,'$[0]')
        order by cast([key] as int)
        for xml path('')
      ),1,3,'') [path]
) PolygonData
OUTER APPLY (
    SELECT  STUFF(
        (
            SELECT CONCAT(',  ', polygon)
            FROM OPENJSON(GeoData.coordinates) as Poly
            CROSS APPLY OPENJSON(Poly.value) as Shape
            CROSS APPLY (
                SELECT '(' + stuff(
                (
                    select concat(',  ', json_value(Value,'$[0]'),' ',json_value(Value,'$[1]'))
                    from OPENJSON(Shape.value)
                    order by cast([key] as int)
                    for xml path('')
                ),1,3,'')+')' polygon
        ) Polygons
        for xml path('')
    ),1,3,'') multi
    WHERE LEN(Path) = 0
) MultigonData
cross apply (
    SELECT concat(upper(GeoData.[type]),'((',IsNull(NULLIF(path,''),multi),'))') WKT
) shapeDef
outer apply (
    select geography::STGeomFromText(WKT,4326).MakeValid()/*.ReorientObject()*/ as geom
) geography
outer apply (
    select CASE WHEN geom.EnvelopeAngle() > 90 THEN geom.ReorientObject() ELSE geom END as fixed
) fixes

The query will run and produce some results but when it hits records where the NAME = 'Fairfax' and 'Roanoke', it stops with the above error.

Can anyone see the issue and know how to resolve this?

[EDIT 2019-05-31 17:35]
GeoJson Header:

{
  "type": "FeatureCollection",
  "name": "USCounty_Simplify_01",
  "crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:EPSG::4269" } },
  "features": [
...

Body:
I've reduced testing data to:

{"type":"FeatureCollection","features":[
    { "type": "Feature", "properties": { "STATEFP": "51", "COUNTYFP": "059", "COUNTYNS": "01480119", "GEOID": "51059", "NAME": "Fairfax" }, "geometry": { "type": "MultiPolygon", "coordinates": [[[[-77.53576, 38.847474], [-77.32828109319901, 39.057794871536501], [-77.246003, 39.024909], [-77.255703, 39.002409], [-77.234803, 38.97631], [-77.148179, 38.965002], [-77.119759, 38.934343], [-77.172276, 38.893245], [-77.194712, 38.899073], [-77.194234, 38.886146], [-77.149701, 38.87567], [-77.110799, 38.843446], [-77.140872, 38.826905], [-77.143135, 38.805321], [-77.040372554526996, 38.785355394851003], [-77.042298, 38.718515], [-77.122001, 38.685816], [-77.1302, 38.635017], [-77.204302, 38.617817], [-77.277032, 38.695026], [-77.355884, 38.725425], [-77.370878, 38.710433], [-77.442956, 38.803796], [-77.492801, 38.797821], [-77.50834, 38.841032], [-77.53576, 38.847474]], [[-77.334852, 38.853737], [-77.318689, 38.834651], [-77.27052, 38.840902], [-77.270597, 38.866075], [-77.334852, 38.853737]]]] } }
  ]}

I've commented out last outer apply and select WKT to see what's in.

SELECT GEOID, GNAME, STATEFP, COUNTYFP, 10--, Geo=fixed
    ,WKT

WKT returns:

MULTIPOLYGON(( ,   ))

So "geography::STGeomFromText(WKT,4326).MakeValid()" cannot build geometry out of this data and fails with the error.


问:
separate subsentences inside sentence without any coordination
I want to separate all subsentences inside a sentence. If the sentence have  punctuation or any coordination, I am able to separate them with spacy. But in case where there is no separation, have you any idea to deal with it?
For example, I have the sentence (in french):

```<code>Je suis Linda je veux savoir votre nom.
</code>```

I want to get:

```<code>Je suis Linda
je veux savoir votre nom.
</code>```

答:
I think you can probably do this using some kind of probabilistic model but it will be rather technical. The idea is that words have a certain probability of having a particular part of speech ("see" is usually a verb but is sometimes a noun, like "Holy See" actually refers to the Pope). Each part of speech has a conditional probability of being beside another part of speech (Noun follows Preposition, for example). Using this information, an algorithm could calculate the probability of clauses and sentences. The algorithm would have to maintain multiple viable interpretations and return the interpretation with the highest probability, which would be either one or more sentences. I believe this is what you are asking for.

Unfortunately, I don't know whether SpaCy is able to do this. I suspect not.

I suggest you look at examples of solving this kind of problem in the academic literature. Here are two to get you started:

Sentence boundary detection in conversational speech transcripts using noisily labeled examples

Comparing and Combining Generative and Posterior Probability Models:
Some Advances in Sentence Boundary Detection in Speech

Body:
I want to separate all subsentences inside a sentence. If the sentence have  punctuation or any coordination, I am able to separate them with spacy. But in case where there is no separation, have you any idea to deal with it?
For example, I have the sentence (in french):

Je suis Linda je veux savoir votre nom.

I want to get:

Je suis Linda
je veux savoir votre nom.


问:
Powershell "UNC paths are not supported" but I'm using Push-Location
I am running a command line program in powershell working on our \servername\files folder as the running folder. I get a "UNC paths are not supported" error even though I am using Push-Location (which is the only solution I find while googling). The simplest code that gives me this error is as follows:</p>

```<code>Push-Location \\servername\files
cmd.exe \c ping 10.1.10.10
Pop-Location
</code>```

答:
*-Location works as designed, as I'll demo below.

Demo ---

```<code>PS C:\Scripts> (Get-CimInstance -ClassName CIM_OperatingSystem).Caption
Microsoft Windows Server 2012 R2 Standard

PS C:\Scripts> $PSVersionTable.PSVersion

Major  Minor  Build  Revision
-----  -----  -----  --------
4      0      -1     -1

PS C:\Scripts> Test-Path -Path '\\FileServer01\Data'
True

PS C:\Scripts> $pwd

Path
----
C:\Scripts

PS C:\Scripts> Push-Location -Path '\\FileServer01\Data'

PS Microsoft.PowerShell.Core\FileSystem::\\FileServer01\Data> $pwd

Path
----
Microsoft.PowerShell.Core\FileSystem::\\FileServer01\Data
</code>```

As for this...

```<code>cmd.exe \c ping 10.1.10.10
</code>```

... is not running from the UNC, that is running from your host, the fact that you pushd to a share is meaningless.

If a share has an exe you want to run there is no reason to change to that location to run it. Just use the defined methods to run external commands (see the link below) via PowerShell and just use the UNC path without switching there first. Even running a remote exe still means is using cmd.exe from your host.

```<code>PS Microsoft.PowerShell.Core\FileSystem::\\FileServer01\Data> Pop-Location

PS C:\Scripts> $pwd

Path
----
C:\Scripts

PS C:\Scripts>
</code>```

Running external commands, always require special consideration.

PowerShell: Running Executables
  https://social.technet.microsoft.com/wiki/contents/articles/7703.powershell-running-executables.aspx

Solve Problems with External Command Lines in PowerShell
  https://devblogs.microsoft.com/scripting/solve-problems-with-external-command-lines-in-powershell

Top 5 tips for running external commands in Powershell
  https://powershelleverydayfaq.blogspot.com/2012/04/top-5-tips-for-running-external.html

Using Windows PowerShell to run old command line tools (and their
  weirdest parameters)
  https://blogs.technet.microsoft.com/josebda/2012/03/03/using-windows-powershell-to-run-old-command-line-tools-and-their-weirdest-parameters

Execution of external commands in PowerShell done right
  https://mnaoumov.wordpress.com/2015/01/11/execution-of-external-commands-in-powershell-done-right
  https://mnaoumov.wordpress.com/2015/03/31/execution-of-external-commands-native-applications-in-powershell-done-right-part-2 https://mnaoumov.wordpress.com/2015/04/05/execution-of-external-commands-native-applications-in-powershell-done-right-part-3

Quoting specifics

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_quoting_rules
  https://trevorsullivan.net/2016/07/20/powershell-quoting

Body:
I am running a command line program in powershell working on our \servername\files folder as the running folder. I get a "UNC paths are not supported" error even though I am using Push-Location (which is the only solution I find while googling). The simplest code that gives me this error is as follows:

Push-Location \\servername\files
cmd.exe \c ping 10.1.10.10
Pop-Location

Body:
*-Location works as designed, as I'll demo below.

Demo ---

PS C:\Scripts> (Get-CimInstance -ClassName CIM_OperatingSystem).Caption
Microsoft Windows Server 2012 R2 Standard

PS C:\Scripts> $PSVersionTable.PSVersion

Major  Minor  Build  Revision
-----  -----  -----  --------
4      0      -1     -1

PS C:\Scripts> Test-Path -Path '\\FileServer01\Data'
True

PS C:\Scripts> $pwd

Path
----
C:\Scripts

PS C:\Scripts> Push-Location -Path '\\FileServer01\Data'

PS Microsoft.PowerShell.Core\FileSystem::\\FileServer01\Data> $pwd

Path
----
Microsoft.PowerShell.Core\FileSystem::\\FileServer01\Data

As for this...

cmd.exe \c ping 10.1.10.10

... is not running from the UNC, that is running from your host, the fact that you pushd to a share is meaningless.

If a share has an exe you want to run there is no reason to change to that location to run it. Just use the defined methods to run external commands (see the link below) via PowerShell and just use the UNC path without switching there first. Even running a remote exe still means is using cmd.exe from your host.

PS Microsoft.PowerShell.Core\FileSystem::\\FileServer01\Data> Pop-Location

PS C:\Scripts> $pwd

Path
----
C:\Scripts

PS C:\Scripts>

Running external commands, always require special consideration.

PowerShell: Running Executables
  https://social.technet.microsoft.com/wiki/contents/articles/7703.powershell-running-executables.aspx

Solve Problems with External Command Lines in PowerShell
  https://devblogs.microsoft.com/scripting/solve-problems-with-external-command-lines-in-powershell

Top 5 tips for running external commands in Powershell
  https://powershelleverydayfaq.blogspot.com/2012/04/top-5-tips-for-running-external.html

Using Windows PowerShell to run old command line tools (and their
  weirdest parameters)
  https://blogs.technet.microsoft.com/josebda/2012/03/03/using-windows-powershell-to-run-old-command-line-tools-and-their-weirdest-parameters

Execution of external commands in PowerShell done right
  https://mnaoumov.wordpress.com/2015/01/11/execution-of-external-commands-in-powershell-done-right
  https://mnaoumov.wordpress.com/2015/03/31/execution-of-external-commands-native-applications-in-powershell-done-right-part-2 https://mnaoumov.wordpress.com/2015/04/05/execution-of-external-commands-native-applications-in-powershell-done-right-part-3

Quoting specifics

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_quoting_rules
  https://trevorsullivan.net/2016/07/20/powershell-quoting


问:
Wrapping Python cProfile runctx API to parameterize runs with anything anywhere
Using Python 3.7.2,

I'm trying to wrap cProfile.runctx() into a separate module such as util.profile_runs() from my main module mymain.py to profile functions in the main module. This requires importing mymain.py in util.profile_runs().

However, I couldn't get importlib working with the following code in util.py:

```<code>import cProfile as profile
import importlib.util
from os.path import basename, splitext
from pprint import pprint
import pstats
import sys

def profile_runs(funcname, modulefile, nruns=5):
    importlib.machinery.SOURCE_SUFFIXES.append('')
    module_name = splitext(basename(modulefile))[0]
    spec = importlib.util.spec_from_file_location(module_name, modulefile)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    # if desired: importlib.machinery.SOURCE_SUFFIXES.pop()

    pprint(dir(module))

    for i in range(nruns):
        filename = 'profile_{}_{}.stats'.format(funcname, i)
        profile.runctx('print({}, {}.{}())'.format(i, module_name, funcname), globals(), locals(), filename)

    # Read all 5 stats files into a single object
    stats = pstats.Stats('profile_stats_0.stats')

    for i in range(1, nruns):
        stats.add('profile_{}_{}.stats'.format(funcname, i))

    # Clean up filenames for the report
    stats.strip_dirs()

    # Sort the statistics by the cumulative time spent
    # in the function
    stats.sort_stats('cumulative')
    stats.print_stats()
</code>```

and mymain.py:

```<code>import util

def func_to_profile()
    print('running func_to_profile')

if __name__ == '__main__':
    util.profile_runs('funct_to_profile')
</code>```

The pprint(dir(module)) line outputs correct info of the module, but the .runctx call keeps saying:

```<code>NameError: name 'mymain' is not defined
</code>```

It works if I explicitly import mymain in the util.profile_runs() code.
Is it a bad idea to profile this way?

答:
I found a workaround: Just insert import module_name; in the run string, like this:

```<code>profile.runctx('import {};print({}, {}.{}())'.format(module_name, i, module_name, funcname), globals(), locals(), filename)
</code>```

and get rid of the whole importlib dance.

Body:
Using Python 3.7.2,

I'm trying to wrap cProfile.runctx() into a separate module such as util.profile_runs() from my main module mymain.py to profile functions in the main module. This requires importing mymain.py in util.profile_runs().

However, I couldn't get importlib working with the following code in util.py:

import cProfile as profile
import importlib.util
from os.path import basename, splitext
from pprint import pprint
import pstats
import sys

def profile_runs(funcname, modulefile, nruns=5):
    importlib.machinery.SOURCE_SUFFIXES.append('')
    module_name = splitext(basename(modulefile))[0]
    spec = importlib.util.spec_from_file_location(module_name, modulefile)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    # if desired: importlib.machinery.SOURCE_SUFFIXES.pop()

    pprint(dir(module))

    for i in range(nruns):
        filename = 'profile_{}_{}.stats'.format(funcname, i)
        profile.runctx('print({}, {}.{}())'.format(i, module_name, funcname), globals(), locals(), filename)

    # Read all 5 stats files into a single object
    stats = pstats.Stats('profile_stats_0.stats')

    for i in range(1, nruns):
        stats.add('profile_{}_{}.stats'.format(funcname, i))

    # Clean up filenames for the report
    stats.strip_dirs()

    # Sort the statistics by the cumulative time spent
    # in the function
    stats.sort_stats('cumulative')
    stats.print_stats()

and mymain.py:

import util

def func_to_profile()
    print('running func_to_profile')

if __name__ == '__main__':
    util.profile_runs('funct_to_profile')

The pprint(dir(module)) line outputs correct info of the module, but the .runctx call keeps saying:

NameError: name 'mymain' is not defined

It works if I explicitly import mymain in the util.profile_runs() code.
Is it a bad idea to profile this way?

Body:
I found a workaround: Just insert import module_name; in the run string, like this:

profile.runctx('import {};print({}, {}.{}())'.format(module_name, i, module_name, funcname), globals(), locals(), filename)

and get rid of the whole importlib dance.


问:
keras K.function error for layer output extraction
I currently have a modified resnet 50 architecture that takes two inputs. Building the model and training the model works fine, but when I’m trying to extract layer outputs using the backend function, I encounter errors.

I would prefer to extract layers using the backend function, rather than creating a new truncated model with just my layer of interest as the output.

The following snippet is self contained, and should be able to run and give the error I’ve been seeing.

I've tried reformatting the function in a few ways, such as  K.function( [ mymodel.input[0],mymodel.input[1] ] ,  [mymodel.layers[-1].layers[-6].output])
or
K.function( [ mymodel.layers[0].input,mymodel.layers[1].input ] ,  [mymodel.layers[-1].layers[-6].output])
but nothing seems to fix the issue

```<code>##imports
from keras.applications.resnet50 import ResNet50
from keras.layers import Input
from keras.layers import Lambda
from keras.models import Model
from keras.optimizers import Adam
import keras
import keras.backend as K
import numpy as np

#pop off the input
res = ResNet50(weights=None,include_top=True,classes=2)
res.layers.pop(0)

#add two inputs
auxinput= Input(batch_shape=(None,224,224,1), name='aux_input')
main_input = Input(batch_shape=(None,224,224,3), name='main_input')

#use a lambda functon to return just our main input (avoids errors from out auxilary input not being used in resnet50 component)
l_output = Lambda(lambda x: x[0])([main_input, auxinput])

#feed our main layer to resnet50
data_passed_thru = res(l_output)

#assemble the model with our two inputs, and output
mymodel = Model(inputs=[main_input, auxinput], outputs=[data_passed_thru])
mymodel.compile(optimizer=Adam(lr=0.001), loss= keras.losses.poisson, metrics=[ 'accuracy'])
print("my model summary:")
mymodel.summary()

##generate some fake data for testing
fake_aux= np.zeros((224,224))
fake_aux=fake_aux[None,...]
fake_aux=fake_aux[...,None]
print('fake aux input shape:', fake_aux.shape)
fake_main= np.zeros((224,224,3))
fake_main=fake_main[None,...]
print('fake main input shape:', fake_main.shape)

#check our model inputs and target layer
print("inputs:", mymodel.input)
print("layer outout I'm trying to extract:", mymodel.layers[-1].layers[-6])

#create function to feed inputs, get our desired layer outputs
get_output_func = K.function( mymodel.input ,  [mymodel.layers[-1].layers[-6].output])

##this is the line that fails
X= [fake_main,fake_aux]
preds=get_output_func(X)
</code>```

The error message I get is

```<code>InvalidArgumentError: You must feed a value for placeholder tensor 'input_1' with dtype float and shape [?,224,224,3]
     [[{{node input_1}}]]
</code>```

答:
I managed to fix it by accessing the Resnet50 inputs directly for the function, rather than just the whole model's initial inputs. The K.function that works is

```<code>get_output_func = K.function( [mymodel.layers[-1].get_input_at(0)] ,  [mymodel.layers[-1].layers[-6].output])
X= [fake_main]
preds=get_output_func(X)
</code>```

It only works because of my architecture only depends on the 1 input passing through, so not sure what the solution would be for other situations, but works for my case

Body:
I currently have a modified resnet 50 architecture that takes two inputs. Building the model and training the model works fine, but when I’m trying to extract layer outputs using the backend function, I encounter errors.

I would prefer to extract layers using the backend function, rather than creating a new truncated model with just my layer of interest as the output.

The following snippet is self contained, and should be able to run and give the error I’ve been seeing.

I've tried reformatting the function in a few ways, such as  K.function( [ mymodel.input[0],mymodel.input[1] ] ,  [mymodel.layers[-1].layers[-6].output])
or
K.function( [ mymodel.layers[0].input,mymodel.layers[1].input ] ,  [mymodel.layers[-1].layers[-6].output])
but nothing seems to fix the issue

##imports
from keras.applications.resnet50 import ResNet50
from keras.layers import Input
from keras.layers import Lambda
from keras.models import Model
from keras.optimizers import Adam
import keras
import keras.backend as K
import numpy as np

#pop off the input
res = ResNet50(weights=None,include_top=True,classes=2)
res.layers.pop(0)

#add two inputs
auxinput= Input(batch_shape=(None,224,224,1), name='aux_input')
main_input = Input(batch_shape=(None,224,224,3), name='main_input')

#use a lambda functon to return just our main input (avoids errors from out auxilary input not being used in resnet50 component)
l_output = Lambda(lambda x: x[0])([main_input, auxinput])

#feed our main layer to resnet50
data_passed_thru = res(l_output)

#assemble the model with our two inputs, and output
mymodel = Model(inputs=[main_input, auxinput], outputs=[data_passed_thru])
mymodel.compile(optimizer=Adam(lr=0.001), loss= keras.losses.poisson, metrics=[ 'accuracy'])
print("my model summary:")
mymodel.summary()

##generate some fake data for testing
fake_aux= np.zeros((224,224))
fake_aux=fake_aux[None,...]
fake_aux=fake_aux[...,None]
print('fake aux input shape:', fake_aux.shape)
fake_main= np.zeros((224,224,3))
fake_main=fake_main[None,...]
print('fake main input shape:', fake_main.shape)

#check our model inputs and target layer
print("inputs:", mymodel.input)
print("layer outout I'm trying to extract:", mymodel.layers[-1].layers[-6])

#create function to feed inputs, get our desired layer outputs
get_output_func = K.function( mymodel.input ,  [mymodel.layers[-1].layers[-6].output])

##this is the line that fails
X= [fake_main,fake_aux]
preds=get_output_func(X)

The error message I get is

InvalidArgumentError: You must feed a value for placeholder tensor 'input_1' with dtype float and shape [?,224,224,3]
     [[{{node input_1}}]]

Body:
I managed to fix it by accessing the Resnet50 inputs directly for the function, rather than just the whole model's initial inputs. The K.function that works is

get_output_func = K.function( [mymodel.layers[-1].get_input_at(0)] ,  [mymodel.layers[-1].layers[-6].output])
X= [fake_main]
preds=get_output_func(X)

It only works because of my architecture only depends on the 1 input passing through, so not sure what the solution would be for other situations, but works for my case


答:
Try this.</p>

```<code>select c2.compteur, ((c1.feb15+c1.nov15+c1.dec15)*100 / (select round(c1.feb15+c1.nov15+c1.dec15) from compteur2015 c15 where c1.compteur = c15.compteur ))
from compteur2015 c1, compteur c2
group by c2.compteur
</code>```

Title: Subquery must return a single row

Body:
When I start this query I got this error:

AnalysisException: Subquery must return a single row: (SELECT round(c1.feb15 + c1.nov15 + c1.dec15) FROM suivisousse.compteur2015)

Query:

SELECT
    c2.compteur,
    ((c1.feb15 + c1.nov15 + c1.dec15) * 100 /
         (SELECT ROUND(c1.feb15 + c1.nov15 + c1.dec15) FROM compteur2015))
FROM
    compteur2015 c1, compteur c2
WHERE
    c1.compteur = c2.compteur
GROUP BY
    c2.compteur

Body:
Try this.

select c2.compteur, ((c1.feb15+c1.nov15+c1.dec15)*100 / (select round(c1.feb15+c1.nov15+c1.dec15) from compteur2015 c15 where c1.compteur = c15.compteur ))
from compteur2015 c1, compteur c2
group by c2.compteur


问:
How do you reset your eclipse browser to start a new homework assignment?
I'm starting to learn eclipse and just got through the first set of hw that was the Hello world exercise. I'm moving on to the next assignment but the Hello world file is still there and when I run the new assignment for the code i just get Hello world. Is there any way to start a fresh new file?</p>

答:
If you are looking for how to create a new Eclipse project take a look here:

http://pages.cs.wisc.edu/~cs302/labs/EclipseTutorial/Step_02.html

If you are looking for how to delete a file from Eclipse:

Right click the file in Package Explorer and select Delete, the choose Ok

Let me know if you need to know anything else concerning this question and let me know if I misunderstood you and didn't properly address your question.


问:
MySQL variable value not changing in WHERE clause
My variable @row_number value is not changing in WHERE clause but is updated in SELECT clause

```<code>SET @row_number := -1;

SELECT (@row_number:=@row_number+1) as num,location_table.* FROM location_table
WHERE loc_userID = 'SP_EGMA001'
      AND (loc_date >= (STR_TO_DATE('05-27-2019 6:00:00', '%m-%d-%Y %H:%i:%s') + INTERVAL (30 * @row_number) minute))
ORDER BY loc_date asc
</code>```

答:
try this - access the @row_number alias num in a outer query. excuse for any syntax errors.</p>

```<code>SET @row_number := -1;

select * from (
SELECT (@row_number:=@row_number+1) as num,location_table.* FROM location_table
WHERE loc_userID = 'SP_EGMA001' ) a
WHERE (loc_date >= (STR_TO_DATE('05-27-2019 6:00:00', '%m-%d-%Y %H:%i:%s') + INTERVAL (30 * num) minute))
ORDER BY loc_date asc
</code>```

Body:
My variable @row_number value is not changing in WHERE clause but is updated in SELECT clause

SET @row_number := -1;

SELECT (@row_number:=@row_number+1) as num,location_table.* FROM location_table
WHERE loc_userID = 'SP_EGMA001'
      AND (loc_date >= (STR_TO_DATE('05-27-2019 6:00:00', '%m-%d-%Y %H:%i:%s') + INTERVAL (30 * @row_number) minute))
ORDER BY loc_date asc

Body:
try this - access the @row_number alias num in a outer query. excuse for any syntax errors.

SET @row_number := -1;

select * from (
SELECT (@row_number:=@row_number+1) as num,location_table.* FROM location_table
WHERE loc_userID = 'SP_EGMA001' ) a
WHERE (loc_date >= (STR_TO_DATE('05-27-2019 6:00:00', '%m-%d-%Y %H:%i:%s') + INTERVAL (30 * num) minute))
ORDER BY loc_date asc


问:
Check for value changes in variable
I have 2 components in my angular app. Component A is a header and component B sets a value that I need in component A. The problem is that component A is getting set before B so the value that I need is not being displayed when I need it. If I refresh my browser then it shows. My code will explain better.

Component A

```<code>  offerExpiry: any;

  constructor(
    public expiry: ExploreOfferService
  ) {

  }
  ngOnChanges() {
    this.expiry.event.subscribe((data) => {
      this.offerExpiry = data;
    });
  }

  <div class="col-5 right">
    <div>
      <span *ngIf="offerExpiry">{{offerExpiry?.data}} days left to respond</span>
      <img src="../../../../assets/icons/calendar(old).png">
    </div>
  </div>
</code>```

Component B

```<code>offerExpiry: any;

...

  async ngOnInit() {
    if (this._exploreService.offer) {
      ...
    } else {
      const offer = await this._exploreService.getOfferDetails();
      const date1 = new Date(offer.expiryDate);
      const date2 = new Date(offer.startDate);
      const diffTime = Math.abs(date2.getTime() - date1.getTime());
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      this.offerExpiry = diffDays;
      this._exploreService.publishExpiryDate({data: this.offerExpiry});
    }
  }
</code>```

service file

```<code>  public publishExpiryDate(data: any) {
    this._subject.next(data);
  }
</code>```

答:
ngOnChanges is life hook for component binding changes, rather than subscribing observable there, subscribe the service variable in constructor or ngOnInit

Service.ts

```<code>public getSubject() {
    return this._subject;
}

public publishExpiryDate(data: any) {
    this._subject.next(data);
}
</code>```

In Component A,

```<code>constructor(service: Service) {
    this.service.getSubject().subscribe((data) => {
      this.offerExpiry = data;
    });
}
</code>```

Title: Check for value changes in variable

Body:
I have 2 components in my angular app. Component A is a header and component B sets a value that I need in component A. The problem is that component A is getting set before B so the value that I need is not being displayed when I need it. If I refresh my browser then it shows. My code will explain better.

Component A

  offerExpiry: any;

  constructor(
    public expiry: ExploreOfferService
  ) {

  }
  ngOnChanges() {
    this.expiry.event.subscribe((data) => {
      this.offerExpiry = data;
    });
  }

      {{offerExpiry?.data}} days left to respond

Component B

offerExpiry: any;

...

  async ngOnInit() {
    if (this._exploreService.offer) {
      ...
    } else {
      const offer = await this._exploreService.getOfferDetails();
      const date1 = new Date(offer.expiryDate);
      const date2 = new Date(offer.startDate);
      const diffTime = Math.abs(date2.getTime() - date1.getTime());
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      this.offerExpiry = diffDays;
      this._exploreService.publishExpiryDate({data: this.offerExpiry});
    }
  }

service file

  public publishExpiryDate(data: any) {
    this._subject.next(data);
  }

Body:
ngOnChanges is life hook for component binding changes, rather than subscribing observable there, subscribe the service variable in constructor or ngOnInit

Service.ts

public getSubject() {
    return this._subject;
}

public publishExpiryDate(data: any) {
    this._subject.next(data);
}

In Component A,

constructor(service: Service) {
    this.service.getSubject().subscribe((data) => {
      this.offerExpiry = data;
    });
}


问:
How to Install Fastutil using the .jar Executable file
I'm trying to install fastutil-8.2.2 library on my pc, however the .jar far I download does not execute. The downloaded file is of type executable jar. I have Java SE Runtime environment installed as well. How do I install this? If installation is not possible, then how do I use these libraries after extraction of the file?

I have tried directly opening it, as well using

```<code>java -jar fastutil-8.2.2.jar
</code>```

which gives me the output

```<code>no main manifest attribute, in fastutil-8.2.2.jar
</code>```

the META-INF\MANIFEST file which I can see on extraction also does not contain any one-liner beginning with main-package.

答:
Maybe you are in wrong way.

I think fastutil DO NOT NEED INSTALL.

You just add fastutil-8.2.2.jar to your project library reference path, then will be fine.

What's your IDE?

Eclipse:  how to add jar in classpath

Intellij Idea the way

Or using maven.

Body:
I'm trying to install fastutil-8.2.2 library on my pc, however the .jar far I download does not execute. The downloaded file is of type executable jar. I have Java SE Runtime environment installed as well. How do I install this? If installation is not possible, then how do I use these libraries after extraction of the file?

I have tried directly opening it, as well using

java -jar fastutil-8.2.2.jar

which gives me the output

no main manifest attribute, in fastutil-8.2.2.jar

the META-INF\MANIFEST file which I can see on extraction also does not contain any one-liner beginning with main-package.


问:
Problem running PHP temperature converter
I've been trying to work a simple form-based temperature converter, but I'm currently getting a white screen, and I cannot see what is wrong with the code. In addition, any ideas / suggestions for best practice are most welcome!</p>

```<code><?php // convert.php

if (isset($_POST['temperature']))
    $temp = sanitize_string($_POST['temperature']);

if (isset($_POST['scale']))
{
    if ($_POST['scale'] == 'fah')
        $conv = 'fah';
        $output = intval((5 / 9) * ($temp - 32));
    elseif ($_POST['scale'] == 'cel')
        $conv = 'cel';
        $output = intval((9 / 5) * ($temp + 32));
    else
        $output = '';
}
?>

<html>

<head>
    <title>Temperature converter</title>
</head>

<body>
    <?php
    if (isset($_POST['submitted']) and isset($conv))
    {
        if ($conv == 'fah')
            print("$temp degrees Fahrenheit is $output degrees Celcius");
        elseif ($conv == 'cel')
            print("$temp degrees Celcius is $output degrees Fahrenheit");
    }
    ?>

<form method="post" action="convert.php">
    <label>Temperature <input type="text" name="temperature"></label>
    <label>Celcius <input type="radio" name="scale" value="cel"></label>
    <label>Fahrenheit <input type="radio" name="scale" value="fah"></label>
    <input type="hidden" name="submitted" value="yes">
    <input type="submit">
</form>
</body>

</html>

<?php
print_r($_POST);

function sanitize_string($var)
{
    $var = stripslashes($var);
    $var = htmlentities($var);
    $var = strip_tags($var);
    return $var;
}
?>
</code>```

答:
Use $searchengine to find pages about "php white page", and you'll get:

http://drupal.org/node/158043

http://php.about.com/od/troubleshooting/f/white_page_php.htm

Body:
I've been trying to work a simple form-based temperature converter, but I'm currently getting a white screen, and I cannot see what is wrong with the code. In addition, any ideas / suggestions for best practice are most welcome!

<?php // convert.php

if (isset($_POST['temperature']))
    $temp = sanitize_string($_POST['temperature']);

if (isset($_POST['scale']))
{
    if ($_POST['scale'] == 'fah')
        $conv = 'fah';
        $output = intval((5 / 9) * ($temp - 32));
    elseif ($_POST['scale'] == 'cel')
        $conv = 'cel';
        $output = intval((9 / 5) * ($temp + 32));
    else
        $output = '';
}
?>

    <title>Temperature converter</title>

    <?php
    if (isset($_POST['submitted']) and isset($conv))
    {
        if ($conv == 'fah')
            print("$temp degrees Fahrenheit is $output degrees Celcius");
        elseif ($conv == 'cel')
            print("$temp degrees Celcius is $output degrees Fahrenheit");
    }
    ?>

<form method="post" action="convert.php">
    Temperature <input type="text" name="temperature">
    Celcius <input type="radio" name="scale" value="cel">
    Fahrenheit <input type="radio" name="scale" value="fah">
    <input type="hidden" name="submitted" value="yes">
    <input type="submit">
</form>

<?php
print_r($_POST);

function sanitize_string($var)
{
    $var = stripslashes($var);
    $var = htmlentities($var);
    $var = strip_tags($var);
    return $var;
}
?>


问:
Pygame No module named pygame error in windows 10
I have installed Python 3.5.2 (32-bit) and Python 3.3 pygame -1.9.2a0 on Windows 10. When I run IDLE (python shell) and try to import pygame i get 'No module named pygame' error. I have found sys.path in the shell but pygame is not there. How can I set the variable for pygame OR how I can resolve this problem. </p>

答:
You can try re-installing pygame!
Go to the terminal**(command prompt)** on windows!
Do Win+R and type cmd.
Once in cmd, type: pip install pygame

If it doesn't work still, try and check out the pygame FAQ site!

It is: https://www.pygame.org/wiki/FrequentlyAskedQuestions


问:
How to get webhook response data
I'm still new to webhook. What I need to do here is to do a callback whenever there's a new registration on the registration platform called Bizzabo. This platform has provided Webhook integration by having us putting the Endpoint URL and select which action that will trigger the Webhook. I've also used Request Bin and it displays the data well.

However, how can I echo the JSON body data like how it displayed in Request Bin in my interface URL php?

This is how the Webhook integration looks like on Bizzabo

Data captured from Webhook when tested using Request Bin

Thank you!

答:
If the data receiving in compressed format(gzip) use gzdecode  :

```<code><?php

    if (!function_exists('gzdecode')){
        function gzdecode($data){
            // strip header and footer and inflate
            return gzinflate(substr($data, 10, -8));
        }
    }

    // get compressed (gzip) POST request into a string
    $comprReq = file_get_contents('php://input');

    // get decompressed POST request
    $decomprReq = gzdecode($comprReq);
     // decode to json
    $jsonData = json_decode($decomprReq, true);
    // do your processing on $jsonData
?>
</code>```

Title: How to get webhook response data

Body:
If the data receiving in compressed format(gzip) use gzdecode  :

<?php

    if (!function_exists('gzdecode')){
        function gzdecode($data){
            // strip header and footer and inflate
            return gzinflate(substr($data, 10, -8));
        }
    }

    // get compressed (gzip) POST request into a string
    $comprReq = file_get_contents('php://input');

    // get decompressed POST request
    $decomprReq = gzdecode($comprReq);
     // decode to json
    $jsonData = json_decode($decomprReq, true);
    // do your processing on $jsonData
?>


问:
Writing Standalone server which can serve multiple clients simultaneously using reslet framework
I am trying to do a project (virtual classroom) which contains  a server and multiple clients.
From server I should be able to handle video streaming,authentication,chat etc.. when multiple instances of clients send requests. Please guide me how can I use Restlet framework for this project?</p>

答:
In order to implement a RESTful application using Restlet, you need to begin by implementing several entities for the server side:

REST resources (classes extending the ServerResource class) that will contains processing.

Restlet application that will define how to access your resources.

Restlet server to serve REST HTTP request.

I recommend you to have a look at the hello world sample application from the Restlet website at the address: http://wiki.restlet.org/docs_2.1/13-restlet/21-restlet/318-restlet.html. For the complete application, you can focus on the "Java SE client" at the first time.

In a first time, you can skip authentication since it can be added after on both client and server sides on ClientResource and within Application.

Don't hesitate if you have more questions!
Thierry


问:
javascript: calculate x% of a number
I am wondering how in javascript if i was given a number (say 10000) and then was given a percentage (say 35.8%)

how would I work out how much that is (eg 3580)

答:
It may be a bit pedantic / redundant with its numeric casting, but here's a safe function to calculate percentage of a given number:</p>

```<code>function getPerc(num, percent) {
    return Number(num) - ((Number(percent) / 100) * Number(num));
}

// Usage: getPerc(10000, 25);
</code>```

Title: javascript: calculate x% of a number

Body:
It may be a bit pedantic / redundant with its numeric casting, but here's a safe function to calculate percentage of a given number:

function getPerc(num, percent) {
    return Number(num) - ((Number(percent) / 100) * Number(num));
}

// Usage: getPerc(10000, 25);


问:
How do I access the encrypted credentials in development mode?
I have this code in the controller

def index
  puts Rails.application.credentials.admin_email
  if (current_admin && current_admin.email == Rails.application.credentials.admin_email)
    #do this
  else
    #do that
  end
end
```

<p>The else branch always happens. I believe this is because I am not getting the string from the encrypted file back, as the puts line never prints anything.</p>

<p>When I type <code>Rails.application.credentials.admin_email</code> in the rails console, I get the correct response, <code>"xxx@xxx.com"</code></p>

<p>My <code>config/credentials.yml.enc</code> file looks like the following:</p>

```admin_email: xxx@xxx.com
```

<p>I have also tried changing the <code>config/credentials.yml.enc</code> file to be:</p>

```development:
  admin_email: xxx@xxx.com
```

<p>And have changed the code to be</p>

<pre class="lang-rb prettyprint-override"><code>puts Rails.application.credentials[:admin_email]
if (current_admin && current_admin.email == Rails.application.credentials[:admin_email]
</code>```

Then in the rails console I get the correct xxx@xxx.com using

Rails.application.credentials[:development][:admin_email]
```

, but still nothing shows up from the development code when running rails s.

答:
This is the correct way to get environment specific credentials and that's why you got the credentials by using below code:-

```<code>Rails.application.credentials.admin_email
</code>```

for more please check here
https://github.com/rails/rails/issues/31349

OR
https://github.com/rails/rails/pull/30067

Body:
I have this code in the controller

def index
  puts Rails.application.credentials.admin_email
  if (current_admin && current_admin.email == Rails.application.credentials.admin_email)
    #do this
  else
    #do that
  end
end

The else branch always happens. I believe this is because I am not getting the string from the encrypted file back, as the puts line never prints anything.

When I type Rails.application.credentials.admin_email in the rails console, I get the correct response, "xxx@xxx.com"

My config/credentials.yml.enc file looks like the following:

admin_email: xxx@xxx.com

I have also tried changing the config/credentials.yml.enc file to be:

development:
  admin_email: xxx@xxx.com

And have changed the code to be

puts Rails.application.credentials[:admin_email]
if (current_admin && current_admin.email == Rails.application.credentials[:admin_email]

Then in the rails console I get the correct xxx@xxx.com using

Rails.application.credentials[:development][:admin_email]

, but still nothing shows up from the development code when running rails s.

Body:
This is the correct way to get environment specific credentials and that's why you got the credentials by using below code:-

Rails.application.credentials.admin_email

for more please check here
https://github.com/rails/rails/issues/31349

OR
https://github.com/rails/rails/pull/30067


问:
Trading view pinescript plot my timestamp points
Question #1

Hello! I want to overlay  my datapoints on tradingview chart with pinescript I already have my data (order history) like:

```<code>0.00002609  buy 1524722057851
0.0000261   buy 1524722057851
</code>```

Is there a chance to plot them there?

Question #2

Is there any chance to overlay my data on the embedded chart widget on my website?

Thank you so much for any help!

答:
I think you may have found the solution...

Question #1 Hello! I want to overlay my datapoints on tradingview chart with pinescript I
  already have my data (order history) like:

Answer: No, I do not think there is such a thing

Question #2 Is there any chance to overlay my data on the embedded chart widget on my
  website?

Yes, this is doable. You may need a Pro account, however. As a matter of fact, many crypto exchanges use the TV charting library to display their data. Go through the documentation here: https://www.tradingview.com/HTML5-stock-forex-bitcoin-charting-library/

Body:
Question #1

Hello! I want to overlay  my datapoints on tradingview chart with pinescript I already have my data (order history) like:

0.00002609  buy 1524722057851
0.0000261   buy 1524722057851

Is there a chance to plot them there?

Question #2

Is there any chance to overlay my data on the embedded chart widget on my website?

Thank you so much for any help!


问:
How to create a new column that returns value from another table under certain criteria in Python
I have two table:

Account Balance

It has three columns: Account_ID, Date, Balance_amount

Account Transaction

It has three columns: Account_ID, date, transaction_amount

These two stables have different rows, and not every account has transaction amount. so i want to create a new column in Account Balance table called transaction_amount that returns transaction_amount if that account is shown in account transaction table otherwise return 0.
I tried thisnp.where(data1.account_id.isin(data2._account_id), data2.amount,0)
but it saysoperands could not be broadcast together with shapes (123171,) (668306,) ()
How can i solve this in Python?

答:
I'm assuming you're using pandas.

If you have multiple transaction_amounts per account_id in data2, using merge is probably your best bet:

```<code>data1.merge(data2, on='account_id', how='left')
</code>```

This will return np.nan for account_ids in data1 but not in data2. It will also return both date columns--from data1 and data2. And it will return a row for each transaction_amount per account_id.

If there is only one transaction_amount per account_id, you can convert data2 to a dictionary and have it mapped to data1 like this:

```<code>data2_dict = data2.set_index('account_id).to_dict()['transaction_amount']
data1['transaction_amount'] = data1['account_id'].map(data2_dict)
</code>```

You'll also get np.nan for account_ids in data1 but not data2.

Body:
I'm assuming you're using pandas.

If you have multiple transaction_amounts per account_id in data2, using merge is probably your best bet:

data1.merge(data2, on='account_id', how='left')

This will return np.nan for account_ids in data1 but not in data2. It will also return both date columns--from data1 and data2. And it will return a row for each transaction_amount per account_id.

If there is only one transaction_amount per account_id, you can convert data2 to a dictionary and have it mapped to data1 like this:

data2_dict = data2.set_index('account_id).to_dict()['transaction_amount']
data1['transaction_amount'] = data1['account_id'].map(data2_dict)

You'll also get np.nan for account_ids in data1 but not data2.