问:
How can I access the AST that VSCode creates
I write a VSCode Extension for UI5 JavaScript. The most missing Feature is to have IntelliSense for UI5. Using UI5 typings it will work but not in all.

This works:

```<code>var testvar1 = new sap.m.Button();
</code>```

Now i can use IntelliSense in VSCode in the testvar1.

The Problem e.g.:

```<code>sap.ui.define([
  "sap/ui/core/mvc/Controller"
  ],
  function (Controller) {
    "use strict";
    return Controller.extend("", {

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

In this case there is a Controller variable in the function, this variable is defined with the Namespace before. I search now for a possibility to assign this variable in my Extension with the Namespace. I know this can be done in the AST but i have now idear how to get access to the AST to set:

```<code>Controller = sap.ui.core.mvc.Controller
</code>```

The goal is to have the full IntelliSense now in the variable Controller

I hope it is clear what i want, so far.

答:
If you only need to give a type to Controller, try using JSDoc:

sap.ui.define([
  "sap/ui/core/mvc/Controller"
], function (/** @type {sap.m.Controller} */Controller) {
  // ...
});
```

To answer the original question, you can access/modify the AST with a TypeScript server plugin. This is not trivial so I would try to avoid doing this unless you really need to.

Body:
I write a VSCode Extension for UI5 JavaScript. The most missing Feature is to have IntelliSense for UI5. Using UI5 typings it will work but not in all.

This works:

var testvar1 = new sap.m.Button();

Now i can use IntelliSense in VSCode in the testvar1.

The Problem e.g.:

sap.ui.define([
  "sap/ui/core/mvc/Controller"
  ],
  function (Controller) {
    "use strict";
    return Controller.extend("", {

    });
  });

In this case there is a Controller variable in the function, this variable is defined with the Namespace before. I search now for a possibility to assign this variable in my Extension with the Namespace. I know this can be done in the AST but i have now idear how to get access to the AST to set:

Controller = sap.ui.core.mvc.Controller

The goal is to have the full IntelliSense now in the variable Controller

I hope it is clear what i want, so far.

Body:
If you only need to give a type to Controller, try using JSDoc:

sap.ui.define([
  "sap/ui/core/mvc/Controller"
], function (/** @type {sap.m.Controller} */Controller) {
  // ...
});

To answer the original question, you can access/modify the AST with a TypeScript server plugin. This is not trivial so I would try to avoid doing this unless you really need to.


来源: stackexchange

问:
Changing the stack size and LD_LIBRARY_PATH using a Makefile
I would like to be able to have a rule inside my makefile that a changes the stack size and that appends to LD_LIBRARY_FILE the current directory.
In the shell I can just do:

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$(pwd)

ulimit -s SOME_NUMBER

Is there way to make a rule inside a makefile that is equivalent to running this two commands and will update the environment variables after the makefile is run?

答:
You can link the executables with -z stack-size=VALUE or -rpath, which might have a similar effect.

You could push the command characters to the TTY layer and hope that the shell will execute them, but that is a bit nasty.  The makefile could also compile a program which does the job using ptrace, but that would be very ugly as well.

ContentLicense: CC BY-SA 3.0


问:
Unexpected Error when deploying braintree server on firebase functions
I'm facing a problem with Braintree Server Node SDK on Firebase functions.

But the weird part is that it works well on my local server (using firebase serve locally).

On firebase, the app just return an unexpectedError on the error object without specifying an understandable error message.

I even tried to set the timeout on the gateway object to a high value but the problem still occurs.

Here's the part of my server code that manage the token generation:

```<code>const functions = require("firebase-functions");
const express = require("express");
const braintree = require("braintree");

var gateway = braintree.connect({
  environment: braintree.Environment.Sandbox,
  merchantId: "************",
  publicKey: "************",
  privateKey: "************"
});

app.get("/generate_token", function (req, res) {
  gateway.clientToken.generate({}, function (err, response) {
    if(response)
      res.send({error: false, token: response.clientToken});
    else
      res.send({error: true, errorObj: err, response: response});
  });
});
</code>```

Running this code locally return a correct result:

```<code>{"error": false, "token": "*********"}
</code>```

But deploying on firebase and running it return an error:

```<code>{
  "error": true,
  "errorObj": {
    "name": "unexpectedError",
    "type": "unexpectedError"
  }
}
</code>```

答: For Firebase projects on the free tier (Spark), outgoing socket connections to non-Google controlled endpoints are blocked.  This is to prevent automated abuse.  Your project will need to be upgraded to the Blaze plan to enable outgoing connections.  The cost of this for the purpose of development will probably be negligible, but you should still check the pricing page before you upgrade.</p>

Body:
I'm facing a problem with Braintree Server Node SDK on Firebase functions.

But the weird part is that it works well on my local server (using firebase serve locally).

On firebase, the app just return an unexpectedError on the error object without specifying an understandable error message.

I even tried to set the timeout on the gateway object to a high value but the problem still occurs.

Here's the part of my server code that manage the token generation:

const functions = require("firebase-functions");
const express = require("express");
const braintree = require("braintree");

var gateway = braintree.connect({
  environment: braintree.Environment.Sandbox,
  merchantId: "************",
  publicKey: "************",
  privateKey: "************"
});

app.get("/generate_token", function (req, res) {
  gateway.clientToken.generate({}, function (err, response) {
    if(response)
      res.send({error: false, token: response.clientToken});
    else
      res.send({error: true, errorObj: err, response: response});
  });
});

Running this code locally return a correct result:

{"error": false, "token": "*********"}

But deploying on firebase and running it return an error:

{
  "error": true,
  "errorObj": {
    "name": "unexpectedError",
    "type": "unexpectedError"
  }
}


问:
How do I style numbers?
I am trying to change the styling of numbers.

I want to add some space between every 3 digits.

I will know exactly where the numbers will be located in the html.

When I retrieve the number from the html it needs to be the exact same number as I entered. So I only want to style the number, not modify the number.

I may use javascript and/or css to try an achieve this

//test for success . . . do not remove
if(document.getElementById('number').innerHTML !== "1000"){
  alert('Wrong answer, you changed the number!!!');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="number">1000<p>

<p>The 1000 above should show up like 1 000<p></code>```

答:
Try something like this.

const numberWithSep = (x) => {
  return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, "

");
}

var num = numberWithSep('12345678');

document.getElementById("number").innerHTML = num;

//retrive like this
console.log(document.getElementById("number").innerText);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.sep {
  display: inline-block;
  padding: 10px;
}</code>```

```

If you want the separator as comma (,) just change the div to ,

Title: How do I style numbers?

Body:
I am trying to change the styling of numbers.

I want to add some space between every 3 digits.

I will know exactly where the numbers will be located in the html.

When I retrieve the number from the html it needs to be the exact same number as I entered. So I only want to style the number, not modify the number.

I may use javascript and/or css to try an achieve this

//test for success . . . do not remove
if(document.getElementById('number').innerHTML !== "1000"){
  alert('Wrong answer, you changed the number!!!');
}

1000

The 1000 above should show up like 1 000

Body:
Try something like this.

const numberWithSep = (x) => {
  return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, "<div class='sep'></div>");
}

var num = numberWithSep('12345678');

document.getElementById("number").innerHTML = num;

//retrive like this
console.log(document.getElementById("number").innerText);

.sep {
  display: inline-block;
  padding: 10px;
}

<p id="number"><p>

If you want the separator as comma (,) just change the div to ,


问:
Pandas - Multiple Stocks Groupby for OHLC
I have a .csv file in following format. There is no header, I am just writing for the same of understanding

```<code>time,stockname,price

09:00:00, ABC, 100
09:00:00, XYZ, 500
09:01:00, ABC, 101
09:01:00, XYZ, 499
</code>```

and goes on

I want to do something like groupby resampling(15 minutes) of price such that the end dataframe has all stocks OHLC time based and I can pass stock name and time and get OHLC columns, which I can

答:
Not 100% sure what you're after -- an expected output would be useful.

In any case, pd.Grouper is great for grouping datetime indices by time intervals. In the example below I generate some sample data that looks like your sample data and do some grouping.

```<code>import numpy as np
import pandas as pd

# generate some data
some_dates = pd.date_range(start='2017-01-01', periods=10, freq='5min')
df = pd.DataFrame(index=some_dates)
df.index.name = 'time'
df['stock_name'] = ['ABC', 'XYZ'] * 5
df['price'] = (np.random.rand(10) * 100).round(2)

print(df)

time                   stock_name  price
2017-01-01 00:00:00    ABC         5.26
2017-01-01 00:05:00    XYZ         68.13
2017-01-01 00:10:00    ABC         91.76
2017-01-01 00:15:00    XYZ         21.16
2017-01-01 00:20:00    ABC         75.69
2017-01-01 00:25:00    XYZ         21.16
2017-01-01 00:30:00    ABC         80.25
2017-01-01 00:35:00    XYZ         4.83
2017-01-01 00:40:00    ABC         10.07
2017-01-01 00:45:00    XYZ         20.67

# do some grouping: e.g by 15 minute intervals & by stock_name
df.groupby([pd.Grouper(freq='15min'), df['stock_name']]).max()

time                stock_name price
2017-01-01 00:00:00 ABC        91.76
2017-01-01 00:00:00 XYZ        68.13
2017-01-01 00:15:00 ABC        75.69
2017-01-01 00:15:00 XYZ        21.16
2017-01-01 00:30:00 ABC        80.25
2017-01-01 00:30:00 XYZ        4.83
2017-01-01 00:45:00 XYZ        20.67
</code>```

Body:
I have a .csv file in following format. There is no header, I am just writing for the same of understanding

time,stockname,price

09:00:00, ABC, 100
09:00:00, XYZ, 500
09:01:00, ABC, 101
09:01:00, XYZ, 499

and goes on

I want to do something like groupby resampling(15 minutes) of price such that the end dataframe has all stocks OHLC time based and I can pass stock name and time and get OHLC columns, which I can

Body:
Not 100% sure what you're after -- an expected output would be useful.

In any case, pd.Grouper is great for grouping datetime indices by time intervals. In the example below I generate some sample data that looks like your sample data and do some grouping.

import numpy as np
import pandas as pd

# generate some data
some_dates = pd.date_range(start='2017-01-01', periods=10, freq='5min')
df = pd.DataFrame(index=some_dates)
df.index.name = 'time'
df['stock_name'] = ['ABC', 'XYZ'] * 5
df['price'] = (np.random.rand(10) * 100).round(2)

print(df)

time                   stock_name  price
2017-01-01 00:00:00    ABC         5.26
2017-01-01 00:05:00    XYZ         68.13
2017-01-01 00:10:00    ABC         91.76
2017-01-01 00:15:00    XYZ         21.16
2017-01-01 00:20:00    ABC         75.69
2017-01-01 00:25:00    XYZ         21.16
2017-01-01 00:30:00    ABC         80.25
2017-01-01 00:35:00    XYZ         4.83
2017-01-01 00:40:00    ABC         10.07
2017-01-01 00:45:00    XYZ         20.67

# do some grouping: e.g by 15 minute intervals & by stock_name
df.groupby([pd.Grouper(freq='15min'), df['stock_name']]).max()

time                stock_name price
2017-01-01 00:00:00 ABC        91.76
2017-01-01 00:00:00 XYZ        68.13
2017-01-01 00:15:00 ABC        75.69
2017-01-01 00:15:00 XYZ        21.16
2017-01-01 00:30:00 ABC        80.25
2017-01-01 00:30:00 XYZ        4.83
2017-01-01 00:45:00 XYZ        20.67


问:
Negating ")" inside a regex search pattern
I'm trying to use regex in python to replace strings. I'd like to replace "SERVERS)" with "SERV" in a string.

```<code>example_String = "This is a great SERVERS)"

re.sub("SERVERS)","SERV", example_String)
</code>```

I expected it to be a straight forward swap, but as I read more into the error, it looks like I need to set the regex pattern to read the ")" as a regular character and not a special regex character.

I'm not very familiar with regex , and would appreciate the help!

Edit : I'm importing data from a database (which is user input), there's quite a few similar issues as mentioned in the question.
re.escape() fits the bill perfectly , thanks!

答:
You could go for

```<code>import re

example_String = "This is a great SERVERS)"
new_string = re.sub(r"SERVERS\)","SERV", example_String)
print(new_string)
</code>```

Which yields

```<code>This is a great SERV
</code>```

To be honest, no regular expression is needed, really:

```<code>example_String = "This is a great SERVERS)"
new_string = example_String.replace('SERVERS)', 'SERV')
print(new_string)
</code>```

In the latter, you don't even need to escape anything and it will be faster.

Body:
I'm trying to use regex in python to replace strings. I'd like to replace "SERVERS)" with "SERV" in a string.

example_String = "This is a great SERVERS)"

re.sub("SERVERS)","SERV", example_String)

I expected it to be a straight forward swap, but as I read more into the error, it looks like I need to set the regex pattern to read the ")" as a regular character and not a special regex character.

I'm not very familiar with regex , and would appreciate the help!

Edit : I'm importing data from a database (which is user input), there's quite a few similar issues as mentioned in the question.
re.escape() fits the bill perfectly , thanks!

Body:
You could go for

import re

example_String = "This is a great SERVERS)"
new_string = re.sub(r"SERVERS\)","SERV", example_String)
print(new_string)

Which yields

This is a great SERV

To be honest, no regular expression is needed, really:

example_String = "This is a great SERVERS)"
new_string = example_String.replace('SERVERS)', 'SERV')
print(new_string)

In the latter, you don't even need to escape anything and it will be faster.


问:
Why can't this iOS app access the network?
My (Unity) app complains that the my iPod does not have network connectivity while the device has full wi-fi connectivity (as evidenced by every other app, including Safari).

This isn't just one API point - all of them (Facebook, StoreKit, etc) claim that the network is not available.

This message is periodically sent to the console from my app:

<Error>: Could not successfully update network info during initialization.

which may (I think) be coming from CoreTelephony.

Any idea what is causing this?  I get it in debug and adhoc builds.  I do not have any Restrictions (from Settings) active on the device.

The device is iOS 6 and the base sdk is iOS 5.

答:
I tried set location in simulator and CTTelephonyNetworkInfo initialization in appDelegate.m but not working. I fixed it by define a new class APIAgent.m:</p>

```<code>+ (APIAgent *)manager {
    static APIAgent *_manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [[APIAgent alloc] initWithBaseURL:[NSURL URLWithString:API_URL]];
        _manager.responseSerializer = [AFJSONResponseSerializer serializer];
        NSMutableIndexSet* codes = [NSMutableIndexSet indexSetWithIndexesInRange: NSMakeRange(200, 100)];
        [codes addIndex: 400];
        [codes addIndex: 401];
        [codes addIndex: 404];
        [codes addIndex: 409];
        [codes addIndex: 500];
        _manager.responseSerializer.acceptableStatusCodes = codes;
    });

    return _manager;
}

- (id)initWithBaseURL:(NSURL *)url {
    self = [super initWithBaseURL:url];
    if (!self) {
        return nil;
    }

    [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];

    [self setHeaders];

    return self;
}

- (NSURLSessionDataTask *)GET:(NSString *)URLString parameters:(id)parameters progress:(void (^)(NSProgress *uploadProgress))uploadProgress
                     complete:(void (^)(NSURLSessionDataTask *task, id responseObject, NSError *error))complete {
    return [self GET:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        if (complete) {
            complete(task, responseObject, nil);
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (complete) {
            complete(task, nil, error);
        }
    }];
}

- (NSURLSessionDataTask *)POST:(NSString *)URLString parameters:(id)parameters complete:(void (^)(NSURLSessionDataTask *task, id responseObject, NSError *error))complete {
    return [self POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        if (complete) {
            complete(task, responseObject, nil);
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (complete) {
            complete(task, nil, error);
        }
    }];
}

- (NSURLSessionDataTask *)GET:(NSString *)URLString parameters:(id)parameters progress:(void (^)(NSProgress *uploadProgress))uploadProgress
                      success:(void (^)(NSURLSessionDataTask *task, id responseObject))success failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure {
    self.securityPolicy.allowInvalidCertificates = YES; // self signed certificate
    self.securityPolicy.validatesDomainName = NO;
    return [super GET:URLString parameters:parameters progress:nil success:success failure:failure];
}

- (NSURLSessionDataTask *)POST:(NSString *)URLString
                    parameters:(id)parameters
                      progress:(void (^)(NSProgress *uploadProgress))uploadProgress
                       success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
                       failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure {
    NSMutableDictionary *params = [parameters mutableCopy];

    self.securityPolicy.allowInvalidCertificates = YES; // self signed certificate
    self.securityPolicy.validatesDomainName = NO;
    return [super POST:URLString parameters:params progress:nil success:success failure:failure];
}

- (NSURLSessionDataTask *)POST:(NSString *)URLString
                    parameters:(id)parameters constructingBodyWithBlock:(void (^)(id<AFMultipartFormData>))block
                      progress:(void (^)(NSProgress *uploadProgress))uploadProgress
                       success:(void (^)(NSURLSessionDataTask *, id))success failure:(void (^)(NSURLSessionDataTask *, NSError *))failure {
    NSMutableDictionary *params = [parameters mutableCopy];

    if (parameters == nil) {
        params = [[NSMutableDictionary alloc] init];
    } else {
        if (parameters[@"postId"] != nil) {
            params[@"postId"] = parameters[@"postId"];
        }
    }

    self.securityPolicy.allowInvalidCertificates = YES; // http://stackoverflow.com/questions/27808249/problems-with-ssl-pinning-and-afnetworking-2-5-0-nsurlerrordomain-error-1012
    self.securityPolicy.validatesDomainName = NO;
    return [super POST:URLString parameters:params constructingBodyWithBlock:block progress:nil success:success failure:failure];

}

- (void)setHeaders {
    NSString *time = [NSString stringWithFormat:@"%f", [[[NSDate alloc] init] timeIntervalSince1970]];
    AFHTTPRequestSerializer * serializer = self.requestSerializer;
    [serializer setValue:time forHTTPHeaderField:@"X-API-TIME"];
    [serializer setValue:[UIDevice currentDevice].identifierForVendor.UUIDString forHTTPHeaderField:@"X-UUID"];

    [serializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];

    NSString *preferredLang = [NSLocale preferredLanguages].firstObject;

    [serializer setValue:preferredLang forHTTPHeaderField:@"X-USER-LANGUAGE"];
}
</code>```

Body:
I tried set location in simulator and CTTelephonyNetworkInfo initialization in appDelegate.m but not working. I fixed it by define a new class APIAgent.m:

+ (APIAgent *)manager {
    static APIAgent *_manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [[APIAgent alloc] initWithBaseURL:[NSURL URLWithString:API_URL]];
        _manager.responseSerializer = [AFJSONResponseSerializer serializer];
        NSMutableIndexSet* codes = [NSMutableIndexSet indexSetWithIndexesInRange: NSMakeRange(200, 100)];
        [codes addIndex: 400];
        [codes addIndex: 401];
        [codes addIndex: 404];
        [codes addIndex: 409];
        [codes addIndex: 500];
        _manager.responseSerializer.acceptableStatusCodes = codes;
    });

    return _manager;
}

- (id)initWithBaseURL:(NSURL *)url {
    self = [super initWithBaseURL:url];
    if (!self) {
        return nil;
    }

    [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];

    [self setHeaders];

    return self;
}

- (NSURLSessionDataTask *)GET:(NSString *)URLString parameters:(id)parameters progress:(void (^)(NSProgress *uploadProgress))uploadProgress
                     complete:(void (^)(NSURLSessionDataTask *task, id responseObject, NSError *error))complete {
    return [self GET:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        if (complete) {
            complete(task, responseObject, nil);
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (complete) {
            complete(task, nil, error);
        }
    }];
}

- (NSURLSessionDataTask *)POST:(NSString *)URLString parameters:(id)parameters complete:(void (^)(NSURLSessionDataTask *task, id responseObject, NSError *error))complete {
    return [self POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        if (complete) {
            complete(task, responseObject, nil);
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (complete) {
            complete(task, nil, error);
        }
    }];
}

- (NSURLSessionDataTask *)GET:(NSString *)URLString parameters:(id)parameters progress:(void (^)(NSProgress *uploadProgress))uploadProgress
                      success:(void (^)(NSURLSessionDataTask *task, id responseObject))success failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure {
    self.securityPolicy.allowInvalidCertificates = YES; // self signed certificate
    self.securityPolicy.validatesDomainName = NO;
    return [super GET:URLString parameters:parameters progress:nil success:success failure:failure];
}

- (NSURLSessionDataTask *)POST:(NSString *)URLString
                    parameters:(id)parameters
                      progress:(void (^)(NSProgress *uploadProgress))uploadProgress
                       success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
                       failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure {
    NSMutableDictionary *params = [parameters mutableCopy];

    self.securityPolicy.allowInvalidCertificates = YES; // self signed certificate
    self.securityPolicy.validatesDomainName = NO;
    return [super POST:URLString parameters:params progress:nil success:success failure:failure];
}

- (NSURLSessionDataTask *)POST:(NSString *)URLString
                    parameters:(id)parameters constructingBodyWithBlock:(void (^)(id<AFMultipartFormData>))block
                      progress:(void (^)(NSProgress *uploadProgress))uploadProgress
                       success:(void (^)(NSURLSessionDataTask *, id))success failure:(void (^)(NSURLSessionDataTask *, NSError *))failure {
    NSMutableDictionary *params = [parameters mutableCopy];

    if (parameters == nil) {
        params = [[NSMutableDictionary alloc] init];
    } else {
        if (parameters[@"postId"] != nil) {
            params[@"postId"] = parameters[@"postId"];
        }
    }

    self.securityPolicy.allowInvalidCertificates = YES; // http://stackoverflow.com/questions/27808249/problems-with-ssl-pinning-and-afnetworking-2-5-0-nsurlerrordomain-error-1012
    self.securityPolicy.validatesDomainName = NO;
    return [super POST:URLString parameters:params constructingBodyWithBlock:block progress:nil success:success failure:failure];

}

- (void)setHeaders {
    NSString *time = [NSString stringWithFormat:@"%f", [[[NSDate alloc] init] timeIntervalSince1970]];
    AFHTTPRequestSerializer * serializer = self.requestSerializer;
    [serializer setValue:time forHTTPHeaderField:@"X-API-TIME"];
    [serializer setValue:[UIDevice currentDevice].identifierForVendor.UUIDString forHTTPHeaderField:@"X-UUID"];

    [serializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];

    NSString *preferredLang = [NSLocale preferredLanguages].firstObject;

    [serializer setValue:preferredLang forHTTPHeaderField:@"X-USER-LANGUAGE"];
}


问:
numpy set_printoptions precision ignored in list of tuples
(Windows 7,Python 3.4.5 |Anaconda 2.2.0 (64-bit)| (default, Jul  5 2016, 14:53:07) [MSC v.1600 64 bit (AMD64)])

I was trying to neatly print some data by using np.set_printoptions(precision= and it seems to be ignored. Why?

```<code>import numpy as np
np.set_printoptions(precision=4)

a=[[1,15.02],
[2,14.38],
[3,14.60]]

b=np.array(a)
print(b)
at=b.T
l=list(zip(at[0],at[1]))
print(l)
</code>```

Output:

```<code>[[  1.    15.02]
 [  2.    14.38]
 [  3.    14.6 ]]
[(1.0, 15.02), (2.0, 14.380000000000001), (3.0, 14.6)]
</code>```

Body:
(Windows 7,Python 3.4.5 |Anaconda 2.2.0 (64-bit)| (default, Jul  5 2016, 14:53:07) [MSC v.1600 64 bit (AMD64)])

I was trying to neatly print some data by using np.set_printoptions(precision= and it seems to be ignored. Why?

import numpy as np
np.set_printoptions(precision=4)

a=[[1,15.02],
[2,14.38],
[3,14.60]]

b=np.array(a)
print(b)
at=b.T
l=list(zip(at[0],at[1]))
print(l)

Output:

[[  1.    15.02]
 [  2.    14.38]
 [  3.    14.6 ]]
[(1.0, 15.02), (2.0, 14.380000000000001), (3.0, 14.6)]

Body:
A problem of float :

In [118]:ref=decimal.Decimal('14.380000000000000000000000000000000000000000000000')

In [119]: decimal.Decimal(14.38)
Out[119]: Decimal('14.3800000000000007815970093361102044582366943359375')

In [120]: decimal.Decimal(14.38)-ref
Out[120]: Decimal('7.815970093361102044582366943E-16')

In [121]: decimal.Decimal(14.38-2**-50)-ref
Out[121]: Decimal('-9.947598300641402602195739746E-16')

This show that 14.380000000000001 is the best float64 approximation of 14.38 .

to workaround this fact, you can downgrade in np.float32 :

In [140]:tuple(zip(*np.array(a).T.astype(np.float32)))
Out[140]: ((1.0, 15.02), (2.0, 14.38), (3.0, 14.6))


问:
javax.xml.soap.SOAPException:unable to find namespace for prefix: wsse HEADER Security
I have the following error when I tried to code the header using security:

javax.xml.soap.SOAPException: unable to find namespace for prefix: wsse
      at weblogic.xml.saaj.SOAPElementImpl.addChildElement(SOAPElementImpl.java:357)
      at pr.com.prt.eppaSapInt.ws.SecurityHeader.doWithMessage(SecurityHeader.java:48)

This is my code:

```<code>public class SecurityHeader implements WebServiceMessageCallback{

@Override
public void doWithMessage(WebServiceMessage wsMessage) throws IOException, TransformerException {
    SOAPMessage soapMessage = ((SaajSoapMessage)wsMessage).getSaajMessage();

    SOAPHeader header;
    SOAPHeaderElement security;
    SOAPHeaderElement usertoken;
    SOAPElement username;
    SOAPElement password;

    try {
        header = soapMessage.getSOAPHeader();
        //header.addNamespaceDeclaration("wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
        //header.addNamespaceDeclaration("wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
        security = header.addHeaderElement(new QName("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Security", "wsse"));
        usertoken = header.addHeaderElement(new QName("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", "UsernameToken", "wsu"));

        username = usertoken.addChildElement("Username", "wsse");
        password = usertoken.addChildElement("Password", "wsse");
        password.setAttribute("Type","http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText");

        username.setTextContent("eppa2SAP_app");
        password.setTextContent("eppa2SAP_app123");

        security.addChildElement(username);
        security.addChildElement(password);
        security.addChildElement(usertoken);

        JAXBContext context = JAXBContext.newInstance();

        Marshaller marshaller = context.createMarshaller();
        marshaller.marshal(null, ((SoapHeader) soapMessage).getResult());

    } catch (JAXBException e) {
        throw new IOException("error while marshalling authentication JAXB.");
    } catch (MarshallingException e) {
        throw new IOException("error while marshalling authentication exception.");
    }  catch (SOAPException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}
</code>```

答: I think the issue is that QNames don't play nice. Try using header.addChildElement(localName, prefix, uri); for Security and UsernameToken instead.

Body:
I have the following error when I tried to code the header using security:

javax.xml.soap.SOAPException: unable to find namespace for prefix: wsse
      at weblogic.xml.saaj.SOAPElementImpl.addChildElement(SOAPElementImpl.java:357)
      at pr.com.prt.eppaSapInt.ws.SecurityHeader.doWithMessage(SecurityHeader.java:48)

This is my code:

public class SecurityHeader implements WebServiceMessageCallback{

@Override
public void doWithMessage(WebServiceMessage wsMessage) throws IOException, TransformerException {
    SOAPMessage soapMessage = ((SaajSoapMessage)wsMessage).getSaajMessage();

    SOAPHeader header;
    SOAPHeaderElement security;
    SOAPHeaderElement usertoken;
    SOAPElement username;
    SOAPElement password;

    try {
        header = soapMessage.getSOAPHeader();
        //header.addNamespaceDeclaration("wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
        //header.addNamespaceDeclaration("wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
        security = header.addHeaderElement(new QName("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Security", "wsse"));
        usertoken = header.addHeaderElement(new QName("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", "UsernameToken", "wsu"));

        username = usertoken.addChildElement("Username", "wsse");
        password = usertoken.addChildElement("Password", "wsse");
        password.setAttribute("Type","http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText");

        username.setTextContent("eppa2SAP_app");
        password.setTextContent("eppa2SAP_app123");

        security.addChildElement(username);
        security.addChildElement(password);
        security.addChildElement(usertoken);

        JAXBContext context = JAXBContext.newInstance();

        Marshaller marshaller = context.createMarshaller();
        marshaller.marshal(null, ((SoapHeader) soapMessage).getResult());

    } catch (JAXBException e) {
        throw new IOException("error while marshalling authentication JAXB.");
    } catch (MarshallingException e) {
        throw new IOException("error while marshalling authentication exception.");
    }  catch (SOAPException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}


问:
MVC Core Root Path Is Not Prefixed with wwwroot
I have deployed an MVC Core 2.0 application and when I load any of my pages I can see that they javascript and css files are not pointing to the correct address.

For example, /lib/bootstrap-table... should be /wwwroot/lib/bootstrap-table....

The application works perfectly when debugging locally via Visual Studio, however.

I have the following configuration in my Startup.cs:

```<code>if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
    app.UseBrowserLink();
    app.UseDatabaseErrorPage();
}
else
{
    app.UseExceptionHandler("/Home/Error");
}

app.UseStaticFiles();

app.UseAuthentication();

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});
</code>```

Yet, the file paths are still not prefixed with /wwwroot.  Why doesn't MVC find the correct file path?

The Layout.cshtml file has the following; however, if I prefix the files with /wwwroot then the files are no longer found when debugging:

```<code><environment include="Development">
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
    <link rel="stylesheet" href="~/lib/fullcalendar/dist/fullcalendar.css" />
    <link rel="stylesheet" href="~/lib/fullcalendar/dist/fullcalendar.print.css" media="print" />
    <link rel="stylesheet" href="~/css/site.css" />
    <link rel="stylesheet" href="~/lib/bootstrap-table/src/bootstrap-table.css" />
</environment>
<environment exclude="Development">
    <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css"
          asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
          asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />
    <link rel="stylesheet" href="~/lib/fullcalendar/dist/fullcalendar.min.css" />
    <link rel="stylesheet" href="~/lib/fullcalendar/dist/fullcalendar.print.min.css" />
    <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
    <link rel="stylesheet" href="~/lib/bootstrap-table/src/bootstrap-table.min.css" />
</environment>
</code>```

I can see in my Program.cs file that ContentRoot is set to CurrentDirectory, but it works when debugging just not when deployed to a server.

```<code>public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .Build();
}
</code>```

答:
WebHost.CreateDefaultBuilder() already sets up the default configurations, i.e., UseKestrel(), UseContentRoot() etc. You don't need to call them again.

Instead you only need this

```<code>    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
</code>```

And app.UseStaticFiles() makes the files in wwwroot folder (by default) servable. That is, a request like http://<your_domain>/<your_app>/css/site.css will try to get the site.css under the structure wwwroot/css/.

You don't need to manually append wwwroot in the static file urls.

Body:
I have deployed an MVC Core 2.0 application and when I load any of my pages I can see that they javascript and css files are not pointing to the correct address.

For example, /lib/bootstrap-table... should be /wwwroot/lib/bootstrap-table....

The application works perfectly when debugging locally via Visual Studio, however.

I have the following configuration in my Startup.cs:

if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
    app.UseBrowserLink();
    app.UseDatabaseErrorPage();
}
else
{
    app.UseExceptionHandler("/Home/Error");
}

app.UseStaticFiles();

app.UseAuthentication();

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});

Yet, the file paths are still not prefixed with /wwwroot.  Why doesn't MVC find the correct file path?

The Layout.cshtml file has the following; however, if I prefix the files with /wwwroot then the files are no longer found when debugging:

<environment include="Development">
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
    <link rel="stylesheet" href="~/lib/fullcalendar/dist/fullcalendar.css" />
    <link rel="stylesheet" href="~/lib/fullcalendar/dist/fullcalendar.print.css" media="print" />
    <link rel="stylesheet" href="~/css/site.css" />
    <link rel="stylesheet" href="~/lib/bootstrap-table/src/bootstrap-table.css" />
</environment>
<environment exclude="Development">
    <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css"
          asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
          asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />
    <link rel="stylesheet" href="~/lib/fullcalendar/dist/fullcalendar.min.css" />
    <link rel="stylesheet" href="~/lib/fullcalendar/dist/fullcalendar.print.min.css" />
    <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
    <link rel="stylesheet" href="~/lib/bootstrap-table/src/bootstrap-table.min.css" />
</environment>

I can see in my Program.cs file that ContentRoot is set to CurrentDirectory, but it works when debugging just not when deployed to a server.

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .Build();
}

Body:
WebHost.CreateDefaultBuilder() already sets up the default configurations, i.e., UseKestrel(), UseContentRoot() etc. You don't need to call them again.

Instead you only need this

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();

And app.UseStaticFiles() makes the files in wwwroot folder (by default) servable. That is, a request like http://<your_domain>/<your_app>/css/site.css will try to get the site.css under the structure wwwroot/css/.

You don't need to manually append wwwroot in the static file urls.


问:
How to prevent a user from entering negative values in Html input
I am using the following html input element for collecting the product quantity in Html page but the user can still go ahead and manually enter negative value. For example: I selected the the textbox and entered -100 and input field took it without complaining about it.

How can I prevent user from entering 0 and non-negative values in Html input element?

```<code><input type="number" id="qty" value="" size="3" min="1" />
</code>```

答:
try this : </p>

```<code><input type="number" min="0">
</code>```

Body:
I am using the following html input element for collecting the product quantity in Html page but the user can still go ahead and manually enter negative value. For example: I selected the the textbox and entered -100 and input field took it without complaining about it.

How can I prevent user from entering 0 and non-negative values in Html input element?

<input type="number" id="qty" value="" size="3" min="1" />

Body:
try this :

<input type="number" min="0">


答:
```<code>In [34]: a
Out[34]: [[1, 15.02], [2, 14.38], [3, 14.6]]
In [35]: b=np.array(a, dtype=float).T
In [36]: b
Out[36]:
array([[  1.  ,   2.  ,   3.  ],
       [ 15.02,  14.38,  14.6 ]])
In [37]: list(zip(*b))
Out[37]: [(1.0, 15.02), (2.0, 14.380000000000001), (3.0, 14.6)]
</code>```

However if I first past b through tolist:

```<code>In [38]: list(zip(*b.tolist()))
Out[38]: [(1.0, 15.02), (2.0, 14.38), (3.0, 14.6)]
</code>```

In the first case the elements of the tuple still have np.float64 wrapper, while tolist extracts them all to native Python numbers:

```<code>In [39]: type(list(zip(*b))[1][1])
Out[39]: numpy.float64
In [40]: type(list(zip(*b.tolist()))[1][1])
Out[40]: float
</code>```

item is another way of extracting the native number:

```<code>In [41]: list(zip(*b))[1][1]
Out[41]: 14.380000000000001
In [42]: list(zip(*b))[1][1].item()
Out[42]: 14.38
</code>```

I can't say why the setprintoptions doesn't apply in the case of np.float64, but does with np.array.

As a general rule, it is better to use tolist() if you want to convert an array, and all its values, into a native Python list.  Operations like list and zip aren't enough.  They iterate on the first dimension of the array, but don't recursively convert the elements:

Partial conversion(s):

```<code>In [43]: list(b)
Out[43]: [array([ 1.,  2.,  3.]), array([ 15.02,  14.38,  14.6 ])]
In [44]: list(b[1])
Out[44]: [15.02, 14.380000000000001, 14.6]
</code>```

Full conversion:

```<code>In [45]: b.tolist()
Out[45]: [[1.0, 2.0, 3.0], [15.02, 14.38, 14.6]]
</code>```

Apparently the formatter for float64 shows all precision, regardless of the set_printoptions values:

```<code>In [58]: 14.380000000000001
Out[58]: 14.38
In [59]: np.array(14.380000000000001)
Out[59]: array(14.38)
In [60]: np.float64(14.380000000000001)
Out[60]: 14.380000000000001
In [61]: np.float32(14.380000000000001)
Out[61]: 14.38
</code>```

An np.float64(...) object is, in many ways like a single item array, but different in subtle ways.  Usually though we don't create such an object directly.

Title: numpy set_printoptions precision ignored in list of tuples

Body:
In [34]: a
Out[34]: [[1, 15.02], [2, 14.38], [3, 14.6]]
In [35]: b=np.array(a, dtype=float).T
In [36]: b
Out[36]:
array([[  1.  ,   2.  ,   3.  ],
       [ 15.02,  14.38,  14.6 ]])
In [37]: list(zip(*b))
Out[37]: [(1.0, 15.02), (2.0, 14.380000000000001), (3.0, 14.6)]

However if I first past b through tolist:

In [38]: list(zip(*b.tolist()))
Out[38]: [(1.0, 15.02), (2.0, 14.38), (3.0, 14.6)]

In the first case the elements of the tuple still have np.float64 wrapper, while tolist extracts them all to native Python numbers:

In [39]: type(list(zip(*b))[1][1])
Out[39]: numpy.float64
In [40]: type(list(zip(*b.tolist()))[1][1])
Out[40]: float

item is another way of extracting the native number:

In [41]: list(zip(*b))[1][1]
Out[41]: 14.380000000000001
In [42]: list(zip(*b))[1][1].item()
Out[42]: 14.38

I can't say why the setprintoptions doesn't apply in the case of np.float64, but does with np.array.

As a general rule, it is better to use tolist() if you want to convert an array, and all its values, into a native Python list.  Operations like list and zip aren't enough.  They iterate on the first dimension of the array, but don't recursively convert the elements:

Partial conversion(s):

In [43]: list(b)
Out[43]: [array([ 1.,  2.,  3.]), array([ 15.02,  14.38,  14.6 ])]
In [44]: list(b[1])
Out[44]: [15.02, 14.380000000000001, 14.6]

Full conversion:

In [45]: b.tolist()
Out[45]: [[1.0, 2.0, 3.0], [15.02, 14.38, 14.6]]

Apparently the formatter for float64 shows all precision, regardless of the set_printoptions values:

In [58]: 14.380000000000001
Out[58]: 14.38
In [59]: np.array(14.380000000000001)
Out[59]: array(14.38)
In [60]: np.float64(14.380000000000001)
Out[60]: 14.380000000000001
In [61]: np.float32(14.380000000000001)
Out[61]: 14.38

An np.float64(...) object is, in many ways like a single item array, but different in subtle ways.  Usually though we don't create such an object directly.


问:
comparing sum of 2 column values in one table with another column value in second table sql server
I have two tables...

table1 ( id, item, price ) values:

```<code>id | item | price
-------------
10 | book | 20
20 | copy | 30
30 | pen  | 10
</code>```

....table2 ( id, item, price) values:

```<code>id | item | price
-------------
10 | book | 20
10 | book | 30
</code>```

now i if do not have a record with id-10,item-book and price-(20+30) in table 1 then i want to insert that row with sum(20+30) in  a new table ...

答:
Try the following

```<code>SELECT T2.id,T2.item,T2.Price as Table2_Price,T1.Price as Table1_Price FROM (
SELECT id,Item,Sum(Price) as Price
FROM Table2
Group BY id,Item ) AS T2 LEFT JOIN Table1 AS T1
ON T1.Item = T2.Item and T1.ID = T2.ID
</code>```

After reading your comments when sum of these two not equals the one in another table it should return the sum from table 2 , you are asking for the following logic

```<code>SELECT T2.id,T2.Item, CASE WHEN T1.Price IS NULL THEN T2.Price
                           WHEN T2.Price <> T1.Price THEN T2.Price
                           ELSE T1.Price END as Price FROM (
SELECT id,Item,Sum(Price) as Price
FROM Table2
Group BY id,Item ) AS T2 LEFT JOIN Table1 AS T1
ON T1.Item = T2.Item and T1.ID = T2.ID
</code>```

But this logic isn't useful, because if Sum(Table2_price) <> Table1_Price you want to select Sum(Table2_price) else when Sum(Table2_price) = Table1_Price you want Table1_Price !! So you want to always choose Sum(Table2_Price)

Body:
I have two tables...

table1 ( id, item, price ) values:

id | item | price
-------------
10 | book | 20
20 | copy | 30
30 | pen  | 10

....table2 ( id, item, price) values:

id | item | price
-------------
10 | book | 20
10 | book | 30

now i if do not have a record with id-10,item-book and price-(20+30) in table 1 then i want to insert that row with sum(20+30) in  a new table ...

Body:
Try the following

SELECT T2.id,T2.item,T2.Price as Table2_Price,T1.Price as Table1_Price FROM (
SELECT id,Item,Sum(Price) as Price
FROM Table2
Group BY id,Item ) AS T2 LEFT JOIN Table1 AS T1
ON T1.Item = T2.Item and T1.ID = T2.ID

After reading your comments when sum of these two not equals the one in another table it should return the sum from table 2 , you are asking for the following logic

SELECT T2.id,T2.Item, CASE WHEN T1.Price IS NULL THEN T2.Price
                           WHEN T2.Price <> T1.Price THEN T2.Price
                           ELSE T1.Price END as Price FROM (
SELECT id,Item,Sum(Price) as Price
FROM Table2
Group BY id,Item ) AS T2 LEFT JOIN Table1 AS T1
ON T1.Item = T2.Item and T1.ID = T2.ID

But this logic isn't useful, because if Sum(Table2_price) <> Table1_Price you want to select Sum(Table2_price) else when Sum(Table2_price) = Table1_Price you want Table1_Price !! So you want to always choose Sum(Table2_Price)


问:
Bash: how to automatically insert spacing characters according to indent?
I've got lots of debug statements making for unreadable stacktraces (not my call) like this:

```<code> 00:53:59,906  - j.util.indexing.FileBasedIndex - START INDEX SHUTDOWN
 00:53:09,192  - .impl.stores.XmlElementStorage - Document was not loaded for $APP_CONFIG$/macros.xml
 00:53:09,195  - s.impl.stores.FileBasedStorage - Document was not loaded for $APP_CONFIG$/quicklists.xml file is null
 00:53:09,195  - .impl.stores.XmlElementStorage - Document was not loaded for $APP_CONFIG$/quicklists.xml
 00:53:09,696  - ij.openapi.wm.impl.IdeRootPane - App initialization took 5584 ms
 00:53:11,677  -                  TestNG Runner - Create TestNG Template Configuration
 00:53:13,628  - indexing.UnindexedFilesUpdater - Unindexed files update started
 00:53:15,370  - indexing.UnindexedFilesUpdater - Unindexed files update done
 00:53:20,873  - tor.impl.FileEditorManagerImpl - Project opening took 10569 ms
 00:53:31,862  - s.impl.stores.FileBasedStorage - Document was not loaded for $APP_CONFIG$/intentionSettings.xml file is null
 00:53:31,862  - .impl.stores.XmlElementStorage - Document was not loaded for $APP_CONFIG$/intentionSettings.xml
 00:54:00,723  - j.util.indexing.FileBasedIndex - END INDEX SHUTDOWN
</code>```

And I want them to look like this:

```<code> 00:53:59,906  - j.util.indexing.FileBasedIndex - START INDEX SHUTDOWN
 00:53:09,192  - .impl.stores.XmlElementStorage -   Document was not loaded for $APP_CONFIG$/macros.xml
 00:53:09,195  - s.impl.stores.FileBasedStorage -   Document was not loaded for $APP_CONFIG$/quicklists.xml file is null
 00:53:09,195  - .impl.stores.XmlElementStorage -   Document was not loaded for $APP_CONFIG$/quicklists.xml
 00:53:09,696  - ij.openapi.wm.impl.IdeRootPane -     App initialization took 5584 ms
 00:53:11,677  -                  TestNG Runner -       Create TestNG Template Configuration
 00:53:13,628  - indexing.UnindexedFilesUpdater -        Unindexed files update started
 00:53:15,370  - indexing.UnindexedFilesUpdater -        Unindexed files update done
 00:53:20,873  - tor.impl.FileEditorManagerImpl -     Project opening took 10569 ms
 00:53:31,862  - s.impl.stores.FileBasedStorage -    Document was not loaded for $APP_CONFIG$/intentionSettings.xml file is null
 00:53:31,862  - .impl.stores.XmlElementStorage -   Document was not loaded for $APP_CONFIG$/intentionSettings.xml
 00:54:00,723  - j.util.indexing.FileBasedIndex - END INDEX SHUTDOWN
</code>```

Now my code is formatted automatically so I know exactly how many characters there are in my source code for indent level.

What I want to do is replace automatically every line in my code looking like:

```<code>log.debug("some silly debug line");
</code>```

with:

```<code>log.debug(" " + "some silly debug line");
</code>```

or:

```<code>log.debug("  " + "some silly debug line");
</code>```

depending on the number of indents before the log.debug line.

I'm pretty sure some Bash/shell magic can do this automatically.

Basically I'd start with a:

```<code>find . -iname "*java" -exec ...
</code>```

then I'd like to insert " " on lines starting with log.debug depending on the indent level of these lines.

How would I go about it?

EDIT

Damn: it needs to be able to run several times, without re-shifting the lines already containing log.debug(" " +).  It gets more complicated but now thanks to the good answer I've got something to start from :)

Note: before yelling and shooting as to why this ain't a good idea, read my comment(s)

答:
And you were right!1

```<code>sed -i .tmp -e 's/^\( *\)log.debug(/\1log.debug("\1" + /' prog.java
</code>```

Integrated with find(1) it becomes:

```<code>find . -name \*.java -a -exec sed -i .tmp -e 's/^\( *\)log.debug(/\1log.debug("\1" + /' {} \;
</code>```

This finds everything named *.java and runs an in-place sed (stream editor) program, matches the lines to change with a \( capture group \) around the space string, and then it tacks the capture group back in where it found it as well as in front of your string.

The -a, -exec, \; and {} are just the arcane find syntax for "and", "execute program", "end the command being executed" and "substitute the found filename here".

1. When you said: "I'm pretty sure some Bash/shell magic can do this automatically."

ContentLicense: CC BY-SA 2.5

Body:
I've got lots of debug statements making for unreadable stacktraces (not my call) like this:

 00:53:59,906  - j.util.indexing.FileBasedIndex - START INDEX SHUTDOWN
 00:53:09,192  - .impl.stores.XmlElementStorage - Document was not loaded for $APP_CONFIG$/macros.xml
 00:53:09,195  - s.impl.stores.FileBasedStorage - Document was not loaded for $APP_CONFIG$/quicklists.xml file is null
 00:53:09,195  - .impl.stores.XmlElementStorage - Document was not loaded for $APP_CONFIG$/quicklists.xml
 00:53:09,696  - ij.openapi.wm.impl.IdeRootPane - App initialization took 5584 ms
 00:53:11,677  -                  TestNG Runner - Create TestNG Template Configuration
 00:53:13,628  - indexing.UnindexedFilesUpdater - Unindexed files update started
 00:53:15,370  - indexing.UnindexedFilesUpdater - Unindexed files update done
 00:53:20,873  - tor.impl.FileEditorManagerImpl - Project opening took 10569 ms
 00:53:31,862  - s.impl.stores.FileBasedStorage - Document was not loaded for $APP_CONFIG$/intentionSettings.xml file is null
 00:53:31,862  - .impl.stores.XmlElementStorage - Document was not loaded for $APP_CONFIG$/intentionSettings.xml
 00:54:00,723  - j.util.indexing.FileBasedIndex - END INDEX SHUTDOWN

And I want them to look like this:

 00:53:59,906  - j.util.indexing.FileBasedIndex - START INDEX SHUTDOWN
 00:53:09,192  - .impl.stores.XmlElementStorage -   Document was not loaded for $APP_CONFIG$/macros.xml
 00:53:09,195  - s.impl.stores.FileBasedStorage -   Document was not loaded for $APP_CONFIG$/quicklists.xml file is null
 00:53:09,195  - .impl.stores.XmlElementStorage -   Document was not loaded for $APP_CONFIG$/quicklists.xml
 00:53:09,696  - ij.openapi.wm.impl.IdeRootPane -     App initialization took 5584 ms
 00:53:11,677  -                  TestNG Runner -       Create TestNG Template Configuration
 00:53:13,628  - indexing.UnindexedFilesUpdater -        Unindexed files update started
 00:53:15,370  - indexing.UnindexedFilesUpdater -        Unindexed files update done
 00:53:20,873  - tor.impl.FileEditorManagerImpl -     Project opening took 10569 ms
 00:53:31,862  - s.impl.stores.FileBasedStorage -    Document was not loaded for $APP_CONFIG$/intentionSettings.xml file is null
 00:53:31,862  - .impl.stores.XmlElementStorage -   Document was not loaded for $APP_CONFIG$/intentionSettings.xml
 00:54:00,723  - j.util.indexing.FileBasedIndex - END INDEX SHUTDOWN

Now my code is formatted automatically so I know exactly how many characters there are in my source code for indent level.

What I want to do is replace automatically every line in my code looking like:

log.debug("some silly debug line");

with:

log.debug(" " + "some silly debug line");

or:

log.debug("  " + "some silly debug line");

depending on the number of indents before the log.debug line.

I'm pretty sure some Bash/shell magic can do this automatically.

Basically I'd start with a:

find . -iname "*java" -exec ...

then I'd like to insert " " on lines starting with log.debug depending on the indent level of these lines.

How would I go about it?

EDIT

Damn: it needs to be able to run several times, without re-shifting the lines already containing log.debug(" " +).  It gets more complicated but now thanks to the good answer I've got something to start from :)

Note: before yelling and shooting as to why this ain't a good idea, read my comment(s)

Body:
And you were right!1

sed -i .tmp -e 's/^\( *\)log.debug(/\1log.debug("\1" + /' prog.java

Integrated with find(1) it becomes:

find . -name \*.java -a -exec sed -i .tmp -e 's/^\( *\)log.debug(/\1log.debug("\1" + /' {} \;

This finds everything named *.java and runs an in-place sed (stream editor) program, matches the lines to change with a \( capture group \) around the space string, and then it tacks the capture group back in where it found it as well as in front of your string.

The -a, -exec, \; and {} are just the arcane find syntax for "and", "execute program", "end the command being executed" and "substitute the found filename here".

1. When you said: "I'm pretty sure some Bash/shell magic can do this automatically."


问:
Android, how to close ListView when "Back" button pressed to close searchView
I have an actionBar with a searchView icon. I click on searchView icon and softInputMode keyboard appears and my ListView appears for searching. However, when you go to close searchView, the searchView closes but I can't get the ListView to also close when searchView closes.

Here's my code for ListView in activity_maps.xml

```<code><ListView
    android:id="@+id/list"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:background="#ffffff"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.0"
    tools:layout_editor_absoluteX="0dp"
    />
</code>```

MapsActivity.java

```<code>    ArrayAdapter<String> adapter;

    @Override
   public boolean onCreateOptionsMenu(final Menu menu){

    final ListView lv = (ListView) findViewById(R.id.list);

    ArrayList<String> arrayList = new ArrayList<>();

      arrayList.addAll(Arrays.asList(getResources().getStringArray(R.array.array_states_trial)));

    adapter = new ArrayAdapter<>(MapsActivity.this, android.R.layout.simple_list_item_1, arrayList);

    lv.setAdapter(adapter);

    lv.setVisibility(View.INVISIBLE);
</code>```

So initially when MapsActivity.java loads I don't want the ListView to show right away.

```<code>    searchView.setOnSearchClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            lv.setVisibility(View.VISIBLE);

        }
    });
</code>```

I want the listView to show when searchView is clicked open and keyboard pops up.

```<code>    searchView.setOnCloseListener(new SearchView.OnCloseListener() {
        @Override
        public boolean onClose() {

               lv.setVisibility(View.INVISIBLE);

            return false;
        }
    });
</code>```

In the above code, I want the listView to close, disappear, be invisible, but it doesn't.

btw I'm referring to the "Back" button in the actionBar that comes with closing searchView.

When searchView and keyboard closes, I want the ListView to also close but for some reason the code isn't recognized and listView never closes.

How do I close ListView?

答:
According to Android reference, try to return true if you want to override the default behavior of clearing the text field and dismissing it, false otherwise.

See this link:
https://developer.android.com/reference/android/widget/SearchView.OnCloseListener.html

```<code>  searchView.setOnCloseListener(new SearchView.OnCloseListener() {
    @Override
    public boolean onClose() {

           lv.setVisibility(View.INVISIBLE);

        return true;//Should work.
    }
});
</code>```

Body:
I have an actionBar with a searchView icon. I click on searchView icon and softInputMode keyboard appears and my ListView appears for searching. However, when you go to close searchView, the searchView closes but I can't get the ListView to also close when searchView closes.

Here's my code for ListView in activity_maps.xml

<ListView
    android:id="@+id/list"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:background="#ffffff"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.0"
    tools:layout_editor_absoluteX="0dp"
    />

MapsActivity.java

    ArrayAdapter<String> adapter;

    @Override
   public boolean onCreateOptionsMenu(final Menu menu){

    final ListView lv = (ListView) findViewById(R.id.list);

    ArrayList<String> arrayList = new ArrayList<>();

      arrayList.addAll(Arrays.asList(getResources().getStringArray(R.array.array_states_trial)));

    adapter = new ArrayAdapter<>(MapsActivity.this, android.R.layout.simple_list_item_1, arrayList);

    lv.setAdapter(adapter);

    lv.setVisibility(View.INVISIBLE);

So initially when MapsActivity.java loads I don't want the ListView to show right away.

    searchView.setOnSearchClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            lv.setVisibility(View.VISIBLE);

        }
    });

I want the listView to show when searchView is clicked open and keyboard pops up.

    searchView.setOnCloseListener(new SearchView.OnCloseListener() {
        @Override
        public boolean onClose() {

               lv.setVisibility(View.INVISIBLE);

            return false;
        }
    });

In the above code, I want the listView to close, disappear, be invisible, but it doesn't.

btw I'm referring to the "Back" button in the actionBar that comes with closing searchView.

When searchView and keyboard closes, I want the ListView to also close but for some reason the code isn't recognized and listView never closes.

How do I close ListView?

Body:
According to Android reference, try to return true if you want to override the default behavior of clearing the text field and dismissing it, false otherwise.

See this link:
https://developer.android.com/reference/android/widget/SearchView.OnCloseListener.html

  searchView.setOnCloseListener(new SearchView.OnCloseListener() {
    @Override
    public boolean onClose() {

           lv.setVisibility(View.INVISIBLE);

        return true;//Should work.
    }
});


问:
How to breach Angularjs using $watch?
In angular js security documentation it is written using $watch to watch the value of user generated content is unsafe:

There are a number of ways that templates and expressions can be controlled:...

Passing an expression generated from user-provided content in calls to the following methods on a scope:
...

$watch(userContent, ...)

What is the meaning of userContent here? If I watch ngModel value of user input field, is this a userContent? Is the form in the fiddle unsafe?

答:
$watch expression is restricted form of eval, where an expression is parsed by AngularJS expression parser and evaluated against current scope.

Although AngularJS expression parser has security measures against evaluating arbitrary JS code with real eval, security hazards may still exist, and known vulnerabilities can be potentially exploited in older framework versions.

This means that $on.constructor('alert(1)')() expression cannot be evaluated and won't create a security threat in any up-to-date AngularJS version. But considering that $window service was exposed to scope (which is a common practice for ES6 controllers), $window.alert(1) expression can be evaluated.

This cannot pose a security threat:

```<code>$scope.$watch('myValue', function () {
    console.log($scope.myValue);
});
</code>```

This can pose a security threat:

```<code>$scope.$watch($scope.myValue, function () {
    console.log($scope.myValue);
});
</code>```

Title: How to breach Angularjs using $watch?

Body:
$watch expression is restricted form of eval, where an expression is parsed by AngularJS expression parser and evaluated against current scope.

Although AngularJS expression parser has security measures against evaluating arbitrary JS code with real eval, security hazards may still exist, and known vulnerabilities can be potentially exploited in older framework versions.

This means that $on.constructor('alert(1)')() expression cannot be evaluated and won't create a security threat in any up-to-date AngularJS version. But considering that $window service was exposed to scope (which is a common practice for ES6 controllers), $window.alert(1) expression can be evaluated.

This cannot pose a security threat:

$scope.$watch('myValue', function () {
    console.log($scope.myValue);
});

This can pose a security threat:

$scope.$watch($scope.myValue, function () {
    console.log($scope.myValue);
});


问:
"IndexError: list index out of range" While using recursion on lists
I'm a programming student and I have just recently started working in Python. I started with learning Rackett which has a very different approach. While trying to use recursion in combination with a for statement I ran into "IndexError: list index out of range". This is my code:

```<code>def search_matching_pokemon(p, l):
    lp = []
    for i in range(len(l) - 1):
        if p[-1] == l[i][0]:
            print ('Found one')
            poke = l.pop(i)
            lp = lp + [poke]
            print (f'List is now {lp}')
            search_matching_pokemon(poke, l)    #problem with the range
        else:
            print ('Trying a different pokémon')
    return lp
</code>```

I think my function doesn't take the reduced list when recursing, at least not during the
range(len(l) - 1)
Help would be very much appreciated, thank you in advance.

答:
List "l" becomes empty and you are still trying to run for loop.Don't run this loop when list is empty.
Also the loop should be for i in range(len(l)).</p>

Body:
I'm a programming student and I have just recently started working in Python. I started with learning Rackett which has a very different approach. While trying to use recursion in combination with a for statement I ran into "IndexError: list index out of range". This is my code:

def search_matching_pokemon(p, l):
    lp = []
    for i in range(len(l) - 1):
        if p[-1] == l[i][0]:
            print ('Found one')
            poke = l.pop(i)
            lp = lp + [poke]
            print (f'List is now {lp}')
            search_matching_pokemon(poke, l)    #problem with the range
        else:
            print ('Trying a different pokémon')
    return lp

I think my function doesn't take the reduced list when recursing, at least not during the
range(len(l) - 1)
Help would be very much appreciated, thank you in advance.


问:
Help with mapping or routing subdomain to Zend Framework Controller (mobile version of site)
What I am trying to do is use a subdomain for a special mobile version of my ZF application. Ideally it would map to a specific controller like the example below, but at this point I'm willing to try any method that works:

Ex. m.domain.com/action would route to the "mobile" controller and whatever action is specified.

I found a number of similar questions here and elsewhere on the Google but I get the feeling I am missing something obvious because no matter what route I set up it's just being ignored. I suspect it has something to do with htaccess but could be wrong there.

Here is the route I currently have in my bootstrap file (but I have tried a number of different patters here). Right now I'm just trying to get it to show the plain index for simplicity:

```<code>$hostRoute = new Zend_Controller_Router_Route_Hostname(':subdomain.domain.com',
        array(
            'controller' => 'index',
            'action' => 'index'
            )
    );
$plainPathRoute = new Zend_Controller_Router_Route(':controller/:action/*',
    array('controller' => 'index', 'action' => 'index'));
$controller->getRouter()->addRoute('mobile', $hostRoute->chain($plainPathRoute));
</code>```

And my htaccess has:

```<code>RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
</code>```

Now there are 2 methods I have been trying out here because I have been so frustrated.

Create the subdomain "m" inside of my hosting account

Subdomain "app" does not exist on my web hosting account

For method 1, it just goes to the generic index.html file that is in domain.com/m/. Method 2 tells me the page doesn't exist.

I'm really hoping there is something obvious here that I'm missing. Like I mentioned above, I'm not picky about how exactly this gets executed, so long as I can have a subdomain point to a specific controller. It's going to be a very simplified version of the site so I don't really need to do anything complex.

Thanks for your help.

答:
I use something similar, but instead of the subdomain mapping to a controller I use it for a module, I use the following route:</p>

```<code>$hostnameRoute = new Zend_Controller_Router_Route_Hostname(
        ':module.domain.com',
        array(
            'module' => 'default'
        )
    );
    $normalRoute = new Zend_Controller_Router_Route(
        ':controller/:action/*',
        array(
            'controller' => 'index',
            'action' => 'index'
        )
    );
    $router->addRoute('default', $hostnameRoute->chain($normalRoute));
</code>```

Body:
What I am trying to do is use a subdomain for a special mobile version of my ZF application. Ideally it would map to a specific controller like the example below, but at this point I'm willing to try any method that works:

Ex. m.domain.com/action would route to the "mobile" controller and whatever action is specified.

I found a number of similar questions here and elsewhere on the Google but I get the feeling I am missing something obvious because no matter what route I set up it's just being ignored. I suspect it has something to do with htaccess but could be wrong there.

Here is the route I currently have in my bootstrap file (but I have tried a number of different patters here). Right now I'm just trying to get it to show the plain index for simplicity:

$hostRoute = new Zend_Controller_Router_Route_Hostname(':subdomain.domain.com',
        array(
            'controller' => 'index',
            'action' => 'index'
            )
    );
$plainPathRoute = new Zend_Controller_Router_Route(':controller/:action/*',
    array('controller' => 'index', 'action' => 'index'));
$controller->getRouter()->addRoute('mobile', $hostRoute->chain($plainPathRoute));

And my htaccess has:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

Now there are 2 methods I have been trying out here because I have been so frustrated.

Create the subdomain "m" inside of my hosting account

Subdomain "app" does not exist on my web hosting account

For method 1, it just goes to the generic index.html file that is in domain.com/m/. Method 2 tells me the page doesn't exist.

I'm really hoping there is something obvious here that I'm missing. Like I mentioned above, I'm not picky about how exactly this gets executed, so long as I can have a subdomain point to a specific controller. It's going to be a very simplified version of the site so I don't really need to do anything complex.

Thanks for your help.

Body:
I use something similar, but instead of the subdomain mapping to a controller I use it for a module, I use the following route:

$hostnameRoute = new Zend_Controller_Router_Route_Hostname(
        ':module.domain.com',
        array(
            'module' => 'default'
        )
    );
    $normalRoute = new Zend_Controller_Router_Route(
        ':controller/:action/*',
        array(
            'controller' => 'index',
            'action' => 'index'
        )
    );
    $router->addRoute('default', $hostnameRoute->chain($normalRoute));


问:
R | Assign Cat() output to variable
I am trying to remove the '\' that is generated, so i run cat() to clear it. But need to assign that output to a variable to later match in a gsubfn string. </p>

```<code>>topheader <-'<div id="editor1" class="shinytinymce shiny-bound-input"
style="resize: none; width: 100%; height: 100%; border-style: none;
background: gainsboro;">'

>topheader
[1] "<div id=\"editor1\" class=\"shinytinymce shiny-bound-input\"
style=\"resize: none; width: 100%; height: 100%; border-style: none;
background: gainsboro;\">"

>cat(topheader)
[1] <div id="editor1" class="shinytinymce shiny-bound-input" style="resize:
none; width: 100%; height: 100%; border-style: none; background:
gainsboro;">

> test<-cat(topheader)

> test
NULL
</code>```

答:
As indicated already in the comments, assigning the output of cat to a variable won't help you, because the \ characters (referred to as an escape characters) don't actually exist in the character string. They are just printed that way when you output the character string to the console.

However, for the benefit of other people who are trying to assign the output of cat for a different reason, a more complete answer is warranted.  cat does have some useful features for formatting output, which someone may have a valid need to store in a variable. In these instances, we can use capture.output to achieve this.  For example,

```<code>cat(paste(letters, 100* 1:26), fill = TRUE, labels = paste0("{", 1:10, "}:"))
</code>```

produces the following output, conveniently split into numbered lines at the width of the console:

```<code># {1}: a 100 b 200 c 300 d 400 e 500 f 600 g 700 h 800 i 900
# {2}: j 1000 k 1100 l 1200 m 1300 n 1400 o 1500 p 1600
# {3}: q 1700 r 1800 s 1900 t 2000 u 2100 v 2200 w 2300
# {4}: x 2400 y 2500 z 2600
</code>```

we can capture this output by

```<code>x = capture.output(
      cat(paste(letters, 100* 1:26), fill = TRUE, labels = paste0("{", 1:10, "}:"))
    )
</code>```

which creates a character vector, x, with each element corresponding to a line of the output:

```<code># [1] "{1}: a 100 b 200 c 300 d 400 e 500 f 600 g 700 h 800 i 900 "
# [2] "{2}: j 1000 k 1100 l 1200 m 1300 n 1400 o 1500 p 1600 "
# [3] "{3}: q 1700 r 1800 s 1900 t 2000 u 2100 v 2200 w 2300 "
# [4] "{4}: x 2400 y 2500 z 2600"
</code>```

If you like, you can collapse this vector into a single string separated with line breaks using:

```<code>x = paste0(x, collapse = '\n')
</code>```

Title: R | Assign Cat() output to variable

Body:
I am trying to remove the '\' that is generated, so i run cat() to clear it. But need to assign that output to a variable to later match in a gsubfn string.

>topheader <-'
'

>topheader
[1] "
"

>cat(topheader)
[1]

> test<-cat(topheader)

> test
NULL

Body:
As indicated already in the comments, assigning the output of cat to a variable won't help you, because the \ characters (referred to as an escape characters) don't actually exist in the character string. They are just printed that way when you output the character string to the console.

However, for the benefit of other people who are trying to assign the output of cat for a different reason, a more complete answer is warranted.  cat does have some useful features for formatting output, which someone may have a valid need to store in a variable. In these instances, we can use capture.output to achieve this.  For example,

cat(paste(letters, 100* 1:26), fill = TRUE, labels = paste0("{", 1:10, "}:"))

produces the following output, conveniently split into numbered lines at the width of the console:

# {1}: a 100 b 200 c 300 d 400 e 500 f 600 g 700 h 800 i 900
# {2}: j 1000 k 1100 l 1200 m 1300 n 1400 o 1500 p 1600
# {3}: q 1700 r 1800 s 1900 t 2000 u 2100 v 2200 w 2300
# {4}: x 2400 y 2500 z 2600

we can capture this output by

x = capture.output(
      cat(paste(letters, 100* 1:26), fill = TRUE, labels = paste0("{", 1:10, "}:"))
    )

which creates a character vector, x, with each element corresponding to a line of the output:

# [1] "{1}: a 100 b 200 c 300 d 400 e 500 f 600 g 700 h 800 i 900 "
# [2] "{2}: j 1000 k 1100 l 1200 m 1300 n 1400 o 1500 p 1600 "
# [3] "{3}: q 1700 r 1800 s 1900 t 2000 u 2100 v 2200 w 2300 "
# [4] "{4}: x 2400 y 2500 z 2600"

If you like, you can collapse this vector into a single string separated with line breaks using:

x = paste0(x, collapse = '\n')


问:
How do you reference a particular AWS::StateMachine in Cloudwatch Dashboard widget Template?
I have a working Cloudwatch Dashboard widget for a Lambda functions in my Cloudformation template like,

```<code>---
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
  MyLambda:
    Type: AWS::Serverless::Function
    ...

  MyStateMachine:
    Type: "AWS::StepFunctions::StateMachine"
    ...

  MyDashboard:
    Type: AWS::CloudWatch::Dashboard
    Properties:
      DashboardName: MyDashboard
      DashboardBody:
        Fn::Sub: '{
          "widgets": [
              {
                  "type": "metric",
                  "x": 0,
                  "y": 3,
                  "width": 24,
                  "height": 3,
                  "properties": {
                      "view": "singleValue",
                      "metrics": [
                          [ "AWS/Lambda", "Invocations", "FunctionName", "${MyLambda}", { "stat": "Sum", "period": 86400 } ],
                          [ ".", "Duration", ".", ".", { "stat": "Average", "period": 86400, "color": "#2ca02c" } ],
                          [ ".", "Errors", ".", ".", { "stat": "Sum", "period": 86400, "color": "#d62728" } ],
                          [ ".", "Throttles", ".", ".", { "stat": "Sum", "period": 86400, "color": "#ff7f0e" } ]
                      ],
                      "region": "us-west-2",
                      "title": "MyLambda",
                      "stacked": true
                  }
              }
          ]
      }'
</code>```

I want to add a widget for MyStateMachine to this dashboard, but I don't know how to write the State Machine equivalent of,

```<code>[ "AWS/Lambda", "Invocations", "FunctionName", "${MyLambda}", { "stat": "Sum", "period": 86400 } ]
</code>```

I found that AWS/Lambda is called and AWS Namespace and the equivalent one is AWS/States and I found all the options I can use in place of Invocations, but I am not sure how to replace FunctionName. This suggests that I could use InstanceId, but there is limited documentation beyond that.

How do I create an AWS Cloudwatch Dashboard widget for my State Machine?

答:
I figured it out by making the widget in the AWS Web Console and then looking at the source it generated. The following worked for me.</p>

```<code>                      "title": "MyLambda",
                    "stacked": true
                  }
+              },
+              {
+                  "type": "metric",
+                  "x": 0,
+                  "y": 9,
+                  "width": 24,
+                  "height": 3,
+                  "properties": {
+                      "view": "timeSeries",
+                      "metrics": [
+                          [ "AWS/States", "ActivitiesStarted", "ActivityArn", "${MyStateMachine}", { "stat": "Sum", "period": 86400 } ]
+                      ],
+                      "region": "us-west-2",
+                      "title": "State Machine Metrics",
+                      "period": 300
+                  }
               }
           ]
       }'
</code>```

Body:
I have a working Cloudwatch Dashboard widget for a Lambda functions in my Cloudformation template like,

---
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
  MyLambda:
    Type: AWS::Serverless::Function
    ...

  MyStateMachine:
    Type: "AWS::StepFunctions::StateMachine"
    ...

  MyDashboard:
    Type: AWS::CloudWatch::Dashboard
    Properties:
      DashboardName: MyDashboard
      DashboardBody:
        Fn::Sub: '{
          "widgets": [
              {
                  "type": "metric",
                  "x": 0,
                  "y": 3,
                  "width": 24,
                  "height": 3,
                  "properties": {
                      "view": "singleValue",
                      "metrics": [
                          [ "AWS/Lambda", "Invocations", "FunctionName", "${MyLambda}", { "stat": "Sum", "period": 86400 } ],
                          [ ".", "Duration", ".", ".", { "stat": "Average", "period": 86400, "color": "#2ca02c" } ],
                          [ ".", "Errors", ".", ".", { "stat": "Sum", "period": 86400, "color": "#d62728" } ],
                          [ ".", "Throttles", ".", ".", { "stat": "Sum", "period": 86400, "color": "#ff7f0e" } ]
                      ],
                      "region": "us-west-2",
                      "title": "MyLambda",
                      "stacked": true
                  }
              }
          ]
      }'

I want to add a widget for MyStateMachine to this dashboard, but I don't know how to write the State Machine equivalent of,

[ "AWS/Lambda", "Invocations", "FunctionName", "${MyLambda}", { "stat": "Sum", "period": 86400 } ]

I found that AWS/Lambda is called and AWS Namespace and the equivalent one is AWS/States and I found all the options I can use in place of Invocations, but I am not sure how to replace FunctionName. This suggests that I could use InstanceId, but there is limited documentation beyond that.

How do I create an AWS Cloudwatch Dashboard widget for my State Machine?

Body:
I figured it out by making the widget in the AWS Web Console and then looking at the source it generated. The following worked for me.

                      "title": "MyLambda",
                    "stacked": true
                  }
+              },
+              {
+                  "type": "metric",
+                  "x": 0,
+                  "y": 9,
+                  "width": 24,
+                  "height": 3,
+                  "properties": {
+                      "view": "timeSeries",
+                      "metrics": [
+                          [ "AWS/States", "ActivitiesStarted", "ActivityArn", "${MyStateMachine}", { "stat": "Sum", "period": 86400 } ]
+                      ],
+                      "region": "us-west-2",
+                      "title": "State Machine Metrics",
+                      "period": 300
+                  }
               }
           ]
       }'


问:
Postgresql function return trigger
I am having a problem with a trigger. I created a trigger and a function
for when performing an INSERT update a field in the same table.
Is returning:

Error: function "loss_func" in FROM has return type trigger that is
  not     supported LINE 1: SELECT * FROM table.loss_func ()

Function

```<code>CREATE OR REPLACE FUNCTION loss_func()
  RETURNS trigger AS $loss_func$
  BEGIN
     NEW.dt_creation := to_char(now(), 'YYYY-MM-DD');

     RETURN NULL;
  END;
  $loss_func$ LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION loss_func()
   OWNER TO postgres;
</code>```

Trigger

```<code>CREATE TRIGGER tgr_loss
  AFTER INSERT ON loss
  FOR EACH ROW
  EXECUTE PROCEDURE loss_func();
</code>```

What am I doing wrong?

答:
A working version of your code.
- The trigger now fires BEFORE insert and updates the value of dt_creation and returns the NEW version of the record :

```<code>drop table loss;

create table loss (
id int ,
dt_created varchar);

CREATE OR REPLACE FUNCTION loss_func()
  RETURNS trigger AS $loss_func$
  BEGIN
     NEW.dt_created := to_char(now(), 'YYYY-MM-DD');
     RETURN NEW;
  END;
  $loss_func$ LANGUAGE plpgsql VOLATILE
  COST 100;

ALTER FUNCTION loss_func()
   OWNER TO postgres;

CREATE TRIGGER tgr_loss
  BEFORE INSERT ON loss
  FOR EACH ROW
  EXECUTE PROCEDURE loss_func();

insert into loss(id) values(1);
</code>```

Another solution that i can propose to avoid the usage of a trigger is to use a default value for dt_creation when you create the table (and use timestamp instead of storing the date as varchar)  :

```<code>...
dt_creation timestamp default now(),
...
</code>```

or you can alter your table to set the default value to now() :

```<code>alter table loss
alter column dt_creation set default now();
</code>```

Title: Postgresql function return trigger

Body:
I am having a problem with a trigger. I created a trigger and a function
for when performing an INSERT update a field in the same table.
Is returning:

Error: function "loss_func" in FROM has return type trigger that is
  not     supported LINE 1: SELECT * FROM table.loss_func ()

Function

CREATE OR REPLACE FUNCTION loss_func()
  RETURNS trigger AS $loss_func$
  BEGIN
     NEW.dt_creation := to_char(now(), 'YYYY-MM-DD');

     RETURN NULL;
  END;
  $loss_func$ LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION loss_func()
   OWNER TO postgres;

Trigger

CREATE TRIGGER tgr_loss
  AFTER INSERT ON loss
  FOR EACH ROW
  EXECUTE PROCEDURE loss_func();

What am I doing wrong?

Body:
A working version of your code.
- The trigger now fires BEFORE insert and updates the value of dt_creation and returns the NEW version of the record :

drop table loss;

create table loss (
id int ,
dt_created varchar);

CREATE OR REPLACE FUNCTION loss_func()
  RETURNS trigger AS $loss_func$
  BEGIN
     NEW.dt_created := to_char(now(), 'YYYY-MM-DD');
     RETURN NEW;
  END;
  $loss_func$ LANGUAGE plpgsql VOLATILE
  COST 100;

ALTER FUNCTION loss_func()
   OWNER TO postgres;

CREATE TRIGGER tgr_loss
  BEFORE INSERT ON loss
  FOR EACH ROW
  EXECUTE PROCEDURE loss_func();

insert into loss(id) values(1);

Another solution that i can propose to avoid the usage of a trigger is to use a default value for dt_creation when you create the table (and use timestamp instead of storing the date as varchar)  :

...
dt_creation timestamp default now(),
...

or you can alter your table to set the default value to now() :

alter table loss
alter column dt_creation set default now();


问:
What's the difference between a browser engine and rendering engine?
I found some similar questions but they do not fully respond to the one I have, here is the list that I hope will help someone else:

What's the difference between a browser engine, a rendering engine and a user agent?

Difference between layout engine and javascript engine

As explained here https://www.html5rocks.com/en/tutorials/internals/howbrowserswork/

The browser engine: marshals actions between the UI and the rendering engine.

The rendering engine: responsible for displaying requested content. For example if the requested content is HTML, the rendering engine parses HTML and CSS, and displays the parsed content on the screen.

According to Wikipedia:
A web browser engine (sometimes called web layout engine or web rendering engine)...

But I little bit confused, I still can't understand what the browser engine is, what are the "actions between the UI and the rendering engine".

答:
I don't know how to explain in terms of "Engine".
Let me explain by using the keyword "process" in the context of chromium browser which has multi-process architecture.

Browser process : Main browser process that manages renderer processes

Renderer process : Basically a tab (in chromium)

In order to prevent the entire browser to crash or compromise the host system, due to a malicious web content, a separate process is delegated with the handling of the web content for each request. This separate process is the Renderer process (tab process), which do not have user privileges (i.e, limited access to OS system calls).

When one requests for a web site, the render process forwards the request to the browser process which in-turn makes the network calls for the website. After the arrival of the web content, the browser process sends the content to the renderer process.
The renderer process parses the HTML,CSS fils, prepares the DOM, maintains the JS run time (V8 instance) and sends the content as a bitmap format to the browser process for displaying it on the UI.

The browser process treats the renderer process as a black box and expects the web content in a certain format from the renderer process.
This conversion of web content to the required format includes several sub-components of which layout engine (process) is one.

So, Browser process handles the user privileged resources/requests like access to filesystem, network etc. where as the sandboxed Renderer process is responsible for converting the web pages to a format that browser-process can put it to display in a OS native window manager.

I wonder why the layout engine is named as the browser engine. The above mentioned Browser process is different from Browser-Engine (Layout engine). I have not explored the layout engine yet.

References :
https://seclab.stanford.edu/websec/chromium/chromium-security-architecture.pdf


问:
Can't import numpy in python 2.7
When running the following code in python 2.7:

```<code>import numpy
</code>```

I get the result:

```<code>ImportError: No module named numpy
</code>```

I have however got numpy installed for python 2.7, which is seen when running the following in terminal:

```<code>pip install numpy
</code>```

I get the following:

```<code>Requirement already satisfied: numpy in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages
</code>```

Working on macOS10.13.1

What am I missing?
Any help will be greatly appreciated!

答: have you tried uninstalling the numpy package and re-installing it? As mentioned you may be running python 3 instead of python 2 which could cause this issue.alternatively you could install an api like anaconda which comes with numpy pre-installed this may resolve the missing module. anaconda website: https://www.anaconda.com/download/ </p>

Title: Can't import numpy in python 2.7

Body:
When running the following code in python 2.7:

import numpy

I get the result:

ImportError: No module named numpy

I have however got numpy installed for python 2.7, which is seen when running the following in terminal:

pip install numpy

I get the following:

Requirement already satisfied: numpy in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages

Working on macOS10.13.1

What am I missing?
Any help will be greatly appreciated!


问:
Should be simple domain alias ala mod_rewrite
Problem.

I am using mod_rewrite on a Godaddy account, shared, cpanel linux webserver...
I am trying to serve content from domain 1, when domain 2 is requested as an invisible redirect.. aka domain aliasing

domain1 is a wordpress site. I'm trying to get a wordpress /catagory/page to act as the content for domain 2. In fact domain 2 should have only that one page of content available, where we have a form 2 email page set up.

Ideally, Any other get requests should visibly redirect to the actual domain.
Naturally a post request should go to the form on the aliased domain (2)...

Googling relevant search terms results in major information overload. I'm sure the answer is out there, I just can't find the solution to this exact scenario. Meanwhile I suspect Godaddy is caching .htaccess, making it even more difficult to find a working solution in a timely manner.

I've tried several variations, waiting 15 minutes between edits, flushing browser cache etc. I can't seem to find the correct syntax, and/or Godaddy caches .htaccess longer than 15 minutes.

My last attempt

```<code>RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} ^www.domainalias.com$[OR]
RewriteCond %{HTTP_HOST} ^domainalias.com$
RewriteRule .* http://www.actualdomain.com/subdir/subdir/ [R=301,L]
</code>```

That seems like it should do exactly what I want, but it doesnt.
It does show the domainalias address in the browser URL bar (GOOD)
BUT, it displays the home page from http://www.actualdomain.com/ (BAD)

It should display http://www.actualdomain.com/subdir/subdir/    while keeping www.domainalias.com in the adress bar.

What am I missing ?

答:
I am still not entirely sure why my prior attempts did not redirect at all, neither visibly or invisibly..  But after some sleep and more reading, I've got exactly what I needed with the following syntax.</p>

```<code>RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^DomainA.com
RewriteRule ^(.*) http://DomainB.com/PathToPageHere [P]
</code>```

Body:
Problem.

I am using mod_rewrite on a Godaddy account, shared, cpanel linux webserver...
I am trying to serve content from domain 1, when domain 2 is requested as an invisible redirect.. aka domain aliasing

domain1 is a wordpress site. I'm trying to get a wordpress /catagory/page to act as the content for domain 2. In fact domain 2 should have only that one page of content available, where we have a form 2 email page set up.

Ideally, Any other get requests should visibly redirect to the actual domain.
Naturally a post request should go to the form on the aliased domain (2)...

Googling relevant search terms results in major information overload. I'm sure the answer is out there, I just can't find the solution to this exact scenario. Meanwhile I suspect Godaddy is caching .htaccess, making it even more difficult to find a working solution in a timely manner.

I've tried several variations, waiting 15 minutes between edits, flushing browser cache etc. I can't seem to find the correct syntax, and/or Godaddy caches .htaccess longer than 15 minutes.

My last attempt

RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} ^www.domainalias.com$[OR]
RewriteCond %{HTTP_HOST} ^domainalias.com$
RewriteRule .* http://www.actualdomain.com/subdir/subdir/ [R=301,L]

That seems like it should do exactly what I want, but it doesnt.
It does show the domainalias address in the browser URL bar (GOOD)
BUT, it displays the home page from http://www.actualdomain.com/ (BAD)

It should display http://www.actualdomain.com/subdir/subdir/    while keeping www.domainalias.com in the adress bar.

What am I missing ?

Body:
I am still not entirely sure why my prior attempts did not redirect at all, neither visibly or invisibly..  But after some sleep and more reading, I've got exactly what I needed with the following syntax.

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^DomainA.com
RewriteRule ^(.*) http://DomainB.com/PathToPageHere [P]


问:
How to check if object already exists in HashSet?
This example makes it look easy:

```<code>HashSet<Integer> hSet = new HashSet<Integer>();

hSet.add(new Integer("1"));
hSet.add(new Integer("2"));
hSet.add(new Integer("3"));

System.out.println(hSet.contains(new Integer("3")));
</code>```

true

But when I use it on a Movie object (which I want to check):

```<code>Set<Movie> hSet = new HashSet<Movie>();

hSet.add(new Movie(222, "Lord of the Rings", "something"));
System.out.println(hSet);

System.out.println(hSet.contains(new Movie(222, "Lord of the Rings", "something")));
</code>```

false

The hSet print shows:

[id: 222name: Lord of the Rings]

I don't see a difference in adding a new Integer or adding a new movie object to the list. So why isn't my example working?

//edit.

If anyone is looking for a good reference, this helped me out.

答:
You need to override the hashcode and equals method in Movie class.

In hashset whenever we add the objects, before adding the object it will check the hashcode value of an object by overridding the hashcode
If the calculated hashcode value is already available in the set, then it will call equals method and check the object which we are going to add is equal with the already available object in set.
If the object is equal then it will not add it into the set or else it will add the object into the set.

Body:
This example makes it look easy:

HashSet<Integer> hSet = new HashSet<Integer>();

hSet.add(new Integer("1"));
hSet.add(new Integer("2"));
hSet.add(new Integer("3"));

System.out.println(hSet.contains(new Integer("3")));

true

But when I use it on a Movie object (which I want to check):

Set<Movie> hSet = new HashSet<Movie>();

hSet.add(new Movie(222, "Lord of the Rings", "something"));
System.out.println(hSet);

System.out.println(hSet.contains(new Movie(222, "Lord of the Rings", "something")));

false

The hSet print shows:

[id: 222name: Lord of the Rings]

I don't see a difference in adding a new Integer or adding a new movie object to the list. So why isn't my example working?

//edit.

If anyone is looking for a good reference, this helped me out.