问:
What is the difference between requiring an SSL cert and accepting an SSL cert?
So I know the fundamental difference between requiring an SSL cert and accepting, one means you must have an SSL certificate and the other means you don't need one.

In my IIS Manager for a certain webpage I have the this setup:

The issue that I am having is that when I set Require SSL Cert and have Client certificates set to accept/ignore I can only get to webpage using HTTPS. Now if I change it to Require, I can no longer access the webpage, even with HTTPS... so I am just trying to figure out what the difference is, and how it effects the webpage.

So maybe my question is phrased wrong... I'm not sure, my understanding on the subject is fairly limited, so any help would be appreciated.

Thanks!

答:
To expand on the answer given by @Bruno. These values can be set in applicationHost.config-file or even web.config if override is allowed.

The attribute is called sslFlags and you will find the possible values as well as an example below.

```<code>None                Disable SSL.
Ssl                 Require SSL.
SslNegotiateCert    Accept client certificates for authentication.
SslRequireCert      Require clients certificates for authentication.
SslMapCert          Enable certificate mapping authentication.
Ssl128              Require 128-bit SSL.
</code>```

Example for a site named Contoso that requires HTTPS and a client certificate trusted by the server:

```<code><location path="Contoso">
   <system.webServer>
      <security>
         <access sslFlags="Ssl,SslNegotiateCert,SslRequireCert">
      </security>
   </system.webServer>
</location>
</code>```

https://learn.microsoft.com/en-us/iis/configuration/system.webserver/security/access

Body:
To expand on the answer given by @Bruno. These values can be set in applicationHost.config-file or even web.config if override is allowed.

The attribute is called sslFlags and you will find the possible values as well as an example below.

None                Disable SSL.
Ssl                 Require SSL.
SslNegotiateCert    Accept client certificates for authentication.
SslRequireCert      Require clients certificates for authentication.
SslMapCert          Enable certificate mapping authentication.
Ssl128              Require 128-bit SSL.

Example for a site named Contoso that requires HTTPS and a client certificate trusted by the server:

<location path="Contoso">
   <system.webServer>
      <security>
         <access sslFlags="Ssl,SslNegotiateCert,SslRequireCert">
      </security>
   </system.webServer>
</location>

https://learn.microsoft.com/en-us/iis/configuration/system.webserver/security/access


来源: stackexchange

问:
Problems with responsive menu displayed on iPhone (z-index?)
I've created a site for a client and it loads great... except on an iPhone.

I've used emulators on my Windows PC, my Android phone, Safari on Windows... all is ok. But on a iPhone it gets wonky.

Here's the issue:

In responsive mode (less than 1024px) when you load the menu, there should be "Close" and "Menu" along with other menu items. However on the iPhone, "Close" and "Menu" do not load. It's like the menu items are being overlaid by a background image that I am using.

I used Z-Index and it now it displays fine on Safari on Windows but not on the iPhone.

Can someone give insight into the problem and a possible fix?

Beta site is at www.conxis.com/nmp

Thanks!

答:
I took a look at the code. The problem seems to be all of the hidden inputs before .menuTable. They're interfering with the top menu buttons.</p>

```<code><div class="screen">
    <input class="hidden" type="radio" name="s1" id="sub1a-open">
    <input class="hidden" type="radio" name="s1" id="sub1b-open">
    <input class="hidden" type="radio" name="s1" id="sub1c-open">
    <input class="hidden" type="radio" name="s1" id="sub1d-open">
    <input class="hidden" type="radio" name="s1" id="sub1-close">
    <input class="hidden" type="radio" name="s2" id="sub2a-open">
    <input class="hidden" type="radio" name="s2" id="sub2b-open">
    <input class="hidden" type="radio" name="s2" id="sub2c-open">
    <input class="hidden" type="radio" name="s2" id="sub2d-open">
    <input class="hidden" type="radio" name="s2" id="sub2e-open">
    <input class="hidden" type="radio" name="s2" id="sub2-close">
    <input class="hidden" type="radio" name="s3" id="sub3a-open">
    <input class="hidden" type="radio" name="s3" id="sub3b-open">
    <input class="hidden" type="radio" name="s3" id="sub3-close">
    <div class="menutablet">
        <ul>
            <li class="m-close"><label for="menu-close" title="close menu"></label>Close</li>
            <li><a href="menu.html">MENU</a></li>
            <li><a href="dinein.html">DINE IN</a></li>
            <li><a href="carryout.html">CARRY OUT</a></li>
            <li><a href="catering.html">CATERING</a></li>
            <li><a href="cheesecakes.html">CHEESECAKES</a></li>
            <li><a href="index.html">HOME</a></li>
        </ul>
    </div>
</div>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I took a look at the code. The problem seems to be all of the hidden inputs before .menuTable. They're interfering with the top menu buttons.

<div class="screen">
    <input class="hidden" type="radio" name="s1" id="sub1a-open">
    <input class="hidden" type="radio" name="s1" id="sub1b-open">
    <input class="hidden" type="radio" name="s1" id="sub1c-open">
    <input class="hidden" type="radio" name="s1" id="sub1d-open">
    <input class="hidden" type="radio" name="s1" id="sub1-close">
    <input class="hidden" type="radio" name="s2" id="sub2a-open">
    <input class="hidden" type="radio" name="s2" id="sub2b-open">
    <input class="hidden" type="radio" name="s2" id="sub2c-open">
    <input class="hidden" type="radio" name="s2" id="sub2d-open">
    <input class="hidden" type="radio" name="s2" id="sub2e-open">
    <input class="hidden" type="radio" name="s2" id="sub2-close">
    <input class="hidden" type="radio" name="s3" id="sub3a-open">
    <input class="hidden" type="radio" name="s3" id="sub3b-open">
    <input class="hidden" type="radio" name="s3" id="sub3-close">
    <div class="menutablet">
        <ul>
            <li class="m-close"><label for="menu-close" title="close menu"></label>Close</li>
            <li><a href="menu.html">MENU</a></li>
            <li><a href="dinein.html">DINE IN</a></li>
            <li><a href="carryout.html">CARRY OUT</a></li>
            <li><a href="catering.html">CATERING</a></li>
            <li><a href="cheesecakes.html">CHEESECAKES</a></li>
            <li><a href="index.html">HOME</a></li>
        </ul>
    </div>
</div>


问:
Initialize and return jagged array in one line
Currently I am doing this

```<code>public int[][] SomeMethod()
{
    if (SomeCondition)
    {
        var result = new int[0][];
        result[0] = new int[0];
        return result;
    }
    // Other code,
}
</code>```

Now in this I only want to return empty jagged array of [0][0]. Is it possible to reduce three lines to one. I want to achieve something like this

```<code>public int[][] SomeMethod()
{
    if (SomeCondition)
    {
        return new int[0][0];
    }
    // Other code,
}
</code>```

Is it possible?

答:
In the general case, you can let the compiler count elements for you:

```<code>    public int[][] JaggedInts()
    {
        return new int[][] { new[] { 1, 2, 3 }, new[] { 4, 5, 6 }, new[] { 7, 8, 9, 10 } };
    }
</code>```

Or if you want it very compact, use an expression body:

```<code> public int[][] JaggedInts() => new int[][] { new[] { 1, 2, 3 }, new[] { 4, 5, 6 }, new[] { 7, 8, 9, 10 } };
</code>```

Since you asked for an empty jagged array, you already had it:

```<code>var result = new int[0][];
</code>```

The next line in your question will throw a run-time exception, since [0] is the first element in an array, which must be 1 or or more elements in length;

```<code> result[0] = new int[0];  // thows IndexOutOfRangeException: Index was outside the bounds of the array.
</code>```

Here is what I think you asked for in just one line:

```<code>public int[][] Empty() => new int[0][];
</code>```

Body:
Currently I am doing this

public int[][] SomeMethod()
{
    if (SomeCondition)
    {
        var result = new int[0][];
        result[0] = new int[0];
        return result;
    }
    // Other code,
}

Now in this I only want to return empty jagged array of [0][0]. Is it possible to reduce three lines to one. I want to achieve something like this

public int[][] SomeMethod()
{
    if (SomeCondition)
    {
        return new int[0][0];
    }
    // Other code,
}

Is it possible?

Body:
In the general case, you can let the compiler count elements for you:

    public int[][] JaggedInts()
    {
        return new int[][] { new[] { 1, 2, 3 }, new[] { 4, 5, 6 }, new[] { 7, 8, 9, 10 } };
    }

Or if you want it very compact, use an expression body:

 public int[][] JaggedInts() => new int[][] { new[] { 1, 2, 3 }, new[] { 4, 5, 6 }, new[] { 7, 8, 9, 10 } };

Since you asked for an empty jagged array, you already had it:

var result = new int[0][];

The next line in your question will throw a run-time exception, since [0] is the first element in an array, which must be 1 or or more elements in length;

 result[0] = new int[0];  // thows IndexOutOfRangeException: Index was outside the bounds of the array.

Here is what I think you asked for in just one line:

public int[][] Empty() => new int[0][];


问:
How to set CmakeLists path in product flavor for each Android ABI?
I need to have a separate CMakeLists.txt for each Android ABI. I tried to use product flavor to set the path for CMakeLists.txt. But I am getting following error on running ./gradlew assembleDebug or any other gradle command from command line.

Could not find method path() for arguments [CMakeLists.txt] on object
  of type
  com.android.build.gradle.internal.dsl.ExternalNativeCmakeOptions.

Here is how I have set product flavor in build.gradle.

```<code>productFlavors {
    arm64_v8a {
        ndk {
            abiFilters "arm64-v8a"
        }
        externalNativeBuild {
            cmake {
                path "CMakeLists.txt"
            }
        }
    }
    x86_64 {
        ndk {
            abiFilters "x86_64"
        }
        externalNativeBuild {
            cmake {
                path "CMakeLists.txt"
            }
        }
    }
}
</code>```

NOTE - I had initially named the files as "CMakeLists_arm64-v8a.txt" and "CMakeLists_x86_64.txt". But that was failing so tried same name.

How to fix this or is there a workaround for this?

答:
No, you cannot have CMakeLists.txt paths different for different flavors and/or ABIs, but you can use the arguments to add conditionals in your cmake script, for example like this:

```<code>flavorDimensions "abi"
productFlavors {
    arm64_v8a {
        dimension "abi"
        ndk {
            abiFilters "arm64-v8a"
        }
        externalNativeBuild {
            cmake {
                arguments "-DFLAVOR=ARM"
            }
        }
    }
    x86_64 {
        dimension "abi"
        ndk {
            abiFilters "x86_64"
        }
        externalNativeBuild {
            cmake {
                arguments "-DFLAVOR=x86"
            }
        }
    }
}
</code>```

Now you can check this in your CMakeLists.txt:

```<code>if (FLAVOR STREQUAL 'ARM')
  include(arm.cmake)
endif()
</code>```

But in your case, you can rely on the argument that is defined by Android Studio, and don't need your own parameter:

```<code>if (ANDROID_ABI STREQUAL 'arm64-v8a')
  include(arm.cmake)
endif()
</code>```

Actually, you probably don't need separate productFlavors at all, but rather use splits to produce thin APKs for each ABI.

Body:
I need to have a separate CMakeLists.txt for each Android ABI. I tried to use product flavor to set the path for CMakeLists.txt. But I am getting following error on running ./gradlew assembleDebug or any other gradle command from command line.

Could not find method path() for arguments [CMakeLists.txt] on object
  of type
  com.android.build.gradle.internal.dsl.ExternalNativeCmakeOptions.

Here is how I have set product flavor in build.gradle.

productFlavors {
    arm64_v8a {
        ndk {
            abiFilters "arm64-v8a"
        }
        externalNativeBuild {
            cmake {
                path "CMakeLists.txt"
            }
        }
    }
    x86_64 {
        ndk {
            abiFilters "x86_64"
        }
        externalNativeBuild {
            cmake {
                path "CMakeLists.txt"
            }
        }
    }
}

NOTE - I had initially named the files as "CMakeLists_arm64-v8a.txt" and "CMakeLists_x86_64.txt". But that was failing so tried same name.

How to fix this or is there a workaround for this?

Body:
No, you cannot have CMakeLists.txt paths different for different flavors and/or ABIs, but you can use the arguments to add conditionals in your cmake script, for example like this:

flavorDimensions "abi"
productFlavors {
    arm64_v8a {
        dimension "abi"
        ndk {
            abiFilters "arm64-v8a"
        }
        externalNativeBuild {
            cmake {
                arguments "-DFLAVOR=ARM"
            }
        }
    }
    x86_64 {
        dimension "abi"
        ndk {
            abiFilters "x86_64"
        }
        externalNativeBuild {
            cmake {
                arguments "-DFLAVOR=x86"
            }
        }
    }
}

Now you can check this in your CMakeLists.txt:

if (FLAVOR STREQUAL 'ARM')
  include(arm.cmake)
endif()

But in your case, you can rely on the argument that is defined by Android Studio, and don't need your own parameter:

if (ANDROID_ABI STREQUAL 'arm64-v8a')
  include(arm.cmake)
endif()

Actually, you probably don't need separate productFlavors at all, but rather use splits to produce thin APKs for each ABI.

ContentLicense: CC BY-SA 4.0


问:
Organize Cloud Functions for Firebase
What is the best practice to organize all our Cloud Functions for Firebase?

I see from the sample GitHub repository that all functions reside in a single index.js file.

I guess for bigger project that there is a better approach to organize  Cloud Functions for Firebase in different files/directory.

答:
I organize my event handlers by provider and resource in a folder called triggers. E.g. where auth is the provider and user is the resource; the folder functions/triggers/auth/user contains an onCreate.js and onDelete.js, which welcomes and cleans up a user respectively.

```<code>+--/auth
|  +--/user
|     +--/onCreate.js
|     +--/onDelete.js
+--/database
+--/storage
</code>```

You can export a particular trigger by using the require function:

```<code>exports.onCreateAuthUser = require('./triggers/auth/user/onCreate');
exports.onDeleteAuthUser = require('./triggers/auth/user/onDelete');
</code>```

I went a step further and created a script that automatically exports the functions for me. I change the extension of the files to f.js and search recursively the triggers directory. For each file found, the function name is concocted by breaking down the directory and file path.

This structure was inspired by inspecting the internals of the firebase-functions npm package.

Title: Organize Cloud Functions for Firebase

Body:
I organize my event handlers by provider and resource in a folder called triggers. E.g. where auth is the provider and user is the resource; the folder functions/triggers/auth/user contains an onCreate.js and onDelete.js, which welcomes and cleans up a user respectively.

+--/auth
|  +--/user
|     +--/onCreate.js
|     +--/onDelete.js
+--/database
+--/storage

You can export a particular trigger by using the require function:

exports.onCreateAuthUser = require('./triggers/auth/user/onCreate');
exports.onDeleteAuthUser = require('./triggers/auth/user/onDelete');

I went a step further and created a script that automatically exports the functions for me. I change the extension of the files to f.js and search recursively the triggers directory. For each file found, the function name is concocted by breaking down the directory and file path.

This structure was inspired by inspecting the internals of the firebase-functions npm package.


问:
c# replicating button click with javascript injection
Hello I want to replicate some button click on site

Button code:

```<code><button type="button" class="btn btn-link btn-xs" onclick="getComponents('188855', '5a0f44a9d70380.12406536');return false;" data-toggle="modal" data-target="#viewMtComponents">View</button>
</code>```

what this does is opens popup window on current page and display some data(which is not loaded with html file)

This is my code for injection:

```<code>public void inject(string a , string b)
    {
        HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
        HtmlElement script = webBrowser1.Document.CreateElement("script");
        IHTMLScriptElement element = (IHTMLScriptElement)script.DomElement;
        element.text = "getComponents('" + a + "', '" + b + "');";
        head.AppendChild(script);
    }
</code>```

But it does absolutely nothing. How can I fix it?

答:
You dont need to append the script.
You can use the InvokeScript method as documented here.</p>

```<code>Object[] args = new Object[2];
args[0] = (Object)a;
args[1] = (Object)b;
webBrowser1.Document.InvokeScript("getComponents", args);
</code>```

Body:
Hello I want to replicate some button click on site

Button code:

<button type="button" class="btn btn-link btn-xs" onclick="getComponents('188855', '5a0f44a9d70380.12406536');return false;" data-toggle="modal" data-target="#viewMtComponents">View</button>

what this does is opens popup window on current page and display some data(which is not loaded with html file)

This is my code for injection:

public void inject(string a , string b)
    {
        HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
        HtmlElement script = webBrowser1.Document.CreateElement("script");
        IHTMLScriptElement element = (IHTMLScriptElement)script.DomElement;
        element.text = "getComponents('" + a + "', '" + b + "');";
        head.AppendChild(script);
    }

But it does absolutely nothing. How can I fix it?

Body:
You dont need to append the script.
You can use the InvokeScript method as documented here.

Object[] args = new Object[2];
args[0] = (Object)a;
args[1] = (Object)b;
webBrowser1.Document.InvokeScript("getComponents", args);


问:
Transition from sentence to one word
What I am trying to achieve is to animate an element width few words in the way that hovered word leaves in the center of the element and the rest smoothly goes out of the bounds. I would also keep it as clear as possible in HTML and not to use fixed pixel amount of margins/widths to position elements.

The very lousy sketch of what I have on my mind is here:

* {
  transition: all 1.5s;
}

div {
  min-width: 150px;
  width: 30%;
  height: 25px;
  line-height: 25px;
  background: orange;
  text-align: center;
  overflow: hidden;
}

div:hover {
  background: white;
  word-spacing: 300px;
}

a:hover::after,
a:hover::before {
  content: ' ';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  First & Second
</div></code>```

Each word on hover should go to center (possibly not with those 'jumps' visible now when other words disapear). Do you have any ideas? I'm pretty sure that the way I try to follow with word-spacing is wrong.

答:
This version uses Flex Box, accommodates multiple items, and does not use fixed widths.

The trouble I kept having playing around with this was centering items without using fixed widths. Especially those that were later in line and trying to push items to the left.

Solution: flex box order.

You can set the order of flex items numerically, so simply setting it to -1 on hover puts the hovered item first in the list so you eliminate the issue of flexing items leftward.

The animation may not be as fluid as you're looking for because you can only transition order by integer.  So it's immediately set along with the width, and then the other properties transition.

div.outer {
  width: 50vw;
  height: 30px;
  background: orange;
  text-align: center;
  overflow: hidden;
  position: relative;
  padding: 0;
}

div.inner {
  position: relative;
  margin: 0 auto;
  height: 30px;
  width: 50vw;
  display: flex;
  justify-content: center;
  align-items: center;
  background: transparent;
  flex-wrap: wrap;
}

span {
   order: 1;
   padding: 0 3px;
   flex-shrink:1;
}

a {
  z-index: 0;
  order: 1;
  height: 30px;
  line-height: 30px;
  flex-grow: 0;
  flex-shrink: 1;
  transition: background .5s, flex-grow .25s, flex-shrink .25s;
 }

a:hover {
  z-index: 10;
  width: 50vw;
  order: -1;
  flex-grow: 1;
  background: #eee;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outer">
  <div class="inner">
    First
    <span>&</span>
    Second
    <span>&</span>
    Third
  </div>
</div></code>```

Title: Transition from sentence to one word

Body:
What I am trying to achieve is to animate an element width few words in the way that hovered word leaves in the center of the element and the rest smoothly goes out of the bounds. I would also keep it as clear as possible in HTML and not to use fixed pixel amount of margins/widths to position elements.

The very lousy sketch of what I have on my mind is here:

* {
  transition: all 1.5s;
}

div {
  min-width: 150px;
  width: 30%;
  height: 25px;
  line-height: 25px;
  background: orange;
  text-align: center;
  overflow: hidden;
}

div:hover {
  background: white;
  word-spacing: 300px;
}

a:hover::after,
a:hover::before {
  content: ' ';
}

  First & Second

Each word on hover should go to center (possibly not with those 'jumps' visible now when other words disapear). Do you have any ideas? I'm pretty sure that the way I try to follow with word-spacing is wrong.

Body:
This version uses Flex Box, accommodates multiple items, and does not use fixed widths.

The trouble I kept having playing around with this was centering items without using fixed widths. Especially those that were later in line and trying to push items to the left.

Solution: flex box order.

You can set the order of flex items numerically, so simply setting it to -1 on hover puts the hovered item first in the list so you eliminate the issue of flexing items leftward.

The animation may not be as fluid as you're looking for because you can only transition order by integer.  So it's immediately set along with the width, and then the other properties transition.

div.outer {
  width: 50vw;
  height: 30px;
  background: orange;
  text-align: center;
  overflow: hidden;
  position: relative;
  padding: 0;
}

div.inner {
  position: relative;
  margin: 0 auto;
  height: 30px;
  width: 50vw;
  display: flex;
  justify-content: center;
  align-items: center;
  background: transparent;
  flex-wrap: wrap;
}

span {
   order: 1;
   padding: 0 3px;
   flex-shrink:1;
}

a {
  z-index: 0;
  order: 1;
  height: 30px;
  line-height: 30px;
  flex-grow: 0;
  flex-shrink: 1;
  transition: background .5s, flex-grow .25s, flex-shrink .25s;
 }

a:hover {
  z-index: 10;
  width: 50vw;
  order: -1;
  flex-grow: 1;
  background: #eee;
}

<div class="outer">
  <div class="inner">
    <a href="">First</a>
    <span>&amp;</span>
    <a href="">Second</a>
    <span>&amp;</span>
    <a href="">Third</a>
  </div>
</div>


问:
Storyboard Global Tint UITabBar Tint changed in IOS 7.1
Have I overlooked something in just using the Global Tint to set the apps overall tint?

My App that worked in IOS 7.06 has suddenly changed today after IOS 7.1 Update.

Basic Storyboard, Tab based App with Global Tint (Orange) set in storyboard in IB.

Today updated to IOS 7.1 IPhone 5S and it is showing the standard blue tint

IPhone 4 IOS 7.06, same app TabBar tint is as it should be.

Had to set as below

```<code>[[UITabBar appearance] setTintColor:[UIColor orangeColor]];
</code>```

in the TabBarControllers ViewDidLoad to correct the issue.

Could it be I have something else set incorrectly?

答:
Swift code that works under iOS 11 (in AppDelegate's didFinishLaunching):</p>

```<code>application.windows[0].rootViewController?.view.tintColor = UIColor.black
</code>```

Body:
Have I overlooked something in just using the Global Tint to set the apps overall tint?

My App that worked in IOS 7.06 has suddenly changed today after IOS 7.1 Update.

Basic Storyboard, Tab based App with Global Tint (Orange) set in storyboard in IB.

Today updated to IOS 7.1 IPhone 5S and it is showing the standard blue tint

IPhone 4 IOS 7.06, same app TabBar tint is as it should be.

Had to set as below

[[UITabBar appearance] setTintColor:[UIColor orangeColor]];

in the TabBarControllers ViewDidLoad to correct the issue.

Could it be I have something else set incorrectly?

Body:
Swift code that works under iOS 11 (in AppDelegate's didFinishLaunching):

application.windows[0].rootViewController?.view.tintColor = UIColor.black


问:
What's the best way to determine at runtime if a browser is too slow to gracefully handle complex JavaScript/CSS?
I'm toying with the idea of progressively enabling/disabling JavaScript (and CSS) effects on a page - depending on how fast/slow the browser seems to be.

I'm specifically thinking about low-powered mobile devices and old desktop computers -- not just IE6 :-)

Are there any examples of this sort of thing being done?

What would be the best ways to measure this - accounting for things, like temporary slowdowns on busy CPUs?

Notes:

I'm not interested in browser/OS detection.

At the moment, I'm not interested in bandwidth measurements - only browser/cpu performance.

Things that might be interesting to measure:

Base JavaScript

DOM manipulation

DOM/CSS rendering

I'd like to do this in a way that affects the page's render-speed as little as possible.

BTW: In order to not confuse/irritate users with inconsistent behavior - this would, of course, require on-screen notifications to allow users to opt in/out of this whole performance-tuning process.

[Update: there's a related question that I missed: Disable JavaScript function based on user's computer's performance. Thanks Andrioid!]

答:
A different approach, that does not need explicit benchmark, would be to progressively enable features.

You could apply features in prioritized order, and after each one, drop the rest if a certain amount of time has passed.

Ensuring that the most expensive features come last, you would present the user with a somewhat appropriate selection of features based on how speedy the browser is.

ContentLicense: CC BY-SA 2.5


问:
Can we rely on onStop() being called?
Concerning Android's Activity lifecycle, I've seen it widely claimed (on SO and elsewhere) that persistent data should be saved in the onPause() method, because there is no guarantee that onStop() will be called, since the OS may need to kill the activity to reclaim its resources if system resources are running low.

However, in a book I'm reading, the opposite is stated:

Practically speaking, the OS will not reclaim a visible (paused or
resumed) > activity. Activities are not marked as "killable" until
onStop() is called and finishes executing.

[Talks about stashed
state and activity record a bit]

Note that your activity can pass into the stashed state without
onDestroy() being called. You can rely on onStop() and
onSaveInstanceState(Bundle)  being called (unless something has gone
horribly wrong on the device) ... Override onStop() to save any
permanent data, such as things the user  is editing, because your
activity may be killed at any time after this method returns.

p70-71, Android Programming: The Big Nerd Ranch Guide, 3rd Edition
(emphasis mine)

Multi-Part Question:

Is this (possibility of an app being killed before onStop() is
called) something that is no longer true in and is still being
propagated, or is the book outright wrong?

Is there some nuance to when or why an Activity might be killed that
makes the answer "sometimes?"

If the book is correct, why is that misconception so widely spread? (E.g. Here, here, and here.)

References to official documentation would be appreciated.

答:
This is an illustration of Activity lifecycle :

According to the official Android documentation,

onPause() execution is very brief, and does not necessarily afford
  enough time to perform save operations. For this reason, you should
  not use onPause() to save application or user data, make network
  calls, or execute database transactions; such work may not complete
  before the method completes. Instead, you should perform heavy-load
  shutdown operations during onStop(). For more information about
  suitable operations to perform during onStop(), see onStop().

There is a case when the app go from onPause() to onCreate() without onStop() and onDestroy()  is when another app with higher priority needs memory as you see the illustration.

Also, The activity could be destroyed without calling onStart(),
   onStop() when you call finish() method on onCreate() see reference

Title: Can we rely on onStop() being called?


问:
PHP count of occurrences of characters of a string within another string
Let's say I have two strings.

```<code>$needle = 'AGUXYZ';
$haystack = 'Agriculture ID XYZ-A';
</code>```

I want to count how often characters that are in $needle occur in $haystack. In $haystack, there are the characters 'A' (twice), 'X', 'Y' and 'Z', all of which are in the needle, thus the result is supposed to be 5 (case-sensitive).

Is there any function for that in PHP or do I have to program it myself?

Thanks in advance!

答: substr_count will get you close. However, it will not do individual characters. So you could loop over each character in $needle and call this function while summing the counts.

Body:
Let's say I have two strings.

$needle = 'AGUXYZ';
$haystack = 'Agriculture ID XYZ-A';

I want to count how often characters that are in $needle occur in $haystack. In $haystack, there are the characters 'A' (twice), 'X', 'Y' and 'Z', all of which are in the needle, thus the result is supposed to be 5 (case-sensitive).

Is there any function for that in PHP or do I have to program it myself?

Thanks in advance!


问:
Can't get background-image url of div and replace with jquery
I am making a lightbox, when an image wit the lightboxtrigger class is clicked it will be displayed a bigger size.

This is what I am doing:
when an image with the lightboxtrigger class is clicked I store the url into an array without all the invalid characters and then I replace I switch the src of the lightbox modal with the array.

I cant seem to get this to work, any idea why the tiny script I am using doesn't properly replace the string?

Here is my code:

```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.photogallery__maincontainer{  width:1300px; height:580px; ; flex:0 0 auto; display:flex; flex-flow:row; flex-wrap:wrap; justify-content:flex-start;}

.photogallery__viewer{ width:55%; height:100%; position:relative; display:flex; }

.photogallery__viewer__image{max-width:80%; height:auto; margin:auto; overflow:hidden; box-shadow:0 0 25px #111;}

.photogallery{

 width:42%;
 height:93%;
 position:relative;
 display:flex;
 flex-wrap:wrap;
 justify-content:flex-start;
 align-content:flex-start;
 overflow:auto;

}

.photogallery__image{
 background-image: url('images/20170819_194526.jpg');
 background-position: center;
 background-repeat: no-repeat;
 background-size:contain;
 max-height:20%;
 min-height:20%;
 flex:0 0 calc(25% - 15px);
 margin-right:15px;
 margin-bottom:35px;
 cursor:pointer;
}

.photogallery__image:hover{
 opacity:0.8;
}

.close{width:3%; cursor:pointer; color:rgba(255, 255, 255, 0.7); font-family: 'Nunito', sans-serif; flex:0 0 3%; text-align:center; display:table;  font-size:25px; font-weight:600; }

.close:hover{color:rgba(255, 255, 255, 0.5);}</code>```

  🠿

  X

```

答:
Something is likely wrong with the regex.

This should work instead:

```<code>bg = bg.split("'")[1];
</code>```

Body:
I am making a lightbox, when an image wit the lightboxtrigger class is clicked it will be displayed a bigger size.

This is what I am doing:
when an image with the lightboxtrigger class is clicked I store the url into an array without all the invalid characters and then I replace I switch the src of the lightbox modal with the array.

I cant seem to get this to work, any idea why the tiny script I am using doesn't properly replace the string?

Here is my code:

.photogallery__maincontainer{  width:1300px; height:580px; ; flex:0 0 auto; display:flex; flex-flow:row; flex-wrap:wrap; justify-content:flex-start;}

.photogallery__viewer{ width:55%; height:100%; position:relative; display:flex; }

.photogallery__viewer__image{max-width:80%; height:auto; margin:auto; overflow:hidden; box-shadow:0 0 25px #111;}

.photogallery{

 width:42%;
 height:93%;
 position:relative;
 display:flex;
 flex-wrap:wrap;
 justify-content:flex-start;
 align-content:flex-start;
 overflow:auto;

}

.photogallery__image{
 background-image: url('images/20170819_194526.jpg');
 background-position: center;
 background-repeat: no-repeat;
 background-size:contain;
 max-height:20%;
 min-height:20%;
 flex:0 0 calc(25% - 15px);
 margin-right:15px;
 margin-bottom:35px;
 cursor:pointer;
}

.photogallery__image:hover{
 opacity:0.8;
}

.close{width:3%; cursor:pointer; color:rgba(255, 255, 255, 0.7); font-family: 'Nunito', sans-serif; flex:0 0 3%; text-align:center; display:table;  font-size:25px; font-weight:600; }

.close:hover{color:rgba(255, 255, 255, 0.5);}

  🠿

  X

Body:
Something is likely wrong with the regex.

This should work instead:

bg = bg.split("'")[1];


问:
JPA LazyLoading Collections transfered via SOAP
I've got the following problem.

I've got an Entity which looks like this:

```<code>@Entity
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Teacher{

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
  @JoinColumn(name = "teacherId", referencedColumnName = "id", nullable = false)
  private final Set<Student> students = new HashSet<>();
}
</code>```

Now I've got two finder methods:

findAllTeachers(): SELECT t from Teacher t

findTeacherByIdWithDetails(Long id): SELECT t from Teacher t JOIN FETCH t.students s where t.id = :id

As long as I'm on server side all is good.
I'm using Hibernate on a wildfly 10 applicationserver.

I've got 2 SOAP webservice methods, one method for return all teachers and one method for returning exactly one teacher by id with the students loaded.

Now of course the LazyInitializationException is thrown when I'm calling the webservice method for return all teachers, because the Teacher Entity is already detached.

Now here is my question. Is there any other option than creating a DTO for this Entity?
If I'm setting @XMLTransient for the students collection, I'm also hiding it when I'm calling the webservice method for the detailed Teacher.

It would be so great if you could help me out with this problem... I tried a lot and I know that it would work with REST by using jackson-datatype-hibernate. But it is required to be a SOAP webservice.

答:
You could try with an custom XmlAdapter that can handle non initialized Hibernate's collection, something like:

```<code>public class StudentSetXmlAdapter extends XmlAdapter<Set<Student>, Set<Student>> {

    @Override
    public Set<Student> marshal(Set<Student> value) throws Exception {
        //PersistentSet is the Hibernate's implementation of Set that handle Lazy-loading etc...
        if (value instanceof PersistentSet) {
            PersistentSet hibernateCollection = (PersistentSet) value;

            //If the data were already loaded you return the collection
            return hibernateCollection.wasInitialized() ? value : null;
        } else
            return value;
    }

    @Override
    public Set<Student> unmarshal(Set value) throws Exception {
        return value;
    }

}
</code>```

and add the annotation @XmlJavaTyAdapter on your field:

```<code>@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "teacherId", referencedColumnName = "id", nullable = false)
@XmlJavaTypeAdapter(StudentSetXmlAdapter.class)
private final Set<Student> students = new HashSet<>();
</code>```

Body:
I've got the following problem.

I've got an Entity which looks like this:

@Entity
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Teacher{

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
  @JoinColumn(name = "teacherId", referencedColumnName = "id", nullable = false)
  private final Set<Student> students = new HashSet<>();
}

Now I've got two finder methods:

findAllTeachers(): SELECT t from Teacher t

findTeacherByIdWithDetails(Long id): SELECT t from Teacher t JOIN FETCH t.students s where t.id = :id

As long as I'm on server side all is good.
I'm using Hibernate on a wildfly 10 applicationserver.

I've got 2 SOAP webservice methods, one method for return all teachers and one method for returning exactly one teacher by id with the students loaded.

Now of course the LazyInitializationException is thrown when I'm calling the webservice method for return all teachers, because the Teacher Entity is already detached.

Now here is my question. Is there any other option than creating a DTO for this Entity?
If I'm setting @XMLTransient for the students collection, I'm also hiding it when I'm calling the webservice method for the detailed Teacher.

It would be so great if you could help me out with this problem... I tried a lot and I know that it would work with REST by using jackson-datatype-hibernate. But it is required to be a SOAP webservice.

Body:
You could try with an custom XmlAdapter that can handle non initialized Hibernate's collection, something like:

public class StudentSetXmlAdapter extends XmlAdapter<Set<Student>, Set<Student>> {

    @Override
    public Set<Student> marshal(Set<Student> value) throws Exception {
        //PersistentSet is the Hibernate's implementation of Set that handle Lazy-loading etc...
        if (value instanceof PersistentSet) {
            PersistentSet hibernateCollection = (PersistentSet) value;

            //If the data were already loaded you return the collection
            return hibernateCollection.wasInitialized() ? value : null;
        } else
            return value;
    }

    @Override
    public Set<Student> unmarshal(Set value) throws Exception {
        return value;
    }

}

and add the annotation @XmlJavaTyAdapter on your field:

@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "teacherId", referencedColumnName = "id", nullable = false)
@XmlJavaTypeAdapter(StudentSetXmlAdapter.class)
private final Set<Student> students = new HashSet<>();


问:
Is there a more elegant way to declare my javascript variables?
I'm writing a hangman game and it's working great, but this block of variables is really quite ugly. I know I've done something in PHP before where I've put all the variables I've needed into an array and pumped them out. Is there a way to accomplish this with Javascript while grabbing my DOM elements?</p>

```<code>let _ = [];
let correct = [];
let wrong = [];
let underscores = document.querySelector('.underscores');
let correctBlock = document.querySelector('.correct');
let wrongBlock = document.querySelector('.wrong');
let scoreBlock = document.querySelector('#score');
let btn = document.querySelector('.btn');
let hint = document.querySelector('.hint');
</code>```

答:
Not really. I like to group my controls in a structure, but I can't say its better.</p>

```<code>let ctrls = {
    underscores: document.querySelector('.underscores'),
    correctBlock: document.querySelector('.correct')
};
</code>```

Body:
I'm writing a hangman game and it's working great, but this block of variables is really quite ugly. I know I've done something in PHP before where I've put all the variables I've needed into an array and pumped them out. Is there a way to accomplish this with Javascript while grabbing my DOM elements?

let _ = [];
let correct = [];
let wrong = [];
let underscores = document.querySelector('.underscores');
let correctBlock = document.querySelector('.correct');
let wrongBlock = document.querySelector('.wrong');
let scoreBlock = document.querySelector('#score');
let btn = document.querySelector('.btn');
let hint = document.querySelector('.hint');

Body:
Not really. I like to group my controls in a structure, but I can't say its better.

let ctrls = {
    underscores: document.querySelector('.underscores'),
    correctBlock: document.querySelector('.correct')
};


问:
Have my cake and eat it too: Binding a Container and It's Contents
I have a custom control, Cake, that contains two DependencyProperties named Slice and Filling. How do I create a style that gives me access to Slice, but also lets me design slice?

```<code><Style TargetType={x:Type local:Cake}>
    //I don't like setting DataContext Here
    <Setter Property="DataContext" Value="{Binding RelativeSource={RelativeSource Self}}/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType={x:Type local:Cake}>
                <Grid DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}}">

                    //This is how I display a slice
                    <ContentPresenter Content={Binding Slice}/>

                    //This is how cake decorations are displayed
                    <ItemsPresenter/>

                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Setter Property="Slice">
        <Setter.Value>

            //Design Slice Here - it's easy to override when I want
            <Slice Filling={Binding Filling}> // it's just in a setter.

        </Setter.Value>
    </Setter>
    <Setter Property="DataContext" Value="{Binding RelativeSource={RelativeSource Self}}/>
</Style>
</code>```

Options I've tried:

I can't use a UserControl, because I want to allow named content, which apparently doesn't work with User Controls. See Here.

I don't like the example above because I have to set the DataContext of the Cake container to self, meaning a user can't use the DataContext for their
bindings.

I can't bind the Filling property using RelativeSource, because with several
cakes, the Style wouldn't know which one was the correct parent. See
Here.

I could replace the Content Presenter directly with a Slice Element,
but because it is in a template, I loose access to the Slice Anywhere
outside the Template. While I could probably typecast my way down the visualTree to the slice, this feels a maintenance nightmare.

I basically want each cake to have a slice, and to be able to set it using

```<code><Cake.Slice>
    <DockPanel>
       <Rectangle Background= “Blue”/>
       <Rectangle Background= “Blue”/>
       <Rectangle Background=“{Binding Filling}”/>
    </DockPanel>
</Cake.Slice>
</code>```

while also giving it a default look.

EDIT:
Apparently my style DOES work, provided that I reference the Cake.dll as opposed to the Cake project.  Why would that be?

答:
This won't be exactly what you need, but I hope it will give you pointers how to achieve that.

First, you don't need to set DataContext to the control itself, you can bind to properties on the Cake control (Filling and Slice) from Cake's ControlTemplate using {TemplateBinding Slice}, which is just a shortcut for {Binding Slice, RelativeSource={RelativeSource TemplatedParent}} (so you can use one or the other).

This will be a simplified version of your control, as I don't know which items the ItemPresenter in your ControlTemplate should present, or what is the Type of your Slice and Filling properties. In this example Filling is SolidColorBrush, and Slice is a Style. That style is applied to a ContentControl within Cake's ControlTemplate, so you can have predefined styles for slices, and apply the filling of your choice (if your Slice property has different purpose, you can introduce another property called SliceStyle for example).

Cake control:

```<code>public class Cake : Control
{
    static Cake()
    {
        DefaultStyleKeyProperty.OverrideMetadata(
            typeof(Cake),
            new FrameworkPropertyMetadata(typeof(Cake)));
    }

    public SolidColorBrush Filling
    {
        get { return (SolidColorBrush)GetValue(FillingProperty); }
        set { SetValue(FillingProperty, value); }
    }

    public static readonly DependencyProperty FillingProperty =
        DependencyProperty.Register(
            "Filling",
            typeof(SolidColorBrush),
            typeof(Cake),
            new PropertyMetadata(Brushes.Transparent));

    public Style Slice
    {
        get { return (Style)GetValue(SliceProperty); }
        set { SetValue(SliceProperty, value); }
    }

    public static readonly DependencyProperty SliceProperty =
        DependencyProperty.Register(
            "Slice",
            typeof(Style),
            typeof(Cake),
            new PropertyMetadata(null));
}
</code>```

Default Style (Generic.xaml):

```<code><Style TargetType="{x:Type local:Cake}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:Cake}">
                <ContentControl Width="{TemplateBinding Width}"
                                Height="{TemplateBinding Height}"
                                Style="{TemplateBinding Slice}"/>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

Different slice styles (these are setting ControlTemplate for ContentControl, so you will not hit the issue number 3 in your question):

```<code><Window.Resources>
    <Style x:Key="TwoLayeredSlice" TargetType="{x:Type ContentControl}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate>
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="*"/>
                            <RowDefinition Height="*"/>
                        </Grid.RowDefinitions>
                        <Rectangle Fill="{Binding Filling,
                            RelativeSource={RelativeSource AncestorType={x:Type local:Cake}}}"/>
                        <Rectangle Fill="Brown"
                                   Grid.Row="1"/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <Style x:Key="FourLayeredSlice" TargetType="{x:Type ContentControl}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate>
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="*"/>
                            <RowDefinition Height="*"/>
                            <RowDefinition Height="*"/>
                            <RowDefinition Height="*"/>
                        </Grid.RowDefinitions>
                        <Rectangle Fill="{Binding Filling,
                            RelativeSource={RelativeSource AncestorType={x:Type local:Cake}}}"/>
                        <Rectangle Fill="Brown"
                                   Grid.Row="1"/>
                        <Rectangle Fill="{Binding Filling,
                            RelativeSource={RelativeSource AncestorType={x:Type local:Cake}}}"
                                   Grid.Row="2"/>
                        <Rectangle Fill="Brown"
                                   Grid.Row="3"/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>
</code>```

And the control in use:

```<code><Grid Background="Gray">
    <local:Cake Width="200"
                Height="100"
                HorizontalAlignment="Left"
                Filling="Gold"
                Slice="{StaticResource TwoLayeredSlice}"/>
    <local:Cake Width="200"
                Height="100"
                HorizontalAlignment="Center"
                Filling="Pink"
                Slice="{StaticResource FourLayeredSlice}"/>
    <local:Cake Width="200"
                Height="100"
                HorizontalAlignment="Right"
                Filling="Blue"
                Slice="{StaticResource FourLayeredSlice}"/>
</Grid>
</code>```

Bon appetit!

Body:
I have a custom control, Cake, that contains two DependencyProperties named Slice and Filling. How do I create a style that gives me access to Slice, but also lets me design slice?

Options I've tried:

I can't use a UserControl, because I want to allow named content, which apparently doesn't work with User Controls. See Here.

I don't like the example above because I have to set the DataContext of the Cake container to self, meaning a user can't use the DataContext for their
bindings.

I can't bind the Filling property using RelativeSource, because with several
cakes, the Style wouldn't know which one was the correct parent. See
Here.

I could replace the Content Presenter directly with a Slice Element,
but because it is in a template, I loose access to the Slice Anywhere
outside the Template. While I could probably typecast my way down the visualTree to the slice, this feels a maintenance nightmare.

I basically want each cake to have a slice, and to be able to set it using

<Cake.Slice>
    <DockPanel>
       <Rectangle Background= “Blue”/>
       <Rectangle Background= “Blue”/>
       <Rectangle Background=“{Binding Filling}”/>
    </DockPanel>
</Cake.Slice>

while also giving it a default look.

EDIT:
Apparently my style DOES work, provided that I reference the Cake.dll as opposed to the Cake project.  Why would that be?

Body:
This won't be exactly what you need, but I hope it will give you pointers how to achieve that.

First, you don't need to set DataContext to the control itself, you can bind to properties on the Cake control (Filling and Slice) from Cake's ControlTemplate using {TemplateBinding Slice}, which is just a shortcut for {Binding Slice, RelativeSource={RelativeSource TemplatedParent}} (so you can use one or the other).

This will be a simplified version of your control, as I don't know which items the ItemPresenter in your ControlTemplate should present, or what is the Type of your Slice and Filling properties. In this example Filling is SolidColorBrush, and Slice is a Style. That style is applied to a ContentControl within Cake's ControlTemplate, so you can have predefined styles for slices, and apply the filling of your choice (if your Slice property has different purpose, you can introduce another property called SliceStyle for example).

Cake control:

public class Cake : Control
{
    static Cake()
    {
        DefaultStyleKeyProperty.OverrideMetadata(
            typeof(Cake),
            new FrameworkPropertyMetadata(typeof(Cake)));
    }

    public SolidColorBrush Filling
    {
        get { return (SolidColorBrush)GetValue(FillingProperty); }
        set { SetValue(FillingProperty, value); }
    }

    public static readonly DependencyProperty FillingProperty =
        DependencyProperty.Register(
            "Filling",
            typeof(SolidColorBrush),
            typeof(Cake),
            new PropertyMetadata(Brushes.Transparent));

    public Style Slice
    {
        get { return (Style)GetValue(SliceProperty); }
        set { SetValue(SliceProperty, value); }
    }

    public static readonly DependencyProperty SliceProperty =
        DependencyProperty.Register(
            "Slice",
            typeof(Style),
            typeof(Cake),
            new PropertyMetadata(null));
}

Default Style (Generic.xaml):

<Style TargetType="{x:Type local:Cake}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:Cake}">
                <ContentControl Width="{TemplateBinding Width}"
                                Height="{TemplateBinding Height}"
                                Style="{TemplateBinding Slice}"/>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Different slice styles (these are setting ControlTemplate for ContentControl, so you will not hit the issue number 3 in your question):

<Window.Resources>
    <Style x:Key="TwoLayeredSlice" TargetType="{x:Type ContentControl}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate>
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="*"/>
                            <RowDefinition Height="*"/>
                        </Grid.RowDefinitions>
                        <Rectangle Fill="{Binding Filling,
                            RelativeSource={RelativeSource AncestorType={x:Type local:Cake}}}"/>
                        <Rectangle Fill="Brown"
                                   Grid.Row="1"/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <Style x:Key="FourLayeredSlice" TargetType="{x:Type ContentControl}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate>
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="*"/>
                            <RowDefinition Height="*"/>
                            <RowDefinition Height="*"/>
                            <RowDefinition Height="*"/>
                        </Grid.RowDefinitions>
                        <Rectangle Fill="{Binding Filling,
                            RelativeSource={RelativeSource AncestorType={x:Type local:Cake}}}"/>
                        <Rectangle Fill="Brown"
                                   Grid.Row="1"/>
                        <Rectangle Fill="{Binding Filling,
                            RelativeSource={RelativeSource AncestorType={x:Type local:Cake}}}"
                                   Grid.Row="2"/>
                        <Rectangle Fill="Brown"
                                   Grid.Row="3"/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>

And the control in use:

<Grid Background="Gray">
    <local:Cake Width="200"
                Height="100"
                HorizontalAlignment="Left"
                Filling="Gold"
                Slice="{StaticResource TwoLayeredSlice}"/>
    <local:Cake Width="200"
                Height="100"
                HorizontalAlignment="Center"
                Filling="Pink"
                Slice="{StaticResource FourLayeredSlice}"/>
    <local:Cake Width="200"
                Height="100"
                HorizontalAlignment="Right"
                Filling="Blue"
                Slice="{StaticResource FourLayeredSlice}"/>
</Grid>

Bon appetit!


问:
sklearn cosine_distances between two strings varies depending on size of total data set?
I am trying to cluster bunch of strings using DBSCAN, with cosine_distances as the metric after doing TfidfVectorizer transform. Say I have two strings. The cosine_distance between them (computed using sklearn.metrics.pairwise.cosine_distance) when it's just those two strings is different than the distance between them when they are part of a larger data set (with many other strings).

Why does this happen and how can I ensure that the distance between any two strings is same regardless of the size of dataset they are part of?

That way, my DBSCAN can do clustering reliably!

EDIT: Adding example code as requested:

```<code>from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_distances

X = [
    'this is a string',
    'this was a string'
    ]

Y = [
    'this could be a string',
    'this may be a string'
    ]

Z = [
    'this is a string',
    'this was a string',
    'this could be a string',
    'this may be a string'
    ]

for d in [X, Y, Z]:
    tv = TfidfVectorizer()
    print(cosine_distances(tv.fit_transform(d)))
</code>```

Outputs:

```<code>[[ 0.          0.49689739]
 [ 0.49689739  0.        ]]

[[ 0.          0.39702518]
 [ 0.39702518  0.        ]]

[[ 0.          0.64740127  0.70225689  0.70225689]
 [ 0.64740127  0.          0.70225689  0.70225689]
 [ 0.70225689  0.70225689  0.          0.46163155]
 [ 0.70225689  0.70225689  0.46163155  0.        ]]
</code>```

As you can see here, the distance between this is a string and this was a string is 0.497 in dataset X, but it is 0.647 in dataset Z. Same for strings this could be a string and this may be a string in datasets Y and Z

In the above example, if I chose max distance (eps) parameter of DBSCAN to be 0.6, then in dataset X, both strings will be put in the same cluster, but in dataset Z, they will be put in different clusters.

答:
Cosine similarity is suitable for long documents.

Short strings don't have enough words.

That the distance changes is due to the IDF part of TFIDF. You opted for a inverse document frequency weighting, so if the document frequency changes, distances change.

Body:
I am trying to cluster bunch of strings using DBSCAN, with cosine_distances as the metric after doing TfidfVectorizer transform. Say I have two strings. The cosine_distance between them (computed using sklearn.metrics.pairwise.cosine_distance) when it's just those two strings is different than the distance between them when they are part of a larger data set (with many other strings).

Why does this happen and how can I ensure that the distance between any two strings is same regardless of the size of dataset they are part of?

That way, my DBSCAN can do clustering reliably!

EDIT: Adding example code as requested:

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_distances

X = [
    'this is a string',
    'this was a string'
    ]

Y = [
    'this could be a string',
    'this may be a string'
    ]

Z = [
    'this is a string',
    'this was a string',
    'this could be a string',
    'this may be a string'
    ]

for d in [X, Y, Z]:
    tv = TfidfVectorizer()
    print(cosine_distances(tv.fit_transform(d)))

Outputs:

[[ 0.          0.49689739]
 [ 0.49689739  0.        ]]

[[ 0.          0.39702518]
 [ 0.39702518  0.        ]]

[[ 0.          0.64740127  0.70225689  0.70225689]
 [ 0.64740127  0.          0.70225689  0.70225689]
 [ 0.70225689  0.70225689  0.          0.46163155]
 [ 0.70225689  0.70225689  0.46163155  0.        ]]

As you can see here, the distance between this is a string and this was a string is 0.497 in dataset X, but it is 0.647 in dataset Z. Same for strings this could be a string and this may be a string in datasets Y and Z

In the above example, if I chose max distance (eps) parameter of DBSCAN to be 0.6, then in dataset X, both strings will be put in the same cluster, but in dataset Z, they will be put in different clusters.


问:
MySQL: having rounded sum not equal to integer
I have a query in which I compare a rounded sum to an integer, and I'm receiving unexpected results.

```<code>SELECT assignments.*
  FROM assignments
  INNER JOIN time_entries
    ON time_entries.assignment_id = assignments.id
  WHERE assignments.organization_id = 2
  AND assignments.allocation_mode = 'fixed'
  AND (fixed_hours is not null)
  HAVING round(sum(time_entries.scheduled_hours)) != round(assignments.fixed_hours);
</code>```

It returns an assignment with fixed_hours of 20. The column is a float.

When I select the sum of the time_entries for that match that record, I get 20.000000298023224. When I call round on that, I get 20:

```<code>SELECT
  round(sum(scheduled_hours))
  FROM time_entries
  WHERE assignment_id=112869;
</code>```

And SELECT round(fixed_hours) from assignments where id=112869 also gives 20.

And of course select round(20.000000298023224) = round(20); returns 1.

So what's wrong with my query that that record is being returned?

答:
Nice try at query summarization :), but you need a group by...</p>

```<code>SELECT
      assignments.*
FROM assignments
INNER JOIN (
      SELECT
            assignment_id
          , ROUND(SUM(time_entries.scheduled_hours)) sum_hrs
      FROM time_entries
      GROUP BY
            assignment_id
) te ON assignments.id = te.assignment_id
WHERE assignments.organization_id = 2
AND assignments.allocation_mode = 'fixed'
AND (fixed_hours IS NOT NULL)
AND te.sum_hrs <> ROUND(assignments.fixed_hours)
;
</code>```

Body:
I have a query in which I compare a rounded sum to an integer, and I'm receiving unexpected results.

SELECT assignments.*
  FROM assignments
  INNER JOIN time_entries
    ON time_entries.assignment_id = assignments.id
  WHERE assignments.organization_id = 2
  AND assignments.allocation_mode = 'fixed'
  AND (fixed_hours is not null)
  HAVING round(sum(time_entries.scheduled_hours)) != round(assignments.fixed_hours);

It returns an assignment with fixed_hours of 20. The column is a float.

When I select the sum of the time_entries for that match that record, I get 20.000000298023224. When I call round on that, I get 20:

SELECT
  round(sum(scheduled_hours))
  FROM time_entries
  WHERE assignment_id=112869;

And SELECT round(fixed_hours) from assignments where id=112869 also gives 20.

And of course select round(20.000000298023224) = round(20); returns 1.

So what's wrong with my query that that record is being returned?

Body:
Nice try at query summarization :), but you need a group by...

SELECT
      assignments.*
FROM assignments
INNER JOIN (
      SELECT
            assignment_id
          , ROUND(SUM(time_entries.scheduled_hours)) sum_hrs
      FROM time_entries
      GROUP BY
            assignment_id
) te ON assignments.id = te.assignment_id
WHERE assignments.organization_id = 2
AND assignments.allocation_mode = 'fixed'
AND (fixed_hours IS NOT NULL)
AND te.sum_hrs <> ROUND(assignments.fixed_hours)
;


问:
Access VBA round by the quarter of the hour
I want to be able to round time by the quarter of the hour, so when it is 3 minutes past the quarter of the hour it rounds up and when it's within the 3 minutes it rounds down.  Like below:

```<code>08:01 (will be 08:00)
08:03 (will be 08:00)
08:04 (will be 08:15)
</code>```

Managed to get it working in excel but cannot get it working in Access.

Here is the excel formula:

```<code>=(TRUNC((VALUE("08:03")+VALUE("00:11"))*96)*VALUE("00:15"))
</code>```

答:
Here is my take on the answer:</p>

```<code>Public Function RoundTime(d As Date) As Date
    'Round 08:03:59 down, round 8:04:00 up
    RoundTime = Int(d * 96 + 11 / 15) / 96
    'or
    'Round 08:03:00 down, round 8:03:01 up
    'RoundTime = Int(d * 96 + 12 / 15) / 96
End Function
</code>```

Body:
I want to be able to round time by the quarter of the hour, so when it is 3 minutes past the quarter of the hour it rounds up and when it's within the 3 minutes it rounds down.  Like below:

08:01 (will be 08:00)
08:03 (will be 08:00)
08:04 (will be 08:15)

Managed to get it working in excel but cannot get it working in Access.

Here is the excel formula:

=(TRUNC((VALUE("08:03")+VALUE("00:11"))*96)*VALUE("00:15"))

Body:
Here is my take on the answer:

Public Function RoundTime(d As Date) As Date
    'Round 08:03:59 down, round 8:04:00 up
    RoundTime = Int(d * 96 + 11 / 15) / 96
    'or
    'Round 08:03:00 down, round 8:03:01 up
    'RoundTime = Int(d * 96 + 12 / 15) / 96
End Function


问:
PHP - How do I access specific array values in nested array?
I have an array like this:

```<code>    Array (
    [0] => Array (
        [0] => 510
        [1] => 984
        [2] => 1045
        [3] => 2068
        [4] => 1054
        [5] => 673
        )
    [1] => Array (
        [0] => 1163
        [1] => 1982
        [2] => 2067
        [3] => 3989
        [4] => 1940
        [5] => 1242
        )
    [2] => Array (
        [0] => june
        [1] => july
        [2] => august
        [3] => september
        [4] => october
        [5] => november
        )
    )
</code>```

I want to access only one of the arrays within the array at a time and echo them out.

For example, I would get: 510, 984, 1045, 2068, 1054, and 673 as one result.

I've looked at multiple threads and answers but nothing that quite solves my issue, I've been able to print out all the values but I just want some specifically.

I'd store it in the variable: $array_item

My most recent attempt was:

```<code>foreach ($array_item as $inner) {
if (is_array($inner)) {
    foreach ($inner[0] as $value) {
        echo "$value \n";
    }
}
}
</code>```

Which gives me: Warning: Invalid argument supplied for foreach().

I thought for sure that would work, what am I doing wrong?

答:
Does is_array($array_item) return true?

```<code>if (is_array($array_item)) {
    foreach ($array_item) {
        if (is_array($inner)) {
            foreach ($inner as $value) {
                echo "$value \n";
            }
        }
    }
}
</code>```

Edit: Also, $inner[0] is not an array.  $inner is the array.

Body:
I have an array like this:

    Array (
    [0] => Array (
        [0] => 510
        [1] => 984
        [2] => 1045
        [3] => 2068
        [4] => 1054
        [5] => 673
        )
    [1] => Array (
        [0] => 1163
        [1] => 1982
        [2] => 2067
        [3] => 3989
        [4] => 1940
        [5] => 1242
        )
    [2] => Array (
        [0] => june
        [1] => july
        [2] => august
        [3] => september
        [4] => october
        [5] => november
        )
    )

I want to access only one of the arrays within the array at a time and echo them out.

For example, I would get: 510, 984, 1045, 2068, 1054, and 673 as one result.

I've looked at multiple threads and answers but nothing that quite solves my issue, I've been able to print out all the values but I just want some specifically.

I'd store it in the variable: $array_item

My most recent attempt was:

foreach ($array_item as $inner) {
if (is_array($inner)) {
    foreach ($inner[0] as $value) {
        echo "$value \n";
    }
}
}

Which gives me: Warning: Invalid argument supplied for foreach().

I thought for sure that would work, what am I doing wrong?

Body:
Does is_array($array_item) return true?

if (is_array($array_item)) {
    foreach ($array_item) {
        if (is_array($inner)) {
            foreach ($inner as $value) {
                echo "$value \n";
            }
        }
    }
}

Edit: Also, $inner[0] is not an array.  $inner is the array.


问:
Codeigniter Multi-lingual language identifier
I am trying to implement CI uri identifier plugin - http://codeigniter.com/wiki/URI_Language_Identifier/

I set the code on a base codeignitor setup. The “ingore_lang” is set to “en”. I am using “alt_site_url” to generate alternative language links.

Now with english it is working all good, links are fine.

But when I click on any other language, the next set of alternate language urls is not replacing the abbr to the present link. For eg. if Spanish is selected, on the new page the link to italian language becomes:

```<code>mysite/es/it
</code>```

I have also observed that the alternate language links never show “english” in the list. I assume they are still taking english as current language.

Please help, am I missing something? I applied the code to all specified files as guided.

Thanks

答: You should remove 'en' from the lang_ignore var, that should add english to alt languages list. Not sure about the es/it part... </p>

Body:
I am trying to implement CI uri identifier plugin - http://codeigniter.com/wiki/URI_Language_Identifier/

I set the code on a base codeignitor setup. The “ingore_lang” is set to “en”. I am using “alt_site_url” to generate alternative language links.

Now with english it is working all good, links are fine.

But when I click on any other language, the next set of alternate language urls is not replacing the abbr to the present link. For eg. if Spanish is selected, on the new page the link to italian language becomes:

mysite/es/it

I have also observed that the alternate language links never show “english” in the list. I assume they are still taking english as current language.

Please help, am I missing something? I applied the code to all specified files as guided.

Thanks


问:
Get All Values of Property in Array
I'm using jQuery to perform an AJAX request that returns a JSON array that looks similar to this:

```<code>[
  {
    "id": 1,
    "message": "test1",
    "expiration": "2017-11-17"
  },
  {
    "id": 2,
    "message": "test2",
    "expiration": "2017-11-17"
  }
]
</code>```

What I want to do is get all of the "message" values. I understand that I could iterate through each object in the array and get the value manually, but what I want to know is if there is a way of getting the values in a one-liner.

The programming language with which I'm most familiar with is VB.NET, and using the same data above, this is basically what I'm wanting to accomplish:

```<code>Dim messages = (From obj In Array Select p.message)
</code>```

答:
Use Array#map()

const data = [{
    "id": 1,
    "message": "test1",
    "expiration": "2017-11-17"
  },
  {
    "id": 2,
    "message": "test2",
    "expiration": "2017-11-17"
  }
]

const messageArray = data.map(e => e.message);

console.log(messageArray)```

Title: Get All Values of Property in Array

Body:
I'm using jQuery to perform an AJAX request that returns a JSON array that looks similar to this:

[
  {
    "id": 1,
    "message": "test1",
    "expiration": "2017-11-17"
  },
  {
    "id": 2,
    "message": "test2",
    "expiration": "2017-11-17"
  }
]

What I want to do is get all of the "message" values. I understand that I could iterate through each object in the array and get the value manually, but what I want to know is if there is a way of getting the values in a one-liner.

The programming language with which I'm most familiar with is VB.NET, and using the same data above, this is basically what I'm wanting to accomplish:

Dim messages = (From obj In Array Select p.message)


答:
You can map with parallel assignment. Shorter, but I personally wouldn't do it this way:</p>

```<code>let [underscores, correctBlock, wrongBlock, scoreBlock, btn, hint] =
  ['.underscores', '.correct', '.wrong', '#score', '.btn', '.hint']
  .map(selector => document.querySelector(selector))
</code>```

Title: Is there a more elegant way to declare my javascript variables?

Body:
You can map with parallel assignment. Shorter, but I personally wouldn't do it this way:

let [underscores, correctBlock, wrongBlock, scoreBlock, btn, hint] =
  ['.underscores', '.correct', '.wrong', '#score', '.btn', '.hint']
  .map(selector => document.querySelector(selector))


问:
OpenCV works with threads but not with processes
Hi everyone and thanks for the help.
I've got this function to save a video from frames taken by my webcam.

```<code>import cv2
import multiprocessing
import threading
def rec():
    # Define the codec and create VideoWriter object
    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))

    while(cap.isOpened()):
        ret, frame = cap.read()
        if ret==True:
            out.write(frame)
        else:
            break

    # Release everything if job is finished
    cap.release()
    out.release()
    cv2.destroyAllWindows()
</code>```

If i use it with threads, and so with this code, it works well:

```<code>s1 = threading.Thread(target=rec)
s1.start()
</code>```

But if i want to start another process, using the following code, when i open the video it contains only black frames with some noise.

```<code>s1 = multiprocessing.Process(target=rec)
s1.start()
</code>```

I searched all around but couldn't find any solution.

Also, i'm using Python 3.6

答: where is cap defined ? Try defining that in the function that you give to multiprocessing. If it is defined in the parent and is passed from the parent to the child, it is being pickled and that probably makes it unusable.

Body:
Hi everyone and thanks for the help.
I've got this function to save a video from frames taken by my webcam.

import cv2
import multiprocessing
import threading
def rec():
    # Define the codec and create VideoWriter object
    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))

    while(cap.isOpened()):
        ret, frame = cap.read()
        if ret==True:
            out.write(frame)
        else:
            break

    # Release everything if job is finished
    cap.release()
    out.release()
    cv2.destroyAllWindows()

If i use it with threads, and so with this code, it works well:

s1 = threading.Thread(target=rec)
s1.start()

But if i want to start another process, using the following code, when i open the video it contains only black frames with some noise.

s1 = multiprocessing.Process(target=rec)
s1.start()

I searched all around but couldn't find any solution.

Also, i'm using Python 3.6


问:
Java coin flip with user entered variables
I am trying to create a java program which accepts a user entered number and then flips a coin that many times and then displays how many heads or tails have been flipped so far.
My problem comes when I can't figure out how to make the program flip the coin the number of times the user says to, any help?</p>

```<code>package E1;
import java.util.Scanner;
public class E1 {
    public static void main(String[] args) {
        int hCount = 0;
        int tCount = 0;
        Scanner input = new Scanner(System.in);
        System.out.println("How many coins should be tossed?");
        input.nextInt();
        if (Math.random() < 0.5) {
            System.out.println("Heads");
            hCount++;
        } else {
            System.out.println("Tails");
            tCount++;
        }
    }
}
</code>```

答:
You can create a dialog window, the User indicates the number of times and then you can work around that, look:

```<code>    package E1;
    import java.util.Scanner;
    import javax.swing.*; // shows the dialogs windows

        public class E1 {
        public static void main(String[] args){

        // This Dialog Window will ask the User how many times the coin will be tossed
                int n_of_flips = JOptionPane.showInputDialog(null,
                    "Please indicate how many times you wish to flip the coin",
                    "Coin Flip",
                    JOptionPane.QUESTION_MESSAGE);

           // the while loop
           int x = 0;
           while(x<= n_of_flips){
            // your code here:
            if (Math.random() < 0.5)
                {
                System.out.println("Heads");
                        x++;
            }else{
                System.out.println("Tails");
                            x++;
            } // END while loop

       } // END public static void

    } // END of E1
</code>```

For more information google "JOptionPane Java", you can also display your results in a dialog window. Have fun :

Body:
I am trying to create a java program which accepts a user entered number and then flips a coin that many times and then displays how many heads or tails have been flipped so far.
My problem comes when I can't figure out how to make the program flip the coin the number of times the user says to, any help?

package E1;
import java.util.Scanner;
public class E1 {
    public static void main(String[] args) {
        int hCount = 0;
        int tCount = 0;
        Scanner input = new Scanner(System.in);
        System.out.println("How many coins should be tossed?");
        input.nextInt();
        if (Math.random() < 0.5) {
            System.out.println("Heads");
            hCount++;
        } else {
            System.out.println("Tails");
            tCount++;
        }
    }
}

Body:
You can create a dialog window, the User indicates the number of times and then you can work around that, look:

    package E1;
    import java.util.Scanner;
    import javax.swing.*; // shows the dialogs windows

        public class E1 {
        public static void main(String[] args){

        // This Dialog Window will ask the User how many times the coin will be tossed
                int n_of_flips = JOptionPane.showInputDialog(null,
                    "Please indicate how many times you wish to flip the coin",
                    "Coin Flip",
                    JOptionPane.QUESTION_MESSAGE);

           // the while loop
           int x = 0;
           while(x<= n_of_flips){
            // your code here:
            if (Math.random() < 0.5)
                {
                System.out.println("Heads");
                        x++;
            }else{
                System.out.println("Tails");
                            x++;
            } // END while loop

       } // END public static void

    } // END of E1

For more information google "JOptionPane Java", you can also display your results in a dialog window. Have fun :


问:
How can I configure IIS to serve directories without trailing slashes and always serve relative to root path?
I have a single page app hosted in IIS and I want make sure all requests are directed to /index.html (which will interpret the url and handle all routing client side). The only exception to this rule is when the request is for an actual file that is on disk such as *.js, *.css, *.png, etc. (I still need to be able to load the app after all ;-). Nearly everything works correctly with the following web.config file:

```<code><configuration>
    <system.webServer>
        <httpErrors errorMode="Custom" existingResponse="Replace">
            <remove statusCode="404"/>
            <error statusCode="404" responseMode="ExecuteURL" path="/index.html" />
        </httpErrors>
    </system.webServer>
</configuration>
</code>```

If I request mydomain.com/contact the /index.html page is served as expected, but if I request mydomain.com/contact/ (note the additional trailing slash) then all the relative paths in my app blow up because the browser tries to load /contact/some-file.js instead of /some-file.js. I can fix this by making all my paths rooted, but for more reasons than just inertia I want to be able to stick with relative paths.

The second related issue occurs when there is a directory on disk matching the requested url. For example, if I request /services and there is a /services directory on disk then the request is automatically changed to /services/ (I think IIS is the culprit here) which then produces a 403 error response because IIS rightfully refuses to serve up the directory contents.

Note that adding this to web.config partially solves the second problem:

```<code><remove statusCode="403"/>
<error statusCode="403" responseMode="ExecuteURL" path="/index.html" />
</code>```

Partially because it causes the 403 failure to use /index.html for its response but the rest of the resources are loaded relative to /services/ instead of / (which is back to the first issue with relative paths above). Also it is partial because a request to /services is still getting changed to /services/.

So my question is how can I prevent paths like /services from being changed to /services/ when there is a matching directory on disk and how can I make all redirects serve the response from the root and leave all path routing to the client (that is to treat a request for /contact/ as if it were a request for /contact)?

Update:
This seems to describe the problem accurately:
https://support.microsoft.com/en-us/help/298408/iis-generates-courtesy-redirect-when-folder-without-trailing-slash-is

I am using IIS 10 but the behavior is the same.

The 403 status code is for 'Forbidden' because the directory listing is correctly denied so adding this to web.config is treating the symptom and not the cause. I tested adding 301 and 302 to web.config and IIS does not allow this and produces the error:

```<code>The 'statusCode' attribute is invalid. Integer value must be between 400 and 999 inclusive
</code>```

答:
According to:

https://forums.iis.net/t/1153462.aspx?Is+it+possible+to+disable+the+courtesy+301+redirect+for+URL+requests+that+lack+a+trailing+slash+

there is no built in way to change the 301 behavior in IIS, and using url rewriting is the only way to deal with this. So I installed the IIS URL Rewrite Module (https://www.microsoft.com/en-us/download/details.aspx?id=47337) and added this to web.config instead:

```<code>    <rewrite>
        <rules>
            <rule name="Remove trailing slash" stopProcessing="true">
                <match url="(.*)/$" />
                <conditions>
                    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                </conditions>
                <action type="Redirect" redirectType="Permanent" url="{R:1}" />
            </rule>
        </rules>
    </rewrite>
</code>```

Now all requests with a trailing slash get it removed, IIS no longer performs 301 redirects to add back the slash, the client side loads resources are loaded relative to the root (thanks to no trailing slash), and the client side routing takes over and loads the correct content.

Body:
I have a single page app hosted in IIS and I want make sure all requests are directed to /index.html (which will interpret the url and handle all routing client side). The only exception to this rule is when the request is for an actual file that is on disk such as *.js, *.css, *.png, etc. (I still need to be able to load the app after all ;-). Nearly everything works correctly with the following web.config file:

<configuration>
    <system.webServer>
        <httpErrors errorMode="Custom" existingResponse="Replace">
            <remove statusCode="404"/>
            <error statusCode="404" responseMode="ExecuteURL" path="/index.html" />
        </httpErrors>
    </system.webServer>
</configuration>

If I request mydomain.com/contact the /index.html page is served as expected, but if I request mydomain.com/contact/ (note the additional trailing slash) then all the relative paths in my app blow up because the browser tries to load /contact/some-file.js instead of /some-file.js. I can fix this by making all my paths rooted, but for more reasons than just inertia I want to be able to stick with relative paths.

The second related issue occurs when there is a directory on disk matching the requested url. For example, if I request /services and there is a /services directory on disk then the request is automatically changed to /services/ (I think IIS is the culprit here) which then produces a 403 error response because IIS rightfully refuses to serve up the directory contents.

Note that adding this to web.config partially solves the second problem:

<remove statusCode="403"/>
<error statusCode="403" responseMode="ExecuteURL" path="/index.html" />

Partially because it causes the 403 failure to use /index.html for its response but the rest of the resources are loaded relative to /services/ instead of / (which is back to the first issue with relative paths above). Also it is partial because a request to /services is still getting changed to /services/.

So my question is how can I prevent paths like /services from being changed to /services/ when there is a matching directory on disk and how can I make all redirects serve the response from the root and leave all path routing to the client (that is to treat a request for /contact/ as if it were a request for /contact)?

Update:
This seems to describe the problem accurately:
https://support.microsoft.com/en-us/help/298408/iis-generates-courtesy-redirect-when-folder-without-trailing-slash-is

I am using IIS 10 but the behavior is the same.

The 403 status code is for 'Forbidden' because the directory listing is correctly denied so adding this to web.config is treating the symptom and not the cause. I tested adding 301 and 302 to web.config and IIS does not allow this and produces the error:

The 'statusCode' attribute is invalid. Integer value must be between 400 and 999 inclusive

Body:
According to:

https://forums.iis.net/t/1153462.aspx?Is+it+possible+to+disable+the+courtesy+301+redirect+for+URL+requests+that+lack+a+trailing+slash+

there is no built in way to change the 301 behavior in IIS, and using url rewriting is the only way to deal with this. So I installed the IIS URL Rewrite Module (https://www.microsoft.com/en-us/download/details.aspx?id=47337) and added this to web.config instead:

    <rewrite>
        <rules>
            <rule name="Remove trailing slash" stopProcessing="true">
                <match url="(.*)/$" />
                <conditions>
                    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                </conditions>
                <action type="Redirect" redirectType="Permanent" url="{R:1}" />
            </rule>
        </rules>
    </rewrite>

Now all requests with a trailing slash get it removed, IIS no longer performs 301 redirects to add back the slash, the client side loads resources are loaded relative to the root (thanks to no trailing slash), and the client side routing takes over and loads the correct content.


问:
Removing nonnumerical data out of a number + SQL
I'm trying find the best way to remove nonnumerical data from a varchar in SQL e.g.

```<code>'(082) 000-0000' to '0820000000' or
'+2782 000 0000' to '0820000000'
</code>```

The difficulty is i'm not always sure what number formats are coming in, as shown above, so I'd like like everything that is not a number removed essentially.

Update:

From what you guys have said this is a little spike done:

```<code>declare @Num varchar(20)

set @Num = ' + (82) 468 6152 '

--strip nonnumrical data out of @num

print @Num

set @Num = replace(@Num, ' ', '')
set @Num = replace(@Num, '+', '')
set @Num = replace(@Num, '-', '')
set @Num = replace(@Num, '(', '')
set @Num = replace(@Num, ')', '')

print @Num
</code>```

Couldn't get the replace [^0-9] expression right though.

答:
The most effective and flexible that I have found is using the numbers/tally table method as shown in mwigdahl's answer on 10 Mar 2009

i.e. an allow list is much safer than the do-not-allow list that you have put in the bottom of your question above.

What you have not stated is how you handle non-integers ... what do you do with decimal points?

OwnerDisplayName: Steven

LastEditorDisplayName: Steven

Body:
I'm trying find the best way to remove nonnumerical data from a varchar in SQL e.g.

'(082) 000-0000' to '0820000000' or
'+2782 000 0000' to '0820000000'

The difficulty is i'm not always sure what number formats are coming in, as shown above, so I'd like like everything that is not a number removed essentially.

Update:

From what you guys have said this is a little spike done:

declare @Num varchar(20)

set @Num = ' + (82) 468 6152 '

--strip nonnumrical data out of @num

print @Num

set @Num = replace(@Num, ' ', '')
set @Num = replace(@Num, '+', '')
set @Num = replace(@Num, '-', '')
set @Num = replace(@Num, '(', '')
set @Num = replace(@Num, ')', '')

print @Num

Couldn't get the replace [^0-9] expression right though.


问:
How to check if user input is empty with bufio?
I'm new with Go syntax, just trying to pass an error if the user did not input anything...

[EDIT] I would like the following function to stop running if the user did not input anything, and print a log. My if required && answer == ""  statement doesn't seem to work as "You must enter a value." does not log when the user does not input anything.

```<code>func QAR(q string, r string, required bool) string {
  reader := bufio.NewReader(os.Stdin)

  // Print the question
  fmt.Printf(q)
  answer, _ := reader.ReadString('\n')

  // If the answer is empty, return a log
  if required && answer == "" {
    log.Fatal("You must enter a value.")

    // Can I just use return to block it?
    return
  }

  // Print the response with the answer
  if r != "" {
    fmt.Println(r, answer)
  }

  return answer
}
</code>```

答:
The typical pattern in go is to return multiple values, the last of which is an error, if one occurred. So your function signature could look like this:

```<code>func QAR(q string, r string, required bool) (string, error)
</code>```

And the return statements like this:

```<code>return "", fmt.Errorf("user provided no input")
// ...
return answer, nil
</code>```

[EDIT]

Note that bufio.Reader.ReadString(...) includes the delimiter, so you probably need to check if answer == "\n".

Body:
I'm new with Go syntax, just trying to pass an error if the user did not input anything...

[EDIT] I would like the following function to stop running if the user did not input anything, and print a log. My if required && answer == ""  statement doesn't seem to work as "You must enter a value." does not log when the user does not input anything.

func QAR(q string, r string, required bool) string {
  reader := bufio.NewReader(os.Stdin)

  // Print the question
  fmt.Printf(q)
  answer, _ := reader.ReadString('\n')

  // If the answer is empty, return a log
  if required && answer == "" {
    log.Fatal("You must enter a value.")

    // Can I just use return to block it?
    return
  }

  // Print the response with the answer
  if r != "" {
    fmt.Println(r, answer)
  }

  return answer
}

Body:
The typical pattern in go is to return multiple values, the last of which is an error, if one occurred. So your function signature could look like this:

func QAR(q string, r string, required bool) (string, error)

And the return statements like this:

return "", fmt.Errorf("user provided no input")
// ...
return answer, nil

[EDIT]

Note that bufio.Reader.ReadString(...) includes the delimiter, so you probably need to check if answer == "\n".


问:
MS SQL Not Like Query
I have 2 tables, one a list of students and one with a list of restaurants.  The people table has PK that is contained within the restaurants table as an FK.  The restaurant table contains the days the students like to eat out at restaurants (along with restaurants they eat at).  I'm trying to find the students who do not like to eat at the restaurant on Monday.  I tried using the query below, but it lists all of the students and not the ones that don't eat out on Monday.</p>

```<code>SELECT DISTINCT SName
FROM Dinner AS D
INNER JOIN Student AS S ON D.SID = S.SID
WHERE DinnerDay NOT LIKE 'Monday'
GROUP BY SName
</code>```

答:
The Inner Join will remove rows that do not match on joining conditions.  So you could have students that never eat out an any restaurant, as written the inner join will eliminate these students. Instead you should use a left join, which will return null.

You also did a DISTINCT with a GROUP BY. This is removing duplicates twice.  You only need to do one of these.

```<code>SELECT DISTINCT CASE WHEN (D.ID IS NOT NULL)
                      THEN S.SName
                END
FROM Student AS S
LEFT JOIN Dinner AS D ON S.SID = D.SID AND D.DinnerDay = 'Monday'
</code>```

This will return NULL for D.ID if the Student does not eat on Monday, or never eats out at any restaurant.  The case statement checks if D.ID IS NOT NULL, if so it returns S.SName.  This select is DISTINCT to remove duplicates.

Title: MS SQL Not Like Query

Body:
I have 2 tables, one a list of students and one with a list of restaurants.  The people table has PK that is contained within the restaurants table as an FK.  The restaurant table contains the days the students like to eat out at restaurants (along with restaurants they eat at).  I'm trying to find the students who do not like to eat at the restaurant on Monday.  I tried using the query below, but it lists all of the students and not the ones that don't eat out on Monday.

SELECT DISTINCT SName
FROM Dinner AS D
INNER JOIN Student AS S ON D.SID = S.SID
WHERE DinnerDay NOT LIKE 'Monday'
GROUP BY SName

Body:
The Inner Join will remove rows that do not match on joining conditions.  So you could have students that never eat out an any restaurant, as written the inner join will eliminate these students. Instead you should use a left join, which will return null.

You also did a DISTINCT with a GROUP BY. This is removing duplicates twice.  You only need to do one of these.

SELECT DISTINCT CASE WHEN (D.ID IS NOT NULL)
                      THEN S.SName
                END
FROM Student AS S
LEFT JOIN Dinner AS D ON S.SID = D.SID AND D.DinnerDay = 'Monday'

This will return NULL for D.ID if the Student does not eat on Monday, or never eats out at any restaurant.  The case statement checks if D.ID IS NOT NULL, if so it returns S.SName.  This select is DISTINCT to remove duplicates.


答:
You can use $.map (http://api.jquery.com/jquery.map/) as the equivalent of your VB.Net 'select' statement, eg:

var json = [
  {
    "id": 1,
    "message": "test1",
    "expiration": "2017-11-17"
  },
  {
    "id": 2,
    "message": "test2",
    "expiration": "2017-11-17"
  }
]

var a = $.map(json, function(e) { return e.message; });
console.log(a);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Title: Get All Values of Property in Array

Body:
You can use $.map (http://api.jquery.com/jquery.map/) as the equivalent of your VB.Net 'select' statement, eg:

var json = [
  {
    "id": 1,
    "message": "test1",
    "expiration": "2017-11-17"
  },
  {
    "id": 2,
    "message": "test2",
    "expiration": "2017-11-17"
  }
]

var a = $.map(json, function(e) { return e.message; });
console.log(a);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
Sending binary image through pipes in python to a C server
so i'm trying to send a file (in this case a .jpg image) in binary from a client in python 3 to a C server through pipes and for some reason it displays the error, broken pipe, here is the code:
python:

```<code>import os,sys,errno,pipes,signal,time

def Tuberia():
    fifo = "/tmp/fifoNombre"
    print ("conecting to a pipe...",fifo)
    file = open("/home/luisro/Pictures/64.jpg","r+b")
    f = open(fifo,'wb')
    for line in file:
        print(line)
        f.write(line)
    f.close()
    file.close()
</code>```

and the C server:

```<code>void reciveFile(){
  int fn;
  char * fifoNombre = "/tmp/fifoNombre";
  // //opens the pipe for reading
  mkfifo(fifoNombre, 0666);
  unsigned char datos[MAX_BUF];
  fn = open(fifoNombre, O_RDONLY);
    read(fn, datos, MAX_BUF);
    saving(datos,"/home/luisro/Desktop/algo.jpg");
   unlink(fifoNombre);

}

void saving(unsigned char *data, char* dirDest){
    FILE *flujoArchivo = fopen(dirDest, "wb");
    if(flujoArchivo == NULL){
        printf("Error saving.\n");
        exit(-1);
    }
    int writed_size = fwrite(data, sizeof(unsigned char), MAX_BUF, flujoArchivo);

    fclose(flujoArchivo);
}
</code>```

so those are the functions i don't know if is the python client or the C server where the problem is, thanks in advance

答:
A binary file is not "line" oriented, which is how your attempting to read it in python.... Here's a link showing how to read a binary file in python: The-link

Additionally, you may have to change your server to perform some looping when it is receiving the binary file, if it is greater than MAX_BUF.

Body:
so i'm trying to send a file (in this case a .jpg image) in binary from a client in python 3 to a C server through pipes and for some reason it displays the error, broken pipe, here is the code:
python:

import os,sys,errno,pipes,signal,time

def Tuberia():
    fifo = "/tmp/fifoNombre"
    print ("conecting to a pipe...",fifo)
    file = open("/home/luisro/Pictures/64.jpg","r+b")
    f = open(fifo,'wb')
    for line in file:
        print(line)
        f.write(line)
    f.close()
    file.close()

and the C server:

void reciveFile(){
  int fn;
  char * fifoNombre = "/tmp/fifoNombre";
  // //opens the pipe for reading
  mkfifo(fifoNombre, 0666);
  unsigned char datos[MAX_BUF];
  fn = open(fifoNombre, O_RDONLY);
    read(fn, datos, MAX_BUF);
    saving(datos,"/home/luisro/Desktop/algo.jpg");
   unlink(fifoNombre);

}

void saving(unsigned char *data, char* dirDest){
    FILE *flujoArchivo = fopen(dirDest, "wb");
    if(flujoArchivo == NULL){
        printf("Error saving.\n");
        exit(-1);
    }
    int writed_size = fwrite(data, sizeof(unsigned char), MAX_BUF, flujoArchivo);

    fclose(flujoArchivo);
}

so those are the functions i don't know if is the python client or the C server where the problem is, thanks in advance