问:
PHP - how to prevent .php files from direct access
i have following folders:

```<code>mywebsite/en/index.php
mywebsite/en/product/info.php
mywebsite/en/tags/tags.php
mywebsite/en/games/list.php
</code>```

my site is running on friendly url, top mentioned files accessable from following friendly urls

```<code>mywebsite/en/?pageno=1
mywebsite/en/product/Nike-glove
mywebsite/en/tags/Nike
mywebsite/en/games/ice-sports
</code>```

i have some examples, but nothing work for me like...i want to prevent direct access to .php files..i want to do that with htaccess...can i?

thanks and kind regards

Reelmark

答:
The solution I've settled on is based on @Fou's answer, but I've modified it to handle the case of /script.php/oops and opted to rewrite the response code as 404 instead of using a temporary redirect:

```<code>RewriteCond %{THE_REQUEST} ^[A-Z]+\ /[^?\ ]*\.php[/?\ ]
RewriteRule .* - [R=404]
</code>```

Body:
i have following folders:

mywebsite/en/index.php
mywebsite/en/product/info.php
mywebsite/en/tags/tags.php
mywebsite/en/games/list.php

my site is running on friendly url, top mentioned files accessable from following friendly urls

mywebsite/en/?pageno=1
mywebsite/en/product/Nike-glove
mywebsite/en/tags/Nike
mywebsite/en/games/ice-sports

i have some examples, but nothing work for me like...i want to prevent direct access to .php files..i want to do that with htaccess...can i?

thanks and kind regards

Reelmark

Body:
The solution I've settled on is based on @Fou's answer, but I've modified it to handle the case of /script.php/oops and opted to rewrite the response code as 404 instead of using a temporary redirect:

RewriteCond %{THE_REQUEST} ^[A-Z]+\ /[^?\ ]*\.php[/?\ ]
RewriteRule .* - [R=404]


来源: stackexchange

问:
HTTP authentication logout via PHP
What is the correct way to log out of HTTP authentication protected folder?

There are workarounds that can achieve this, but they are potentially dangerous because they can be buggy or don't work in certain situations / browsers. That is why I am looking for correct and clean solution.

答: Typically, once a browser has asked the user for credentials and supplied them to a particular web site, it will continue to do so without further prompting. Unlike the various ways you can clear cookies on the client side, I don't know of a similar way to ask the browser to forget its supplied authentication credentials.</p>

OwnerDisplayName: JS

ContentLicense: CC BY-SA 2.5

Title: HTTP authentication logout via PHP

LastEditorDisplayName: JS

OwnerDisplayName: Greg Hewgill


问:
How to tell if a mobile page was designed specifically for mobile?
Is there a way to tell if a mobile page you've downloaded is just a desktop page modified with media queries, or is a separate page designed specifically for mobile? I'd like to go through a list of the "20 Best Mobile Pages" and see what percent were designed specially for mobile. </p>

答: Go on the site on desktop, then use Chrome's inspect element to test a mobile sized browser. Then go on your phone and go to the site. If the results are different, then it was designed for mobile, if not then the website was just built to be responsive.</p>

ContentLicense: CC BY-SA 3.0


问:
IOS/Objective-C: Change tint of an image view
I would like to change the color of an image view when the user touches it.  I don't need it to change a great deal.  However, I would like it to change to a shade of blue.  I found the following code to change the gradient but it is not having any effect.  I don't need a gradient, actually, only a tint.  Would appreciate any suggestions.</p>

```<code> UIView *snapshot = [[UIImageView alloc] initWithImage:image];
        snapshot.layer.masksToBounds = NO;
          CAGradientLayer *gradient = [CAGradientLayer layer];

        gradient.colors = @[(id)[UIColor redColor].CGColor, (id)[UIColor blackColor].CGColor];

        [snapshot.layer insertSublayer:gradient atIndex:0];
</code>```

答:
You can try giving the UIImage a tint

```<code>UIImage *image = [[UIImage imageNamed:@"Your Image"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.tintColor = [UIColor clearColor]; // Or any color really you'd like would work
imageView.image = newImage;
</code>```

And then changing that tint when the user touches the image using a tap gesture recognizer

Body:
I would like to change the color of an image view when the user touches it.  I don't need it to change a great deal.  However, I would like it to change to a shade of blue.  I found the following code to change the gradient but it is not having any effect.  I don't need a gradient, actually, only a tint.  Would appreciate any suggestions.

 UIView *snapshot = [[UIImageView alloc] initWithImage:image];
        snapshot.layer.masksToBounds = NO;
          CAGradientLayer *gradient = [CAGradientLayer layer];

        gradient.colors = @[(id)[UIColor redColor].CGColor, (id)[UIColor blackColor].CGColor];

        [snapshot.layer insertSublayer:gradient atIndex:0];

Body:
You can try giving the UIImage a tint

UIImage *image = [[UIImage imageNamed:@"Your Image"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.tintColor = [UIColor clearColor]; // Or any color really you'd like would work
imageView.image = newImage;

And then changing that tint when the user touches the image using a tap gesture recognizer


问:
Set background image of a mutated TableViewController
I am working on a swift project in Xcode right now and one of my view controllers is a UITableViewController. I used swift to alter the size of the table view in the controller so that it does not fill up the entire screen. However, I want to set a background image for the entire view controller which I am unable to do since XCode is not letting me add an image view between the table view controller and the table view. Is there any way to do it using swift? Thank you.</p>

答:
I think I can help out.

If you're using Apple's UITableViewController - does that mean you altered the tableView's height in the storyboard? I think a better solution is to just use a regular UIViewController, add a tableView with whatever height you want it inside a UIViewController's view.

Often times I would recommend steering away from using Apple's custom things because you lose flexibility. Just make your own custom thing instead!

UIViewController > View > TableView & UIImageView

Make sure your tableview has a clear background!


问:
How get a valid JSON output from the response in Zend Framework 3?
I'm writing a client for an API...

```<code>use Zend\Http\Client;
use Zend\Http\Request;
use Zend\Json\Json;
...
$request = new Request();
$request->getHeaders()->addHeaders([
    'Accept-Charset' => 'UTF-8',
    'Accept' => 'application/hal+json',
    'Content-Type' => 'application/hal+json; charset=UTF-8',
]);
$apiAddress = 'http://my.project.tld/categories';
$request->setUri($apiAddress);
$request->setMethod('GET');
$client = new Client();
$response = $client->dispatch($request);
$data = $response->getContent();
</code>```

... and get a broken JSON like this:

```<code>1f9e <-- What is it?
{"_links...
\u043 <-- What is it?
1a6...
tfoli <-- What is it?
0
</code>```

The string is separaten into five lines:

1st line: only 1f9e

2nd line: first content part

3d line: string 1a6

4th line: the second content part

5th line: 0

Why am I getting additional symbols/strings? How to avoid this a get valid JSON output?

答:
The problem with the getContent() method of the response object. It may not decode the content it gets in it from the request. Please have a look at here. This might be the reason. I may be wrong!

So the getBody() method of it does the decoding job for the content of the request. So please use this method instead of getContent().

```<code>$data = $response->getBody();
</code>```

Hope this would help you!

Body:
I'm writing a client for an API...

use Zend\Http\Client;
use Zend\Http\Request;
use Zend\Json\Json;
...
$request = new Request();
$request->getHeaders()->addHeaders([
    'Accept-Charset' => 'UTF-8',
    'Accept' => 'application/hal+json',
    'Content-Type' => 'application/hal+json; charset=UTF-8',
]);
$apiAddress = 'http://my.project.tld/categories';
$request->setUri($apiAddress);
$request->setMethod('GET');
$client = new Client();
$response = $client->dispatch($request);
$data = $response->getContent();

... and get a broken JSON like this:

1f9e <-- What is it?
{"_links...
\u043 <-- What is it?
1a6...
tfoli <-- What is it?
0

The string is separaten into five lines:

1st line: only 1f9e

2nd line: first content part

3d line: string 1a6

4th line: the second content part

5th line: 0

Why am I getting additional symbols/strings? How to avoid this a get valid JSON output?

Body:
The problem with the getContent() method of the response object. It may not decode the content it gets in it from the request. Please have a look at here. This might be the reason. I may be wrong!

So the getBody() method of it does the decoding job for the content of the request. So please use this method instead of getContent().

$data = $response->getBody();

Hope this would help you!


问:
Cannot hide the match messages in Angular password form

Hi, I got a problem I want to show the messages only when passwords match or not match but the messages appear all the time any suggestions? And I would like to not be able to click the button if the passwords are different!

```<code>@*<form name="form" ng-submit="vm.login()" role="form">*@
<form accept-charset="UTF-8" role="form" id="login-recordar" ng-submit="vm.login()">

    @*New password field!*@
    <div>
        <div class="form-group input-group" ng-class="{ 'has-error': form.password.$dirty && form.password.$error.required }">
            <span class="input-group-addon">
                <i class="glyphicon glyphicon-lock"></i><label for="password1">New Password</label>
            </span>
            <input class="form-control" placeholder="Password" name="password" type="password" data-toggle="popover" data-trigger="focus" data-content="Minimum 8 characters long and should contain at least one (small- and capital letter and number)." id="password" value="" required="" autofocus="" onkeypress="capLock(event)" ng-model="mAddEditView.User.Password" ng-pattern="/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})/" />
        </div>
        <span ng-show="form.password.$dirty && form.password.$error.required" class="help-block">Password is required</span>
        <span id="divMayus" style="visibility:hidden">Caps Lock is on!</span>
    </div>

    @*Confirm Password field!*@
    <div>
        <div class="form-group input-group" ng-class="{ 'has-error': form.password1.$dirty && form.password1.$error.required }">
            <span class="input-group-addon">
                <i class="glyphicon glyphicon-lock"></i><label for="password1">Confirm Password</label>
            </span>
            <input class="form-control" placeholder="Password" name="password1" type="password" data-toggle="popover" data-trigger="focus" data-content="The password should match." id="password1" value="" required="" onkeypress="capLock(event)" ng-model="mAddEditView.User.Password" ng-pattern="/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})/" />

        </div>
        <span ng-show="form.password1.$dirty && form.password1.$error.required" class="help-block">Password is required</span>
        <span ng-show="mAddEditView.User.Password !== mAddEditView.User.Password1" class="help-block"><font style="color:red;">Password is not valid!</font></span>
        @* code for checking if password match *@
        <span ng-show="form.password1.$valid && mAddEditView.User.Password === mAddEditView.User.Password1"><font style="color:white;">Password Matched</font></span>

        <span id="divMayus" style="visibility:hidden">Caps Lock is on!</span>
    </div>

    <div class="form-group">
        <button type="submit" class="btn btn-primary btn-block" value="Login" ng-disabled="form.$invalid || vm.dataLoading || errors.mail.isExists || mAddEditView.User.Password !== mAddEditView.User.Password1">
            Change Password
        </button>

    </div>
</code>```

答:
You should also check whether password1 is passing required validation or not.

```<code>ng-show="!form.password1.$error.required &&
         form.password1.$valid &&
         mAddEditView.User.Password === mAddEditView.User.Password1"
</code>```

Body:
Hi, I got a problem I want to show the messages only when passwords match or not match but the messages appear all the time any suggestions? And I would like to not be able to click the button if the passwords are different!

@*<form name="form" ng-submit="vm.login()" role="form">*@
<form accept-charset="UTF-8" role="form" id="login-recordar" ng-submit="vm.login()">

    @*New password field!*@

                New Password

            <input class="form-control" placeholder="Password" name="password" type="password" data-toggle="popover" data-trigger="focus" data-content="Minimum 8 characters long and should contain at least one (small- and capital letter and number)." id="password" value="" required="" autofocus="" onkeypress="capLock(event)" ng-model="mAddEditView.User.Password" ng-pattern="/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})/" />

        Password is required
        Caps Lock is on!

    @*Confirm Password field!*@

                Confirm Password

            <input class="form-control" placeholder="Password" name="password1" type="password" data-toggle="popover" data-trigger="focus" data-content="The password should match." id="password1" value="" required="" onkeypress="capLock(event)" ng-model="mAddEditView.User.Password" ng-pattern="/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})/" />

        Password is required
        Password is not valid!
        @* code for checking if password match *@
        Password Matched

        Caps Lock is on!

        <button type="submit" class="btn btn-primary btn-block" value="Login" ng-disabled="form.$invalid || vm.dataLoading || errors.mail.isExists || mAddEditView.User.Password !== mAddEditView.User.Password1">
            Change Password
        </button>

Body:
You should also check whether password1 is passing required validation or not.

ng-show="!form.password1.$error.required &&
         form.password1.$valid &&
         mAddEditView.User.Password === mAddEditView.User.Password1"


问:
Should you correct compiler warnings about type conversions using explicit typecasts?
In my current project, the compiler shows hundreds of warnings about type conversions.

There is a lot of code like this

```<code>iVar = fVar1*fVar2/fVar3;
// or even
iVar = fVar1*fVar2/fVar3+.5f;
</code>```

which intentionally assign float values to int.

Of course, I could fix these warnings using

```<code>iVar = (int)(...);
</code>```

but that looks kind of ugly.

Would you rather live with the ugliness or live with the warnings?

Or is there even a clean solution?

答:
Having hundreds of warnings that aren't an issue is dangerous, one day a warning that's a real issue will appear and drown in the noise.

Keep the code free of warnings.

If you know what you're doing, add the casts or conversion.

Body:
In my current project, the compiler shows hundreds of warnings about type conversions.

There is a lot of code like this

iVar = fVar1*fVar2/fVar3;
// or even
iVar = fVar1*fVar2/fVar3+.5f;

which intentionally assign float values to int.

Of course, I could fix these warnings using

iVar = (int)(...);

but that looks kind of ugly.

Would you rather live with the ugliness or live with the warnings?

Or is there even a clean solution?


问:
I Need Help Changing The Text In My asp:Button
I currently designing on a website where the developer uses (asp:Button)'s to add a product to the "cart" and another asp:Button to add the product to the wish list. The developer has the button code like this:

```<code><asp:Button ID="AddToBasketButton" runat="server" Visible="true" OnClick="AddToBasketButton_Click" Text="+ Add to Quote" EnableViewState="false" ValidationGroup="AddToBasket"></asp:Button>
</code>```

From this little snippet you can see that the button will ultimately say "+ Add to Quote"

I am looking for a way to implement html in the Text=""

For example if I wanted to put

```<code>Text="<p>+ Add to Quote</p>"
</code>```

In the real life scenario I am trying to add a Glyphicon to replace the "+" sign so I was trying to add a  before the Add to Quote button.

Is there another attribute I could be using to accomplish this without having to remap the backend function that "adds" the product to the quote list?

答:
This option hasn't html in text attribute, but you can do by this way:

```<code><asp:Button ID="AddToBasketButton" runat="server" Visible="true" OnClick="AddToBasketButton_Click" EnableViewState="false" ValidationGroup="AddToBasket" CssClass="btn btn-primary">

    <span aria-hidden="true" class="glyphicon glyphicon-plus"></span> Add to Quote

</asp:Button>
</code>```

Body:
I currently designing on a website where the developer uses (asp:Button)'s to add a product to the "cart" and another asp:Button to add the product to the wish list. The developer has the button code like this:

<asp:Button ID="AddToBasketButton" runat="server" Visible="true" OnClick="AddToBasketButton_Click" Text="+ Add to Quote" EnableViewState="false" ValidationGroup="AddToBasket"></asp:Button>

From this little snippet you can see that the button will ultimately say "+ Add to Quote"

I am looking for a way to implement html in the Text=""

For example if I wanted to put

Text="
+ Add to Quote
"

In the real life scenario I am trying to add a Glyphicon to replace the "+" sign so I was trying to add a  before the Add to Quote button.

Is there another attribute I could be using to accomplish this without having to remap the backend function that "adds" the product to the quote list?

Body:
This option hasn't html in text attribute, but you can do by this way:

<asp:Button ID="AddToBasketButton" runat="server" Visible="true" OnClick="AddToBasketButton_Click" EnableViewState="false" ValidationGroup="AddToBasket" CssClass="btn btn-primary">

    <span aria-hidden="true" class="glyphicon glyphicon-plus"></span> Add to Quote

</asp:Button>


问:
Access to raw sockets in Android instrumented tests
I've trawled through many of the answers here regarding socket access via native code on Android, and others regarding socket access for "androidTest" instrumented tests, but none are able to fully explain some odd behaviour I'm seeing.

Android Studio 2.3.3 on Windows 10, NDK 15.1.x, build tools 25.0.3. Building with Cmake. I am porting some native code over to Android intended to be distributed as a library that is wrapped in a Java JNI-based API. This part seems to be working fine; at least I can debug and log into the native code and see where things go wrong.

I've created a few instrumented tests to exercise the JNI, but it looks like the native side does not have access to sockets, even if the test app that Android Studio wraps up for your intrumented tests does (i.e., it has the INTERNET permission applied, and I can see that it is part of the pushed manifest of the test app. I also applied the ACCESS_NETWORK_STATE perm in a fit of pique.)

That is, parts of the library know how to set up and use TCP sockets (datagram and stream; in this case stream) and resolve DNS, which fails (This might be a bug in my port, since the device itself still seems to resolve DNS based on the adb shell output below). If I test with an IP address it retries until it fails. Each call to socket() returns an ERRNO of 11 EAGAIN ("Try again").

If I use the adb shell to login to the device under test over USB, I can ping and use curl, etc. But, as soon as I run-as as the test app I am no longer allowed to use any network device.

```<code>shell@venice:/data/data/org.clvrmnky.library.test $ ping www.example.com
PING www.example.com (93.184.216.34) 56(84) bytes of data.
ping: sendmsg: Operation not permitted
ping: sendmsg: Operation not permitted
ping: sendmsg: Operation not permitted
^C
--- www.example.com ping statistics ---
3 packets transmitted, 0 received, 100% packet loss, time 2004ms

1|shell@venice:/data/data/org.clvrmnky.library.test $ ping -I wlan0 www.example.com
ping: SO_BINDTODEVICE: Operation not permitted
2|shell@venice:/data/data/org.clvrmnky.library.test $ curl -4 --verbose www.example.com/
*   Trying 93.184.216.34...
* connect to 93.184.216.34 port 80 failed: Connection timed out
* Failed to connect to www.example.com port 80: Connection timed out
* Closing connection 0
curl: (7) Failed to connect to www.example.com port 80: Connection timed out
7|shell@venice:/data/data/org.clvrmnky.library.test $
</code>```

I won't paste it here, but wlan0 (and others) exists and is UP with a valid, reachable IP address. It is "Link encap:UNSPEC" which I admit I don't fully grok.

I'm making an assumption that the app failing on the successive socket calls and the inability to bind to a network device in and use it in an adb shell are related in some manner, but if someone has a reason why this may not be so, please let me know.

I've tried:

Invoking the test methods in a background thread, just in case the instrumented tests were running in the test app main thread.

Setting the StrictMode thread policy to permitAll() in the @Before clause of the test class.

Running with and without the INTERNET permission set in the test manifest. Without this permission it reaches the native code, but fails much earlier in the initialization. I'd have to dig into my notes to fetch more details about that. I assume that I need this permission. (Side note: if I enable INTERNET then the remote debugger can no longer attach to the device, so I can debug via logs only.)

答:
It looks like instrumented tests, at least as of this writing, do not support access to raw sockets through the NDK. The .test app that is auto-created seemed to have everything it needed in the manifest (I checked base.apk right from the device).

Once a DemoApp was created with identical manifest settings I was able to open sockets, connect to them, do name lookups, etc. Furthermore, I was able to access the network via adb shell when running as ("run-as") the DemoApp.

There is still something strange going on, as I created a separate JNI app that opens sockets, and hacked an instrumented test against that. At least briefly adb shell running as ext.other.app.test did have internet access.

Body:
I've trawled through many of the answers here regarding socket access via native code on Android, and others regarding socket access for "androidTest" instrumented tests, but none are able to fully explain some odd behaviour I'm seeing.

Android Studio 2.3.3 on Windows 10, NDK 15.1.x, build tools 25.0.3. Building with Cmake. I am porting some native code over to Android intended to be distributed as a library that is wrapped in a Java JNI-based API. This part seems to be working fine; at least I can debug and log into the native code and see where things go wrong.

I've created a few instrumented tests to exercise the JNI, but it looks like the native side does not have access to sockets, even if the test app that Android Studio wraps up for your intrumented tests does (i.e., it has the INTERNET permission applied, and I can see that it is part of the pushed manifest of the test app. I also applied the ACCESS_NETWORK_STATE perm in a fit of pique.)

That is, parts of the library know how to set up and use TCP sockets (datagram and stream; in this case stream) and resolve DNS, which fails (This might be a bug in my port, since the device itself still seems to resolve DNS based on the adb shell output below). If I test with an IP address it retries until it fails. Each call to socket() returns an ERRNO of 11 EAGAIN ("Try again").

If I use the adb shell to login to the device under test over USB, I can ping and use curl, etc. But, as soon as I run-as as the test app I am no longer allowed to use any network device.

shell@venice:/data/data/org.clvrmnky.library.test $ ping www.example.com
PING www.example.com (93.184.216.34) 56(84) bytes of data.
ping: sendmsg: Operation not permitted
ping: sendmsg: Operation not permitted
ping: sendmsg: Operation not permitted
^C
--- www.example.com ping statistics ---
3 packets transmitted, 0 received, 100% packet loss, time 2004ms

1|shell@venice:/data/data/org.clvrmnky.library.test $ ping -I wlan0 www.example.com
ping: SO_BINDTODEVICE: Operation not permitted
2|shell@venice:/data/data/org.clvrmnky.library.test $ curl -4 --verbose www.example.com/
*   Trying 93.184.216.34...
* connect to 93.184.216.34 port 80 failed: Connection timed out
* Failed to connect to www.example.com port 80: Connection timed out
* Closing connection 0
curl: (7) Failed to connect to www.example.com port 80: Connection timed out
7|shell@venice:/data/data/org.clvrmnky.library.test $

I won't paste it here, but wlan0 (and others) exists and is UP with a valid, reachable IP address. It is "Link encap:UNSPEC" which I admit I don't fully grok.

I'm making an assumption that the app failing on the successive socket calls and the inability to bind to a network device in and use it in an adb shell are related in some manner, but if someone has a reason why this may not be so, please let me know.

I've tried:

Invoking the test methods in a background thread, just in case the instrumented tests were running in the test app main thread.

Setting the StrictMode thread policy to permitAll() in the @Before clause of the test class.

Running with and without the INTERNET permission set in the test manifest. Without this permission it reaches the native code, but fails much earlier in the initialization. I'd have to dig into my notes to fetch more details about that. I assume that I need this permission. (Side note: if I enable INTERNET then the remote debugger can no longer attach to the device, so I can debug via logs only.)


问:
Show div depending on input And position Property with jQuery

$(document).ready(function() {
  $('#input').focusin(function() {
    if ($(this).val() != '') {
      $('#div').show();
    } else {
      $('#div').hide();
    }
    $('#input').keyup(function() {
      // If not empty value, show div
      if ($(this).val() != '') {
        $('#div').show();
      } else {
        $('#div').hide();
      }
    });
  });
  $('#input').focusout(function() {
    $('#div').hide();

  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#div {
  display: none;
  position: absolute;
  bottom: 20px;
}</code>```

  href='website.com'>Link From AJAX
  href='website.com'>Link From AJAX
  href='website.com'>Link From AJAX

<input id='input' type='text'>```

In my code here, While typing it shows a div, And hide it if not typing, Before setting the position: absolute, bottom: 20px; the links was clickable and doesn't disappear onclick, But now it doesn't

答:
1st not sure why you need the focusout, but what you can do is to add a small delay (50ms) to hide stuff so you got the small window when you click the link:

```<code>setTimeout(function() {
   $('#div').hide();
}, 50);
</code>```

$(document).ready(function() {
  $('#input').focusin(function() {
    if ($(this).val() != '') {
      $('#div').show();
    } else {
      $('#div').hide();
    }
    $('#input').keyup(function() {
      // If not empty value, show div
      if ($(this).val() != '') {
        $('#div').show();
      } else {
        $('#div').hide();
      }
    });
  });
  $('#input').focusout(function() {
    setTimeout(function() {
      $('#div').hide();
    }, 50);
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#div {
  display: none;
  position: absolute;
  bottom: 20px;
}</code>```

  href='website.com'>Link From AJAX
  href='website.com'>Link From AJAX
  href='website.com'>Link From AJAX

<input id='input' type='text'>```

Body:
$(document).ready(function() {
  $('#input').focusin(function() {
    if ($(this).val() != '') {
      $('#div').show();
    } else {
      $('#div').hide();
    }
    $('#input').keyup(function() {
      // If not empty value, show div
      if ($(this).val() != '') {
        $('#div').show();
      } else {
        $('#div').hide();
      }
    });
  });
  $('#input').focusout(function() {
    $('#div').hide();

  });

});

#div {
  display: none;
  position: absolute;
  bottom: 20px;
}

  Link From AJAX
  Link From AJAX
  Link From AJAX

<input id='input' type='text'>

In my code here, While typing it shows a div, And hide it if not typing, Before setting the position: absolute, bottom: 20px; the links was clickable and doesn't disappear onclick, But now it doesn't

Body:
1st not sure why you need the focusout, but what you can do is to add a small delay (50ms) to hide stuff so you got the small window when you click the link:

setTimeout(function() {
   $('#div').hide();
}, 50);

$(document).ready(function() {
  $('#input').focusin(function() {
    if ($(this).val() != '') {
      $('#div').show();
    } else {
      $('#div').hide();
    }
    $('#input').keyup(function() {
      // If not empty value, show div
      if ($(this).val() != '') {
        $('#div').show();
      } else {
        $('#div').hide();
      }
    });
  });
  $('#input').focusout(function() {
    setTimeout(function() {
      $('#div').hide();
    }, 50);
  });

});

#div {
  display: none;
  position: absolute;
  bottom: 20px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='div'>
  <a href='website.com'>Link From AJAX<a>
  <a href='website.com'>Link From AJAX<a>
  <a href='website.com'>Link From AJAX<a>
</div>
<input id='input' type='text'>


问:
Angular <app-root> is not recognized in Node views
I am building a MEAN app, and have run into a problem I have not faced before.  When I include my app-root selector in my index.ejs file in the Node views, the selector is not recognized and is discarded.  The editor shows this error:

```<code><app-root> is not recognized!  Discarding Unexpected <app-root>
</code>```

I checked the selector in the App Component to make sure the selector matched, checked the AppModule to make sure I was declaring it, and checked the main.ts to make sure I was bootstrapping correctly.  Everything looks fine, and there isn't an error in the terminal when I run the app.  I've spent about an hour looking for similar questions here and in the Angular documentation, but haven't found anything.

So I'm curious whether anyone else has faced this problem or has an idea of what's happening.  Code below.

 index.ejs

```<code><!DOCTYPE html>
<html>
  <head>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <app-root>Loading...</app-root>

  <script src="/js/app/bundle.js"></script>

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

 App Component

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';
}
</code>```

 App Module

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { routes } from './route/app.routing';
import { RouterModule } from "@angular/router";
import { AmChartsModule } from "amcharts3-angular2";

import { AppComponent } from './app.component';
import { MapComponent } from './map/map.component';
import { NavbarComponent } from './navbar/navbar.component';
import { MainComponent } from './main/main.component';

//Services
import { NewsApiService } from './service/news-api.service';

@NgModule({
  declarations: [
    AppComponent,
    MapComponent,
    NavbarComponent,
    MainComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule,
    AmChartsModule,
    BrowserModule,
    RouterModule.forRoot(routes)
  ],
  providers: [NewsApiService],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

 main.ts

```<code>import './polyfills';

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule);
</code>```

 dependencies

```<code>{
  "name": "aether-news",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./server/bin/www",
    "build": "del-cli public/js/app && webpack --config webpack.config.dev.js --progress --profile --watch"
  },
  "engines": {
    "node": "7.4.0"
  },
  "dependencies": {
    "@angular/animations": "^4.2.5",
    "@angular/common": "^4.2.5",
    "@angular/compiler": "^4.2.5",
    "@angular/compiler-cli": "^4.2.5",
    "@angular/core": "^4.2.5",
    "@angular/forms": "^4.2.5",
    "@angular/platform-browser": "^4.2.5",
    "@angular/platform-browser-dynamic": "^4.2.5",
    "@angular/platform-server": "^4.2.5",
    "@angular/router": "^4.2.5",
    "@angular/upgrade": "^4.2.5",
    "bcrypt": "^1.0.2",
    "body-parser": "^1.16.1",
    "cookie-parser": "^1.4.3",
    "cors": "^2.8.2",
    "debug": "^2.6.3",
    "ejs": "~2.5.5",
    "express": "^4.14.1",
    "hbs": "^4.0.1",
    "jsonwebtoken": "^7.3.0",
    "mongoose": "^4.9.2",
    "morgan": "^1.7.0",
    "multer": "^1.3.0",
    "passport": "^0.3.2",
    "passport-jwt": "^2.2.1",
    "preboot": "^5.0.0-rc.11",
    "request": "^2.81.0",
    "request-promise": "^4.2.0",
    "rxjs": "^5.4.2",
    "serve-favicon": "^2.3.2",
    "zone.js": "^0.8.12"
  },
  "devDependencies": {
    "angular2-router-loader": "^0.3.5",
    "angular2-template-loader": "^0.6.2",
    "awesome-typescript-loader": "^3.2.1",
    "del-cli": "^1.1.0",
    "html-loader": "^0.4.5",
    "raw-loader": "^0.5.1",
    "typescript": "^2.4.1",
    "webpack": "^3.1.0",
    "webpack-merge": "^4.1.0"
  }
}
</code>```

Thanks for taking a look...

答:
Your <app-root> is AngularJS selector, and your ejs was bootstrapped by nodeJS ejs engine, it won't recognize the AngularJS selector.

just compile your angularJS project by using "ng build" command, then copy all contents in "dist" fold to the "public" fold of your nodejs project (or you need to config the dist path in your nodejs project), it should work, you don't need the index.ejs at all.

Body:
I am building a MEAN app, and have run into a problem I have not faced before.  When I include my app-root selector in my index.ejs file in the Node views, the selector is not recognized and is discarded.  The editor shows this error:

<app-root> is not recognized!  Discarding Unexpected <app-root>

I checked the selector in the App Component to make sure the selector matched, checked the AppModule to make sure I was declaring it, and checked the main.ts to make sure I was bootstrapping correctly.  Everything looks fine, and there isn't an error in the terminal when I run the app.  I've spent about an hour looking for similar questions here and in the Angular documentation, but haven't found anything.

So I'm curious whether anyone else has faced this problem or has an idea of what's happening.  Code below.

 index.ejs

<!DOCTYPE html>

    <link rel='stylesheet' href='/stylesheets/style.css' />

    <app-root>Loading...</app-root>

 App Component

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';
}

 App Module

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { routes } from './route/app.routing';
import { RouterModule } from "@angular/router";
import { AmChartsModule } from "amcharts3-angular2";

import { AppComponent } from './app.component';
import { MapComponent } from './map/map.component';
import { NavbarComponent } from './navbar/navbar.component';
import { MainComponent } from './main/main.component';

//Services
import { NewsApiService } from './service/news-api.service';

@NgModule({
  declarations: [
    AppComponent,
    MapComponent,
    NavbarComponent,
    MainComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule,
    AmChartsModule,
    BrowserModule,
    RouterModule.forRoot(routes)
  ],
  providers: [NewsApiService],
  bootstrap: [AppComponent]
})
export class AppModule { }

 main.ts

import './polyfills';

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule);

 dependencies

{
  "name": "aether-news",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./server/bin/www",
    "build": "del-cli public/js/app && webpack --config webpack.config.dev.js --progress --profile --watch"
  },
  "engines": {
    "node": "7.4.0"
  },
  "dependencies": {
    "@angular/animations": "^4.2.5",
    "@angular/common": "^4.2.5",
    "@angular/compiler": "^4.2.5",
    "@angular/compiler-cli": "^4.2.5",
    "@angular/core": "^4.2.5",
    "@angular/forms": "^4.2.5",
    "@angular/platform-browser": "^4.2.5",
    "@angular/platform-browser-dynamic": "^4.2.5",
    "@angular/platform-server": "^4.2.5",
    "@angular/router": "^4.2.5",
    "@angular/upgrade": "^4.2.5",
    "bcrypt": "^1.0.2",
    "body-parser": "^1.16.1",
    "cookie-parser": "^1.4.3",
    "cors": "^2.8.2",
    "debug": "^2.6.3",
    "ejs": "~2.5.5",
    "express": "^4.14.1",
    "hbs": "^4.0.1",
    "jsonwebtoken": "^7.3.0",
    "mongoose": "^4.9.2",
    "morgan": "^1.7.0",
    "multer": "^1.3.0",
    "passport": "^0.3.2",
    "passport-jwt": "^2.2.1",
    "preboot": "^5.0.0-rc.11",
    "request": "^2.81.0",
    "request-promise": "^4.2.0",
    "rxjs": "^5.4.2",
    "serve-favicon": "^2.3.2",
    "zone.js": "^0.8.12"
  },
  "devDependencies": {
    "angular2-router-loader": "^0.3.5",
    "angular2-template-loader": "^0.6.2",
    "awesome-typescript-loader": "^3.2.1",
    "del-cli": "^1.1.0",
    "html-loader": "^0.4.5",
    "raw-loader": "^0.5.1",
    "typescript": "^2.4.1",
    "webpack": "^3.1.0",
    "webpack-merge": "^4.1.0"
  }
}

Thanks for taking a look...


问:
How do I shape my input data for use with Conv1D in keras?
I have in my dummy dataset 12 vectors of length 200, each vector representing one sample. Let's say x_train is an array with shape (12, 200).

When I do:

```<code>model = Sequential()
model.add(Conv1D(2, 4, input_shape=(1, 200)))
</code>```

I get the error:

```<code>ValueError: Error when checking model input: expected conv1d_1_input to have 3 dimensions, but got array with shape (12, 200)
</code>```

How do I shape my input array correctly?

Here is my updated script:

```<code>data = np.loadtxt('temp/data.csv', delimiter=' ')
trainData = []
testData = []
trainlabels = []
testlabels = []

with open('temp/trainlabels', 'r') as f:
    trainLabelFile = list(csv.reader(f))

with open('temp/testlabels', 'r') as f:
    testLabelFile = list(csv.reader(f))

for i in range(2):
    for idx in trainLabelFile[i]:
        trainData.append(data[int(idx)])
        # append 0 to labels for neg, 1 for pos
        trainlabels.append(i)

for i in range(2):
    for idx in testLabelFile[i]:
        testData.append(data[int(idx)])
        # append 0 to labels for neg, 1 for pos
        testlabels.append(i)

# print(trainData.shape)
X = np.array(trainData)
Y = np.array(trainlabels)
X2 = np.array(testData)
Y2 = np.array(testlabels)

model = Sequential()
model.add(Conv1D(1, 1, input_shape=(12, 1, 200)))

opt = 'adam'
model.compile(loss='mean_squared_error', optimizer=opt, metrics=['accuracy'])

model.fit(X, Y, epochs=epochs)
</code>```

I am now getting a new error:

```<code>ValueError: Input 0 is incompatible with layer conv1d_1: expected ndim=3, found ndim=4
</code>```

答:
You needs to reshape your input data according to Conv1D layer input format - (batch_size, steps, input_dim). Try

```<code>x_train = x_train.reshape(x_train.shape[0], 1, x_train.shape[1])
</code>```

Body:
I have in my dummy dataset 12 vectors of length 200, each vector representing one sample. Let's say x_train is an array with shape (12, 200).

When I do:

model = Sequential()
model.add(Conv1D(2, 4, input_shape=(1, 200)))

I get the error:

ValueError: Error when checking model input: expected conv1d_1_input to have 3 dimensions, but got array with shape (12, 200)

How do I shape my input array correctly?

Here is my updated script:

data = np.loadtxt('temp/data.csv', delimiter=' ')
trainData = []
testData = []
trainlabels = []
testlabels = []

with open('temp/trainlabels', 'r') as f:
    trainLabelFile = list(csv.reader(f))

with open('temp/testlabels', 'r') as f:
    testLabelFile = list(csv.reader(f))

for i in range(2):
    for idx in trainLabelFile[i]:
        trainData.append(data[int(idx)])
        # append 0 to labels for neg, 1 for pos
        trainlabels.append(i)

for i in range(2):
    for idx in testLabelFile[i]:
        testData.append(data[int(idx)])
        # append 0 to labels for neg, 1 for pos
        testlabels.append(i)

# print(trainData.shape)
X = np.array(trainData)
Y = np.array(trainlabels)
X2 = np.array(testData)
Y2 = np.array(testlabels)

model = Sequential()
model.add(Conv1D(1, 1, input_shape=(12, 1, 200)))

opt = 'adam'
model.compile(loss='mean_squared_error', optimizer=opt, metrics=['accuracy'])

model.fit(X, Y, epochs=epochs)

I am now getting a new error:

ValueError: Input 0 is incompatible with layer conv1d_1: expected ndim=3, found ndim=4

Body:
You needs to reshape your input data according to Conv1D layer input format - (batch_size, steps, input_dim). Try

x_train = x_train.reshape(x_train.shape[0], 1, x_train.shape[1])


问:
Report Distance Between Two Turtles
I have a model with two turtles, and the measurement of interest is the distance between them. I'd like to create a reporter that can be plotted that says simply that: the distance between the turtles. Can someone please help? I'm sure this is a simple thing, but I haven't been able to get it.

Thanks!

答:
Since Nicolas urges me to move this from comments to answers, you can retrieve the desired value with:</p>

```<code>[distance turtle 1] of turtle 0
</code>```

Title: Report Distance Between Two Turtles

Body:
Since Nicolas urges me to move this from comments to answers, you can retrieve the desired value with:

[distance turtle 1] of turtle 0


问:
CSS Blend Background with Parent Background
I have a div identified by #front.

It is inside a div identified by #back.

#back is a canvas that constantly changes.

I'd like #front, a square, plain square to take the colour of the parent and invert it.

E.g. if the background is white, the square should be black.
If the background is black, the square should be white. If the background is partially white and partially black, the square should be partially black and partially white.

I have tried background-blend-mode: overlay and mix-blend-mode: screen on the #front element but these had no effect.

Is this possible in any way?

HTML:

CSS:

```<code>#back {
   position:absolute;
   top:0;
   bottom:0;
   left:0;
   right:0;
   background-image:url('http://example.com/image.png');
   background-size:cover;
}

#front {
   width:100px;
   height:100px;
   display:block;
}
</code>```

答:
Use white for the front element, and mix-blend-mode difference:

#back {
   position:absolute;
   top:0;
   left:0;
   width: 600px;
   height: 400px;
   background-image:url(http://lorempixel.com/600/400/);
   background-size:cover;
}

#front {
   width:400px;
   height:300px;
   display:block;
   background-color: white;
    mix-blend-mode: difference;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="back">
<div id="front">
</div>
</div></code>```

Body:
I have a div identified by #front.

It is inside a div identified by #back.

#back is a canvas that constantly changes.

I'd like #front, a square, plain square to take the colour of the parent and invert it.

E.g. if the background is white, the square should be black.
If the background is black, the square should be white. If the background is partially white and partially black, the square should be partially black and partially white.

I have tried background-blend-mode: overlay and mix-blend-mode: screen on the #front element but these had no effect.

Is this possible in any way?

HTML:

CSS:

#back {
   position:absolute;
   top:0;
   bottom:0;
   left:0;
   right:0;
   background-image:url('http://example.com/image.png');
   background-size:cover;
}

#front {
   width:100px;
   height:100px;
   display:block;
}

Body:
Use white for the front element, and mix-blend-mode difference:

#back {
   position:absolute;
   top:0;
   left:0;
   width: 600px;
   height: 400px;
   background-image:url(http://lorempixel.com/600/400/);
   background-size:cover;
}

#front {
   width:400px;
   height:300px;
   display:block;
   background-color: white;
    mix-blend-mode: difference;
}

<div id="back">
<div id="front">
</div>
</div>


问:
Expo on iOS is constantly refreshing my React Native app on MacOS, caused by Dropbox / iCloud
I'm building a simple React Native app and using the Expo iOS app to run it. But Expo is constantly refreshing my app, making it unusable / untestable. It refreshes every few seconds, sometimes multiple times a second, when I haven't changed anything. The only times when there is enough of a break between refreshes for me to test out the app is when, in my terminal, the app decides to rebuild (Again, nothing changed) and takes a few seconds to rebuild the bundle.

I set up the app using create-react-native-app and run it with npm start -- I've changed nothing else, besides adding a few components.

I've tried quitting my IDE (Sublime) and changing to a stronger wifi network.

I'm developing on macOS Sierra 10.12.2 and running on an iPhone 6S.

答:
Do you have watchman installed?

The React Native packager ("metro bundler") watches your app directory for changes and reloads the app whenever a file is changed in the directory, oddly this doesn't cause any problems for me when I use Dropbox, though.


问:
How to send messages from Windows Live Messenger to MS Lync users?
Is there a way to send message from Windows Live Messenger to MS Lync users?

Change some settings or something else?

答:
Yes - you can do this through configuration. Public IM Connectivity (PIC) needs to be enabled on the server.

This article walks through how to enable PIC for IM and presence


问:
beyond basics with rx in python
Started using this fantastic Rx library for validating a YAML file against a schema.

Just wondered, if I can use it for more advanced stuff like:

if a given string value is in a known range. example: value color must be either red/blue/green

can I use regex with it? Example: known file formats are either .txt or .log, so I want to validate any file with these formats - *.txt / *.log

How can I represent a tuple of 2 ints in YAML scheme?

How can I add validation to the keys of map type? for example that the keys are strings, and the key "must_be" must be in it?

答:
You seem to have solved two of these on your own.  On the other two:

can I use regex with it? Example: known file formats are either .txt or .log, so I want to validate any file with these formats - *.txt / *.log

No.  Regex are not sufficiently cross-platform.  I wrote a Perl-only plugin for PCRE, here: https://metacpan.org/release/Data-Rx-Type-PCRE

It should be easy to write a compatible PCRE plugin for any language using PCRE.  Alternately, if you're only using one language, you can just write a plugin in that language for whatever you need like /my/string-ending-with {substr:".txt"} etc.

How can I represent a tuple of 2 ints in YAML scheme?

You have a few options.  I would write:

type: //seq
contents:
- type: //int
- type: //int

Another option:

type: //arr
contents: //int
length:
  min: 2
  max: 2

Title: beyond basics with rx in python


问:
Is there a way to add missing version constraints in Gemfile automatically?
I have many lines in my Gemfile that don't have a version constraint specified. Is there a way to automatically add any missing ones based on what is currently installed?</p>

答:
You could use the output from bundle list to make things a lot quicker, but there's nothing totally automated.

For details on what version constraints to use, check out Thoughtbot's blog post on adding version constraints to Gemfiles, and their Ruby best practice guide.


问:
XSLT - XML to XML Transformation with xsl:for-each
The XML I'm trying to transform looks as follows. I can't post the actual file as it contains sensitive information.

```<code>   <?xml version="1.0" encoding="utf-16"?>
    <TimesheetDetails>
     <timeAllocations>
       <TimeAllocationEntryDetails>
         <activity>
           <displayText> Value </displayText>
         </activity>
       </TimeAllocationEntryDetails>
       <TimeAllocationEntryDetails>
          <activity>
           <displayText> Value </displayText>
         </activity>
       </TimeAllocationEntryDetails>
       <TimeAllocationEntryDetails>
          <activity>
           <displayText> Value </displayText>
         </activity>
       </TimeAllocationEntryDetails>
       <TimeAllocationEntryDetails>
          <activity>
           <displayText> Value </displayText>
         </activity>
       </TimeAllocationEntryDetails>
     </timeAllocations>
    </TimesheetDetais>
</code>```

Here's a simple XSLT stylesheet I wrote to extract the data from the child nodes. It works as expected, however it only returns data from ONE of the TimesheetEntryDetails

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/TimeSheetDetails">
   <xsl:apply-templates select="timeAllocations"/>
</xsl:template>

<xsl:template match="timeAllocations">

<xsl:for-each select="TimeAllocationEntryDetails">
      <xsl:for-each select=".">
          <DisplayText>
          <xsl:value-of select="displayText"/>
          </DisplayText>
      </xsl:for-each>

</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
</code>```

My expected output should look something like

```<code><DisplayText>
   SomeData
</DisplayText>
</code>```

one for each TimeSheetAllocationEntryDetails node under timeheetAllocations.

Any help appreciated. I'm new to XSLT and I have a feeling I'm not using the xsl:for-each construct correctly.

Output I'm getting looks like (just one element ... the first)

```<code><DisplayText>
       SomeData
 </DisplayText>
</code>```

答:
Sample output not matching what I get

Your sample output does not match mine.  You say you're getting:

```<code><DisplayText>
    SomeData
</DisplayText>
</code>```

When I run your XSL against your sample input XML, I get this:

```<code><DisplayText/><DisplayText/><DisplayText/><DisplayText/>
</code>```

I do indeed get one <DisplayText> element per input <TimeAllocationEntryDetails> element, as expected.  These elements are also empty, as expected.

Breaking down issues in your code

Your first template is in order:

```<code><xsl:template match="/TimeSheetDetails">
    <xsl:apply-templates select="timeAllocations"/>
</xsl:template>
</code>```

<TimeSheetDetails> is indeed the topmost element in the input XML, and this has <timeAllocations> children.

The next template has some problems:

```<code><xsl:template match="timeAllocations">
    <xsl:for-each select="TimeAllocationEntryDetails">
        <xsl:for-each select=".">
            <DisplayText>
                <xsl:value-of select="displayText"/>
            </DisplayText>
        </xsl:for-each>
    </xsl:for-each>
</xsl:template>
</code>```

One stylistic issue is the use of <xsl:for-each select="TimeAllocationEntryDetails"> here.  Since the <timeAllocations> element has <TimeAllocationEntryDetails> children, it is more common to use <xsl:apply-templates/>, optionally specifying select="TimeAllocationEntryDetails", and then define a template for handling these elements -- much as you do in your first template.

That aside, you process each <TimeAllocationEntryDetails>, and then within each one of these, you have another <xsl:for-each select=".">.  This selects ., which means "the context element" -- which is just the current <TimeAllocationEntryDetails> again.  This second nested for-each is thus wholly unnecessary.

Within the for-each structure, you next have:

```<code>        <DisplayText>
            <xsl:value-of select="displayText"/>
        </DisplayText>
</code>```

So for each <TimeAllocationEntryDetails> element, we create one <DisplayText> element.  We have four <TimeAllocationEntryDetails> elements in the input XML, and four <DisplayText> elements in the output XML -- so this works just fine.

Within that <DisplayText> element, you try to get the value of the <displayText> element that is a child of the <TimeAllocationEntryDetails> context element.  Since no such <displayText> element exists, this value-of produces nothing -- so the output <DisplayText> elements are all empty.

UPDATE

Your edit changed your input XML.  This is what I was responding to:

```<code><TimesheetDetails>
    <timeAllocations>
        <TimeAllocationEntryDetails>
            .. some child nodes
        </TimeAllocationEntryDetails>
        <TimeAllocationEntryDetails>
            .. some child nodes
        </TimeAllocationEntryDetails>
        <TimeAllocationEntryDetails>
            .. some child nodes
        </TimeAllocationEntryDetails>
        <TimeAllocationEntryDetails>
            .. some child nodes
        </TimeAllocationEntryDetails>
    </timeAllocations>
</TimesheetDetails>
</code>```

With your new input XML, the <displayText> elements now exist, but not at the XPath you're using in <xsl:value-of select="displayText"/>.  This again is looking for the value of the <displayText> element that is an immediate child of the context element, which in your case would be the <TimeAllocationEntryDetails> element.  Since <displayText> is not an immediate child, this call to value-of produces nothing.

If you want to just output the string value of the entire context XML structure, you could just use <xsl:value-of select="."/> instead.

If you want only the value of the <displayText> element to the exclusion of anything else, either 1) specify the exact XPath to this element, as <xsl:value-of select="activity/displayText"/>, or 2) use the descendant:: axis, as <xsl:value-of select="descendant::displayText"/>, or 3) use the // shorthand for descendant::, as <xsl:value-of select=".//displayText"/> (note that you need the ., or //displayText equates to the collection of all displayText elements anywhere in the entire file).

Body:
The XML I'm trying to transform looks as follows. I can't post the actual file as it contains sensitive information.

   <?xml version="1.0" encoding="utf-16"?>
    <TimesheetDetails>
     <timeAllocations>
       <TimeAllocationEntryDetails>
         <activity>
           <displayText> Value </displayText>
         </activity>
       </TimeAllocationEntryDetails>
       <TimeAllocationEntryDetails>
          <activity>
           <displayText> Value </displayText>
         </activity>
       </TimeAllocationEntryDetails>
       <TimeAllocationEntryDetails>
          <activity>
           <displayText> Value </displayText>
         </activity>
       </TimeAllocationEntryDetails>
       <TimeAllocationEntryDetails>
          <activity>
           <displayText> Value </displayText>
         </activity>
       </TimeAllocationEntryDetails>
     </timeAllocations>
    </TimesheetDetais>

Here's a simple XSLT stylesheet I wrote to extract the data from the child nodes. It works as expected, however it only returns data from ONE of the TimesheetEntryDetails

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/TimeSheetDetails">
   <xsl:apply-templates select="timeAllocations"/>
</xsl:template>

<xsl:template match="timeAllocations">

<xsl:for-each select="TimeAllocationEntryDetails">
      <xsl:for-each select=".">
          <DisplayText>
          <xsl:value-of select="displayText"/>
          </DisplayText>
      </xsl:for-each>

</xsl:for-each>
</xsl:template>
</xsl:stylesheet>

My expected output should look something like

<DisplayText>
   SomeData
</DisplayText>

one for each TimeSheetAllocationEntryDetails node under timeheetAllocations.

Any help appreciated. I'm new to XSLT and I have a feeling I'm not using the xsl:for-each construct correctly.

Output I'm getting looks like (just one element ... the first)

<DisplayText>
       SomeData
 </DisplayText>

Body:
Sample output not matching what I get

Your sample output does not match mine.  You say you're getting:

<DisplayText>
    SomeData
</DisplayText>

When I run your XSL against your sample input XML, I get this:

<DisplayText/><DisplayText/><DisplayText/><DisplayText/>

I do indeed get one <DisplayText> element per input <TimeAllocationEntryDetails> element, as expected.  These elements are also empty, as expected.

Breaking down issues in your code

Your first template is in order:

<xsl:template match="/TimeSheetDetails">
    <xsl:apply-templates select="timeAllocations"/>
</xsl:template>

<TimeSheetDetails> is indeed the topmost element in the input XML, and this has <timeAllocations> children.

The next template has some problems:

<xsl:template match="timeAllocations">
    <xsl:for-each select="TimeAllocationEntryDetails">
        <xsl:for-each select=".">
            <DisplayText>
                <xsl:value-of select="displayText"/>
            </DisplayText>
        </xsl:for-each>
    </xsl:for-each>
</xsl:template>

One stylistic issue is the use of <xsl:for-each select="TimeAllocationEntryDetails"> here.  Since the <timeAllocations> element has <TimeAllocationEntryDetails> children, it is more common to use <xsl:apply-templates/>, optionally specifying select="TimeAllocationEntryDetails", and then define a template for handling these elements -- much as you do in your first template.

That aside, you process each <TimeAllocationEntryDetails>, and then within each one of these, you have another <xsl:for-each select=".">.  This selects ., which means "the context element" -- which is just the current <TimeAllocationEntryDetails> again.  This second nested for-each is thus wholly unnecessary.

Within the for-each structure, you next have:

        <DisplayText>
            <xsl:value-of select="displayText"/>
        </DisplayText>

So for each <TimeAllocationEntryDetails> element, we create one <DisplayText> element.  We have four <TimeAllocationEntryDetails> elements in the input XML, and four <DisplayText> elements in the output XML -- so this works just fine.

Within that <DisplayText> element, you try to get the value of the <displayText> element that is a child of the <TimeAllocationEntryDetails> context element.  Since no such <displayText> element exists, this value-of produces nothing -- so the output <DisplayText> elements are all empty.

UPDATE

Your edit changed your input XML.  This is what I was responding to:

<TimesheetDetails>
    <timeAllocations>
        <TimeAllocationEntryDetails>
            .. some child nodes
        </TimeAllocationEntryDetails>
        <TimeAllocationEntryDetails>
            .. some child nodes
        </TimeAllocationEntryDetails>
        <TimeAllocationEntryDetails>
            .. some child nodes
        </TimeAllocationEntryDetails>
        <TimeAllocationEntryDetails>
            .. some child nodes
        </TimeAllocationEntryDetails>
    </timeAllocations>
</TimesheetDetails>

With your new input XML, the <displayText> elements now exist, but not at the XPath you're using in <xsl:value-of select="displayText"/>.  This again is looking for the value of the <displayText> element that is an immediate child of the context element, which in your case would be the <TimeAllocationEntryDetails> element.  Since <displayText> is not an immediate child, this call to value-of produces nothing.

If you want to just output the string value of the entire context XML structure, you could just use <xsl:value-of select="."/> instead.

If you want only the value of the <displayText> element to the exclusion of anything else, either 1) specify the exact XPath to this element, as <xsl:value-of select="activity/displayText"/>, or 2) use the descendant:: axis, as <xsl:value-of select="descendant::displayText"/>, or 3) use the // shorthand for descendant::, as <xsl:value-of select=".//displayText"/> (note that you need the ., or //displayText equates to the collection of all displayText elements anywhere in the entire file).


问:
How to retrieve RouteValues in ActionSelector in ASP.NET Core
I've created a GitHub repo to better understand the problem here. I have two actions on two different controllers bound to the same route.

```<code>http://localhost/sameControllerRoute/{identifier}/values

[Route("sameControllerRoute")]
public class FirstController : Controller
{
    public FirstController()
    {
        // different EF Core DataContext than SecondController and possibly other dependencies than SecondController
    }

    [HttpGet("{identifier}/values")]
    public IActionResult Values(string identifier, DateTime from, DateTime to) // other parameters than SecondController/Values
    {
        return this.Ok("Was in FirstController");
    }
}

[Route("sameControllerRoute")]
public class SecondController : Controller
{
    public SecondController()
    {
        // different EF Core DataContext than FirstController and possibly other dependencies than FirstController
    }

    [HttpGet("{identifier}/values")]
    public IActionResult Values(string identifier, int number, string somethingElse) // other parameters than FirstController/Values
    {
        return this.Ok("Was in SecondController");
    }
}
</code>```

Since there are two matching routes, the default ActionSelector fails with:

'[...] AmbiguousActionException: Multiple actions matched. [...]'
  which is comprehensible.

So I thought I can implement my own ActionSelector. In there I would implement the logic that resolves the issue of multiple routes via same logic depending on the 'identifier' route value (line 27 in code)

If 'identifier' value is a --> then FirstController

If 'identifier' value is b --> then SecondController

and so on...

```<code>    protected override IReadOnlyList<ActionDescriptor> SelectBestActions(IReadOnlyList<ActionDescriptor> actions)
    {
        if (actions.HasLessThan(2)) return base.SelectBestActions(actions); // works like base implementation

        foreach (var action in actions)
        {
            if (action.Parameters.Any(p => p.Name == "identifier"))
            {
                /*** get value of identifier from route (launchSettings this would result in 'someIdentifier') ***/

                // call logic that decides whether value of identifier matches the controller

                // if yes
                return new List<ActionDescriptor>(new[] { action }).AsReadOnly();

                // else
                // keep going
            }
        }

        return base.SelectBestActions(actions); // fail in all other cases with AmbiguousActionException
    }
</code>```

But I haven't found a good solution to get access to the route values in ActionSelector. Which is comprehensible as well because ModelBinding hasn't kicked in yet since MVC is still trying to figure out the Route.

A dirty solution could be to get hold of IHttpContextAccessor and regex somehow against the path.

But I'm still hoping you could provide a better idea to retrieve the route values even though ModelBinding hasn't happend yet in the request pipeline.

答:
I ended up implementing the proposed solution by the ASP.NET team. This was to implement an IActionConstrain as shown here:

```<code>// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using Microsoft.AspNetCore.Mvc.ActionConstraints;

namespace ActionConstraintSample.Web
{
    public class CountrySpecificAttribute : Attribute, IActionConstraint
    {
        private readonly string _countryCode;

        public CountrySpecificAttribute(string countryCode)
        {
            _countryCode = countryCode;
        }

        public int Order
        {
            get
            {
                return 0;
            }
        }

        public bool Accept(ActionConstraintContext context)
        {
            return string.Equals(
                context.RouteContext.RouteData.Values["country"].ToString(),
                _countryCode,
                StringComparison.OrdinalIgnoreCase);
        }
    }
}
</code>```

https://github.com/aspnet/Entropy/blob/dev/samples/Mvc.ActionConstraintSample.Web/CountrySpecificAttribute.cs

Body:
I've created a GitHub repo to better understand the problem here. I have two actions on two different controllers bound to the same route.

http://localhost/sameControllerRoute/{identifier}/values

[Route("sameControllerRoute")]
public class FirstController : Controller
{
    public FirstController()
    {
        // different EF Core DataContext than SecondController and possibly other dependencies than SecondController
    }

    [HttpGet("{identifier}/values")]
    public IActionResult Values(string identifier, DateTime from, DateTime to) // other parameters than SecondController/Values
    {
        return this.Ok("Was in FirstController");
    }
}

[Route("sameControllerRoute")]
public class SecondController : Controller
{
    public SecondController()
    {
        // different EF Core DataContext than FirstController and possibly other dependencies than FirstController
    }

    [HttpGet("{identifier}/values")]
    public IActionResult Values(string identifier, int number, string somethingElse) // other parameters than FirstController/Values
    {
        return this.Ok("Was in SecondController");
    }
}

Since there are two matching routes, the default ActionSelector fails with:

'[...] AmbiguousActionException: Multiple actions matched. [...]'
  which is comprehensible.

So I thought I can implement my own ActionSelector. In there I would implement the logic that resolves the issue of multiple routes via same logic depending on the 'identifier' route value (line 27 in code)

If 'identifier' value is a --> then FirstController

If 'identifier' value is b --> then SecondController

and so on...

    protected override IReadOnlyList<ActionDescriptor> SelectBestActions(IReadOnlyList<ActionDescriptor> actions)
    {
        if (actions.HasLessThan(2)) return base.SelectBestActions(actions); // works like base implementation

        foreach (var action in actions)
        {
            if (action.Parameters.Any(p => p.Name == "identifier"))
            {
                /*** get value of identifier from route (launchSettings this would result in 'someIdentifier') ***/

                // call logic that decides whether value of identifier matches the controller

                // if yes
                return new List<ActionDescriptor>(new[] { action }).AsReadOnly();

                // else
                // keep going
            }
        }

        return base.SelectBestActions(actions); // fail in all other cases with AmbiguousActionException
    }

But I haven't found a good solution to get access to the route values in ActionSelector. Which is comprehensible as well because ModelBinding hasn't kicked in yet since MVC is still trying to figure out the Route.

A dirty solution could be to get hold of IHttpContextAccessor and regex somehow against the path.

But I'm still hoping you could provide a better idea to retrieve the route values even though ModelBinding hasn't happend yet in the request pipeline.

Body:
I ended up implementing the proposed solution by the ASP.NET team. This was to implement an IActionConstrain as shown here:

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using Microsoft.AspNetCore.Mvc.ActionConstraints;

namespace ActionConstraintSample.Web
{
    public class CountrySpecificAttribute : Attribute, IActionConstraint
    {
        private readonly string _countryCode;

        public CountrySpecificAttribute(string countryCode)
        {
            _countryCode = countryCode;
        }

        public int Order
        {
            get
            {
                return 0;
            }
        }

        public bool Accept(ActionConstraintContext context)
        {
            return string.Equals(
                context.RouteContext.RouteData.Values["country"].ToString(),
                _countryCode,
                StringComparison.OrdinalIgnoreCase);
        }
    }
}

https://github.com/aspnet/Entropy/blob/dev/samples/Mvc.ActionConstraintSample.Web/CountrySpecificAttribute.cs


问:
Why does CDT rebuild my C-project on Ant build in unrelated project?
I have an Eclipse workspace where a CDT project lives together with other unrelated projects. However, when I run "build as Ant build" in one of those projects, CDT insists on rebuilding its projects too.

Anyone have any ideas where to look to disconnect this "hidden" dependency? (And no, it's not in the "Linked Resources" or the "Project References"...)

答:
Project builders are run at the request of some build trigger. This might be resource changes (when you have build automatically enabled) or it could be the build action you're using: "build as Ant build".  The build action may be inadvertently requesting a build of the whole workspace.

Put the following in a text file:

```<code># Eclipse build
org.eclipse.core.resources/debug=true
org.eclipse.core.resources/build/interrupt=true
org.eclipse.core.resources/build/invoking=true
org.eclipse.core.resources/build/needbuild=true
#Managedbuild
org.eclipse.cdt.managedbuilder.core/debug/builder=true
org.eclipse.cdt.managedbuilder.core/debug=true
org.eclipse.cdt.managedbuilder.core/debug/pathEntryInit=false
org.eclipse.cdt.managedbuilder.core/debug/pathEntry=false
</code>```

And run Eclipse with the additional switches:

```<code>-debug <trace_options>.file
</code>```

This will echo trace prints to the shell in which you started Eclipse. You can use this to better target the bug report you'll no doubt file :)

Body:
Project builders are run at the request of some build trigger. This might be resource changes (when you have build automatically enabled) or it could be the build action you're using: "build as Ant build".  The build action may be inadvertently requesting a build of the whole workspace.

Put the following in a text file:

# Eclipse build
org.eclipse.core.resources/debug=true
org.eclipse.core.resources/build/interrupt=true
org.eclipse.core.resources/build/invoking=true
org.eclipse.core.resources/build/needbuild=true
#Managedbuild
org.eclipse.cdt.managedbuilder.core/debug/builder=true
org.eclipse.cdt.managedbuilder.core/debug=true
org.eclipse.cdt.managedbuilder.core/debug/pathEntryInit=false
org.eclipse.cdt.managedbuilder.core/debug/pathEntry=false

And run Eclipse with the additional switches:

-debug <trace_options>.file

This will echo trace prints to the shell in which you started Eclipse. You can use this to better target the bug report you'll no doubt file :)


问:
Android Virtual Device/ Android Emulator - Decryption Unsuccessful
I just installed Android Studio, and I am very new with this program.

So when I run the Android Emulator it says: "To Start Android, enter your password", although I have never set a password. When I just enter a word with 4 letters it says "The Password you entered is correct, but unfortunately your data is corrupt".

After that, I have to Reset the Phone, but when I do that the same menu with "To Start Android, enter your password" appears.

Maybe it is just an easy mistake, but as I said I am new with this. I also did some research on the internet but I did not find anything useful.

this is the 2 images that it showe me:

1)
2)

and after i clicked on reset phone, nothing happened.

I would be very glad if someone has an answer for this.

答:
Check out "Viewing and managing your Avds" part. Try wiping data of your emulator or create a new emulator for yourself.

https://developer.android.com/studio/run/managing-avds.html


问:
How to complete a function execution before starting to execute another function
Please I have used .done() to ensure a function is completely executed before starting to execute next function. I borrowed the idea from Ajax. But it is not working. I keep getting error message done() is not a function.
Is done() only for Ajax? If yes, how can I accomplish my wish.

```<code>document.onreadystatechange = function () {
  if (document.readyState === "complete") {
    //do somethings

  }
}

//This must be completely executed before addNu()
$( "#mybutton" ).click(function() {
  //Do some things

}).done(addNu());

function addNu() {
  //do some things
}
</code>```

Note that none of the script is async. each must be completed before running the next

答:
I have gone through solutions given here and references prescribed. None worked because these scripts are neither ajax nor async.
I solved it this way:</p>

```<code>document.onreadystatechange = function () {
  if (document.readyState === "complete") {
    //do somethings

  }
}

//This must be completely executed before addNu()
$( "#mybutton" ).click(function() {
  //Do some things

  //Check if completely done e.g.
  length = $('img').length;

  if (!length) {
     addNu();
  }
});

function addNu() {
 //do some things

}
</code>```

Body:
Please I have used .done() to ensure a function is completely executed before starting to execute next function. I borrowed the idea from Ajax. But it is not working. I keep getting error message done() is not a function.
Is done() only for Ajax? If yes, how can I accomplish my wish.

document.onreadystatechange = function () {
  if (document.readyState === "complete") {
    //do somethings

  }
}

//This must be completely executed before addNu()
$( "#mybutton" ).click(function() {
  //Do some things

}).done(addNu());

function addNu() {
  //do some things
}

Note that none of the script is async. each must be completed before running the next

Body:
I have gone through solutions given here and references prescribed. None worked because these scripts are neither ajax nor async.
I solved it this way:

document.onreadystatechange = function () {
  if (document.readyState === "complete") {
    //do somethings

  }
}

//This must be completely executed before addNu()
$( "#mybutton" ).click(function() {
  //Do some things

  //Check if completely done e.g.
  length = $('img').length;

  if (!length) {
     addNu();
  }
});

function addNu() {
 //do some things

}


问:
How can I monitor the number of incoming and processed files in a directory with PowerShell?
I have this PowerShell script that monitors the number of files present in a directory. Here it is:

```<code>#sleep in seconds
$SleepTimeOut = 300

#start looping here
Do{
     $path = 'TargetDirectory'
     $stats = 0
     $files = @(Get-ChildItem -Path $path -Filter '*.ZIP')
     if ($files -ne $null) {
          $stats = $files.Count
          } else {
     $msg = 'Message: No files'
     Write-Output $msg
     }
     Get-Date | Out-File -Append 'C:\Monitoring\Logs.csv'
     Write-Output "Count: $stats files" | Out-File -Append 'C:\Monitoring\Logs.csv'

     Write-Output ".. Files COUNT in Progress...Please Don't Close ..`n"
     sleep $SleepTimeOut

}
while ($Exit -ne $True)
</code>```

It appends the results to a CSV file. I just want to know if there is a way to monitor the incoming and processed files within that 5-minute sleep duration of the script. Any help would be very appreciated.

答: As BenH mentioned you can try using events with IO.FileSystemWather. If that option does not work for you the other option you have is to use GetChildItem for the folder you want to watch and check for the LastWriteTime in each file. Do a comparison check from the last time your loop ran and document any new or updated files.

Body:
I have this PowerShell script that monitors the number of files present in a directory. Here it is:

#sleep in seconds
$SleepTimeOut = 300

#start looping here
Do{
     $path = 'TargetDirectory'
     $stats = 0
     $files = @(Get-ChildItem -Path $path -Filter '*.ZIP')
     if ($files -ne $null) {
          $stats = $files.Count
          } else {
     $msg = 'Message: No files'
     Write-Output $msg
     }
     Get-Date | Out-File -Append 'C:\Monitoring\Logs.csv'
     Write-Output "Count: $stats files" | Out-File -Append 'C:\Monitoring\Logs.csv'

     Write-Output ".. Files COUNT in Progress...Please Don't Close ..`n"
     sleep $SleepTimeOut

}
while ($Exit -ne $True)

It appends the results to a CSV file. I just want to know if there is a way to monitor the incoming and processed files within that 5-minute sleep duration of the script. Any help would be very appreciated.


问:
UITableView - Custom selectedBackgroundView in custom UITableViewCell hides cell separator when selected
I have a UITableView that renders cells of the custom class DrawerTableCell, that is declared this way:

```<code>class DrawerTableCell: UITableViewCell {

    @IBInspectable var selectionColor: UIColor = .gray {
        didSet {
            configureSelectedBackgroundView()
        }
    }

    func configureSelectedBackgroundView() {
        let view = UIView()
        view.backgroundColor = selectionColor
        selectedBackgroundView = view
    }
}
</code>```

This UITableViewCell child class was created in order to be able to specify the selected background color for the cell.

In my View Controller I set:

```<code>tableView.separatorColor = .white
</code>```

and I configure the cell this way:

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "drawerCell") as! DrawerTableCell
    cell.selectionColor = UIColor.blue
    return cell
}
</code>```

The results is that when there is no cell selected, all the separators display correctly. When I select a cell, the background color is showed, but the separator is hidden only in the selected cell.

Any ideas on how to keep the separator line in the selected cell?

Thanks.

答:
according to Apple's documentation, UITableViewCell adds the value of this property as a subview only when the cell is selected. It adds the selected background view as a subview directly above the background view (backgroundView) if it is not nil, or behind all other views. </p>

<p>So according to this, I think your separator is hidden because it's underneath your new view. Try setting your selectionColor to .clear and see what happens. If this doesn't work, you can also try removing separators on your table view completely, and just add a 0.5px line to the bottom of each cell instead. </p>

Body:
I have a UITableView that renders cells of the custom class DrawerTableCell, that is declared this way:

class DrawerTableCell: UITableViewCell {

    @IBInspectable var selectionColor: UIColor = .gray {
        didSet {
            configureSelectedBackgroundView()
        }
    }

    func configureSelectedBackgroundView() {
        let view = UIView()
        view.backgroundColor = selectionColor
        selectedBackgroundView = view
    }
}

This UITableViewCell child class was created in order to be able to specify the selected background color for the cell.

In my View Controller I set:

tableView.separatorColor = .white

and I configure the cell this way:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "drawerCell") as! DrawerTableCell
    cell.selectionColor = UIColor.blue
    return cell
}

The results is that when there is no cell selected, all the separators display correctly. When I select a cell, the background color is showed, but the separator is hidden only in the selected cell.

Any ideas on how to keep the separator line in the selected cell?

Thanks.

Body:
according to Apple's documentation, UITableViewCell adds the value of this property as a subview only when the cell is selected. It adds the selected background view as a subview directly above the background view (backgroundView) if it is not nil, or behind all other views.

So according to this, I think your separator is hidden because it's underneath your new view. Try setting your selectionColor to .clear and see what happens. If this doesn't work, you can also try removing separators on your table view completely, and just add a 0.5px line to the bottom of each cell instead.


问:
.NET Multi-Target with .NET Standard and Portable Library MSBuild 15
Porting to .NET standard version, you may be source identical to a portable library, but the platforms supported may not.

For example .NET standard 1.6 might be the lowest version that has your api's available from portable Profile47. Profile47 supports .net 4.5 or later, nut .NET Standard 1.6 only supports 4.6.1 and later!

With the new multi-targeting with the new msbuild 15 csproj/fsproj (also VS2017) is it possible to compile for both a Portable Library and .Net Standard at the same time to make the transition easier?

答:
Yes, but it's not as obvious as cross compiling .netstandard with .net45 or .net40 as the aren't easy monikers for your portable libraries predefined.

In the new sdk's Microsoft.NET.TargetFrameworkInference.targets it says:

For cases where inference is not supported, identifier, version and
  profile can be specified explicitly as follows:

```<code>   <PropertyGroup>
     <TargetFrameworks>portable-net451+win81;xyz1.0</TargetFrameworks>
   <PropertyGroup>
   <PropertyGroup Condition="'$(TargetFramework)' == 'portable-net451+win81'">
     <TargetFrameworkIdentifier>.NETPortable</TargetFrameworkIdentifier>
     <TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
     <TargetFrameworkProfile>Profile44</TargetFrameworkProfile>
   </PropertyGroup>
   <PropertyGroup Condition="'$(TargetFramework)' == 'xyz1.0'">
     <TargetFrameworkIdentifier>Xyz</TargetFrameworkVersion>
   <PropertyGroup>
</code>```

TargetFrameworkProfile You get that from your old csproj/fsproj. That's the Profile identifier your portable library. You can also look it up from Nuget Target Frameworks as well.

TargetFrameworkIdentifier is easy, it's .NETPortable

TargetFrameworkProfile Probably also can get from your old csproj/fsprog. But you can also check C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETPortable\ and check the v4.0, v4.5, and v4.6 Profile directories and find your Profile. A listing of those directories is as follows:

v4.0

```<code>Profile1/    Profile143/  Profile2/    Profile3/    Profile4/   Profile6/
Profile102/  Profile147/  Profile225/  Profile328/  Profile41/  Profile88/
Profile104/  Profile154/  Profile23/   Profile336/  Profile42/  Profile92/
Profile131/  Profile158/  Profile24/   Profile344/  Profile46/  Profile95/
Profile136/  Profile18/   Profile240/  Profile36/   Profile47/  Profile96/
Profile14/   Profile19/   Profile255/  Profile37/   Profile5/
</code>```

v4.5

```<code>Profile111/  Profile259/  Profile49/  Profile7/  Profile75/  Profile78/
</code>```

v4.6

```<code>Profile151/  Profile157/  Profile31/  Profile32/  Profile44/  Profile84/
</code>```

Does the moniker you choose for your portable targets? Yes and no, it matters for automatically packaging for nuget, so it's best to use the value from Nuget Target Frameworks with one caveat. I'm not sure if it's because of the newest version of nuget, but it seems to want the TargetFrameworkVersion added to portable in the moniker. So for Profile47, which is v4.0, should actually be portable40-net45+sl5+win8

Another item to add a compiler define which you might find useful using DefineConstants. You can make it anything you want, it's been historically the PROFILEXXX in caps, just add it to the Conditional Group.

```<code><DefineConstants>$(DefineConstants);PROFILE47</DefineConstants>
</code>```

The final thing to note, default Reference includes are not provided so you will have to add your own.

```<code><ItemGroup Condition="'$(TargetFramework)'=='portable40-net45+sl5+win8'">
  <Reference Include="System" />
  <Reference Include="System.Core" />
  <Reference Include="System.Windows" />
</ItemGroup>
</code>```

CSharp Example

```<code><Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFrameworks>netstandard1.6;portable40-net45+sl5+win8</TargetFrameworks>
    <Description>YOUR DESCRIPTION</Description>
    <Company>YOUR COMPANY</Company>
    <Authors> YOUR AUTHORS </Authors>
    <Copyright>YOUR COPYRIGHT</Copyright>
    <AssemblyVersion>YOUR VERSION</AssemblyVersion>
    <FileVersion>YOUR VERSION</FileVersion>
    <PackageProjectUrl>YOUR PROJECT URL</PackageProjectUrl>
    <PackageLicenseUrl>YOUR LICENSE</PackageLicenseUrl>
    <PackageTags>YOUR TAGS</PackageTags>
    <IncludeSymbols>True</IncludeSymbols>
    <IncludeSource>True</IncludeSource>
    <GeneratePackageOnBuild>True</GeneratePackageOnBuild>
    <PackageRequireLicenseAcceptance>True</PackageRequireLicenseAcceptance>
    <Version>YOUR NUGET VERSION</Version>
  </PropertyGroup>

  <PropertyGroup Condition="'$(TargetFramework)'=='portable40-net45+sl5+win8'">
     <TargetFrameworkIdentifier>.NETPortable</TargetFrameworkIdentifier>
     <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
     <TargetFrameworkProfile>Profile47</TargetFrameworkProfile>
     <DefineConstants>$(DefineConstants);PROFILE47</DefineConstants>
   </PropertyGroup>

  <ItemGroup Condition="'$(TargetFramework)'=='portable40-net45+sl5+win8'">
    <Reference Include="System" />
    <Reference Include="System.Core" />
    <Reference Include="System.Windows" />
  </ItemGroup>

</Project>
</code>```

F# Example

*Caveat: F# requires beta version of Mono for Mac or Visual Studio 2017 preview 15.3 presently for this fsproj. Also a change from examples includes a PackageReference to FSharp.Compiler.Tools and FSharp.Core 4.1 the last portable supported FSharp versions (which is relatively quite recent.)

```<code><Project Sdk="FSharp.NET.Sdk;Microsoft.NET.Sdk" ToolsVersion="15.0">

  <PropertyGroup>
    <TargetFrameworks>netstandard1.6;portable40-net45+sl5+win8</TargetFrameworks>
    <Description>YOUR DESCRIPTION</Description>
    <Company>YOUR COMPANY</Company>
    <Authors> YOUR AUTHORS </Authors>
    <Copyright>YOUR COPYRIGHT</Copyright>
    <AssemblyVersion>YOUR VERSION</AssemblyVersion>
    <FileVersion>YOUR VERSION</FileVersion>
    <PackageProjectUrl>YOUR PROJECT URL</PackageProjectUrl>
    <PackageLicenseUrl>YOUR LICENSE</PackageLicenseUrl>
    <PackageTags>YOUR TAGS</PackageTags>
    <IncludeSymbols>True</IncludeSymbols>
    <IncludeSource>True</IncludeSource>
    <GeneratePackageOnBuild>True</GeneratePackageOnBuild>
    <PackageRequireLicenseAcceptance>True</PackageRequireLicenseAcceptance>
    <Version>YOUR NUGET VERSION</Version>
  </PropertyGroup>

  <PropertyGroup Condition="'$(TargetFramework)'=='portable40-net45+sl5+win8'">
     <TargetFrameworkIdentifier>.NETPortable</TargetFrameworkIdentifier>
     <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
     <TargetFrameworkProfile>Profile47</TargetFrameworkProfile>
     <DefineConstants>$(DefineConstants);PROFILE47</DefineConstants>
   </PropertyGroup>

  <ItemGroup Condition="'$(TargetFramework)'=='portable40-net45+sl5+win8'">
    <Reference Include="System" />
    <Reference Include="System.Core" />
    <Reference Include="System.Windows" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="FSharp.Core" Version="4.1.*" />
    <PackageReference Include="FSharp.Compiler.Tools" Version="4.1.*" PrivateAssets="All"
    />
    <PackageReference Include="FSharp.NET.Sdk" Version="1.0.*" PrivateAssets="All"
    />
  </ItemGroup>

  <ItemGroup>
    <Compile Include="YourModule1.fs" />
    <Compile Include="YourModule2.fs" />
  </ItemGroup>

</Project>
</code>```

Body:
Yes, but it's not as obvious as cross compiling .netstandard with .net45 or .net40 as the aren't easy monikers for your portable libraries predefined.

In the new sdk's Microsoft.NET.TargetFrameworkInference.targets it says:

For cases where inference is not supported, identifier, version and
  profile can be specified explicitly as follows:

   <PropertyGroup>
     <TargetFrameworks>portable-net451+win81;xyz1.0</TargetFrameworks>
   <PropertyGroup>
   <PropertyGroup Condition="'$(TargetFramework)' == 'portable-net451+win81'">
     <TargetFrameworkIdentifier>.NETPortable</TargetFrameworkIdentifier>
     <TargetFrameworkVersion>v4.6</TargetFrameworkVersion>
     <TargetFrameworkProfile>Profile44</TargetFrameworkProfile>
   </PropertyGroup>
   <PropertyGroup Condition="'$(TargetFramework)' == 'xyz1.0'">
     <TargetFrameworkIdentifier>Xyz</TargetFrameworkVersion>
   <PropertyGroup>

TargetFrameworkProfile You get that from your old csproj/fsproj. That's the Profile identifier your portable library. You can also look it up from Nuget Target Frameworks as well.

TargetFrameworkIdentifier is easy, it's .NETPortable

TargetFrameworkProfile Probably also can get from your old csproj/fsprog. But you can also check C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETPortable\ and check the v4.0, v4.5, and v4.6 Profile directories and find your Profile. A listing of those directories is as follows:

v4.0

Profile1/    Profile143/  Profile2/    Profile3/    Profile4/   Profile6/
Profile102/  Profile147/  Profile225/  Profile328/  Profile41/  Profile88/
Profile104/  Profile154/  Profile23/   Profile336/  Profile42/  Profile92/
Profile131/  Profile158/  Profile24/   Profile344/  Profile46/  Profile95/
Profile136/  Profile18/   Profile240/  Profile36/   Profile47/  Profile96/
Profile14/   Profile19/   Profile255/  Profile37/   Profile5/

v4.5

Profile111/  Profile259/  Profile49/  Profile7/  Profile75/  Profile78/

v4.6

Profile151/  Profile157/  Profile31/  Profile32/  Profile44/  Profile84/

Does the moniker you choose for your portable targets? Yes and no, it matters for automatically packaging for nuget, so it's best to use the value from Nuget Target Frameworks with one caveat. I'm not sure if it's because of the newest version of nuget, but it seems to want the TargetFrameworkVersion added to portable in the moniker. So for Profile47, which is v4.0, should actually be portable40-net45+sl5+win8

Another item to add a compiler define which you might find useful using DefineConstants. You can make it anything you want, it's been historically the PROFILEXXX in caps, just add it to the Conditional Group.

<DefineConstants>$(DefineConstants);PROFILE47</DefineConstants>

The final thing to note, default Reference includes are not provided so you will have to add your own.

<ItemGroup Condition="'$(TargetFramework)'=='portable40-net45+sl5+win8'">
  <Reference Include="System" />
  <Reference Include="System.Core" />
  <Reference Include="System.Windows" />
</ItemGroup>

CSharp Example

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFrameworks>netstandard1.6;portable40-net45+sl5+win8</TargetFrameworks>
    <Description>YOUR DESCRIPTION</Description>
    <Company>YOUR COMPANY</Company>
    <Authors> YOUR AUTHORS </Authors>
    <Copyright>YOUR COPYRIGHT</Copyright>
    <AssemblyVersion>YOUR VERSION</AssemblyVersion>
    <FileVersion>YOUR VERSION</FileVersion>
    <PackageProjectUrl>YOUR PROJECT URL</PackageProjectUrl>
    <PackageLicenseUrl>YOUR LICENSE</PackageLicenseUrl>
    <PackageTags>YOUR TAGS</PackageTags>
    <IncludeSymbols>True</IncludeSymbols>
    <IncludeSource>True</IncludeSource>
    <GeneratePackageOnBuild>True</GeneratePackageOnBuild>
    <PackageRequireLicenseAcceptance>True</PackageRequireLicenseAcceptance>
    <Version>YOUR NUGET VERSION</Version>
  </PropertyGroup>

  <PropertyGroup Condition="'$(TargetFramework)'=='portable40-net45+sl5+win8'">
     <TargetFrameworkIdentifier>.NETPortable</TargetFrameworkIdentifier>
     <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
     <TargetFrameworkProfile>Profile47</TargetFrameworkProfile>
     <DefineConstants>$(DefineConstants);PROFILE47</DefineConstants>
   </PropertyGroup>

  <ItemGroup Condition="'$(TargetFramework)'=='portable40-net45+sl5+win8'">
    <Reference Include="System" />
    <Reference Include="System.Core" />
    <Reference Include="System.Windows" />
  </ItemGroup>

</Project>

F# Example

*Caveat: F# requires beta version of Mono for Mac or Visual Studio 2017 preview 15.3 presently for this fsproj. Also a change from examples includes a PackageReference to FSharp.Compiler.Tools and FSharp.Core 4.1 the last portable supported FSharp versions (which is relatively quite recent.)

<Project Sdk="FSharp.NET.Sdk;Microsoft.NET.Sdk" ToolsVersion="15.0">

  <PropertyGroup>
    <TargetFrameworks>netstandard1.6;portable40-net45+sl5+win8</TargetFrameworks>
    <Description>YOUR DESCRIPTION</Description>
    <Company>YOUR COMPANY</Company>
    <Authors> YOUR AUTHORS </Authors>
    <Copyright>YOUR COPYRIGHT</Copyright>
    <AssemblyVersion>YOUR VERSION</AssemblyVersion>
    <FileVersion>YOUR VERSION</FileVersion>
    <PackageProjectUrl>YOUR PROJECT URL</PackageProjectUrl>
    <PackageLicenseUrl>YOUR LICENSE</PackageLicenseUrl>
    <PackageTags>YOUR TAGS</PackageTags>
    <IncludeSymbols>True</IncludeSymbols>
    <IncludeSource>True</IncludeSource>
    <GeneratePackageOnBuild>True</GeneratePackageOnBuild>
    <PackageRequireLicenseAcceptance>True</PackageRequireLicenseAcceptance>
    <Version>YOUR NUGET VERSION</Version>
  </PropertyGroup>

  <PropertyGroup Condition="'$(TargetFramework)'=='portable40-net45+sl5+win8'">
     <TargetFrameworkIdentifier>.NETPortable</TargetFrameworkIdentifier>
     <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
     <TargetFrameworkProfile>Profile47</TargetFrameworkProfile>
     <DefineConstants>$(DefineConstants);PROFILE47</DefineConstants>
   </PropertyGroup>

  <ItemGroup Condition="'$(TargetFramework)'=='portable40-net45+sl5+win8'">
    <Reference Include="System" />
    <Reference Include="System.Core" />
    <Reference Include="System.Windows" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="FSharp.Core" Version="4.1.*" />
    <PackageReference Include="FSharp.Compiler.Tools" Version="4.1.*" PrivateAssets="All"
    />
    <PackageReference Include="FSharp.NET.Sdk" Version="1.0.*" PrivateAssets="All"
    />
  </ItemGroup>

  <ItemGroup>
    <Compile Include="YourModule1.fs" />
    <Compile Include="YourModule2.fs" />
  </ItemGroup>

</Project>


问:
What problems could disabling Java bytecode verification cause?
This answer says that verification is used to ensure that Java bytecode "follows Java language rules for safety".

If this verification were not performed, unsafe bytecode would be allowed to run. What problems could this cause?

Are there any situations in which disabling bytecode verification would be acceptable?

答:
Bytecode verification ensures that the code can't do stuff like reinterpret an int as a pointer and do arbitrary memory accesses. This is most useful if you are trying to run untrusted code within the Java sandbox.

If you completely trust all the code you are running, it is less useful, since it would just catch accidental bugs in that case. It's also possible that the verification information gets fed into the optimizer - I'm not sure about this, but the optimizer essentially has to verify the code anyway in order to do any useful static analysis.