问:
UIPopover presentFromBarButton off center
I've noticed in a project that the positioning of a popover over a right bar button item seems to be off to the right for some reason. I've tried instead using a UIButton for the custom view, then presenting the popover from that button, but popover seems to ignore the showFromRect if I actually provide it with the 'centered' value.

The code behind this is quite simple:

```<code>- (void)viewDidLoad {
    [super viewDidLoad];

     UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"share"] style:UIBarButtonItemStylePlain target:self action:@selector(shareTap:)];

     self.navigationItem.rightBarButtonItem = button;
}

- (void)shareTap:(UIBarButtonItem *)button {
    self.popover = [[UIPopoverController alloc] initWithContentViewController:[[UIViewController alloc] init]];

    [self.popover presentPopoverFromBarButtonItem:button permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
}
</code>```

Now, if I switch to using the internal button, as mentioned, I see similar behavior (note color change so image shows up).

The code for this is still fairly simple:

```<code>- (void)viewDidLoad {
    [super viewDidLoad];

    UIButton *innerButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 22, 22)];
    [innerButton setImage:[UIImage imageNamed:@"share"] forState:UIControlStateNormal];
    [innerButton addTarget:self action:@selector(shareTap:) forControlEvents:UIControlEventTouchUpInside];

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:innerButton];;
}

- (void)shareTap:(UIButton *)button {
    self.popover = [[UIPopoverController alloc] initWithContentViewController:[[UIViewController alloc] init]];

//    CGRect bottomCenter = CGRectMake(button.frame.size.width / 2, button.frame.size.height, 1, 1);
    CGRect bottomCenter = CGRectMake(2, button.frame.size.height, 1, 1);

    [self.popover presentPopoverFromRect:bottomCenter inView:button permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
}
</code>```

Note here that instead of using the actual center, I've used the arbitrary value, 2. If I use 1 or 0, the popover becomes left-aligned. Anything greater than one is right aligned again.

I searched around a bit looking for a similar question, but I can't seem to find anyone with the same problem. Any idea around what causes this or how to avoid it would be greatly appreciated. The only thing I've been able to guess at is that due to its proximity to the edge, Apple does some positioning voodoo to force it to be where they want it. The problem is that top-right corner button seems like a pretty standard drop down position.

Edit: I've confirmed this same behavior occurs with a long-press on the "New Message" icon in the native Mail app.

Edit 2: I was able to confirm with Apple that this is an issue. In one of the more recent versions (I can't remember which, one of the 9s I think), they made it so you can manually set this. The default behavior is still wrong I believe (I haven't tried this for a while), but you can use the CGRect offset method to make it work correctly, should you be so inclined.

答:
Here's one way to do this:  Instead of using a UIBarButtonSystemItem, use a UIBarButtonItem with a custom view. Just drag a UIButton into the UINavigationBar to get a UIBarButtonItem with an embedded UIButton, which shows up as the UIBarButtonItem's customView.

```<code>@IBAction func didTapActionButton(_ sender: Any) {
    if let vc = self.storyboard?.instantiateViewController(withIdentifier: "myPopover") {
        vc.modalPresentationStyle = .popover
        guard let innerView = actionButton.customView else {
            // Unexpected missing custom view
            return
        }

        vc.popoverPresentationController?.sourceView = navigationController?.navigationBar
        vc.popoverPresentationController?.sourceRect = innerView.frame
        self.present(vc, animated: true, completion: nil)
    }
}
</code>```

Body:
I've noticed in a project that the positioning of a popover over a right bar button item seems to be off to the right for some reason. I've tried instead using a UIButton for the custom view, then presenting the popover from that button, but popover seems to ignore the showFromRect if I actually provide it with the 'centered' value.

The code behind this is quite simple:

- (void)viewDidLoad {
    [super viewDidLoad];

     UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"share"] style:UIBarButtonItemStylePlain target:self action:@selector(shareTap:)];

     self.navigationItem.rightBarButtonItem = button;
}

- (void)shareTap:(UIBarButtonItem *)button {
    self.popover = [[UIPopoverController alloc] initWithContentViewController:[[UIViewController alloc] init]];

    [self.popover presentPopoverFromBarButtonItem:button permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
}

Now, if I switch to using the internal button, as mentioned, I see similar behavior (note color change so image shows up).

The code for this is still fairly simple:

- (void)viewDidLoad {
    [super viewDidLoad];

    UIButton *innerButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 22, 22)];
    [innerButton setImage:[UIImage imageNamed:@"share"] forState:UIControlStateNormal];
    [innerButton addTarget:self action:@selector(shareTap:) forControlEvents:UIControlEventTouchUpInside];

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:innerButton];;
}

- (void)shareTap:(UIButton *)button {
    self.popover = [[UIPopoverController alloc] initWithContentViewController:[[UIViewController alloc] init]];

//    CGRect bottomCenter = CGRectMake(button.frame.size.width / 2, button.frame.size.height, 1, 1);
    CGRect bottomCenter = CGRectMake(2, button.frame.size.height, 1, 1);

    [self.popover presentPopoverFromRect:bottomCenter inView:button permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
}

Note here that instead of using the actual center, I've used the arbitrary value, 2. If I use 1 or 0, the popover becomes left-aligned. Anything greater than one is right aligned again.

I searched around a bit looking for a similar question, but I can't seem to find anyone with the same problem. Any idea around what causes this or how to avoid it would be greatly appreciated. The only thing I've been able to guess at is that due to its proximity to the edge, Apple does some positioning voodoo to force it to be where they want it. The problem is that top-right corner button seems like a pretty standard drop down position.

Edit: I've confirmed this same behavior occurs with a long-press on the "New Message" icon in the native Mail app.

Edit 2: I was able to confirm with Apple that this is an issue. In one of the more recent versions (I can't remember which, one of the 9s I think), they made it so you can manually set this. The default behavior is still wrong I believe (I haven't tried this for a while), but you can use the CGRect offset method to make it work correctly, should you be so inclined.

Body:
Here's one way to do this:  Instead of using a UIBarButtonSystemItem, use a UIBarButtonItem with a custom view. Just drag a UIButton into the UINavigationBar to get a UIBarButtonItem with an embedded UIButton, which shows up as the UIBarButtonItem's customView.

@IBAction func didTapActionButton(_ sender: Any) {
    if let vc = self.storyboard?.instantiateViewController(withIdentifier: "myPopover") {
        vc.modalPresentationStyle = .popover
        guard let innerView = actionButton.customView else {
            // Unexpected missing custom view
            return
        }

        vc.popoverPresentationController?.sourceView = navigationController?.navigationBar
        vc.popoverPresentationController?.sourceRect = innerView.frame
        self.present(vc, animated: true, completion: nil)
    }
}


来源: stackexchange

问:
How to create CSR in Azure?
I have bought my domain from whois and my site (Asp.Net MVC) in deployed in Azure. I want to add SSL which I want to buy from GoDaddy.com. To do that I have to generate CSR (certificate signing request) in Azure so that I can use it to get my SSL certificate from GoDaddy.

So how can I generate CSR in Azure?

答:
We can't generate CSR in Azure. We could used IIS ,Certreq.exe or makecert.exe to generate your certificate request, install the certificate to your local machine, and then export the certificate to PFX. More details about how to bind custom-ssl, please refer to official tutorial. The following is details about how to use makecert.exe to create CSR:

Create a cert with makecert.exe that is under the VS folder after install the VS. The following code is just for demo

```<code> makecert -sky exchange -r -n "CN=[CertificateName]" -pe -a sha1 -len 2048 -ss My "[CertificateName].cer
</code>```

After that we could export Base64-encoded .cer file

Update:

Requirements for your SSL certificate, the following is the snippet from the tutorial

To use a certificate in App Service, the certificate must meet all the following requirements:

Signed by a trusted certificate authority

Exported as a password-protected PFX file

Contains private key at least 2048 bits long

Contains all intermediate certificates in the certificate chain

If we want to use self signature certificate we need to Export a Certificate with the Private Key. And then we could follow official tutorial to upload the .PFX file to Azure WebApp.

Note:  If we use self signature certificate , it will be not trusted.

ContentLicense: CC BY-SA 3.0

Title: How to create CSR in Azure?

Body:
We can't generate CSR in Azure. We could used IIS ,Certreq.exe or makecert.exe to generate your certificate request, install the certificate to your local machine, and then export the certificate to PFX. More details about how to bind custom-ssl, please refer to official tutorial. The following is details about how to use makecert.exe to create CSR:

Create a cert with makecert.exe that is under the VS folder after install the VS. The following code is just for demo

 makecert -sky exchange -r -n "CN=[CertificateName]" -pe -a sha1 -len 2048 -ss My "[CertificateName].cer

After that we could export Base64-encoded .cer file

Update:

Requirements for your SSL certificate, the following is the snippet from the tutorial

To use a certificate in App Service, the certificate must meet all the following requirements:

Signed by a trusted certificate authority

Exported as a password-protected PFX file

Contains private key at least 2048 bits long

Contains all intermediate certificates in the certificate chain

If we want to use self signature certificate we need to Export a Certificate with the Private Key. And then we could follow official tutorial to upload the .PFX file to Azure WebApp.

Note:  If we use self signature certificate , it will be not trusted.


问:
Action Bar is in ''grey"/invisible color
I'm trying to create an options menu for my activity.
First off, it doesn't show, I followed instruction and I added the requestWindowFeature(Window.FEATURE_ACTION_BAR); in the onCreate method and the action bar is showing but it is in 'grey'/invisible color. I still can click on an menu item. Could you please tell me how to make the action bar visible? Thanks.
Here is my Activity, is extending FragmentActivity which is a must because I need it for my map fragment:

```<code>public class MapsActivity extends FragmentActivity{
 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_ACTION_BAR);
    setContentView(R.layout.activity_map);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
</code>```

}

And here is my style, the manifest is using the FMSTheme below:

```<code><!-- FMS theme -->
<style name="FMSTheme" parent="AppBaseTheme">
    <item name="android:windowNoTitle">false</item>
    <item name="android:windowActionBar">false</item>
    <item name="android:windowActionModeOverlay">false</item>
</style>
</code>```

Invisible actionbar image

答:
Let your MapsActivity to extend AppCompatActivity (from the support library) which itself extends a FragmentActivity:

```<code>public class MapsActivity extends AppCompatActivity {
</code>```

Once you've done so, I would recommend to set a Toolbar as an actionbar:

```<code>Toolbar toolbar = (Toolbar) findViewById(R.id.maps_activity_toolbar);
toolbar.setTitle("A title");
setSupportActionBar(toolbar);
</code>```

You can then configure your Toolbar's themes using these 2 properties:

```<code><android.support.v7.widget.Toolbar
    android:theme="@style/MyToolbarTheme"
    app:popupTheme="@style/MyToolbarPopupTheme">
</code>```

which you can customize at your wish, for instance you could have a dark action bar theme with a light menu theme (or viceversa):

```<code><!-- the theme of the toolbar on MapsActivity -->
<style name="ToolbarTheme" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
    <!-- Customize your theme here. -->
    <!-- default text color and menu dots -->
    <item name="android:textColorPrimary">@color/my_toolbar_text_color</item>
</style>

<!-- the theme of the menu which opens from ActionBar on MapsActivity -->
<style name="MyToolbarPopupTheme" parent="ThemeOverlay.AppCompat.Light">
    <!-- Customize your theme here. -->
</style>
</code>```

Body:
I'm trying to create an options menu for my activity.
First off, it doesn't show, I followed instruction and I added the requestWindowFeature(Window.FEATURE_ACTION_BAR); in the onCreate method and the action bar is showing but it is in 'grey'/invisible color. I still can click on an menu item. Could you please tell me how to make the action bar visible? Thanks.
Here is my Activity, is extending FragmentActivity which is a must because I need it for my map fragment:

public class MapsActivity extends FragmentActivity{
 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_ACTION_BAR);
    setContentView(R.layout.activity_map);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

}

And here is my style, the manifest is using the FMSTheme below:

Invisible actionbar image

Body:
Let your MapsActivity to extend AppCompatActivity (from the support library) which itself extends a FragmentActivity:

public class MapsActivity extends AppCompatActivity {

Once you've done so, I would recommend to set a Toolbar as an actionbar:

Toolbar toolbar = (Toolbar) findViewById(R.id.maps_activity_toolbar);
toolbar.setTitle("A title");
setSupportActionBar(toolbar);

You can then configure your Toolbar's themes using these 2 properties:

<android.support.v7.widget.Toolbar
    android:theme="@style/MyToolbarTheme"
    app:popupTheme="@style/MyToolbarPopupTheme">

which you can customize at your wish, for instance you could have a dark action bar theme with a light menu theme (or viceversa):

<!-- the theme of the toolbar on MapsActivity -->
<style name="ToolbarTheme" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
    <!-- Customize your theme here. -->
    <!-- default text color and menu dots -->
    <item name="android:textColorPrimary">@color/my_toolbar_text_color</item>
</style>

<!-- the theme of the menu which opens from ActionBar on MapsActivity -->
<style name="MyToolbarPopupTheme" parent="ThemeOverlay.AppCompat.Light">
    <!-- Customize your theme here. -->
</style>


问:
Converting a single BGR color with cvtColor and using the result to extract that color from image
I'm using c++ but answers in python are fine too.

I need to convert a known BGR color to HSV in order to use the cv::inRange method which allows you to extract a certain part of an image. I already have code that estimates the BGR color I need well enough so I thought I should be able to just guess around it's range.

So I refereed to this link: Convert a single color with cvtColor which seems to work for converting an BGR to HSV, though I still got some weird output as I will explain later.

Anyways here is my code:

```<code>//store BGR values and convert BGR to HSV
cv::Mat3f hairColor(cv::Vec3f(averageBlue, averageGreen, averageRed));
cv::Mat3f finalHSV;
cv::cvtColor(hairColor, finalHSV, CV_BGR2HSV);

//change values to be valid with the cv::inRange function (find this part odd)
finalHSV.ptr<float>(0)[0] /= 2;
finalHSV.ptr<float>(0)[1] *= 255;

//store hsv values as integers
int averageHue = finalHSV.ptr<float>(0)[0];
int averageSat = finalHSV.ptr<float>(0)[1];
int averageValue = finalHSV.ptr<float>(0)[2];

//try to appromimate ranges. I'm trying to mess wtih these values but can't calibrate it whatsoever
int hueMin = averageHue - 20;   int hueMax = averageHue + 100;
int saturationMin = averageSat - 20;    int saturationMax = averageSat + 20;
int valueMin = averageValue - 50;   int valueMax = averageValue + 50;

//bw is the output array for my mask.
cv::inRange(hsv, cv::Scalar(hueMin, saturationMin, valueMin), cv::Scalar(hueMax, saturationMax, valueMax), bw);
</code>```

So here is quick example: my code determines the approximate BGR color I want has values [126, 105, 98]. Converting to HSV intially gives [225, 0.22, 126] which seems to oddly be incorrect with how opencv stores hsv (like hue is 0-179 I think) so I do 2 conversions to get [112, 56, 126] which I think should be correct?

Anyways when I try to tinker with values in my inRange function I can't really get any good extraction, I tend to just get a black screen (I tested that my mask works and it does so the issue should be in the code provided).

Is there a better way of going about this task?

答:
Your second conversion is correct (well, if you truncate to int instead of rounding).

You can always just do the actual calculations for the value as given in the OpenCV docs for cvtColor.

This is the exact formula linked written in Python. Sorry it's not C++ but I wrote it as basic as possible so it was followable for someone in any other language:

```<code>b, g, r = 126, 105, 98

b = b/255
g = g/255
r = r/255

v = max([b, g, r])

if v is 0:
    s = 0
else:
    s = (v-min([b, g, r]))/v

if v is r:
    h = 60*(g-b)/(v-min([b,g,r]))
elif v is g:
    h = 120 + 60*(b-r)/(v-min([b,g,r]))
elif v is b:
    h = 240 + 60*(r-g)/(v-min([b,g,r]))

if h < 0:
    h = h + 360

v = np.round(255*v).astype(int)
s = np.round(255*s).astype(int)
h = np.round(h/2).astype(int)

print(h,s,v)
</code>```

113 57 126

There are a few different methods you can employ to get good automatic values for color filtering. One method I like is to select an area that is the color you want, and finding the standard deviation and mean of those color values. That way you can easily set the lower and upper bounds of the inRange() function as mean-stddev and mean+stddev respectively. Or you can be less restrictive and multiply your standard deviation by some scalar, and you could choose which direction to be more or less choosy in. E.g., lowerb = mean - 3*stddev and upperb = mean + 1.5*stddev.

This can be super useful when say you have multiple ROIs with an object in the middle that you care about. You can filter out the colors that are in the border of each ROI separately using the mean and standard deviation of the border pixels!

Body:
I'm using c++ but answers in python are fine too.

I need to convert a known BGR color to HSV in order to use the cv::inRange method which allows you to extract a certain part of an image. I already have code that estimates the BGR color I need well enough so I thought I should be able to just guess around it's range.

So I refereed to this link: Convert a single color with cvtColor which seems to work for converting an BGR to HSV, though I still got some weird output as I will explain later.

Anyways here is my code:

//store BGR values and convert BGR to HSV
cv::Mat3f hairColor(cv::Vec3f(averageBlue, averageGreen, averageRed));
cv::Mat3f finalHSV;
cv::cvtColor(hairColor, finalHSV, CV_BGR2HSV);

//change values to be valid with the cv::inRange function (find this part odd)
finalHSV.ptr<float>(0)[0] /= 2;
finalHSV.ptr<float>(0)[1] *= 255;

//store hsv values as integers
int averageHue = finalHSV.ptr<float>(0)[0];
int averageSat = finalHSV.ptr<float>(0)[1];
int averageValue = finalHSV.ptr<float>(0)[2];

//try to appromimate ranges. I'm trying to mess wtih these values but can't calibrate it whatsoever
int hueMin = averageHue - 20;   int hueMax = averageHue + 100;
int saturationMin = averageSat - 20;    int saturationMax = averageSat + 20;
int valueMin = averageValue - 50;   int valueMax = averageValue + 50;

//bw is the output array for my mask.
cv::inRange(hsv, cv::Scalar(hueMin, saturationMin, valueMin), cv::Scalar(hueMax, saturationMax, valueMax), bw);

So here is quick example: my code determines the approximate BGR color I want has values [126, 105, 98]. Converting to HSV intially gives [225, 0.22, 126] which seems to oddly be incorrect with how opencv stores hsv (like hue is 0-179 I think) so I do 2 conversions to get [112, 56, 126] which I think should be correct?

Anyways when I try to tinker with values in my inRange function I can't really get any good extraction, I tend to just get a black screen (I tested that my mask works and it does so the issue should be in the code provided).

Is there a better way of going about this task?

Body:
Your second conversion is correct (well, if you truncate to int instead of rounding).

You can always just do the actual calculations for the value as given in the OpenCV docs for cvtColor.

This is the exact formula linked written in Python. Sorry it's not C++ but I wrote it as basic as possible so it was followable for someone in any other language:

b, g, r = 126, 105, 98

b = b/255
g = g/255
r = r/255

v = max([b, g, r])

if v is 0:
    s = 0
else:
    s = (v-min([b, g, r]))/v

if v is r:
    h = 60*(g-b)/(v-min([b,g,r]))
elif v is g:
    h = 120 + 60*(b-r)/(v-min([b,g,r]))
elif v is b:
    h = 240 + 60*(r-g)/(v-min([b,g,r]))

if h < 0:
    h = h + 360

v = np.round(255*v).astype(int)
s = np.round(255*s).astype(int)
h = np.round(h/2).astype(int)

print(h,s,v)

113 57 126

There are a few different methods you can employ to get good automatic values for color filtering. One method I like is to select an area that is the color you want, and finding the standard deviation and mean of those color values. That way you can easily set the lower and upper bounds of the inRange() function as mean-stddev and mean+stddev respectively. Or you can be less restrictive and multiply your standard deviation by some scalar, and you could choose which direction to be more or less choosy in. E.g., lowerb = mean - 3*stddev and upperb = mean + 1.5*stddev.

This can be super useful when say you have multiple ROIs with an object in the middle that you care about. You can filter out the colors that are in the border of each ROI separately using the mean and standard deviation of the border pixels!


问:
How to filter multiple data using keywords in VBA?
I want to filter out the unnecessary data with these 3 keywords: Proton, Hyundai, Perodua. But I am getting the "Named argument not found" error after I run this code.

```<code>''Filtering return reason for Sheet1
Rows("1:1").Select
Selection.AutoFilter

Dim rng As Range

Set rng = ActiveSheet.Range("A1:L2671")
FilterField = WorksheetFunction.Match("Car", rng.Rows(1), 0)

'Turn on filter if not already turned on
If ActiveSheet.AutoFilterMode = False Then rng.AutoFilter

'Filter Specific Countries
rng.AutoFilter Field:=FilterField, Criteria1:="=*Proton*" _
    , Operator:=xlOr, Criteria2:="=*Hyundai*" _
    , Operator:=xlOr, Criteria3:="=*Perodua*"
</code>```

The Criteria3 was highlighted after I ran this code. Why can't I insert the 3 criteria onto the filter filed?

Here's the example of my data:

答:
I am not sure if autofilter can take more than 2 criteria as given in MSDN article

However, you may want to try passing an array into criteria1 as proposed in another solution here

Personally, I would prefer to use helper columns with functions (e.g. if statements) to narrow down my selection before using autofilter.

Body:
I want to filter out the unnecessary data with these 3 keywords: Proton, Hyundai, Perodua. But I am getting the "Named argument not found" error after I run this code.

''Filtering return reason for Sheet1
Rows("1:1").Select
Selection.AutoFilter

Dim rng As Range

Set rng = ActiveSheet.Range("A1:L2671")
FilterField = WorksheetFunction.Match("Car", rng.Rows(1), 0)

'Turn on filter if not already turned on
If ActiveSheet.AutoFilterMode = False Then rng.AutoFilter

'Filter Specific Countries
rng.AutoFilter Field:=FilterField, Criteria1:="=*Proton*" _
    , Operator:=xlOr, Criteria2:="=*Hyundai*" _
    , Operator:=xlOr, Criteria3:="=*Perodua*"

The Criteria3 was highlighted after I ran this code. Why can't I insert the 3 criteria onto the filter filed?

Here's the example of my data:


问:
NSButton state issues
I have two ViewControllers.
On VC1 I have search criteria and on VC2 I have the search results. If you want to go from VC2 to VC1 the VC2 is dismissed.

On VC1 I have an NSButton(style Check, type Switch) which by default I want it to be in ON state. The purpose of the NSButton is to include photos in the results.

If the user unchecks the button and presses search, it will go on to VC2 showing the search results without photos.

BUT when the user goes back to VC1 for a new search that's where the unwanted behaviour occurs:
The NSButton is unchecked(i want it to be checked by default, every time the user is at the VC1. Also, the button is nil.

Why is this happening, and how can i make it the button box to be ticked everytime the VC2 is dismissed?

I tried enabling it and setting it to ONState but as its nil it would crash.

答:
I have managed to make it perform the way I want it by adding

```<code>switch.state=1
</code>```

just before the segue from VC1 to VC2 is performed.

However, I don't think this is the most elegant solution as the button is still nil.

UPDATE:
I have figured out that the issue occurs as when it goes from VC1 to VC2 the VC1 becomes nil, when the VC2 is dismissed it becomes nil as well. Hence the crash. One solution is to use delegates.

VC1:

```<code>class FirstViewController: UIViewController,SecondViewControllerProtocol {

@IBOutlet var firstName: UITextField!
@IBOutlet var lastName: UITextField!
@IBOutlet var subscribeSwitch: UISwitch!

@IBAction func goToSecondVC(_ sender: Any) {
    let viewController = self.storyboard?.instantiateViewController(withIdentifier: String(describing: SecondViewController.self)) as! SecondViewController
    viewController.delegate = self
    self.present(viewController, animated: true, completion: nil)

}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func dismissViewController() {
    if let viewController = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController"){
        subscribeSwitch.isOn=true
    }
}

}
</code>```

VC2:

```<code>protocol SecondViewControllerProtocol {
func dismissViewController()
}

class SecondViewController: UIViewController {

var delegate:SecondViewControllerProtocol!

@IBAction func goBackToFirstVC(_ sender: Any) {
    self.dismiss(animated: true) {
        self.delegate!.dismissViewController()
    }
}

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}
</code>```

Title: NSButton state issues

Body:
I have managed to make it perform the way I want it by adding

switch.state=1

just before the segue from VC1 to VC2 is performed.

However, I don't think this is the most elegant solution as the button is still nil.

UPDATE:
I have figured out that the issue occurs as when it goes from VC1 to VC2 the VC1 becomes nil, when the VC2 is dismissed it becomes nil as well. Hence the crash. One solution is to use delegates.

VC1:

class FirstViewController: UIViewController,SecondViewControllerProtocol {

@IBOutlet var firstName: UITextField!
@IBOutlet var lastName: UITextField!
@IBOutlet var subscribeSwitch: UISwitch!

@IBAction func goToSecondVC(_ sender: Any) {
    let viewController = self.storyboard?.instantiateViewController(withIdentifier: String(describing: SecondViewController.self)) as! SecondViewController
    viewController.delegate = self
    self.present(viewController, animated: true, completion: nil)

}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func dismissViewController() {
    if let viewController = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController"){
        subscribeSwitch.isOn=true
    }
}

}

VC2:

protocol SecondViewControllerProtocol {
func dismissViewController()
}

class SecondViewController: UIViewController {

var delegate:SecondViewControllerProtocol!

@IBAction func goBackToFirstVC(_ sender: Any) {
    self.dismiss(animated: true) {
        self.delegate!.dismissViewController()
    }
}

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}


问:
'Variable is never used' warning in android studio
i have created a button(id- btnBank).
But there is waraning of variable 'btnBank'is never used.

code in activity_maps.xml

```<code><Button
        android:id="@+id/btnBank"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Bank" />
</code>```

code in MapsActivity.java

Button btnBank = (Button) findViewById(R.id.btnBank);

```<code>    btnRestaurant.setOnClickListener(new View.OnClickListener() {
        String Bank = "bank";
        @Override
        public void onClick(View v) {
            Log.d("onClick", "Button is Clicked");
            mMap.clear();
            String url = getUrl(latitude, longitude, Bank);
            Object[] DataTransfer = new Object[2];
            DataTransfer[0] = mMap;
            DataTransfer[1] = url;
            Log.d("onClick", url);
            GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
            getNearbyPlacesData.execute(DataTransfer);
            Toast.makeText(MapsActivity.this,"Nearby Bank", Toast.LENGTH_LONG).show();
        }
    });
</code>```

In first line of java code 'btnBank' appears grey

答: The code you apply is about btnRestaurant, but what the IDE warns is about btnBank. Remember that method findViewById doesn't belong to usage of a view.

Body:
i have created a button(id- btnBank).
But there is waraning of variable 'btnBank'is never used.

code in activity_maps.xml

<Button
        android:id="@+id/btnBank"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Bank" />

code in MapsActivity.java

Button btnBank = (Button) findViewById(R.id.btnBank);

    btnRestaurant.setOnClickListener(new View.OnClickListener() {
        String Bank = "bank";
        @Override
        public void onClick(View v) {
            Log.d("onClick", "Button is Clicked");
            mMap.clear();
            String url = getUrl(latitude, longitude, Bank);
            Object[] DataTransfer = new Object[2];
            DataTransfer[0] = mMap;
            DataTransfer[1] = url;
            Log.d("onClick", url);
            GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
            getNearbyPlacesData.execute(DataTransfer);
            Toast.makeText(MapsActivity.this,"Nearby Bank", Toast.LENGTH_LONG).show();
        }
    });

In first line of java code 'btnBank' appears grey


问:
format string in datetime c# to insert in MYSQL datetime column
I have code like this:

```<code>AutoParkDataDataContext Db = new AutoParkDataDataContext();
Dailyreport dailyRep = new Dailyreport();
string time = Convert.ToDateTime("10-10-2014 15:00:00");
dailyRep.order_time = time;
Db.Dailyreports.InsertOnSubmit(dailyRep);
Db.SubmitChanges();
</code>```

When I see it in the DailyReport table it shows me only the date ("10-10-2014 00:00:00:00"), so the time is ignored.  How could i fix it?
The column type is DateTime.

答:
```<code>DateTime dateTimeVariable = DateTime.Now;
string date = dateTimeVariable.ToString("yyyy-MM-dd H:mm:ss");
</code>```

The insert Statement will look kind of like this:

```<code>string InsertQuery   = "INSERT INTO table( `fieldName` ) VALUES ( '" + date + "' )";
</code>```

Body:
I have code like this:

AutoParkDataDataContext Db = new AutoParkDataDataContext();
Dailyreport dailyRep = new Dailyreport();
string time = Convert.ToDateTime("10-10-2014 15:00:00");
dailyRep.order_time = time;
Db.Dailyreports.InsertOnSubmit(dailyRep);
Db.SubmitChanges();

When I see it in the DailyReport table it shows me only the date ("10-10-2014 00:00:00:00"), so the time is ignored.  How could i fix it?
The column type is DateTime.

Body:
DateTime dateTimeVariable = DateTime.Now;
string date = dateTimeVariable.ToString("yyyy-MM-dd H:mm:ss");

The insert Statement will look kind of like this:

string InsertQuery   = "INSERT INTO table( `fieldName` ) VALUES ( '" + date + "' )";

ContentLicense: CC BY-SA 4.0


问:
Problems with insertion into an array

vm.categorias = function () {
  ConectaVagas('get', 'categorias').then(function (val) {
      vm.categorias = val;
      for (var a = 0; a < vm.categorias.length; a++) {
          console.log(a); // Here returns 0,1,2,3 ( number with categories )
          ConectaVagas('get', 'subcategoria', vm.categorias[a].id_categoria).then(function (val) { // List the subcategories related the categorie in loopfor
              vm.subAplicar = val;
              console.log(a); // Here returns the number 4 but i want returns 0, 1, 2, 3 and i do the insertion in arrayNova
              vm.categoria[a].arrayNova = vm.subAplicar;
          });
      }
  });
}```

I need to insert into the object vm.category [a] an array (arrayNova) with all subcategories, but I am not following :(

答:
You need to enclose in a new function the second call to ConnectVagas. Your variable a always prints to 4, because in javascript variables have a function scope. In order to correct this, create an anonymous function with parameters the current_item and a, so the value of a will not get overwritten because it creates a new function scope.</p>

```<code>vm.categorias = function() {
  ConectaVagas('get', 'categorias').then(function(val) {
    vm.categorias = val;
    for (var a = 0; a < vm.categorias.length; a++) {
      console.log(a); // Here returns 0,1,2,3 ( number with categories )
      var categorias_item = vm.categorias[a].id_categoria
      (function(categorias_item, a) {
        ConectaVagas('get', 'subcategoria', categorias_item.id_categoria).then(function(val) { // List the subcategories related the categorie in loopfor
          vm.subAplicar = val;
          console.log(a); // Here returns the number 4 but i want returns 0, 1, 2, 3 and i do the insertion in arrayNova
          categorias_item.arrayNova = vm.subAplicar;
        });
      })(categorias_item, a);
    }
  });
}
</code>```

Title: Problems with insertion into an array

Body:
vm.categorias = function () {
  ConectaVagas('get', 'categorias').then(function (val) {
      vm.categorias = val;
      for (var a = 0; a < vm.categorias.length; a++) {
          console.log(a); // Here returns 0,1,2,3 ( number with categories )
          ConectaVagas('get', 'subcategoria', vm.categorias[a].id_categoria).then(function (val) { // List the subcategories related the categorie in loopfor
              vm.subAplicar = val;
              console.log(a); // Here returns the number 4 but i want returns 0, 1, 2, 3 and i do the insertion in arrayNova
              vm.categoria[a].arrayNova = vm.subAplicar;
          });
      }
  });
}

I need to insert into the object vm.category [a] an array (arrayNova) with all subcategories, but I am not following :(

Body:
You need to enclose in a new function the second call to ConnectVagas. Your variable a always prints to 4, because in javascript variables have a function scope. In order to correct this, create an anonymous function with parameters the current_item and a, so the value of a will not get overwritten because it creates a new function scope.

vm.categorias = function() {
  ConectaVagas('get', 'categorias').then(function(val) {
    vm.categorias = val;
    for (var a = 0; a < vm.categorias.length; a++) {
      console.log(a); // Here returns 0,1,2,3 ( number with categories )
      var categorias_item = vm.categorias[a].id_categoria
      (function(categorias_item, a) {
        ConectaVagas('get', 'subcategoria', categorias_item.id_categoria).then(function(val) { // List the subcategories related the categorie in loopfor
          vm.subAplicar = val;
          console.log(a); // Here returns the number 4 but i want returns 0, 1, 2, 3 and i do the insertion in arrayNova
          categorias_item.arrayNova = vm.subAplicar;
        });
      })(categorias_item, a);
    }
  });
}


问:
Does using Node.JS to call PHP scripts degrade performance?
I have some legacy PHP wrappers that are used to call API's via simple curl requests.

I am creating a Node.JS application to call these wrappers and do some additional asynchronous processing.

However, does linking Node and PHP in this simple manner:

Node<->PHP<->External Server

degrade the speed/ performance of the code?

答:
Some, sure. Any time you add a layer, it impacts performance. However, in such a case, if it's degrading it enough to be noticed by your users, it means your infrastructure is under-resourced even with out that layer.

While there isn't enough information to know what the impact of your implementation is, and how much of your code would be running back through the legacy scripts, keep an eye on your performance metrics and make sure that things aren't getting hammered in any one area.

It could very well be that the PHP scripts themselves (if they're too legacy) would be a bottle neck even if they weren't being served via node.


问:
Finding max and count in one join
This problem might have an easy solution, but unfortunately, I can't figure it out.

I have two tables: Table A and Table B

```<code>Table A                         Table B
-------------------             ------------------------------
Id      NoOfItems               Id     itemNo         deliveredDate
X1          3                   X1       1              2017-07-01
                                X1       2              2017-07-02
                                X1       3              2017-07-03
</code>```

So what I need is to add the maximum deliveredDate of each Id to table A, but only if the number of delivered items in Table B equals NoOfItems in Table A.

So far I have written this query:

```<code>SELECT  *
FROM    A
OUTER APPLY
    (
    SELECT  TOP 1 *
    FROM    B
    WHERE   A.Id =B.Id
    ORDER BY
            B.DeliveredDate DESC
    ) s
    where A.NoOfItems= (select count(1) from B )
</code>```

)

答:
I would just do this with a simple join and group by:

```<code>select a.*,
       (case when b.cnt = a.noofitems then b.deliveredDate end)
from a join
     (select b.id, count(*) as cnt, max(deliveredDate) as deliveredDate
      from b
      group by b.id
     ) b;
     on a.id = b.id;
</code>```

It is unclear whether you want to assign the delivered date to all rows, with NULL values for the matching ones (as in the above query).  Or if you want to filter out the non-matching rows (in which case use where).

Title: Finding max and count in one join

Body:
This problem might have an easy solution, but unfortunately, I can't figure it out.

I have two tables: Table A and Table B

Table A                         Table B
-------------------             ------------------------------
Id      NoOfItems               Id     itemNo         deliveredDate
X1          3                   X1       1              2017-07-01
                                X1       2              2017-07-02
                                X1       3              2017-07-03

So what I need is to add the maximum deliveredDate of each Id to table A, but only if the number of delivered items in Table B equals NoOfItems in Table A.

So far I have written this query:

SELECT  *
FROM    A
OUTER APPLY
    (
    SELECT  TOP 1 *
    FROM    B
    WHERE   A.Id =B.Id
    ORDER BY
            B.DeliveredDate DESC
    ) s
    where A.NoOfItems= (select count(1) from B )

)

Body:
I would just do this with a simple join and group by:

select a.*,
       (case when b.cnt = a.noofitems then b.deliveredDate end)
from a join
     (select b.id, count(*) as cnt, max(deliveredDate) as deliveredDate
      from b
      group by b.id
     ) b;
     on a.id = b.id;

It is unclear whether you want to assign the delivered date to all rows, with NULL values for the matching ones (as in the above query).  Or if you want to filter out the non-matching rows (in which case use where).


问:
Intercepting method called from a method of the same object
Here's the situation:

```<code>/// <summary>
/// A business logic class.
/// </summary>
public class BusinessClassWithInterceptor : BusinessClass, IBusinessClass
{
    /// <summary>
    /// Initializes a new instance of the <see cref="BusinessClassWithoutInterceptor"/> class.
    /// </summary>
    /// <param name="logger">The logger.</param>
    public BusinessClassWithInterceptor(Logger logger)
        : base(logger)
    {
    }

    /// <summary>
    /// Displays all cows.
    /// </summary>
    public void DisplayAllCows()
    {
        this.Logger.Write("Displaying all cows:");
        var repository = new CowRepository();
        foreach (CowEntity cow in repository.GetAllCows())
        {
            this.Logger.Write("    " + cow);
        }
    }

    /// <summary>
    /// Inserts a normande.
    /// </summary>
    public void InsertNormande(int id, string name)
    {
        this.DisplayAllCows();

        var repository = new CowRepository();
        repository.InsertCow(new CowEntity { Id = id, Name = name, Origin = CowOrigin.Normandie });
    }
}
</code>```

With castle windsor, this class is configured to be intercepted with this interceptor:

```<code>/// <summary>
/// Interceptor for logging business methods.
/// </summary>
public class BusinessLogInterceptor : IInterceptor
{
    /// <summary>
    /// Intercepts the specified invocation.
    /// </summary>
    /// <param name="invocation">The invocation.</param>
    public void Intercept(IInvocation invocation)
    {
        Logger logger = ((IBusinessClass)invocation.InvocationTarget).Logger;

        var parameters = new StringBuilder();
        ParameterInfo[] methodParameters = invocation.Method.GetParameters();
        for (int index = 0; index < methodParameters.Length; index++)
        {
            parameters.AppendFormat("{0} = {1}", methodParameters[index].Name, invocation.Arguments[index]);
            if (index < methodParameters.Length - 1)
            {
                parameters.Append(", ");
            }
        }

        logger.Format("Calling {0}( {1} )", invocation.Method.Name, parameters.ToString());
        invocation.Proceed();
        logger.Format("Exiting {0}", invocation.Method.Name);
    }
}
</code>```

The issue takes place during the call to InsertNormande.
The call to InsertNormande is well intercepted, but the call to DisplayAllCows in InsertNormande is not intercepted...

It really bothers me.

Is there a way to achieve interception in this scenario ?

答:
I don't think there's an easy way of doing it... method calls that are internal to the class can't be intercepted, since they don't go through the proxy.

You could achieve logging of all methods by other means, such as an AOP framework like PostSharp

ContentLicense: CC BY-SA 2.5

Body:
Here's the situation:

///
/// A business logic class.
///
public class BusinessClassWithInterceptor : BusinessClass, IBusinessClass
{
    ///
    /// Initializes a new instance of the <see cref="BusinessClassWithoutInterceptor"/> class.
    ///
    /// <param name="logger">The logger.</param>
    public BusinessClassWithInterceptor(Logger logger)
        : base(logger)
    {
    }

    ///
    /// Displays all cows.
    ///
    public void DisplayAllCows()
    {
        this.Logger.Write("Displaying all cows:");
        var repository = new CowRepository();
        foreach (CowEntity cow in repository.GetAllCows())
        {
            this.Logger.Write("    " + cow);
        }
    }

    ///
    /// Inserts a normande.
    ///
    public void InsertNormande(int id, string name)
    {
        this.DisplayAllCows();

        var repository = new CowRepository();
        repository.InsertCow(new CowEntity { Id = id, Name = name, Origin = CowOrigin.Normandie });
    }
}

With castle windsor, this class is configured to be intercepted with this interceptor:

///
/// Interceptor for logging business methods.
///
public class BusinessLogInterceptor : IInterceptor
{
    ///
    /// Intercepts the specified invocation.
    ///
    /// <param name="invocation">The invocation.</param>
    public void Intercept(IInvocation invocation)
    {
        Logger logger = ((IBusinessClass)invocation.InvocationTarget).Logger;

        var parameters = new StringBuilder();
        ParameterInfo[] methodParameters = invocation.Method.GetParameters();
        for (int index = 0; index < methodParameters.Length; index++)
        {
            parameters.AppendFormat("{0} = {1}", methodParameters[index].Name, invocation.Arguments[index]);
            if (index < methodParameters.Length - 1)
            {
                parameters.Append(", ");
            }
        }

        logger.Format("Calling {0}( {1} )", invocation.Method.Name, parameters.ToString());
        invocation.Proceed();
        logger.Format("Exiting {0}", invocation.Method.Name);
    }
}

The issue takes place during the call to InsertNormande.
The call to InsertNormande is well intercepted, but the call to DisplayAllCows in InsertNormande is not intercepted...

It really bothers me.

Is there a way to achieve interception in this scenario ?


问:
How to refresh laravel template and disable caching?
Hey guys i am just playing around with laravel and bascally have the following view:

```<code><!doctype html>
<html class="no-js" lang="">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title>Title</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="apple-touch-icon" href="apple-touch-icon.png">
        <!-- Place favicon.ico in the root directory -->
        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/style.css">
        <style>
            h1 {
                color: #727272;
                font: bold 2em/1.4 verdana;
            }
            .nav-items {
                padding: 0;
                margin: 0;
                list-style-type: none;
            }

            .nav-items li {
                display: inline-block;
                margin-right: 10px;
                padding: 1em 1.5em;
                border: 1px solid #ccc;
                background-color: #eee;
                -webkit-box-shadow: 0 0 2px rgba(0,0,0,.2);
                box-shadow: 0 0 2px rgba(0,0,0,.2);
                color: #727272;
                text-shadow: 0 0 1px rgba(255,255,255,1);
            }
        </style>

    </head>
    <body>
        <!--[if lt IE 8]>
<p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]-->

           <ul class="nav-items">

               @foreach($categories as $category)

                   <li>
                       Category id is {{ $category-> id }}
                   </li>

               @endforeach

            </ul>

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
        <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.3.min.js"><\/script>')</script>

    </body>
</html>
</code>```

Now suppose i change the below code:

```<code><ul class="nav-items">

               @foreach($categories as $category)

                   <li>
                       Category id is {{ $category-> id }}
                   </li>

               @endforeach

 </ul>
</code>```

To the following:

```<code><ul class="nav-items">

               @foreach($categories as $category)

                   <li>
                       Product id is {{ $category-> id }} // I have only changed the word "Categories" to "Products"
                   </li>

               @endforeach

 </ul>
</code>```

I have only changed the word Categories to Products , but when my view loads in the browser i still see the word "Category" instead of "Products" .

The only current solution i have is to change the view file name and than change the view name in the controller, which is quite inconvenient ! , Is there another solution to this problem ? Is this something to do with caching ?

P.S. i have seen a couple of threads on this topic on SO and they did't solve my problem.

答:
I encountered the same problem.
I was using laragon apache server.
What I did is I turned off my apache server and started using the php artisan serve command. It seems the apache is responsible for caching my files. :)</p>

Body:
Hey guys i am just playing around with laravel and bascally have the following view:

<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title>Title</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="apple-touch-icon" href="apple-touch-icon.png">

        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/style.css">

               @foreach($categories as $category)

                       Category id is {{ $category-> id }}

               @endforeach

Now suppose i change the below code:

               @foreach($categories as $category)

                       Category id is {{ $category-> id }}

               @endforeach

To the following:

               @foreach($categories as $category)

                       Product id is {{ $category-> id }} // I have only changed the word "Categories" to "Products"

               @endforeach

I have only changed the word Categories to Products , but when my view loads in the browser i still see the word "Category" instead of "Products" .

The only current solution i have is to change the view file name and than change the view name in the controller, which is quite inconvenient ! , Is there another solution to this problem ? Is this something to do with caching ?

P.S. i have seen a couple of threads on this topic on SO and they did't solve my problem.


问:
Parsing xml response in JAVA
I have a xml file which looks as below. I want to parse this xml and display the result as PASS if <PROCESSED>1</PROCESSED> is having the value as 1 and the <STATE>Finished</STATE> is showing as Finished.

```<code><?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE SCAN_LIST_OUTPUT SYSTEM "https://qualysapi.qualys.com/api/2.0/fo/scan/scan_list_output.dtd">
<SCAN_LIST_OUTPUT>
    <RESPONSE>
        <DATETIME>2017-06-12T07:28:46Z</DATETIME>
        <SCAN_LIST>
            <SCAN>
                <ID>3332486</ID>
                <REF>compliance/1347341337.35943</REF>
                <TYPE>Scheduled</TYPE>
                <TITLE><![CDATA[MY PC Scan]]></TITLE>
                <USER_LOGIN>USER</USER_LOGIN>
                <LAUNCH_DATETIME>2017-06-13T07:30:09Z</LAUNCH_DATETIME>
                <DURATION>00:06:29</DURATION>
                <PROCESSED>1</PROCESSED>
                <STATUS>
                    <STATE>Finished</STATE>
                </STATUS>
                <TARGET><![CDATA[10.10.25.50]]></TARGET>
            </SCAN>
        </SCAN_LIST>
    </RESPONSE>
</SCAN_LIST_OUTPUT>
</code>```

Please let me know how this can be done using Java.

答:
Using XPath and VTD-XML it is a 10-line app.</p>

```<code>import com.ximpleware.*;

public class testData {

    public static void main(String[] args) throws VTDException {
        // TODO Auto-generated method stub
        VTDGen vg = new VTDGen();
        if (!vg.parseFile("d:\\xml\\scan_input.xml", false))
            return ;
        VTDNav vn = vg.getNav();
        AutoPilot ap = new AutoPilot(vn);
        String xpath = "/SCAN_LIST_OUTPUT/RESPONSE/SCAN_LIST/SCAN/PROCESSED=1 "+
                       "and /SCAN_LIST_OUTPUT/RESPONSE/SCAN_LIST/SCAN/STATUS/STATE='Finished' ";
        ap.selectXPath(xpath);
        if (ap.evalXPathToBoolean())
            System.out.println("pass");
    }

}
</code>```

Title: Parsing xml response in JAVA

Body:
I have a xml file which looks as below. I want to parse this xml and display the result as PASS if <PROCESSED>1</PROCESSED> is having the value as 1 and the <STATE>Finished</STATE> is showing as Finished.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE SCAN_LIST_OUTPUT SYSTEM "https://qualysapi.qualys.com/api/2.0/fo/scan/scan_list_output.dtd">
<SCAN_LIST_OUTPUT>
    <RESPONSE>
        <DATETIME>2017-06-12T07:28:46Z</DATETIME>
        <SCAN_LIST>
            <SCAN>
                <ID>3332486</ID>
                <REF>compliance/1347341337.35943</REF>
                <TYPE>Scheduled</TYPE>
                <TITLE><![CDATA[MY PC Scan]]></TITLE>
                <USER_LOGIN>USER</USER_LOGIN>
                <LAUNCH_DATETIME>2017-06-13T07:30:09Z</LAUNCH_DATETIME>
                <DURATION>00:06:29</DURATION>
                <PROCESSED>1</PROCESSED>
                <STATUS>
                    <STATE>Finished</STATE>
                </STATUS>
                <TARGET><![CDATA[10.10.25.50]]></TARGET>
            </SCAN>
        </SCAN_LIST>
    </RESPONSE>
</SCAN_LIST_OUTPUT>

Please let me know how this can be done using Java.

Body:
Using XPath and VTD-XML it is a 10-line app.

import com.ximpleware.*;

public class testData {

    public static void main(String[] args) throws VTDException {
        // TODO Auto-generated method stub
        VTDGen vg = new VTDGen();
        if (!vg.parseFile("d:\\xml\\scan_input.xml", false))
            return ;
        VTDNav vn = vg.getNav();
        AutoPilot ap = new AutoPilot(vn);
        String xpath = "/SCAN_LIST_OUTPUT/RESPONSE/SCAN_LIST/SCAN/PROCESSED=1 "+
                       "and /SCAN_LIST_OUTPUT/RESPONSE/SCAN_LIST/SCAN/STATUS/STATE='Finished' ";
        ap.selectXPath(xpath);
        if (ap.evalXPathToBoolean())
            System.out.println("pass");
    }

}


问:
Best way to implement ArrayList in Android Studio
i have 30 items in ArrayList and its implement in Spinner, i placed it in java file like this

```<code>ArrayList<String> listProblemSolving = new ArrayList<>();
    listProblemSolving.add("List1");
    listProblemSolving.add("List2");
    listProblemSolving.add("List3");
    listProblemSolving.add("List4");
    listProblemSolving.add("List5");
    listProblemSolving.add("List6");
    listProblemSolving.add("List7");
    ...
    ArrayAdapter<String> adapterProblemSolving = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_dropdown_item, listProblemSolving);
</code>```

and i implement in spinner like this

```<code>sp.setAdapter(adapterProblemSolving);
</code>```

The question is, can i store the list item in strings file?
And is there any simply way if i want to give different action to item list, for example i try this one

```<code>    sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
             if (position == 1)
                // do something

             if (position == 2)
                // do something

             ...
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });
</code>```

Thank you and sorry i you found this as dupplicate question.

答:
Well, if your entries are simple strings then you can try this

In your strings.xml

```<code><string-array name="data_array">
   <item>value 1</item>
   <item>value 2</item>
   <item>value 3</item>
 </string-array>
</code>```

In your xml layout for spinner

```<code><Spinner
 ...
 ...
android:entries="@array/data_array" />
</code>```

Body:
i have 30 items in ArrayList and its implement in Spinner, i placed it in java file like this

ArrayList<String> listProblemSolving = new ArrayList<>();
    listProblemSolving.add("List1");
    listProblemSolving.add("List2");
    listProblemSolving.add("List3");
    listProblemSolving.add("List4");
    listProblemSolving.add("List5");
    listProblemSolving.add("List6");
    listProblemSolving.add("List7");
    ...
    ArrayAdapter<String> adapterProblemSolving = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_dropdown_item, listProblemSolving);

and i implement in spinner like this

sp.setAdapter(adapterProblemSolving);

The question is, can i store the list item in strings file?
And is there any simply way if i want to give different action to item list, for example i try this one

    sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
             if (position == 1)
                // do something

             if (position == 2)
                // do something

             ...
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

Thank you and sorry i you found this as dupplicate question.

Body:
Well, if your entries are simple strings then you can try this

In your strings.xml

<string-array name="data_array">
   <item>value 1</item>
   <item>value 2</item>
   <item>value 3</item>
 </string-array>

In your xml layout for spinner

<Spinner
 ...
 ...
android:entries="@array/data_array" />


问:
Swift remove reference to UIView
I want to completely remove a reference to a UIView when it is tapped (it is a subview.

```<code>@IBAction private func handleTap(_ sender: UITapGestureRecognizer) {
    if (delegate != nil) {
        delegate?.imageWasTapped(imageView.image!, photoURL: photoURL!)
        self.removeFromSuperview()
    }
    print ("tap")
}
</code>```

removeFromSuperview() seems to be insufficient to completely remove the instance (from what I've read), so would like to

```<code>self = nil
</code>```

but of course self is immutable.

I tried to pass the value to my superview as an inout argument, but of course self is still immutable.

```<code>        delegate?.imageWasTapped(imageView.image!, photoURL: photoURL!, imageView: self)
</code>```

Is removeFromSumerview() sufficent to deallocate a UIView from memory, or how is this best done?

答: You can weak reference to that UIView. Then the UIView will be nil with ARC after you removed it by using removeFromSuperview.

Title: Swift remove reference to UIView

Body:
I want to completely remove a reference to a UIView when it is tapped (it is a subview.

@IBAction private func handleTap(_ sender: UITapGestureRecognizer) {
    if (delegate != nil) {
        delegate?.imageWasTapped(imageView.image!, photoURL: photoURL!)
        self.removeFromSuperview()
    }
    print ("tap")
}

removeFromSuperview() seems to be insufficient to completely remove the instance (from what I've read), so would like to

self = nil

but of course self is immutable.

I tried to pass the value to my superview as an inout argument, but of course self is still immutable.

        delegate?.imageWasTapped(imageView.image!, photoURL: photoURL!, imageView: self)

Is removeFromSumerview() sufficent to deallocate a UIView from memory, or how is this best done?


问:
PyEphem: AlwaysUpError for the Sun occurs in a location where this shouldn't happen
```<code>import ephem
rwth = ephem.Observer()
rwth.lat = '50.8'
rwth.long = '6.1'
rwth.horizon = '-18'
rwth.next_setting(ephem.Sun())
</code>```

This will result in an error

Traceback (most recent call last):   File "", line 1, in
     File
  "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/ephem/init.py",
  line 498, in next_setting
      return self._riset_helper(body, start, use_center, False, False)   File
  "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/ephem/init.py",
  line 470, in _riset_helper
      d1 = visit_antitransit()   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/ephem/init.py",
  line 418, in visit_antitransit
      % (body.name, d)) ephem.AlwaysUpError: 'Sun' is still above the horizon at 2017/7/3 23:39:58

However, at this location, the sun should definitely reach astronomical twilight (which -18 degrees corresponds to). Do you know what the problem is?

答:
At that latitude at this date (very early July), the Sun never does, in fact, reach –18° altitude, because 50.8° north is too close to the Arctic Circle. On the solstice itself — around June 21 each year — the Sun is at 23.5° north, which, if we think through the consequences, means:

An observer at the North Pole would see the Sun circle the sky at 23.5° above the horizon all day.

An observer at 90° – 23.5° = 66.5° would see the Sun spend the whole day on the horizon, making a circle along its circumference.

An observer would have to be at 90° – 23.5° – 18° = 48.5° latitude or even further south in order for the Sun to dip low enough for them to observe the level of darkness defined as astronomical twilight.

Even though the current date is a few days after the equinox, the Sun has not yet retreated far enough from its farthest-north latitude to begin to bring astronomical twilights to the location you are asking about. PyEphem’s answer looks correct here.

Body:
import ephem
rwth = ephem.Observer()
rwth.lat = '50.8'
rwth.long = '6.1'
rwth.horizon = '-18'
rwth.next_setting(ephem.Sun())

This will result in an error

Traceback (most recent call last):   File "", line 1, in
     File
  "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/ephem/init.py",
  line 498, in next_setting
      return self._riset_helper(body, start, use_center, False, False)   File
  "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/ephem/init.py",
  line 470, in _riset_helper
      d1 = visit_antitransit()   File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/ephem/init.py",
  line 418, in visit_antitransit
      % (body.name, d)) ephem.AlwaysUpError: 'Sun' is still above the horizon at 2017/7/3 23:39:58

However, at this location, the sun should definitely reach astronomical twilight (which -18 degrees corresponds to). Do you know what the problem is?


问:
Laravel 5.4 change password
I am currently working on the profile page wherein the user can change its password. I created a new function changePassword() in the UserController

```<code>public function changePassword(Request $request, User $employee) {
    $validator = Validator::make($data, [
        'password' => 'required|string|min:6|confirmed',
        'password_confirmation' => 'required|string|min:6|same:password'
    ]);

    if ($validator->fails()) {
        Session::flash('error', "Fill-out the form correctly. Try again!");
        return redirect()->back()->withErrors($validator);
    }

    $employee->password = bcrypt($request->password);
    $employee->save();
    return view('users.show', ['employee'=>$employee]);
}
</code>```

I created this new route in web.php above the resource route of the User model

```<code>Route::put('users/{user}', 'UserController@changePassword')->name('users.changePassword');
</code>```

I am getting a MethodNotAllowedHttpException every time I click the submit button. I think the problem is the route but I am not sure. Is there a Laravel functionality aside the one that sends email, because I want the users to change its password without using email. Thanks!

Here is my form

```<code>{!! Form::model($employee, ['method'=>'PUT', 'route'=>['users.changePassword', $employee]]) !!}
</code>```

答:
You need to add PUT http verb in your form field. If you are using laravelcollective:

```<code>{!! Form::model($employee, ['method' => 'put','route' =>
['users.changePassword']]) !!}

--- Your Fields Code will go here ----

{!! Form::close() !!}
</code>```

Or

```<code><form action="your-url" method="POST">

 {{ method_field('PUT') }}

</form>
</code>```

Title: Laravel 5.4 change password

Body:
I am currently working on the profile page wherein the user can change its password. I created a new function changePassword() in the UserController

public function changePassword(Request $request, User $employee) {
    $validator = Validator::make($data, [
        'password' => 'required|string|min:6|confirmed',
        'password_confirmation' => 'required|string|min:6|same:password'
    ]);

    if ($validator->fails()) {
        Session::flash('error', "Fill-out the form correctly. Try again!");
        return redirect()->back()->withErrors($validator);
    }

    $employee->password = bcrypt($request->password);
    $employee->save();
    return view('users.show', ['employee'=>$employee]);
}

I created this new route in web.php above the resource route of the User model

Route::put('users/{user}', 'UserController@changePassword')->name('users.changePassword');

I am getting a MethodNotAllowedHttpException every time I click the submit button. I think the problem is the route but I am not sure. Is there a Laravel functionality aside the one that sends email, because I want the users to change its password without using email. Thanks!

Here is my form

{!! Form::model($employee, ['method'=>'PUT', 'route'=>['users.changePassword', $employee]]) !!}

Body:
You need to add PUT http verb in your form field. If you are using laravelcollective:

{!! Form::model($employee, ['method' => 'put','route' =>
['users.changePassword']]) !!}

--- Your Fields Code will go here ----

{!! Form::close() !!}

Or

<form action="your-url" method="POST">

 {{ method_field('PUT') }}

</form>


问:
Training a neural network to compute 'XOR' in scikit-learn
I am trying to learn how to use scikit-learn's MLPClassifier. For a very simple example, I thought I'd try just to get it to learn how to compute the XOR function, since I have done that one by hand as an exercise before.

However, it just spits out zeros after I try to fit the model.

```<code>xs = np.array([
    0, 0,
    0, 1,
    1, 0,
    1, 1
]).reshape(4, 2)

ys = np.array([0, 1, 1, 0]).reshape(4,)

model = sklearn.neural_network.MLPClassifier(
    activation='logistic', max_iter=10000, hidden_layer_sizes=(4,2))
model.fit(xs, ys)

print('score:', model.score(xs, ys)) # outputs 0.5
print('predictions:', model.predict(xs)) # outputs [0, 0, 0, 0]
print('expected:', np.array([0, 1, 1, 0]))
</code>```

I put my code in a jupyter notebook on github as well https://gist.github.com/zrbecker/6173ac01ed30be4eea9cc96e21f4896f

Why can't scikit-learn come to a solution, when I can show explicitly that one exists? Is the cost function getting stuck in a local minimum? Is there some kind of regularization happening on the parameters that force them to stay close to 0? The parameters I used were reasonably large (i.e. -30 to 30).

答:
It appears a logistic activation is the root cause here.

Change your activation to either tanh or relu (my favourite). Demo:

```<code>model = sklearn.neural_network.MLPClassifier(
    activation='relu', max_iter=10000, hidden_layer_sizes=(4,2))
model.fit(xs, ys)
</code>```

Outputs for this model:

```<code>score: 1.0
predictions: [0 1 1 0]
expected: [0 1 1 0]
</code>```

It's always a good idea to experiment with different network configurations before you settle on the best one or give up altogether.

Body:
I am trying to learn how to use scikit-learn's MLPClassifier. For a very simple example, I thought I'd try just to get it to learn how to compute the XOR function, since I have done that one by hand as an exercise before.

However, it just spits out zeros after I try to fit the model.

xs = np.array([
    0, 0,
    0, 1,
    1, 0,
    1, 1
]).reshape(4, 2)

ys = np.array([0, 1, 1, 0]).reshape(4,)

model = sklearn.neural_network.MLPClassifier(
    activation='logistic', max_iter=10000, hidden_layer_sizes=(4,2))
model.fit(xs, ys)

print('score:', model.score(xs, ys)) # outputs 0.5
print('predictions:', model.predict(xs)) # outputs [0, 0, 0, 0]
print('expected:', np.array([0, 1, 1, 0]))

I put my code in a jupyter notebook on github as well https://gist.github.com/zrbecker/6173ac01ed30be4eea9cc96e21f4896f

Why can't scikit-learn come to a solution, when I can show explicitly that one exists? Is the cost function getting stuck in a local minimum? Is there some kind of regularization happening on the parameters that force them to stay close to 0? The parameters I used were reasonably large (i.e. -30 to 30).

Body:
It appears a logistic activation is the root cause here.

Change your activation to either tanh or relu (my favourite). Demo:

model = sklearn.neural_network.MLPClassifier(
    activation='relu', max_iter=10000, hidden_layer_sizes=(4,2))
model.fit(xs, ys)

Outputs for this model:

score: 1.0
predictions: [0 1 1 0]
expected: [0 1 1 0]

It's always a good idea to experiment with different network configurations before you settle on the best one or give up altogether.


问:
How to migrate data after upgrading from Azure mobile service to app service?
Scenario: I have a migrated Azure mobile service, with data tables, that I would like to upgrade to an Azure app service. I have followed  this upgrade documentation. I have copied the connection string and the application name as described in the documentation.

Expectations: What I would like to see are the same data tables from my mobile service in my new app service's Easy Tables. I would also like these to map to the same tables in the same database.

Problem: The problem is however that I don't see the data tables from my mobile service in my new app service (in Easy Tables).

More info: I have also tried to recreate the tables in the new app service. But if I create a new table in easy tables it creates a new table in the database, probably because the created table name does not match the schema from my mobile service? My mobile service uses the following schema: [database name].[mobileservice name].[table name]. The app service uses this schema: [database name].[table name].

So my question is: does anybody know how to migrate the data tables from a migrated mobile service to an app service?

答:
Expectations: What I would like to see are the same data tables from my mobile service in my new app service's Easy Tables. I would also like these to map to the same tables in the same database.

AFAIK, when using Easy Tables, you could add your new table or existing table with the same name, then it would help you to build the node.js backend for your added tables automatically.

Note:

Table names can contain only letters, numbers, and underscores. The name must begin with a letter or a underscore character.

You could leverage "DEVELOPMENT TOOLS > App Service Editor (Preview)" of your mobile app service for checking your backend as follows:

So my question is: does anybody know how to migrate the data tables from a migrated mobile service to an app service?

According to the upgrade documentation you provided, I assumed that you are developing the C# backend, you just need to refer to Updating the server project, then deploy your modified project to your new app service.

Moreover, I would recommend that you could navigate to "DEPLOYMENT > Quickstart" of your app service, then download the C# backend project to be familiar with the new server project before you updating your mobile services backend project. Additionally, I would prefer creating a new mobile app project, then create the table controllers and migrate the logical code from your mobile service project. For more details about creating table controllers, you could refer to adrian hall's book Implementing Table Controllers.


问:
Null set property with innerHTML
I have been trying to merge the data from openweathermap's api together with google map's api. However, whenever I try to get my data down from the api using innerHTML, it shows that Uncaught TypeError: Cannot set property 'innerHTML' of null.

Javascript

var map;
var weather;
var temp;
var APPID = 'e9e239c6585f081bee7b0d7f6045a53f';

function updateByCity(q) {
  var url = "http://api.openweathermap.org/data/2.5/weather?q={" +
    q +
    "}&APPID=" + APPID;
  sendRequest(url);
}

function sendRequest(url) {
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      var data = JSON.parse(xmlhttp.responseText);
      var weather = {};
      weather.temp = data.main.temp;

      update(weather);
    }
  };
  xmlhttp.open("GET", url, true);
  xmlhttp.send();
}

function update(weather) {
  temp.innerHTML = weather.temp;
}

window.onload = function() {
  temp = document.getElementById("temperature");
  var weather = {};
  weather.temp = "35";

  update(weather);
}

function initMap() {
  var KL = {
    lat: 3.1390,
    lng: 101.6869
  };
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 6,
    center: {
      lat: 4.444997,
      lng: 106.554199
    }
  });

  var marker = new google.maps.Marker({
    position: KL,
    map: map
  });

  var contentString = '
' +
    '
' +
    '
' +
    '
Kuala Lumpur
' +
    '
' +
    '
Temperature: ' + temp + '
' +
    '
' +
    '
';

  var infowindow = new google.maps.InfoWindow({
    content: contentString
  });
  marker.addListener('click', function() {
    infowindow.open(map, marker);
  });

}```
</div>
</div>
</p>

<p><strong>HTML</strong></p>

<pre class="lang-html prettyprint-override"><code><!doctype>
<html>

<head>
  <script src="mapJS.js"></script>
  <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBuhL2_brcvjW12heXCPV8G-lXd7Kmue84&callback=initMap">
  </script>
  <title>Simple Map</title>
  <meta name="viewport" content="initial-scale=1.0">
  <meta charset="utf-8">
  <style>
    #map {
      height: 100%;
    }

    html,
    body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
  </style>
  <div id="map"></div>
</head>

</html>
</code>```

答:
In your onload function, you're targeting the HTML ID temperature but it doesn't exist, I think you want to target map

```<code>window.onload = function() {
  temp = document.getElementById("map");
  var weather = {};
  weather.temp = "35";

  update(weather);
}
</code>```

Title: Null set property with innerHTML

Body:
I have been trying to merge the data from openweathermap's api together with google map's api. However, whenever I try to get my data down from the api using innerHTML, it shows that Uncaught TypeError: Cannot set property 'innerHTML' of null.

Javascript

var map;
var weather;
var temp;
var APPID = 'e9e239c6585f081bee7b0d7f6045a53f';

function updateByCity(q) {
  var url = "http://api.openweathermap.org/data/2.5/weather?q={" +
    q +
    "}&APPID=" + APPID;
  sendRequest(url);
}

function sendRequest(url) {
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      var data = JSON.parse(xmlhttp.responseText);
      var weather = {};
      weather.temp = data.main.temp;

      update(weather);
    }
  };
  xmlhttp.open("GET", url, true);
  xmlhttp.send();
}

function update(weather) {
  temp.innerHTML = weather.temp;
}

window.onload = function() {
  temp = document.getElementById("temperature");
  var weather = {};
  weather.temp = "35";

  update(weather);
}

function initMap() {
  var KL = {
    lat: 3.1390,
    lng: 101.6869
  };
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 6,
    center: {
      lat: 4.444997,
      lng: 106.554199
    }
  });

  var marker = new google.maps.Marker({
    position: KL,
    map: map
  });

  var contentString = '
' +
    '
' +
    '
' +
    '
Kuala Lumpur
' +
    '
' +
    '
Temperature: ' + temp + '
' +
    '
' +
    '
';

  var infowindow = new google.maps.InfoWindow({
    content: contentString
  });
  marker.addListener('click', function() {
    infowindow.open(map, marker);
  });

}

HTML

<!doctype>

  <title>Simple Map</title>
  <meta name="viewport" content="initial-scale=1.0">
  <meta charset="utf-8">

Body:
In your onload function, you're targeting the HTML ID temperature but it doesn't exist, I think you want to target map

window.onload = function() {
  temp = document.getElementById("map");
  var weather = {};
  weather.temp = "35";

  update(weather);
}


问:
all strings of length k that can be formed from a set of n characters
This question has been asked for other languages but I'm looking for the most idiomatic way to find all strings of length k that can be formed from a set of n characters in R

Example input and output:

```<code>input <- c('a', 'b')

output <- c('aa', 'ab', 'ba', 'bb')
</code>```

答:
```<code>m <- outer(input, input, paste, sep="")
output = as.vector(m)

## "aa" "ba" "ab" "bb"
</code>```

Body:
This question has been asked for other languages but I'm looking for the most idiomatic way to find all strings of length k that can be formed from a set of n characters in R

Example input and output:

input <- c('a', 'b')

output <- c('aa', 'ab', 'ba', 'bb')


问:
How to check asset pipeline is working properly without deploying
Is it possible to check that asset pipeline related code and configuration is working without deploying?

Deploying to the testing server takes a couple of minutes, which is time I'd rather not waste.

Should I just run the application in production mode, or keep it in development mode and change asset pipeline related configuration?

Are there any risks that it will mess things up when running the application in development mode in the future?

I'm running on Rails 4.1.

答:
It shouldn't mess up things.

You can safely run RAILS_ENV=development rake assets:precompile to test things.

Do remember to do the following changes before you run the above :

Set config.assets.debug = false in your development.rb file. This will tell Sprockets to concatenate and run the necessary preprocessors on all assets.

Ensure config.assets.digest is set to true

Set Rails.application.config.assets.precompile += %w( search.js ) in config/initializers/assets.rb if you have additional assets that aren’t already referenced in your application.js or application.css.


问:
yii2 : cannot be displayed because it contains an error
This is my controller:

```<code> public function actionFind($id, $c, $t, $width = false, $height = false)
      {

        $image = \app\models\Picture::finding($id, $c, $t, $width, $height);

        \Yii::$app->response->format = yii\web\Response::FORMAT_RAW;
        \Yii::$app->response->headers->add('content-type', 'image/jpeg');
        \Yii::$app->response->data = file_get_contents($image);
        return \Yii::$app->response;

        }
</code>```

This is my model:

```<code>public static function finding($id, $c, $t, $width = false, $height = false)
        {

        $query = new Query;
        // compose the query
        $query->select('*')
                ->from($t)
                ->where("Active=1 AND Code = $id")
                ->limit(1);
        $query->orderBy('Code desc');
        // build and execute the query
        $rows = $query->all();
        // alternatively, you can create DB command and execute it
        $command = $query->createCommand();
        // $command->sql returns the actual SQL
        $rows = $command->queryAll();

        if (isset($rows[0]["$c"]))
            {

            return $image = "data:image/jpeg;base64," . base64_encode($rows[0]["$c"]);
            }

        }
</code>```

and this is my error:

```<code>cannot be displayed because it contains an error
</code>```

my image save in database!!

Picture : longblob

in another project with database this code is run correct:

```<code>header("Content-Type: image/jpeg");
if (strlen($image) == 0 || $id == "")
    {
    if (!$w)
        $w = $w1;
    if (!$h)
        $h = $h1;
    if (!$w)
        $w = 120;
    if (!$h)
        $h = 140;
    $dst = imagecreatetruecolor($w, $h);

    $gray = imagecolorallocate($dst, 255, 255, 255);
    imagefill($dst, 1, 1, $gray);
    if ($q)
        imagejpeg($dst, NULL, $q);
    else
        imagejpeg($dst);
    }
</code>```

答:
As I mentioned in the comments, I used your code to display an image, here is an example:

```<code>/**
 * Displays homepage.
 *
 * @return string
 */
public function actionIndex()
{
        \Yii::$app->response->format = yii\web\Response::FORMAT_RAW;
        \Yii::$app->response->headers->add('content-type', 'image/png');
        \Yii::$app->response->data = file_get_contents("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4
    9TXL0Y4OHwAAAABJRU5ErkJggg==");
        return \Yii::$app->response;
}
</code>```

Eventhough the data is saved in the database, when you retrieve it you just encode it in a 64-base string, which is something similar to the hardcoded string I used. Again, check your data.

Note: I also used the image/jpeg header with the png image and it worked, not recommended though

Body:
This is my controller:

 public function actionFind($id, $c, $t, $width = false, $height = false)
      {

        $image = \app\models\Picture::finding($id, $c, $t, $width, $height);

        \Yii::$app->response->format = yii\web\Response::FORMAT_RAW;
        \Yii::$app->response->headers->add('content-type', 'image/jpeg');
        \Yii::$app->response->data = file_get_contents($image);
        return \Yii::$app->response;

        }

This is my model:

public static function finding($id, $c, $t, $width = false, $height = false)
        {

        $query = new Query;
        // compose the query
        $query->select('*')
                ->from($t)
                ->where("Active=1 AND Code = $id")
                ->limit(1);
        $query->orderBy('Code desc');
        // build and execute the query
        $rows = $query->all();
        // alternatively, you can create DB command and execute it
        $command = $query->createCommand();
        // $command->sql returns the actual SQL
        $rows = $command->queryAll();

        if (isset($rows[0]["$c"]))
            {

            return $image = "data:image/jpeg;base64," . base64_encode($rows[0]["$c"]);
            }

        }

and this is my error:

cannot be displayed because it contains an error

my image save in database!!

Picture : longblob

in another project with database this code is run correct:

header("Content-Type: image/jpeg");
if (strlen($image) == 0 || $id == "")
    {
    if (!$w)
        $w = $w1;
    if (!$h)
        $h = $h1;
    if (!$w)
        $w = 120;
    if (!$h)
        $h = 140;
    $dst = imagecreatetruecolor($w, $h);

    $gray = imagecolorallocate($dst, 255, 255, 255);
    imagefill($dst, 1, 1, $gray);
    if ($q)
        imagejpeg($dst, NULL, $q);
    else
        imagejpeg($dst);
    }

Body:
As I mentioned in the comments, I used your code to display an image, here is an example:

/**
 * Displays homepage.
 *
 * @return string
 */
public function actionIndex()
{
        \Yii::$app->response->format = yii\web\Response::FORMAT_RAW;
        \Yii::$app->response->headers->add('content-type', 'image/png');
        \Yii::$app->response->data = file_get_contents("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4
    9TXL0Y4OHwAAAABJRU5ErkJggg==");
        return \Yii::$app->response;
}

Eventhough the data is saved in the database, when you retrieve it you just encode it in a 64-base string, which is something similar to the hardcoded string I used. Again, check your data.

Note: I also used the image/jpeg header with the png image and it worked, not recommended though


问:
Error while connecting to sftp using shell script
I am getting following error while trying to connect to a sftp server:-

ncftpput: cannot open
  http://mydomain.com:
  unknown host.

Code which I am using is as following:-

FTPU="username" # ftp login name

FTPP="password" # ftp password

FTPS="http://mydomain.com"#
    remote ftp server

FTPF="/home" # remote ftp server
  directory for $FTPU> & $FTPP

LOCALD="/localpath"

ncftpput -m -u $FTPU -p $FTPP $FTPS
  $FTPF $LOCALD

I am currently running this script on fedora 10...

thanks.....

答: ncftpput is an FTP client that does not support SSH (see their FAQs). Also, in your script you're providing an HTTP URL instead of just a server name. If mydomain.com actually runs an FTP server, try FTPS=mydomain.com instead.</p>


问:
CSS color sections dived diagonally
Is it possible to accomplish a diagonal line stroke, with a bit of an off-set in any side. I've seen a variation of this accomplished with css linear-gradient, but I need something slightly different. I don't know how to describe what I need exactly in words. I'll use pictures.

I've tried playing with gradients:

.diagonal{
  background-color: #34ADFF;
  background-image: linear-gradient(to right top, whitesmoke 50%, #34ADFF 50%);
  height: 300px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="diagonal">
</div></code>```

That's how far I've gone. I'm thinking of playing around with child divs, but I'm not sure yet.

Any ideas ?

I don't want to use images, I want to use just CSS.

答:
An extremely unsophisticated demo using transform: rotate()

The rotateZ() CSS function defines a transformation that moves the element around the z-axis without deforming it. The amount of movement is defined by the specified angle; if positive, the movement will be clockwise, if negative, it will be counter-clockwise.

The working content of your slanted containers would require careful placement, and there are some potential positioning issues, but with effort, I think this could work.

body {
  background: lightgray;
  margin: 0;
  height: 300vh;
}
header, footer {
  position: fixed;
  height: 20vh;
  width: 120vw;
  left: -10vw;
  overflow: hidden;
}
header {
  background: lightblue;
  top: -6vh;
}
footer {
  background: lightgreen;
  bottom: -6vh;
}
footer,
header p {
  transform: rotateZ( -3deg );
}
header,
footer p {
  transform: rotateZ( 3deg );
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</header>
<footer>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</footer></code>```

Title: CSS color sections dived diagonally

Body:
Is it possible to accomplish a diagonal line stroke, with a bit of an off-set in any side. I've seen a variation of this accomplished with css linear-gradient, but I need something slightly different. I don't know how to describe what I need exactly in words. I'll use pictures.

I've tried playing with gradients:

.diagonal{
  background-color: #34ADFF;
  background-image: linear-gradient(to right top, whitesmoke 50%, #34ADFF 50%);
  height: 300px;
}

That's how far I've gone. I'm thinking of playing around with child divs, but I'm not sure yet.

Any ideas ?

I don't want to use images, I want to use just CSS.

Body:
An extremely unsophisticated demo using transform: rotate()

The rotateZ() CSS function defines a transformation that moves the element around the z-axis without deforming it. The amount of movement is defined by the specified angle; if positive, the movement will be clockwise, if negative, it will be counter-clockwise.

The working content of your slanted containers would require careful placement, and there are some potential positioning issues, but with effort, I think this could work.

body {
  background: lightgray;
  margin: 0;
  height: 300vh;
}
header, footer {
  position: fixed;
  height: 20vh;
  width: 120vw;
  left: -10vw;
  overflow: hidden;
}
header {
  background: lightblue;
  top: -6vh;
}
footer {
  background: lightgreen;
  bottom: -6vh;
}
footer,
header p {
  transform: rotateZ( -3deg );
}
header,
footer p {
  transform: rotateZ( 3deg );
}

<header>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</header>
<footer>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</footer>


问:
Syntax for suppressing SPSS output
I am trying to analyze a very large amount of variables in SPSS and I have created syntax to export the tables I want to a .sav file, but the program gets hung up and freezes trying to generate the results in the output file.  I am trying to find SPSS syntax that will do this so I can just get the .sav file of the results without it using up all the local memory trying to create the tables in the output file.  All I could find was the following for suppressing the output:

```<code>OMS /SELECT ALL EXCEPT = [WARNINGS]
/DESTINATION VIEWER = NO
/TAG = 'NoJunk'.
*Your Commands here.
OMSEND TAG = 'NoJunk'.
</code>```

The Syntax I am using to run my analysis and export the results to a .sav file is pasted below, and it works perfectly, but I need help incorporating this with the syntax above to suppress the output file so I just get the .sav file and it doesn't use up all my memory trying to create the tables in the output file.

```<code>* OMS.
DATASET DECLARE  GLM_genomicTables.
OMS
/SELECT TABLES
/IF COMMANDS=['GLM'] SUBTYPES=['Test of Between Subjects Fixed Effects' ' Test
of Between '+ 'Subjects Mixed Effects']
/DESTINATION FORMAT=SAV NUMBERED=TableNumber_
OUTFILE='GLM_genomicTables' VIEWER=NO.

DATASET ACTIVATE DataSet1.
GLM A_42_P454311
A_42_P456851
A_42_P458530
A_42_P458661
A_42_P461946
Y Region Condition Timepoint
/METHOD=SSTYPE(3)
/INTERCEPT=INCLUDE
/EMMEANS=TABLES(Condition)
/EMMEANS=TABLES(Region*Condition)
/EMMEANS=TABLES(Region*Condition*Timepoint)
/PRINT=DESCRIPTIVE ETASQ OPOWER
/CRITERIA=ALPHA(.05)
/DESIGN= Region Condition Timepoint Region*Condition Region*Timepoint
Condition*Timepoint
Region*Condition*Timepoint.

OMSEND.
DATASET ACTIVATE GLM_genomicTables.

SAVE OUTFILE='M:\Users\jessicanielson\Desktop\Ferguson Lab\Preclinical TBI
datasets\UTMB Data\GLM_genomicTables.sav'
/COMPRESSED.
DATASET CLOSE GLM_genomicTables.
</code>```

答:
I don't know why the system would hang unless the Viewer objects are so big that you run out of memory.  But you can nest OMS commands with the most recent one taking priority if there are conflicts.  So you could do something like this.

```<code>OMS /SELECT ALL EXCEPT = [WARNINGS] /DESTINATION VIEWER = NO.
OMS /SELECT TABLES
/IF COMMANDS=['GLM'] SUBTYPES=['Test of Between Subjects Fixed Effects' '
Test of Between '+ 'Subjects Mixed Effects']
/DESTINATION FORMAT=SAV NUMBERED=TableNumber_
OUTFILE='M:\Users\jessicanielson\Desktop\Ferguson Lab\Preclinical TBI
datasets\UTMB Data\GLM_genomicTables.sav'  VIEWER=NO.

*Your Commands here....

OMSEND.
</code>```

(with proper quote continuation as needed).  That will suppress everything but warnings and will write the selected table objects directly to the designated sav file.  However, with three different table types selected, you should write each type to a separate sav file.  Just used three OMS commands before the GLM each one selecting a different type.

And note that using just one untagged OMSEND command will terminate all active OMS requests and write the selected objects at that time.

Title: Syntax for suppressing SPSS output

Body:
I am trying to analyze a very large amount of variables in SPSS and I have created syntax to export the tables I want to a .sav file, but the program gets hung up and freezes trying to generate the results in the output file.  I am trying to find SPSS syntax that will do this so I can just get the .sav file of the results without it using up all the local memory trying to create the tables in the output file.  All I could find was the following for suppressing the output:

OMS /SELECT ALL EXCEPT = [WARNINGS]
/DESTINATION VIEWER = NO
/TAG = 'NoJunk'.
*Your Commands here.
OMSEND TAG = 'NoJunk'.

The Syntax I am using to run my analysis and export the results to a .sav file is pasted below, and it works perfectly, but I need help incorporating this with the syntax above to suppress the output file so I just get the .sav file and it doesn't use up all my memory trying to create the tables in the output file.

* OMS.
DATASET DECLARE  GLM_genomicTables.
OMS
/SELECT TABLES
/IF COMMANDS=['GLM'] SUBTYPES=['Test of Between Subjects Fixed Effects' ' Test
of Between '+ 'Subjects Mixed Effects']
/DESTINATION FORMAT=SAV NUMBERED=TableNumber_
OUTFILE='GLM_genomicTables' VIEWER=NO.

DATASET ACTIVATE DataSet1.
GLM A_42_P454311
A_42_P456851
A_42_P458530
A_42_P458661
A_42_P461946
Y Region Condition Timepoint
/METHOD=SSTYPE(3)
/INTERCEPT=INCLUDE
/EMMEANS=TABLES(Condition)
/EMMEANS=TABLES(Region*Condition)
/EMMEANS=TABLES(Region*Condition*Timepoint)
/PRINT=DESCRIPTIVE ETASQ OPOWER
/CRITERIA=ALPHA(.05)
/DESIGN= Region Condition Timepoint Region*Condition Region*Timepoint
Condition*Timepoint
Region*Condition*Timepoint.

OMSEND.
DATASET ACTIVATE GLM_genomicTables.

SAVE OUTFILE='M:\Users\jessicanielson\Desktop\Ferguson Lab\Preclinical TBI
datasets\UTMB Data\GLM_genomicTables.sav'
/COMPRESSED.
DATASET CLOSE GLM_genomicTables.

Body:
I don't know why the system would hang unless the Viewer objects are so big that you run out of memory.  But you can nest OMS commands with the most recent one taking priority if there are conflicts.  So you could do something like this.

OMS /SELECT ALL EXCEPT = [WARNINGS] /DESTINATION VIEWER = NO.
OMS /SELECT TABLES
/IF COMMANDS=['GLM'] SUBTYPES=['Test of Between Subjects Fixed Effects' '
Test of Between '+ 'Subjects Mixed Effects']
/DESTINATION FORMAT=SAV NUMBERED=TableNumber_
OUTFILE='M:\Users\jessicanielson\Desktop\Ferguson Lab\Preclinical TBI
datasets\UTMB Data\GLM_genomicTables.sav'  VIEWER=NO.

*Your Commands here....

OMSEND.

(with proper quote continuation as needed).  That will suppress everything but warnings and will write the selected table objects directly to the designated sav file.  However, with three different table types selected, you should write each type to a separate sav file.  Just used three OMS commands before the GLM each one selecting a different type.

And note that using just one untagged OMSEND command will terminate all active OMS requests and write the selected objects at that time.


问:
Autofac- externally owned container?
I'm using an Autofac container for the entire lifetime of my application, but I want to dispose the components myself.

I.E if I have builder.RegisterType<SomeType>(), I don't want the container to keep references of SomeType which will keep those alive even if not referenced anywhere else (if RegisterInstance is used OTOH, then of course the container must keep a reference to the singleton).

I can see that I can do builder.RegisterType<SomeType>().ExternallyOwned() which solves my problem for one type, but I don't want to write it for every type, and more importantly I also use builder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource()); which doesn't give me the option of using ExternallyOwned.

Is there a way to specify "ExternallyOwned" for the entire container? Or, to put it another way, tell the container to disable the entire dispose feature and not keep references for objects it doesn't need?

答:
There is not a way to disable container disposal services. You might try to hook in with something like the logging module but I could see that not working 100% and missing edge cases of you're not careful.

Automatic tracking and disposal is a pretty common container feature. I'd recommend instead of fighting it you refactor your code to embrace it. It'll make life a lot easier.

Title: Autofac- externally owned container?